repo_name stringlengths 5 100 | path stringlengths 4 294 | copies stringclasses 990
values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15
values |
|---|---|---|---|---|---|
epitron/youtube-dl | youtube_dl/extractor/mitele.py | 5 | 7923 | # coding: utf-8
from __future__ import unicode_literals
import json
import uuid
from .common import InfoExtractor
from .ooyala import OoyalaIE
from ..compat import (
compat_str,
compat_urlparse,
)
from ..utils import (
int_or_none,
extract_attributes,
determine_ext,
smuggle_url,
parse_duration,
)
class MiTeleBaseIE(InfoExtractor):
def _get_player_info(self, url, webpage):
player_data = extract_attributes(self._search_regex(
r'(?s)(<ms-video-player.+?</ms-video-player>)',
webpage, 'ms video player'))
video_id = player_data['data-media-id']
if player_data.get('data-cms-id') == 'ooyala':
return self.url_result(
'ooyala:%s' % video_id, ie=OoyalaIE.ie_key(), video_id=video_id)
config_url = compat_urlparse.urljoin(url, player_data['data-config'])
config = self._download_json(
config_url, video_id, 'Downloading config JSON')
mmc_url = config['services']['mmc']
duration = None
formats = []
for m_url in (mmc_url, mmc_url.replace('/flash.json', '/html5.json')):
mmc = self._download_json(
m_url, video_id, 'Downloading mmc JSON')
if not duration:
duration = int_or_none(mmc.get('duration'))
for location in mmc['locations']:
gat = self._proto_relative_url(location.get('gat'), 'http:')
gcp = location.get('gcp')
ogn = location.get('ogn')
if None in (gat, gcp, ogn):
continue
token_data = {
'gcp': gcp,
'ogn': ogn,
'sta': 0,
}
media = self._download_json(
gat, video_id, data=json.dumps(token_data).encode('utf-8'),
headers={
'Content-Type': 'application/json;charset=utf-8',
'Referer': url,
})
stream = media.get('stream') or media.get('file')
if not stream:
continue
ext = determine_ext(stream)
if ext == 'f4m':
formats.extend(self._extract_f4m_formats(
stream + '&hdcore=3.2.0&plugin=aasp-3.2.0.77.18',
video_id, f4m_id='hds', fatal=False))
elif ext == 'm3u8':
formats.extend(self._extract_m3u8_formats(
stream, video_id, 'mp4', 'm3u8_native',
m3u8_id='hls', fatal=False))
self._sort_formats(formats)
return {
'id': video_id,
'formats': formats,
'thumbnail': player_data.get('data-poster') or config.get('poster', {}).get('imageUrl'),
'duration': duration,
}
class MiTeleIE(InfoExtractor):
IE_DESC = 'mitele.es'
_VALID_URL = r'https?://(?:www\.)?mitele\.es/(?:[^/]+/)+(?P<id>[^/]+)/player'
_TESTS = [{
'url': 'http://www.mitele.es/programas-tv/diario-de/57b0dfb9c715da65618b4afa/player',
'info_dict': {
'id': '57b0dfb9c715da65618b4afa',
'ext': 'mp4',
'title': 'Tor, la web invisible',
'description': 'md5:3b6fce7eaa41b2d97358726378d9369f',
'series': 'Diario de',
'season': 'La redacción',
'season_number': 14,
'season_id': 'diario_de_t14_11981',
'episode': 'Programa 144',
'episode_number': 3,
'thumbnail': r're:(?i)^https?://.*\.jpg$',
'duration': 2913,
},
'add_ie': ['Ooyala'],
}, {
# no explicit title
'url': 'http://www.mitele.es/programas-tv/cuarto-milenio/57b0de3dc915da14058b4876/player',
'info_dict': {
'id': '57b0de3dc915da14058b4876',
'ext': 'mp4',
'title': 'Cuarto Milenio Temporada 6 Programa 226',
'description': 'md5:5ff132013f0cd968ffbf1f5f3538a65f',
'series': 'Cuarto Milenio',
'season': 'Temporada 6',
'season_number': 6,
'season_id': 'cuarto_milenio_t06_12715',
'episode': 'Programa 226',
'episode_number': 24,
'thumbnail': r're:(?i)^https?://.*\.jpg$',
'duration': 7313,
},
'params': {
'skip_download': True,
},
'add_ie': ['Ooyala'],
}, {
'url': 'http://www.mitele.es/series-online/la-que-se-avecina/57aac5c1c915da951a8b45ed/player',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
gigya_url = self._search_regex(
r'<gigya-api>[^>]*</gigya-api>[^>]*<script\s+src="([^"]*)">[^>]*</script>',
webpage, 'gigya', default=None)
gigya_sc = self._download_webpage(
compat_urlparse.urljoin('http://www.mitele.es/', gigya_url),
video_id, 'Downloading gigya script')
# Get a appKey/uuid for getting the session key
appKey = self._search_regex(
r'constant\s*\(\s*["\']_appGridApplicationKey["\']\s*,\s*["\']([0-9a-f]+)',
gigya_sc, 'appKey')
session_json = self._download_json(
'https://appgrid-api.cloud.accedo.tv/session',
video_id, 'Downloading session keys', query={
'appKey': appKey,
'uuid': compat_str(uuid.uuid4()),
})
paths = self._download_json(
'https://appgrid-api.cloud.accedo.tv/metadata/general_configuration,%20web_configuration',
video_id, 'Downloading paths JSON',
query={'sessionKey': compat_str(session_json['sessionKey'])})
ooyala_s = paths['general_configuration']['api_configuration']['ooyala_search']
source = self._download_json(
'http://%s%s%s/docs/%s' % (
ooyala_s['base_url'], ooyala_s['full_path'],
ooyala_s['provider_id'], video_id),
video_id, 'Downloading data JSON', query={
'include_titles': 'Series,Season',
'product_name': 'test',
'format': 'full',
})['hits']['hits'][0]['_source']
embedCode = source['offers'][0]['embed_codes'][0]
titles = source['localizable_titles'][0]
title = titles.get('title_medium') or titles['title_long']
description = titles.get('summary_long') or titles.get('summary_medium')
def get(key1, key2):
value1 = source.get(key1)
if not value1 or not isinstance(value1, list):
return
if not isinstance(value1[0], dict):
return
return value1[0].get(key2)
series = get('localizable_titles_series', 'title_medium')
season = get('localizable_titles_season', 'title_medium')
season_number = int_or_none(source.get('season_number'))
season_id = source.get('season_id')
episode = titles.get('title_sort_name')
episode_number = int_or_none(source.get('episode_number'))
duration = parse_duration(get('videos', 'duration'))
return {
'_type': 'url_transparent',
# for some reason only HLS is supported
'url': smuggle_url('ooyala:' + embedCode, {'supportedformats': 'm3u8,dash'}),
'id': video_id,
'title': title,
'description': description,
'series': series,
'season': season,
'season_number': season_number,
'season_id': season_id,
'episode': episode,
'episode_number': episode_number,
'duration': duration,
'thumbnail': get('images', 'url'),
}
| unlicense |
slint/zenodo | zenodo/modules/fixtures/records.py | 2 | 2256 | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016, 2017 CERN.
#
# Zenodo 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.
#
# Zenodo 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 Zenodo; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""CLI for Zenodo fixtures."""
from __future__ import absolute_import, print_function
from uuid import uuid4
from flask import current_app
from flask_security import login_user
from invenio_db import db
from invenio_sipstore.models import SIPMetadataType
from six import BytesIO
from zenodo.modules.deposit.api import ZenodoDeposit
from zenodo.modules.deposit.loaders import legacyjson_v1
from zenodo.modules.deposit.minters import zenodo_deposit_minter
def loaddemorecords(records, owner):
"""Load demo records."""
with current_app.test_request_context():
login_user(owner)
for record in records:
deposit_data = legacyjson_v1(record)
deposit_id = uuid4()
zenodo_deposit_minter(deposit_id, deposit_data)
deposit = ZenodoDeposit.create(deposit_data, id_=deposit_id)
db.session.commit()
filename = record['files'][0]
deposit.files[filename] = BytesIO(filename)
db.session.commit()
deposit.publish()
db.session.commit()
def loadsipmetadatatypes(types):
"""Load SIP metadata types."""
with db.session.begin_nested():
for type in types:
db.session.add(SIPMetadataType(**type))
db.session.commit()
| gpl-2.0 |
google/riscv-dv | pygen/pygen_src/isa/rv32m_instr.py | 3 | 1996 | """
Copyright 2020 Google LLC
Copyright 2020 PerfectVIPs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
"""
from pygen_src.riscv_defines import DEFINE_INSTR
from pygen_src.riscv_instr_pkg import (riscv_instr_name_t, riscv_instr_format_t,
riscv_instr_category_t, riscv_instr_group_t)
# Multiplication and Division Instructions
DEFINE_INSTR(riscv_instr_name_t.MUL, riscv_instr_format_t.R_FORMAT,
riscv_instr_category_t.ARITHMETIC, riscv_instr_group_t.RV32M, g=globals())
DEFINE_INSTR(riscv_instr_name_t.MULH, riscv_instr_format_t.R_FORMAT,
riscv_instr_category_t.ARITHMETIC, riscv_instr_group_t.RV32M, g=globals())
DEFINE_INSTR(riscv_instr_name_t.MULHSU, riscv_instr_format_t.R_FORMAT,
riscv_instr_category_t.ARITHMETIC, riscv_instr_group_t.RV32M, g=globals())
DEFINE_INSTR(riscv_instr_name_t.MULHU, riscv_instr_format_t.R_FORMAT,
riscv_instr_category_t.ARITHMETIC, riscv_instr_group_t.RV32M, g=globals())
DEFINE_INSTR(riscv_instr_name_t.DIV, riscv_instr_format_t.R_FORMAT,
riscv_instr_category_t.ARITHMETIC, riscv_instr_group_t.RV32M, g=globals())
DEFINE_INSTR(riscv_instr_name_t.DIVU, riscv_instr_format_t.R_FORMAT,
riscv_instr_category_t.ARITHMETIC, riscv_instr_group_t.RV32M, g=globals())
DEFINE_INSTR(riscv_instr_name_t.REM, riscv_instr_format_t.R_FORMAT,
riscv_instr_category_t.ARITHMETIC, riscv_instr_group_t.RV32M, g=globals())
DEFINE_INSTR(riscv_instr_name_t.REMU, riscv_instr_format_t.R_FORMAT,
riscv_instr_category_t.LOAD, riscv_instr_group_t.RV32M, g=globals())
| apache-2.0 |
pfctgeorge/shadowsocks | shadowsocks/common.py | 945 | 8921 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013-2015 clowwindy
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import, division, print_function, \
with_statement
import socket
import struct
import logging
def compat_ord(s):
if type(s) == int:
return s
return _ord(s)
def compat_chr(d):
if bytes == str:
return _chr(d)
return bytes([d])
_ord = ord
_chr = chr
ord = compat_ord
chr = compat_chr
def to_bytes(s):
if bytes != str:
if type(s) == str:
return s.encode('utf-8')
return s
def to_str(s):
if bytes != str:
if type(s) == bytes:
return s.decode('utf-8')
return s
def inet_ntop(family, ipstr):
if family == socket.AF_INET:
return to_bytes(socket.inet_ntoa(ipstr))
elif family == socket.AF_INET6:
import re
v6addr = ':'.join(('%02X%02X' % (ord(i), ord(j))).lstrip('0')
for i, j in zip(ipstr[::2], ipstr[1::2]))
v6addr = re.sub('::+', '::', v6addr, count=1)
return to_bytes(v6addr)
def inet_pton(family, addr):
addr = to_str(addr)
if family == socket.AF_INET:
return socket.inet_aton(addr)
elif family == socket.AF_INET6:
if '.' in addr: # a v4 addr
v4addr = addr[addr.rindex(':') + 1:]
v4addr = socket.inet_aton(v4addr)
v4addr = map(lambda x: ('%02X' % ord(x)), v4addr)
v4addr.insert(2, ':')
newaddr = addr[:addr.rindex(':') + 1] + ''.join(v4addr)
return inet_pton(family, newaddr)
dbyts = [0] * 8 # 8 groups
grps = addr.split(':')
for i, v in enumerate(grps):
if v:
dbyts[i] = int(v, 16)
else:
for j, w in enumerate(grps[::-1]):
if w:
dbyts[7 - j] = int(w, 16)
else:
break
break
return b''.join((chr(i // 256) + chr(i % 256)) for i in dbyts)
else:
raise RuntimeError("What family?")
def is_ip(address):
for family in (socket.AF_INET, socket.AF_INET6):
try:
if type(address) != str:
address = address.decode('utf8')
inet_pton(family, address)
return family
except (TypeError, ValueError, OSError, IOError):
pass
return False
def patch_socket():
if not hasattr(socket, 'inet_pton'):
socket.inet_pton = inet_pton
if not hasattr(socket, 'inet_ntop'):
socket.inet_ntop = inet_ntop
patch_socket()
ADDRTYPE_IPV4 = 1
ADDRTYPE_IPV6 = 4
ADDRTYPE_HOST = 3
def pack_addr(address):
address_str = to_str(address)
for family in (socket.AF_INET, socket.AF_INET6):
try:
r = socket.inet_pton(family, address_str)
if family == socket.AF_INET6:
return b'\x04' + r
else:
return b'\x01' + r
except (TypeError, ValueError, OSError, IOError):
pass
if len(address) > 255:
address = address[:255] # TODO
return b'\x03' + chr(len(address)) + address
def parse_header(data):
addrtype = ord(data[0])
dest_addr = None
dest_port = None
header_length = 0
if addrtype == ADDRTYPE_IPV4:
if len(data) >= 7:
dest_addr = socket.inet_ntoa(data[1:5])
dest_port = struct.unpack('>H', data[5:7])[0]
header_length = 7
else:
logging.warn('header is too short')
elif addrtype == ADDRTYPE_HOST:
if len(data) > 2:
addrlen = ord(data[1])
if len(data) >= 2 + addrlen:
dest_addr = data[2:2 + addrlen]
dest_port = struct.unpack('>H', data[2 + addrlen:4 +
addrlen])[0]
header_length = 4 + addrlen
else:
logging.warn('header is too short')
else:
logging.warn('header is too short')
elif addrtype == ADDRTYPE_IPV6:
if len(data) >= 19:
dest_addr = socket.inet_ntop(socket.AF_INET6, data[1:17])
dest_port = struct.unpack('>H', data[17:19])[0]
header_length = 19
else:
logging.warn('header is too short')
else:
logging.warn('unsupported addrtype %d, maybe wrong password or '
'encryption method' % addrtype)
if dest_addr is None:
return None
return addrtype, to_bytes(dest_addr), dest_port, header_length
class IPNetwork(object):
ADDRLENGTH = {socket.AF_INET: 32, socket.AF_INET6: 128, False: 0}
def __init__(self, addrs):
self._network_list_v4 = []
self._network_list_v6 = []
if type(addrs) == str:
addrs = addrs.split(',')
list(map(self.add_network, addrs))
def add_network(self, addr):
if addr is "":
return
block = addr.split('/')
addr_family = is_ip(block[0])
addr_len = IPNetwork.ADDRLENGTH[addr_family]
if addr_family is socket.AF_INET:
ip, = struct.unpack("!I", socket.inet_aton(block[0]))
elif addr_family is socket.AF_INET6:
hi, lo = struct.unpack("!QQ", inet_pton(addr_family, block[0]))
ip = (hi << 64) | lo
else:
raise Exception("Not a valid CIDR notation: %s" % addr)
if len(block) is 1:
prefix_size = 0
while (ip & 1) == 0 and ip is not 0:
ip >>= 1
prefix_size += 1
logging.warn("You did't specify CIDR routing prefix size for %s, "
"implicit treated as %s/%d" % (addr, addr, addr_len))
elif block[1].isdigit() and int(block[1]) <= addr_len:
prefix_size = addr_len - int(block[1])
ip >>= prefix_size
else:
raise Exception("Not a valid CIDR notation: %s" % addr)
if addr_family is socket.AF_INET:
self._network_list_v4.append((ip, prefix_size))
else:
self._network_list_v6.append((ip, prefix_size))
def __contains__(self, addr):
addr_family = is_ip(addr)
if addr_family is socket.AF_INET:
ip, = struct.unpack("!I", socket.inet_aton(addr))
return any(map(lambda n_ps: n_ps[0] == ip >> n_ps[1],
self._network_list_v4))
elif addr_family is socket.AF_INET6:
hi, lo = struct.unpack("!QQ", inet_pton(addr_family, addr))
ip = (hi << 64) | lo
return any(map(lambda n_ps: n_ps[0] == ip >> n_ps[1],
self._network_list_v6))
else:
return False
def test_inet_conv():
ipv4 = b'8.8.4.4'
b = inet_pton(socket.AF_INET, ipv4)
assert inet_ntop(socket.AF_INET, b) == ipv4
ipv6 = b'2404:6800:4005:805::1011'
b = inet_pton(socket.AF_INET6, ipv6)
assert inet_ntop(socket.AF_INET6, b) == ipv6
def test_parse_header():
assert parse_header(b'\x03\x0ewww.google.com\x00\x50') == \
(3, b'www.google.com', 80, 18)
assert parse_header(b'\x01\x08\x08\x08\x08\x00\x35') == \
(1, b'8.8.8.8', 53, 7)
assert parse_header((b'\x04$\x04h\x00@\x05\x08\x05\x00\x00\x00\x00\x00'
b'\x00\x10\x11\x00\x50')) == \
(4, b'2404:6800:4005:805::1011', 80, 19)
def test_pack_header():
assert pack_addr(b'8.8.8.8') == b'\x01\x08\x08\x08\x08'
assert pack_addr(b'2404:6800:4005:805::1011') == \
b'\x04$\x04h\x00@\x05\x08\x05\x00\x00\x00\x00\x00\x00\x10\x11'
assert pack_addr(b'www.google.com') == b'\x03\x0ewww.google.com'
def test_ip_network():
ip_network = IPNetwork('127.0.0.0/24,::ff:1/112,::1,192.168.1.1,192.0.2.0')
assert '127.0.0.1' in ip_network
assert '127.0.1.1' not in ip_network
assert ':ff:ffff' in ip_network
assert '::ffff:1' not in ip_network
assert '::1' in ip_network
assert '::2' not in ip_network
assert '192.168.1.1' in ip_network
assert '192.168.1.2' not in ip_network
assert '192.0.2.1' in ip_network
assert '192.0.3.1' in ip_network # 192.0.2.0 is treated as 192.0.2.0/23
assert 'www.google.com' not in ip_network
if __name__ == '__main__':
test_inet_conv()
test_parse_header()
test_pack_header()
test_ip_network()
| apache-2.0 |
defance/edx-platform | lms/djangoapps/courseware/tests/test_i18n.py | 109 | 7964 | """
Tests i18n in courseware
"""
import re
from nose.plugins.attrib import attr
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse, NoReverseMatch
from django.test import TestCase
from django.test.client import Client
from dark_lang.models import DarkLangConfig
from lang_pref import LANGUAGE_KEY
from openedx.core.djangoapps.user_api.preferences.api import set_user_preference
from student.tests.factories import UserFactory, RegistrationFactory, UserProfileFactory
class BaseI18nTestCase(TestCase):
"""
Base utilities for i18n test classes to derive from
"""
def assert_tag_has_attr(self, content, tag, attname, value):
"""Assert that a tag in `content` has a certain value in a certain attribute."""
regex = r"""<{tag} [^>]*\b{attname}=['"]([\w\d\- ]+)['"][^>]*>""".format(tag=tag, attname=attname)
match = re.search(regex, content)
self.assertTrue(match, "Couldn't find desired tag '%s' with attr '%s' in %r" % (tag, attname, content))
attvalues = match.group(1).split()
self.assertIn(value, attvalues)
def release_languages(self, languages):
"""
Release a set of languages using the dark lang interface.
languages is a list of comma-separated lang codes, eg, 'ar, es-419'
"""
user = User()
user.save()
DarkLangConfig(
released_languages=languages,
changed_by=user,
enabled=True
).save()
@attr('shard_1')
class I18nTestCase(BaseI18nTestCase):
"""
Tests for i18n
"""
def test_default_is_en(self):
self.release_languages('fr')
response = self.client.get('/')
self.assert_tag_has_attr(response.content, "html", "lang", "en")
self.assertEqual(response['Content-Language'], 'en')
self.assert_tag_has_attr(response.content, "body", "class", "lang_en")
def test_esperanto(self):
self.release_languages('fr, eo')
response = self.client.get('/', HTTP_ACCEPT_LANGUAGE='eo')
self.assert_tag_has_attr(response.content, "html", "lang", "eo")
self.assertEqual(response['Content-Language'], 'eo')
self.assert_tag_has_attr(response.content, "body", "class", "lang_eo")
def test_switching_languages_bidi(self):
self.release_languages('ar, eo')
response = self.client.get('/')
self.assert_tag_has_attr(response.content, "html", "lang", "en")
self.assertEqual(response['Content-Language'], 'en')
self.assert_tag_has_attr(response.content, "body", "class", "lang_en")
self.assert_tag_has_attr(response.content, "body", "class", "ltr")
response = self.client.get('/', HTTP_ACCEPT_LANGUAGE='ar')
self.assert_tag_has_attr(response.content, "html", "lang", "ar")
self.assertEqual(response['Content-Language'], 'ar')
self.assert_tag_has_attr(response.content, "body", "class", "lang_ar")
self.assert_tag_has_attr(response.content, "body", "class", "rtl")
@attr('shard_1')
class I18nRegressionTests(BaseI18nTestCase):
"""
Tests for i18n
"""
def test_es419_acceptance(self):
# Regression test; LOC-72, and an issue with Django
self.release_languages('es-419')
response = self.client.get('/', HTTP_ACCEPT_LANGUAGE='es-419')
self.assert_tag_has_attr(response.content, "html", "lang", "es-419")
def test_unreleased_lang_resolution(self):
# Regression test; LOC-85
self.release_languages('fa')
# We've released 'fa', AND we have language files for 'fa-ir' but
# we want to keep 'fa-ir' as a dark language. Requesting 'fa-ir'
# in the http request (NOT with the ?preview-lang query param) should
# receive files for 'fa'
response = self.client.get('/', HTTP_ACCEPT_LANGUAGE='fa-ir')
self.assert_tag_has_attr(response.content, "html", "lang", "fa")
# Now try to access with dark lang
response = self.client.get('/?preview-lang=fa-ir')
self.assert_tag_has_attr(response.content, "html", "lang", "fa-ir")
def test_preview_lang(self):
# Regression test; LOC-87
self.release_languages('es-419')
site_lang = settings.LANGUAGE_CODE
# Visit the front page; verify we see site default lang
response = self.client.get('/')
self.assert_tag_has_attr(response.content, "html", "lang", site_lang)
# Verify we can switch language using the preview-lang query param
response = self.client.get('/?preview-lang=eo')
self.assert_tag_has_attr(response.content, "html", "lang", "eo")
# We should be able to see released languages using preview-lang, too
response = self.client.get('/?preview-lang=es-419')
self.assert_tag_has_attr(response.content, "html", "lang", "es-419")
# Clearing the language should go back to site default
response = self.client.get('/?clear-lang')
self.assert_tag_has_attr(response.content, "html", "lang", site_lang)
@attr('shard_1')
class I18nLangPrefTests(BaseI18nTestCase):
"""
Regression tests of language presented to the user, when they
choose a language preference, and when they have a preference
and use the dark lang preview functionality.
"""
def setUp(self):
super(I18nLangPrefTests, self).setUp()
# Create one user and save it to the database
email = 'test@edx.org'
pwd = 'test_password'
self.user = UserFactory.build(username='test', email=email)
self.user.set_password(pwd)
self.user.save()
# Create a registration for the user
RegistrationFactory(user=self.user)
# Create a profile for the user
UserProfileFactory(user=self.user)
# Create the test client
self.client = Client()
# Get the login url & log in our user
try:
login_url = reverse('login_post')
except NoReverseMatch:
login_url = reverse('login')
self.client.post(login_url, {'email': email, 'password': pwd})
# Url and site lang vars for tests to use
self.url = reverse('dashboard')
self.site_lang = settings.LANGUAGE_CODE
def test_lang_preference(self):
# Regression test; LOC-87
self.release_languages('ar, es-419')
# Visit the front page; verify we see site default lang
response = self.client.get(self.url)
self.assert_tag_has_attr(response.content, "html", "lang", self.site_lang)
# Set user language preference
set_user_preference(self.user, LANGUAGE_KEY, 'ar')
# and verify we now get an ar response
response = self.client.get(self.url)
self.assert_tag_has_attr(response.content, "html", "lang", 'ar')
# Verify that switching language preference gives the right language
set_user_preference(self.user, LANGUAGE_KEY, 'es-419')
response = self.client.get(self.url)
self.assert_tag_has_attr(response.content, "html", "lang", 'es-419')
def test_preview_precedence(self):
# Regression test; LOC-87
self.release_languages('ar, es-419')
# Set user language preference
set_user_preference(self.user, LANGUAGE_KEY, 'ar')
# Verify preview-lang takes precedence
response = self.client.get('{}?preview-lang=eo'.format(self.url))
self.assert_tag_has_attr(response.content, "html", "lang", 'eo')
# Hitting another page should keep the dark language set.
response = self.client.get(reverse('courses'))
self.assert_tag_has_attr(response.content, "html", "lang", "eo")
# Clearing language must set language back to preference language
response = self.client.get('{}?clear-lang'.format(self.url))
self.assert_tag_has_attr(response.content, "html", "lang", 'ar')
| agpl-3.0 |
wolfmanstout/dragonfly | dragonfly/grammar/recobs.py | 2 | 6928 | #
# This file is part of Dragonfly.
# (c) Copyright 2007, 2008 by Christo Butcher
# Licensed under the LGPL.
#
# Dragonfly is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Dragonfly is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with Dragonfly. If not, see
# <http://www.gnu.org/licenses/>.
#
"""
Recognition observer classes
============================================================================
"""
import time
import logging
from six import integer_types
from ..actions.actions import Playback
from ..engines import get_engine
#---------------------------------------------------------------------------
class RecognitionObserver(object):
"""
Recognition observer base class.
Sub-classes should override one or more of the event methods.
"""
_log = logging.getLogger("grammar")
def __init__(self):
pass
def __del__(self):
try:
self.unregister()
except Exception:
pass
def register(self):
"""
Register the observer for recognition state events.
"""
engine = get_engine()
engine.register_recognition_observer(self)
def unregister(self):
"""
Unregister the observer for recognition state events.
"""
engine = get_engine()
engine.unregister_recognition_observer(self)
def on_begin(self):
"""
Method called when the observer is registered and speech start is
detected.
"""
def on_recognition(self, words, rule, node, results):
"""
Method called when speech successfully decoded to a grammar rule or
to dictation.
This is called *before* grammar rule processing (i.e.
``Rule.process_recognition()``).
:param words: recognized words
:type words: tuple
:param rule: *optional* recognized rule
:type rule: Rule
:param node: *optional* parse tree node
:type node: Node
:param results: *optional* engine recognition results object
:type results: :ref:`engine-specific type<RefGrammarCallbackResultsTypes>`
"""
def on_failure(self, results):
"""
Method called when speech failed to decode to a grammar rule or to
dictation.
:param results: *optional* engine recognition results object
:type results: :ref:`engine-specific type<RefGrammarCallbackResultsTypes>`
"""
def on_end(self, results):
"""
Method called when speech ends, either with a successful
recognition (after ``on_recognition``) or in failure (after
``on_failure``).
:param results: *optional* engine recognition results object
:type results: :ref:`engine-specific type<RefGrammarCallbackResultsTypes>`
"""
def on_post_recognition(self, words, rule, node, results):
"""
Method called when speech successfully decoded to a grammar rule or
to dictation.
This is called *after* grammar rule processing (i.e.
``Rule.process_recognition()``).
:param words: recognized words
:type words: tuple
:param rule: *optional* recognized rule
:type rule: Rule
:param node: *optional* parse tree node
:type node: Node
:param results: *optional* engine recognition results object
:type results: :ref:`engine-specific type<RefGrammarCallbackResultsTypes>`
"""
#---------------------------------------------------------------------------
class RecognitionHistory(list, RecognitionObserver):
"""
Storage class for recent recognitions.
Instances of this class monitor recognitions and store them
internally. This class derives from the built in *list* type
and can be accessed as if it were a normal *list* containing
recent recognitions. Note that an instance's contents are
updated automatically as recognitions are received.
"""
def __init__(self, length=10):
list.__init__(self)
RecognitionObserver.__init__(self)
self._complete = True
if (length is None or (isinstance(length, integer_types) and
length >= 1)):
self._length = length
else:
raise ValueError("length must be a positive int or None,"
" received %r." % length)
@property
def complete(self):
""" *False* if phrase-start detected but no recognition yet. """
return self._complete
def on_begin(self):
""""""
self._complete = False
def on_recognition(self, words):
""""""
self._complete = True
self.append(self._recognition_to_item(words))
if self._length:
while len(self) > self._length:
self.pop(0)
def _recognition_to_item(self, words):
""""""
# pylint: disable=no-self-use
return words
#---------------------------------------------------------------------------
class PlaybackHistory(RecognitionHistory):
"""
Storage class for playing back recent recognitions via the
:class:`Playback` action.
Instances of this class monitor recognitions and store them
internally. This class derives from the built in *list* type
and can be accessed as if it were a normal *list* containing
:class:`Playback` actions for recent recognitions. Note that an
instance's contents are updated automatically as recognitions are
received.
"""
def __init__(self, length=10):
RecognitionHistory.__init__(self, length)
def _recognition_to_item(self, words):
return (words, time.time())
def __getitem__(self, key):
result = RecognitionHistory.__getitem__(self, key)
if len(result) == 1:
return Playback([(result[0][0], 0)])
elif len(result) == 2 and isinstance(result[1], float):
return Playback([(result[0], 0)])
elif len(result) == 0:
return Playback(())
else:
pairs = [(w1, t2 - t1)
for ((w1, t1), (w2, t2))
in zip(result[:-1], result[1:])]
pairs.append((result[-1][0], 0))
return Playback(pairs)
def __getslice__(self, i, j):
return self.__getitem__(slice(i, j))
| lgpl-3.0 |
0todd0000/spm1d | spm1d/examples/nonparam/1d/ex_anova3onerm.py | 1 | 1117 |
import numpy as np
from matplotlib import pyplot
import spm1d
#(0) Load dataset:
dataset = spm1d.data.uv1d.anova3onerm.SPM1D_ANOVA3ONERM_2x2x2()
# dataset = spm1d.data.uv1d.anova3onerm.SPM1D_ANOVA3ONERM_2x3x4()
y,A,B,C,SUBJ = dataset.get_data()
#(1) Conduct non-parametric test:
np.random.seed(0)
alpha = 0.05
FFn = spm1d.stats.nonparam.anova3onerm(y, A, B, C, SUBJ)
FFni = FFn.inference(alpha, iterations=200)
print( FFni )
#(2) Compare with parametric result:
FF = spm1d.stats.anova3onerm(y, A, B, C, SUBJ, equal_var=True)
FFi = FF.inference(alpha)
print( FFi )
#(3) Plot
pyplot.close('all')
pyplot.figure(figsize=(15,10))
for i,(Fi,Fni) in enumerate( zip(FFi,FFni) ):
ax = pyplot.subplot(3,3,i+1)
Fni.plot(ax=ax)
Fni.plot_threshold_label(ax=ax, fontsize=8)
Fni.plot_p_values(ax=ax, size=10)
ax.axhline( Fi.zstar, color='orange', linestyle='--', label='Parametric threshold')
if (Fi.zstar > Fi.z.max()) and (Fi.zstar>Fni.zstar):
ax.set_ylim(0, Fi.zstar+1)
if i==0:
ax.legend(fontsize=10, loc='best')
ax.set_title( Fni.effect )
pyplot.show()
| gpl-3.0 |
alindt/Cinnamon | files/usr/lib/cinnamon-looking-glass/page_results.py | 1 | 2291 | from pageutils import *
from gi.repository import Gio, Gtk, GObject, Gdk, Pango, GLib
class ModulePage(BaseListView):
def __init__(self):
store = Gtk.ListStore(int, str, str, str)
BaseListView.__init__(self, store)
column = self.createTextColumn(0, "ID")
column.set_cell_data_func(self.rendererText, self.cellDataFuncID)
self.createTextColumn(1, "Name")
self.createTextColumn(2, "Type")
self.createTextColumn(3, "Value")
self.treeView.connect("row-activated", self.onRowActivated)
self.treeView.connect("button-press-event", self.onButtonPress)
self.getUpdates()
lookingGlassProxy.connect("ResultUpdate", self.getUpdates)
lookingGlassProxy.connect("InspectorDone", self.onInspectorDone)
lookingGlassProxy.addStatusChangeCallback(self.onStatusChange)
#Popup menu
self.popup = Gtk.Menu()
clear = Gtk.MenuItem('Clear all results')
self.popup.append(clear)
self.popup.show_all()
def cellDataFuncID(self, column, cell, model, iter, data=None):
cell.set_property("text", "r(%d)" % model.get_value(iter, 0))
def onRowActivated(self, treeview, path, view_column):
iter = self.store.get_iter(path)
id = self.store.get_value(iter, 0)
name = self.store.get_value(iter, 1)
objType = self.store.get_value(iter, 2)
value = self.store.get_value(iter, 3)
cinnamonLog.pages["inspect"].inspectElement("r(%d)" % id, objType, name, value)
def onButtonPress(self, treeview, event):
if event.button == 3:
treeview.grab_focus()
self.popup.popup( None, None, None, None, event.button, event.time)
return True
def onStatusChange(self, online):
if online:
self.getUpdates()
def getUpdates(self):
self.store.clear()
success, data = lookingGlassProxy.GetResults()
if success:
try:
for item in data:
self.store.append([int(item["index"]), item["command"], item["type"], item["object"]])
except Exception as e:
print e
def onInspectorDone(self):
cinnamonLog.activatePage("results")
self.getUpdates()
| gpl-2.0 |
lanthaler/schemaorg | lib/html5lib/sanitizer.py | 100 | 14472 | import re
from xml.sax.saxutils import escape, unescape
from tokenizer import HTMLTokenizer
from constants import tokenTypes
class HTMLSanitizerMixin(object):
""" sanitization of XHTML+MathML+SVG and of inline style attributes."""
acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area',
'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button',
'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup',
'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn',
'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset',
'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1',
'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins',
'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter',
'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option',
'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select',
'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong',
'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot',
'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video']
mathml_elements = ['maction', 'math', 'merror', 'mfrac', 'mi',
'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom',
'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub',
'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
'munderover', 'none']
svg_elements = ['a', 'animate', 'animateColor', 'animateMotion',
'animateTransform', 'clipPath', 'circle', 'defs', 'desc', 'ellipse',
'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern',
'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph',
'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect',
'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use']
acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis',
'background', 'balance', 'bgcolor', 'bgproperties', 'border',
'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding',
'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff',
'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color',
'cols', 'colspan', 'compact', 'contenteditable', 'controls', 'coords',
'data', 'datafld', 'datapagesize', 'datasrc', 'datetime', 'default',
'delay', 'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end',
'face', 'for', 'form', 'frame', 'galleryimg', 'gutter', 'headers',
'height', 'hidefocus', 'hidden', 'high', 'href', 'hreflang', 'hspace',
'icon', 'id', 'inputmode', 'ismap', 'keytype', 'label', 'leftspacing',
'lang', 'list', 'longdesc', 'loop', 'loopcount', 'loopend',
'loopstart', 'low', 'lowsrc', 'max', 'maxlength', 'media', 'method',
'min', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'open',
'optimum', 'pattern', 'ping', 'point-size', 'prompt', 'pqg',
'radiogroup', 'readonly', 'rel', 'repeat-max', 'repeat-min',
'replace', 'required', 'rev', 'rightspacing', 'rows', 'rowspan',
'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'start',
'step', 'style', 'summary', 'suppress', 'tabindex', 'target',
'template', 'title', 'toppadding', 'type', 'unselectable', 'usemap',
'urn', 'valign', 'value', 'variable', 'volume', 'vspace', 'vrml',
'width', 'wrap', 'xml:lang']
mathml_attributes = ['actiontype', 'align', 'columnalign', 'columnalign',
'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'depth',
'display', 'displaystyle', 'equalcolumns', 'equalrows', 'fence',
'fontstyle', 'fontweight', 'frame', 'height', 'linethickness', 'lspace',
'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant', 'maxsize',
'minsize', 'other', 'rowalign', 'rowalign', 'rowalign', 'rowlines',
'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection',
'separator', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show',
'xlink:type', 'xmlns', 'xmlns:xlink']
svg_attributes = ['accent-height', 'accumulate', 'additive', 'alphabetic',
'arabic-form', 'ascent', 'attributeName', 'attributeType',
'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height',
'class', 'clip-path', 'color', 'color-rendering', 'content', 'cx',
'cy', 'd', 'dx', 'dy', 'descent', 'display', 'dur', 'end', 'fill',
'fill-opacity', 'fill-rule', 'font-family', 'font-size',
'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from',
'fx', 'fy', 'g1', 'g2', 'glyph-name', 'gradientUnits', 'hanging',
'height', 'horiz-adv-x', 'horiz-origin-x', 'id', 'ideographic', 'k',
'keyPoints', 'keySplines', 'keyTimes', 'lang', 'marker-end',
'marker-mid', 'marker-start', 'markerHeight', 'markerUnits',
'markerWidth', 'mathematical', 'max', 'min', 'name', 'offset',
'opacity', 'orient', 'origin', 'overline-position',
'overline-thickness', 'panose-1', 'path', 'pathLength', 'points',
'preserveAspectRatio', 'r', 'refX', 'refY', 'repeatCount',
'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart',
'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv', 'stop-color',
'stop-opacity', 'strikethrough-position', 'strikethrough-thickness',
'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap',
'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity',
'stroke-width', 'systemLanguage', 'target', 'text-anchor', 'to',
'transform', 'type', 'u1', 'u2', 'underline-position',
'underline-thickness', 'unicode', 'unicode-range', 'units-per-em',
'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x',
'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole',
'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type',
'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y',
'y1', 'y2', 'zoomAndPan']
attr_val_is_uri = ['href', 'src', 'cite', 'action', 'longdesc',
'xlink:href', 'xml:base']
svg_attr_val_allows_ref = ['clip-path', 'color-profile', 'cursor', 'fill',
'filter', 'marker', 'marker-start', 'marker-mid', 'marker-end',
'mask', 'stroke']
svg_allow_local_href = ['altGlyph', 'animate', 'animateColor',
'animateMotion', 'animateTransform', 'cursor', 'feImage', 'filter',
'linearGradient', 'pattern', 'radialGradient', 'textpath', 'tref',
'set', 'use']
acceptable_css_properties = ['azimuth', 'background-color',
'border-bottom-color', 'border-collapse', 'border-color',
'border-left-color', 'border-right-color', 'border-top-color', 'clear',
'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font',
'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight',
'height', 'letter-spacing', 'line-height', 'overflow', 'pause',
'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness',
'speak', 'speak-header', 'speak-numeral', 'speak-punctuation',
'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent',
'unicode-bidi', 'vertical-align', 'voice-family', 'volume',
'white-space', 'width']
acceptable_css_keywords = ['auto', 'aqua', 'black', 'block', 'blue',
'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed',
'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left',
'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive',
'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top',
'transparent', 'underline', 'white', 'yellow']
acceptable_svg_properties = [ 'fill', 'fill-opacity', 'fill-rule',
'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
'stroke-opacity']
acceptable_protocols = [ 'ed2k', 'ftp', 'http', 'https', 'irc',
'mailto', 'news', 'gopher', 'nntp', 'telnet', 'webcal',
'xmpp', 'callto', 'feed', 'urn', 'aim', 'rsync', 'tag',
'ssh', 'sftp', 'rtsp', 'afs' ]
# subclasses may define their own versions of these constants
allowed_elements = acceptable_elements + mathml_elements + svg_elements
allowed_attributes = acceptable_attributes + mathml_attributes + svg_attributes
allowed_css_properties = acceptable_css_properties
allowed_css_keywords = acceptable_css_keywords
allowed_svg_properties = acceptable_svg_properties
allowed_protocols = acceptable_protocols
# Sanitize the +html+, escaping all elements not in ALLOWED_ELEMENTS, and
# stripping out all # attributes not in ALLOWED_ATTRIBUTES. Style
# attributes are parsed, and a restricted set, # specified by
# ALLOWED_CSS_PROPERTIES and ALLOWED_CSS_KEYWORDS, are allowed through.
# attributes in ATTR_VAL_IS_URI are scanned, and only URI schemes specified
# in ALLOWED_PROTOCOLS are allowed.
#
# sanitize_html('<script> do_nasty_stuff() </script>')
# => <script> do_nasty_stuff() </script>
# sanitize_html('<a href="javascript: sucker();">Click here for $100</a>')
# => <a>Click here for $100</a>
def sanitize_token(self, token):
# accommodate filters which use token_type differently
token_type = token["type"]
if token_type in tokenTypes.keys():
token_type = tokenTypes[token_type]
if token_type in (tokenTypes["StartTag"], tokenTypes["EndTag"],
tokenTypes["EmptyTag"]):
if token["name"] in self.allowed_elements:
if token.has_key("data"):
attrs = dict([(name,val) for name,val in
token["data"][::-1]
if name in self.allowed_attributes])
for attr in self.attr_val_is_uri:
if not attrs.has_key(attr):
continue
val_unescaped = re.sub("[`\000-\040\177-\240\s]+", '',
unescape(attrs[attr])).lower()
#remove replacement characters from unescaped characters
val_unescaped = val_unescaped.replace(u"\ufffd", "")
if (re.match("^[a-z0-9][-+.a-z0-9]*:",val_unescaped) and
(val_unescaped.split(':')[0] not in
self.allowed_protocols)):
del attrs[attr]
for attr in self.svg_attr_val_allows_ref:
if attr in attrs:
attrs[attr] = re.sub(r'url\s*\(\s*[^#\s][^)]+?\)',
' ',
unescape(attrs[attr]))
if (token["name"] in self.svg_allow_local_href and
'xlink:href' in attrs and re.search('^\s*[^#\s].*',
attrs['xlink:href'])):
del attrs['xlink:href']
if attrs.has_key('style'):
attrs['style'] = self.sanitize_css(attrs['style'])
token["data"] = [[name,val] for name,val in attrs.items()]
return token
else:
if token_type == tokenTypes["EndTag"]:
token["data"] = "</%s>" % token["name"]
elif token["data"]:
attrs = ''.join([' %s="%s"' % (k,escape(v)) for k,v in token["data"]])
token["data"] = "<%s%s>" % (token["name"],attrs)
else:
token["data"] = "<%s>" % token["name"]
if token.get("selfClosing"):
token["data"]=token["data"][:-1] + "/>"
if token["type"] in tokenTypes.keys():
token["type"] = "Characters"
else:
token["type"] = tokenTypes["Characters"]
del token["name"]
return token
elif token_type == tokenTypes["Comment"]:
pass
else:
return token
def sanitize_css(self, style):
# disallow urls
style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style)
# gauntlet
if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): return ''
if not re.match("^\s*([-\w]+\s*:[^:;]*(;\s*|$))*$", style): return ''
clean = []
for prop,value in re.findall("([-\w]+)\s*:\s*([^:;]*)",style):
if not value: continue
if prop.lower() in self.allowed_css_properties:
clean.append(prop + ': ' + value + ';')
elif prop.split('-')[0].lower() in ['background','border','margin',
'padding']:
for keyword in value.split():
if not keyword in self.acceptable_css_keywords and \
not re.match("^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$",keyword):
break
else:
clean.append(prop + ': ' + value + ';')
elif prop.lower() in self.allowed_svg_properties:
clean.append(prop + ': ' + value + ';')
return ' '.join(clean)
class HTMLSanitizer(HTMLTokenizer, HTMLSanitizerMixin):
def __init__(self, stream, encoding=None, parseMeta=True, useChardet=True,
lowercaseElementName=False, lowercaseAttrName=False, parser=None):
#Change case matching defaults as we only output lowercase html anyway
#This solution doesn't seem ideal...
HTMLTokenizer.__init__(self, stream, encoding, parseMeta, useChardet,
lowercaseElementName, lowercaseAttrName, parser=parser)
def __iter__(self):
for token in HTMLTokenizer.__iter__(self):
token = self.sanitize_token(token)
if token:
yield token
| apache-2.0 |
ChristinaZografou/sympy | sympy/polys/tests/test_groebnertools.py | 85 | 18116 | """Tests for Groebner bases. """
from sympy.polys.groebnertools import (
groebner, sig, sig_key,
lbp, lbp_key, critical_pair,
cp_key, is_rewritable_or_comparable,
Sign, Polyn, Num, s_poly, f5_reduce,
groebner_lcm, groebner_gcd,
)
from sympy.polys.fglmtools import _representing_matrices
from sympy.polys.orderings import lex, grlex
from sympy.polys.rings import ring, xring
from sympy.polys.domains import ZZ, QQ
from sympy.utilities.pytest import slow
from sympy.polys import polyconfig as config
from sympy.core.compatibility import range
def _do_test_groebner():
R, x,y = ring("x,y", QQ, lex)
f = x**2 + 2*x*y**2
g = x*y + 2*y**3 - 1
assert groebner([f, g], R) == [x, y**3 - QQ(1,2)]
R, y,x = ring("y,x", QQ, lex)
f = 2*x**2*y + y**2
g = 2*x**3 + x*y - 1
assert groebner([f, g], R) == [y, x**3 - QQ(1,2)]
R, x,y,z = ring("x,y,z", QQ, lex)
f = x - z**2
g = y - z**3
assert groebner([f, g], R) == [f, g]
R, x,y = ring("x,y", QQ, grlex)
f = x**3 - 2*x*y
g = x**2*y + x - 2*y**2
assert groebner([f, g], R) == [x**2, x*y, -QQ(1,2)*x + y**2]
R, x,y,z = ring("x,y,z", QQ, lex)
f = -x**2 + y
g = -x**3 + z
assert groebner([f, g], R) == [x**2 - y, x*y - z, x*z - y**2, y**3 - z**2]
R, x,y,z = ring("x,y,z", QQ, grlex)
f = -x**2 + y
g = -x**3 + z
assert groebner([f, g], R) == [y**3 - z**2, x**2 - y, x*y - z, x*z - y**2]
R, x,y,z = ring("x,y,z", QQ, lex)
f = -x**2 + z
g = -x**3 + y
assert groebner([f, g], R) == [x**2 - z, x*y - z**2, x*z - y, y**2 - z**3]
R, x,y,z = ring("x,y,z", QQ, grlex)
f = -x**2 + z
g = -x**3 + y
assert groebner([f, g], R) == [-y**2 + z**3, x**2 - z, x*y - z**2, x*z - y]
R, x,y,z = ring("x,y,z", QQ, lex)
f = x - y**2
g = -y**3 + z
assert groebner([f, g], R) == [x - y**2, y**3 - z]
R, x,y,z = ring("x,y,z", QQ, grlex)
f = x - y**2
g = -y**3 + z
assert groebner([f, g], R) == [x**2 - y*z, x*y - z, -x + y**2]
R, x,y,z = ring("x,y,z", QQ, lex)
f = x - z**2
g = y - z**3
assert groebner([f, g], R) == [x - z**2, y - z**3]
R, x,y,z = ring("x,y,z", QQ, grlex)
f = x - z**2
g = y - z**3
assert groebner([f, g], R) == [x**2 - y*z, x*z - y, -x + z**2]
R, x,y,z = ring("x,y,z", QQ, lex)
f = -y**2 + z
g = x - y**3
assert groebner([f, g], R) == [x - y*z, y**2 - z]
R, x,y,z = ring("x,y,z", QQ, grlex)
f = -y**2 + z
g = x - y**3
assert groebner([f, g], R) == [-x**2 + z**3, x*y - z**2, y**2 - z, -x + y*z]
R, x,y,z = ring("x,y,z", QQ, lex)
f = y - z**2
g = x - z**3
assert groebner([f, g], R) == [x - z**3, y - z**2]
R, x,y,z = ring("x,y,z", QQ, grlex)
f = y - z**2
g = x - z**3
assert groebner([f, g], R) == [-x**2 + y**3, x*z - y**2, -x + y*z, -y + z**2]
R, x,y,z = ring("x,y,z", QQ, lex)
f = 4*x**2*y**2 + 4*x*y + 1
g = x**2 + y**2 - 1
assert groebner([f, g], R) == [
x - 4*y**7 + 8*y**5 - 7*y**3 + 3*y,
y**8 - 2*y**6 + QQ(3,2)*y**4 - QQ(1,2)*y**2 + QQ(1,16),
]
def test_groebner_buchberger():
with config.using(groebner='buchberger'):
_do_test_groebner()
def test_groebner_f5b():
with config.using(groebner='f5b'):
_do_test_groebner()
def _do_test_benchmark_minpoly():
R, x,y,z = ring("x,y,z", QQ, lex)
F = [x**3 + x + 1, y**2 + y + 1, (x + y) * z - (x**2 + y)]
G = [x + QQ(155,2067)*z**5 - QQ(355,689)*z**4 + QQ(6062,2067)*z**3 - QQ(3687,689)*z**2 + QQ(6878,2067)*z - QQ(25,53),
y + QQ(4,53)*z**5 - QQ(91,159)*z**4 + QQ(523,159)*z**3 - QQ(387,53)*z**2 + QQ(1043,159)*z - QQ(308,159),
z**6 - 7*z**5 + 41*z**4 - 82*z**3 + 89*z**2 - 46*z + 13]
assert groebner(F, R) == G
def test_benchmark_minpoly_buchberger():
with config.using(groebner='buchberger'):
_do_test_benchmark_minpoly()
def test_benchmark_minpoly_f5b():
with config.using(groebner='f5b'):
_do_test_benchmark_minpoly()
def test_benchmark_coloring():
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), (3, 4)]
R, V = xring([ "x%d" % v for v in V ], QQ, lex)
E = [(V[i - 1], V[j - 1]) for i, j in E]
x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12 = V
I3 = [x**3 - 1 for x in V]
Ig = [x**2 + x*y + y**2 for x, y in E]
I = I3 + Ig
assert groebner(I[:-1], R) == [
x1 + x11 + x12,
x2 - x11,
x3 - x12,
x4 - x12,
x5 + x11 + x12,
x6 - x11,
x7 - x12,
x8 + x11 + x12,
x9 - x11,
x10 + x11 + x12,
x11**2 + x11*x12 + x12**2,
x12**3 - 1,
]
assert groebner(I, R) == [1]
def _do_test_benchmark_katsura_3():
R, x0,x1,x2 = ring("x:3", ZZ, lex)
I = [x0 + 2*x1 + 2*x2 - 1,
x0**2 + 2*x1**2 + 2*x2**2 - x0,
2*x0*x1 + 2*x1*x2 - x1]
assert groebner(I, R) == [
-7 + 7*x0 + 8*x2 + 158*x2**2 - 420*x2**3,
7*x1 + 3*x2 - 79*x2**2 + 210*x2**3,
x2 + x2**2 - 40*x2**3 + 84*x2**4,
]
R, x0,x1,x2 = ring("x:3", ZZ, grlex)
I = [ i.set_ring(R) for i in I ]
assert groebner(I, R) == [
7*x1 + 3*x2 - 79*x2**2 + 210*x2**3,
-x1 + x2 - 3*x2**2 + 5*x1**2,
-x1 - 4*x2 + 10*x1*x2 + 12*x2**2,
-1 + x0 + 2*x1 + 2*x2,
]
def test_benchmark_katsura3_buchberger():
with config.using(groebner='buchberger'):
_do_test_benchmark_katsura_3()
def test_benchmark_katsura3_f5b():
with config.using(groebner='f5b'):
_do_test_benchmark_katsura_3()
def _do_test_benchmark_katsura_4():
R, x0,x1,x2,x3 = ring("x:4", ZZ, lex)
I = [x0 + 2*x1 + 2*x2 + 2*x3 - 1,
x0**2 + 2*x1**2 + 2*x2**2 + 2*x3**2 - x0,
2*x0*x1 + 2*x1*x2 + 2*x2*x3 - x1,
x1**2 + 2*x0*x2 + 2*x1*x3 - x2]
assert groebner(I, R) == [
5913075*x0 - 159690237696*x3**7 + 31246269696*x3**6 + 27439610544*x3**5 - 6475723368*x3**4 - 838935856*x3**3 + 275119624*x3**2 + 4884038*x3 - 5913075,
1971025*x1 - 97197721632*x3**7 + 73975630752*x3**6 - 12121915032*x3**5 - 2760941496*x3**4 + 814792828*x3**3 - 1678512*x3**2 - 9158924*x3,
5913075*x2 + 371438283744*x3**7 - 237550027104*x3**6 + 22645939824*x3**5 + 11520686172*x3**4 - 2024910556*x3**3 - 132524276*x3**2 + 30947828*x3,
128304*x3**8 - 93312*x3**7 + 15552*x3**6 + 3144*x3**5 -
1120*x3**4 + 36*x3**3 + 15*x3**2 - x3,
]
R, x0,x1,x2,x3 = ring("x:4", ZZ, grlex)
I = [ i.set_ring(R) for i in I ]
assert groebner(I, R) == [
393*x1 - 4662*x2**2 + 4462*x2*x3 - 59*x2 + 224532*x3**4 - 91224*x3**3 - 678*x3**2 + 2046*x3,
-x1 + 196*x2**3 - 21*x2**2 + 60*x2*x3 - 18*x2 - 168*x3**3 + 83*x3**2 - 9*x3,
-6*x1 + 1134*x2**2*x3 - 189*x2**2 - 466*x2*x3 + 32*x2 - 630*x3**3 + 57*x3**2 + 51*x3,
33*x1 + 63*x2**2 + 2268*x2*x3**2 - 188*x2*x3 + 34*x2 + 2520*x3**3 - 849*x3**2 + 3*x3,
7*x1**2 - x1 - 7*x2**2 - 24*x2*x3 + 3*x2 - 15*x3**2 + 5*x3,
14*x1*x2 - x1 + 14*x2**2 + 18*x2*x3 - 4*x2 + 6*x3**2 - 2*x3,
14*x1*x3 - x1 + 7*x2**2 + 32*x2*x3 - 4*x2 + 27*x3**2 - 9*x3,
x0 + 2*x1 + 2*x2 + 2*x3 - 1,
]
def test_benchmark_kastura_4_buchberger():
with config.using(groebner='buchberger'):
_do_test_benchmark_katsura_4()
def test_benchmark_kastura_4_f5b():
with config.using(groebner='f5b'):
_do_test_benchmark_katsura_4()
def _do_test_benchmark_czichowski():
R, x,t = ring("x,t", ZZ, lex)
I = [9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9,
(-72 - 72*t)*x**7 + (-256 - 252*t)*x**6 + (192 + 192*t)*x**5 + (1280 + 1260*t)*x**4 + (312 + 312*t)*x**3 + (-404*t)*x**2 + (-576 - 576*t)*x + 96 + 108*t]
assert groebner(I, R) == [
3725588592068034903797967297424801242396746870413359539263038139343329273586196480000*x -
160420835591776763325581422211936558925462474417709511019228211783493866564923546661604487873*t**7 -
1406108495478033395547109582678806497509499966197028487131115097902188374051595011248311352864*t**6 -
5241326875850889518164640374668786338033653548841427557880599579174438246266263602956254030352*t**5 -
10758917262823299139373269714910672770004760114329943852726887632013485035262879510837043892416*t**4 -
13119383576444715672578819534846747735372132018341964647712009275306635391456880068261130581248*t**3 -
9491412317016197146080450036267011389660653495578680036574753839055748080962214787557853941760*t**2 -
3767520915562795326943800040277726397326609797172964377014046018280260848046603967211258368000*t -
632314652371226552085897259159210286886724229880266931574701654721512325555116066073245696000,
610733380717522355121*t**8 +
6243748742141230639968*t**7 +
27761407182086143225024*t**6 +
70066148869420956398592*t**5 +
109701225644313784229376*t**4 +
109009005495588442152960*t**3 +
67072101084384786432000*t**2 +
23339979742629593088000*t +
3513592776846090240000,
]
R, x,t = ring("x,t", ZZ, grlex)
I = [ i.set_ring(R) for i in I ]
assert groebner(I, R) == [
16996618586000601590732959134095643086442*t**3*x -
32936701459297092865176560282688198064839*t**3 +
78592411049800639484139414821529525782364*t**2*x -
120753953358671750165454009478961405619916*t**2 +
120988399875140799712152158915653654637280*t*x -
144576390266626470824138354942076045758736*t +
60017634054270480831259316163620768960*x**2 +
61976058033571109604821862786675242894400*x -
56266268491293858791834120380427754600960,
576689018321912327136790519059646508441672750656050290242749*t**4 +
2326673103677477425562248201573604572527893938459296513327336*t**3 +
110743790416688497407826310048520299245819959064297990236000*t**2*x +
3308669114229100853338245486174247752683277925010505284338016*t**2 +
323150205645687941261103426627818874426097912639158572428800*t*x +
1914335199925152083917206349978534224695445819017286960055680*t +
861662882561803377986838989464278045397192862768588480000*x**2 +
235296483281783440197069672204341465480107019878814196672000*x +
361850798943225141738895123621685122544503614946436727532800,
-117584925286448670474763406733005510014188341867*t**3 +
68566565876066068463853874568722190223721653044*t**2*x -
435970731348366266878180788833437896139920683940*t**2 +
196297602447033751918195568051376792491869233408*t*x -
525011527660010557871349062870980202067479780112*t +
517905853447200553360289634770487684447317120*x**3 +
569119014870778921949288951688799397569321920*x**2 +
138877356748142786670127389526667463202210102080*x -
205109210539096046121625447192779783475018619520,
-3725142681462373002731339445216700112264527*t**3 +
583711207282060457652784180668273817487940*t**2*x -
12381382393074485225164741437227437062814908*t**2 +
151081054097783125250959636747516827435040*t*x**2 +
1814103857455163948531448580501928933873280*t*x -
13353115629395094645843682074271212731433648*t +
236415091385250007660606958022544983766080*x**2 +
1390443278862804663728298060085399578417600*x -
4716885828494075789338754454248931750698880,
]
# NOTE: This is very slow (> 2 minutes on 3.4 GHz) without GMPY
@slow
def test_benchmark_czichowski_buchberger():
with config.using(groebner='buchberger'):
_do_test_benchmark_czichowski()
def test_benchmark_czichowski_f5b():
with config.using(groebner='f5b'):
_do_test_benchmark_czichowski()
def _do_test_benchmark_cyclic_4():
R, a,b,c,d = ring("a,b,c,d", ZZ, lex)
I = [a + b + c + d,
a*b + a*d + b*c + b*d,
a*b*c + a*b*d + a*c*d + b*c*d,
a*b*c*d - 1]
assert groebner(I, R) == [
4*a + 3*d**9 - 4*d**5 - 3*d,
4*b + 4*c - 3*d**9 + 4*d**5 + 7*d,
4*c**2 + 3*d**10 - 4*d**6 - 3*d**2,
4*c*d**4 + 4*c - d**9 + 4*d**5 + 5*d, d**12 - d**8 - d**4 + 1
]
R, a,b,c,d = ring("a,b,c,d", ZZ, grlex)
I = [ i.set_ring(R) for i in I ]
assert groebner(I, R) == [
3*b*c - c**2 + d**6 - 3*d**2,
-b + 3*c**2*d**3 - c - d**5 - 4*d,
-b + 3*c*d**4 + 2*c + 2*d**5 + 2*d,
c**4 + 2*c**2*d**2 - d**4 - 2,
c**3*d + c*d**3 + d**4 + 1,
b*c**2 - c**3 - c**2*d - 2*c*d**2 - d**3,
b**2 - c**2, b*d + c**2 + c*d + d**2,
a + b + c + d
]
def test_benchmark_cyclic_4_buchberger():
with config.using(groebner='buchberger'):
_do_test_benchmark_cyclic_4()
def test_benchmark_cyclic_4_f5b():
with config.using(groebner='f5b'):
_do_test_benchmark_cyclic_4()
def test_sig_key():
s1 = sig((0,) * 3, 2)
s2 = sig((1,) * 3, 4)
s3 = sig((2,) * 3, 2)
assert sig_key(s1, lex) > sig_key(s2, lex)
assert sig_key(s2, lex) < sig_key(s3, lex)
def test_lbp_key():
R, x,y,z,t = ring("x,y,z,t", ZZ, lex)
p1 = lbp(sig((0,) * 4, 3), R.zero, 12)
p2 = lbp(sig((0,) * 4, 4), R.zero, 13)
p3 = lbp(sig((0,) * 4, 4), R.zero, 12)
assert lbp_key(p1) > lbp_key(p2)
assert lbp_key(p2) < lbp_key(p3)
def test_critical_pair():
# from cyclic4 with grlex
R, x,y,z,t = ring("x,y,z,t", QQ, grlex)
p1 = (((0, 0, 0, 0), 4), y*z*t**2 + z**2*t**2 - t**4 - 1, 4)
q1 = (((0, 0, 0, 0), 2), -y**2 - y*t - z*t - t**2, 2)
p2 = (((0, 0, 0, 2), 3), z**3*t**2 + z**2*t**3 - z - t, 5)
q2 = (((0, 0, 2, 2), 2), y*z + z*t**5 + z*t + t**6, 13)
assert critical_pair(p1, q1, R) == (
((0, 0, 1, 2), 2), ((0, 0, 1, 2), QQ(-1, 1)), (((0, 0, 0, 0), 2), -y**2 - y*t - z*t - t**2, 2),
((0, 1, 0, 0), 4), ((0, 1, 0, 0), QQ(1, 1)), (((0, 0, 0, 0), 4), y*z*t**2 + z**2*t**2 - t**4 - 1, 4)
)
assert critical_pair(p2, q2, R) == (
((0, 0, 4, 2), 2), ((0, 0, 2, 0), QQ(1, 1)), (((0, 0, 2, 2), 2), y*z + z*t**5 + z*t + t**6, 13),
((0, 0, 0, 5), 3), ((0, 0, 0, 3), QQ(1, 1)), (((0, 0, 0, 2), 3), z**3*t**2 + z**2*t**3 - z - t, 5)
)
def test_cp_key():
# from cyclic4 with grlex
R, x,y,z,t = ring("x,y,z,t", QQ, grlex)
p1 = (((0, 0, 0, 0), 4), y*z*t**2 + z**2*t**2 - t**4 - 1, 4)
q1 = (((0, 0, 0, 0), 2), -y**2 - y*t - z*t - t**2, 2)
p2 = (((0, 0, 0, 2), 3), z**3*t**2 + z**2*t**3 - z - t, 5)
q2 = (((0, 0, 2, 2), 2), y*z + z*t**5 + z*t + t**6, 13)
cp1 = critical_pair(p1, q1, R)
cp2 = critical_pair(p2, q2, R)
assert cp_key(cp1, R) < cp_key(cp2, R)
cp1 = critical_pair(p1, p2, R)
cp2 = critical_pair(q1, q2, R)
assert cp_key(cp1, R) < cp_key(cp2, R)
def test_is_rewritable_or_comparable():
# from katsura4 with grlex
R, x,y,z,t = ring("x,y,z,t", QQ, grlex)
p = lbp(sig((0, 0, 2, 1), 2), R.zero, 2)
B = [lbp(sig((0, 0, 0, 1), 2), QQ(2,45)*y**2 + QQ(1,5)*y*z + QQ(5,63)*y*t + z**2*t + QQ(4,45)*z**2 + QQ(76,35)*z*t**2 - QQ(32,105)*z*t + QQ(13,7)*t**3 - QQ(13,21)*t**2, 6)]
# rewritable:
assert is_rewritable_or_comparable(Sign(p), Num(p), B) is True
p = lbp(sig((0, 1, 1, 0), 2), R.zero, 7)
B = [lbp(sig((0, 0, 0, 0), 3), QQ(10,3)*y*z + QQ(4,3)*y*t - QQ(1,3)*y + 4*z**2 + QQ(22,3)*z*t - QQ(4,3)*z + 4*t**2 - QQ(4,3)*t, 3)]
# comparable:
assert is_rewritable_or_comparable(Sign(p), Num(p), B) is True
def test_f5_reduce():
# katsura3 with lex
R, x,y,z = ring("x,y,z", QQ, lex)
F = [(((0, 0, 0), 1), x + 2*y + 2*z - 1, 1),
(((0, 0, 0), 2), 6*y**2 + 8*y*z - 2*y + 6*z**2 - 2*z, 2),
(((0, 0, 0), 3), QQ(10,3)*y*z - QQ(1,3)*y + 4*z**2 - QQ(4,3)*z, 3),
(((0, 0, 1), 2), y + 30*z**3 - QQ(79,7)*z**2 + QQ(3,7)*z, 4),
(((0, 0, 2), 2), z**4 - QQ(10,21)*z**3 + QQ(1,84)*z**2 + QQ(1,84)*z, 5)]
cp = critical_pair(F[0], F[1], R)
s = s_poly(cp)
assert f5_reduce(s, F) == (((0, 2, 0), 1), R.zero, 1)
s = lbp(sig(Sign(s)[0], 100), Polyn(s), Num(s))
assert f5_reduce(s, F) == s
def test_representing_matrices():
R, x,y = ring("x,y", QQ, grlex)
basis = [(0, 0), (0, 1), (1, 0), (1, 1)]
F = [x**2 - x - 3*y + 1, -2*x + y**2 + y - 1]
assert _representing_matrices(basis, F, R) == [
[[QQ(0, 1), QQ(0, 1),-QQ(1, 1), QQ(3, 1)],
[QQ(0, 1), QQ(0, 1), QQ(3, 1),-QQ(4, 1)],
[QQ(1, 1), QQ(0, 1), QQ(1, 1), QQ(6, 1)],
[QQ(0, 1), QQ(1, 1), QQ(0, 1), QQ(1, 1)]],
[[QQ(0, 1), QQ(1, 1), QQ(0, 1),-QQ(2, 1)],
[QQ(1, 1),-QQ(1, 1), QQ(0, 1), QQ(6, 1)],
[QQ(0, 1), QQ(2, 1), QQ(0, 1), QQ(3, 1)],
[QQ(0, 1), QQ(0, 1), QQ(1, 1),-QQ(1, 1)]]]
def test_groebner_lcm():
R, x,y,z = ring("x,y,z", ZZ)
assert groebner_lcm(x**2 - y**2, x - y) == x**2 - y**2
assert groebner_lcm(2*x**2 - 2*y**2, 2*x - 2*y) == 2*x**2 - 2*y**2
R, x,y,z = ring("x,y,z", QQ)
assert groebner_lcm(x**2 - y**2, x - y) == x**2 - y**2
assert groebner_lcm(2*x**2 - 2*y**2, 2*x - 2*y) == 2*x**2 - 2*y**2
R, x,y = ring("x,y", ZZ)
assert groebner_lcm(x**2*y, x*y**2) == x**2*y**2
f = 2*x*y**5 - 3*x*y**4 - 2*x*y**3 + 3*x*y**2
g = y**5 - 2*y**3 + y
h = 2*x*y**7 - 3*x*y**6 - 4*x*y**5 + 6*x*y**4 + 2*x*y**3 - 3*x*y**2
assert groebner_lcm(f, g) == h
f = x**3 - 3*x**2*y - 9*x*y**2 - 5*y**3
g = x**4 + 6*x**3*y + 12*x**2*y**2 + 10*x*y**3 + 3*y**4
h = x**5 + x**4*y - 18*x**3*y**2 - 50*x**2*y**3 - 47*x*y**4 - 15*y**5
assert groebner_lcm(f, g) == h
def test_groebner_gcd():
R, x,y,z = ring("x,y,z", ZZ)
assert groebner_gcd(x**2 - y**2, x - y) == x - y
assert groebner_gcd(2*x**2 - 2*y**2, 2*x - 2*y) == 2*x - 2*y
R, x,y,z = ring("x,y,z", QQ)
assert groebner_gcd(x**2 - y**2, x - y) == x - y
assert groebner_gcd(2*x**2 - 2*y**2, 2*x - 2*y) == x - y
| bsd-3-clause |
sanguinariojoe/FreeCAD | src/Mod/Fem/feminout/importZ88O2Results.py | 12 | 6123 | # ***************************************************************************
# * Copyright (c) 2016 Bernd Hahnebach <bernd@bimstatik.org> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * 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 Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
__title__ = "Result import for Z88 displacements format"
__author__ = "Bernd Hahnebach"
__url__ = "https://www.freecadweb.org"
## @package importZ88O2Results
# \ingroup FEM
# \brief FreeCAD Z88 Disp Reader for FEM workbench
import os
import FreeCAD
from FreeCAD import Console
# ********* generic FreeCAD import and export methods *********
if open.__module__ == "__builtin__":
# because we'll redefine open below (Python2)
pyopen = open
elif open.__module__ == "io":
# because we'll redefine open below (Python3)
pyopen = open
def open(
filename
):
"called when freecad opens a file"
docname = os.path.splitext(os.path.basename(filename))[0]
insert(filename, docname)
def insert(
filename,
docname
):
"called when freecad wants to import a file"
try:
doc = FreeCAD.getDocument(docname)
except NameError:
doc = FreeCAD.newDocument(docname)
FreeCAD.ActiveDocument = doc
import_z88_disp(filename)
# ********* module specific methods *********
def import_z88_disp(
filename,
analysis=None,
result_name_prefix=None
):
"""insert a FreeCAD FEM mechanical result object in the ActiveDocument
pure usage:
import feminout.importZ88O2Results as importZ88O2Results
disp_file = "/pathtofile/z88o2.txt"
importZ88O2Results.import_z88_disp(disp_file)
the z888i1.txt FEMMesh file needs to be in the same directory as z88o2.txt
# ahh, make a new document first ;-)
"""
import ObjectsFem
from . import importZ88Mesh
from . import importToolsFem
from femresult import resulttools
if result_name_prefix is None:
result_name_prefix = ""
disp_read = read_z88_disp(filename)
result_mesh_object = None
if len(disp_read["Nodes"]) > 0:
if analysis:
analysis_object = analysis
# read result mesh
if filename.endswith("z88o2.txt"):
mesh_file = filename.replace("o2", "i1")
mesh_data = importZ88Mesh.read_z88_mesh(mesh_file)
femmesh = importToolsFem.make_femmesh(mesh_data)
result_mesh_object = ObjectsFem.makeMeshResult(
FreeCAD.ActiveDocument,
"Result_mesh"
)
result_mesh_object.FemMesh = femmesh
else:
Console.PrintError("Z88 mesh file z88i1.txt not found.\n")
# create result obj
for result_set in disp_read["Results"]:
results_name = result_name_prefix + "results"
res_obj = ObjectsFem.makeResultMechanical(FreeCAD.ActiveDocument, results_name)
res_obj.Mesh = result_mesh_object
res_obj = importToolsFem.fill_femresult_mechanical(res_obj, result_set)
res_obj = resulttools.add_disp_apps(res_obj) # fill DisplacementLengths
res_obj = resulttools.fill_femresult_stats(res_obj) # fill Stats
if analysis:
analysis_object.addObject(res_obj)
if FreeCAD.GuiUp:
if analysis:
import FemGui
FemGui.setActiveAnalysis(analysis_object)
FreeCAD.ActiveDocument.recompute()
else:
Console.PrintError(
"Problem on Z88 result file import. No nodes found in Z88 result file.\n"
)
return res_obj
def read_z88_disp(
z88_disp_input
):
"""
read a z88 disp file and extract the nodes and elements
z88 Displacement output file is z88o2.txt
works with Z88OS14
"""
nodes = {}
mode_disp = {}
mode_results = {}
results = []
z88_disp_file = pyopen(z88_disp_input, "r")
for no, line in enumerate(z88_disp_file):
lno = no + 1
linelist = line.split()
if lno >= 6:
# disp line
node_no = int(linelist[0])
mode_disp_x = float(linelist[1])
mode_disp_y = float(linelist[2])
if len(linelist) > 3:
mode_disp_z = float(linelist[3])
else:
mode_disp_z = 0.0
mode_disp[node_no] = FreeCAD.Vector(mode_disp_x, mode_disp_y, mode_disp_z)
nodes[node_no] = node_no
mode_results["disp"] = mode_disp
results.append(mode_results)
for r in results[0]["disp"]:
Console.PrintLog("{} --> {}\n".format(r, results[0]["disp"][r]))
z88_disp_file.close()
return {"Nodes": nodes, "Results": results}
| lgpl-2.1 |
valkjsaaa/sl4a | python/src/Tools/pybench/systimes.py | 37 | 6621 | #!/usr/bin/env python
""" systimes() user and system timer implementations for use by
pybench.
This module implements various different strategies for measuring
performance timings. It tries to choose the best available method
based on the platforma and available tools.
On Windows, it is recommended to have the Mark Hammond win32
package installed. Alternatively, the Thomas Heller ctypes
packages can also be used.
On Unix systems, the standard resource module provides the highest
resolution timings. Unfortunately, it is not available on all Unix
platforms.
If no supported timing methods based on process time can be found,
the module reverts to the highest resolution wall-clock timer
instead. The system time part will then always be 0.0.
The module exports one public API:
def systimes():
Return the current timer values for measuring user and system
time as tuple of seconds (user_time, system_time).
Copyright (c) 2006, Marc-Andre Lemburg (mal@egenix.com). See the
documentation for further information on copyrights, or contact
the author. All Rights Reserved.
"""
import time, sys
#
# Note: Please keep this module compatible to Python 1.5.2.
#
# TODOs:
#
# * Add ctypes wrapper for new clock_gettime() real-time POSIX APIs;
# these will then provide nano-second resolution where available.
#
# * Add a function that returns the resolution of systimes()
# values, ie. systimesres().
#
### Choose an implementation
SYSTIMES_IMPLEMENTATION = None
USE_CTYPES_GETPROCESSTIMES = 'ctypes GetProcessTimes() wrapper'
USE_WIN32PROCESS_GETPROCESSTIMES = 'win32process.GetProcessTimes()'
USE_RESOURCE_GETRUSAGE = 'resource.getrusage()'
USE_PROCESS_TIME_CLOCK = 'time.clock() (process time)'
USE_WALL_TIME_CLOCK = 'time.clock() (wall-clock)'
USE_WALL_TIME_TIME = 'time.time() (wall-clock)'
if sys.platform[:3] == 'win':
# Windows platform
try:
import win32process
except ImportError:
try:
import ctypes
except ImportError:
# Use the wall-clock implementation time.clock(), since this
# is the highest resolution clock available on Windows
SYSTIMES_IMPLEMENTATION = USE_WALL_TIME_CLOCK
else:
SYSTIMES_IMPLEMENTATION = USE_CTYPES_GETPROCESSTIMES
else:
SYSTIMES_IMPLEMENTATION = USE_WIN32PROCESS_GETPROCESSTIMES
else:
# All other platforms
try:
import resource
except ImportError:
pass
else:
SYSTIMES_IMPLEMENTATION = USE_RESOURCE_GETRUSAGE
# Fall-back solution
if SYSTIMES_IMPLEMENTATION is None:
# Check whether we can use time.clock() as approximation
# for systimes()
start = time.clock()
time.sleep(0.1)
stop = time.clock()
if stop - start < 0.001:
# Looks like time.clock() is usable (and measures process
# time)
SYSTIMES_IMPLEMENTATION = USE_PROCESS_TIME_CLOCK
else:
# Use wall-clock implementation time.time() since this provides
# the highest resolution clock on most systems
SYSTIMES_IMPLEMENTATION = USE_WALL_TIME_TIME
### Implementations
def getrusage_systimes():
return resource.getrusage(resource.RUSAGE_SELF)[:2]
def process_time_clock_systimes():
return (time.clock(), 0.0)
def wall_clock_clock_systimes():
return (time.clock(), 0.0)
def wall_clock_time_systimes():
return (time.time(), 0.0)
# Number of clock ticks per second for the values returned
# by GetProcessTimes() on Windows.
#
# Note: Ticks returned by GetProcessTimes() are 100ns intervals on
# Windows XP. However, the process times are only updated with every
# clock tick and the frequency of these is somewhat lower: depending
# on the OS version between 10ms and 15ms. Even worse, the process
# time seems to be allocated to process currently running when the
# clock interrupt arrives, ie. it is possible that the current time
# slice gets accounted to a different process.
WIN32_PROCESS_TIMES_TICKS_PER_SECOND = 1e7
def win32process_getprocesstimes_systimes():
d = win32process.GetProcessTimes(win32process.GetCurrentProcess())
return (d['UserTime'] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND,
d['KernelTime'] / WIN32_PROCESS_TIMES_TICKS_PER_SECOND)
def ctypes_getprocesstimes_systimes():
creationtime = ctypes.c_ulonglong()
exittime = ctypes.c_ulonglong()
kerneltime = ctypes.c_ulonglong()
usertime = ctypes.c_ulonglong()
rc = ctypes.windll.kernel32.GetProcessTimes(
ctypes.windll.kernel32.GetCurrentProcess(),
ctypes.byref(creationtime),
ctypes.byref(exittime),
ctypes.byref(kerneltime),
ctypes.byref(usertime))
if not rc:
raise TypeError('GetProcessTimes() returned an error')
return (usertime.value / WIN32_PROCESS_TIMES_TICKS_PER_SECOND,
kerneltime.value / WIN32_PROCESS_TIMES_TICKS_PER_SECOND)
# Select the default for the systimes() function
if SYSTIMES_IMPLEMENTATION is USE_RESOURCE_GETRUSAGE:
systimes = getrusage_systimes
elif SYSTIMES_IMPLEMENTATION is USE_PROCESS_TIME_CLOCK:
systimes = process_time_clock_systimes
elif SYSTIMES_IMPLEMENTATION is USE_WALL_TIME_CLOCK:
systimes = wall_clock_clock_systimes
elif SYSTIMES_IMPLEMENTATION is USE_WALL_TIME_TIME:
systimes = wall_clock_time_systimes
elif SYSTIMES_IMPLEMENTATION is USE_WIN32PROCESS_GETPROCESSTIMES:
systimes = win32process_getprocesstimes_systimes
elif SYSTIMES_IMPLEMENTATION is USE_CTYPES_GETPROCESSTIMES:
systimes = ctypes_getprocesstimes_systimes
else:
raise TypeError('no suitable systimes() implementation found')
def processtime():
""" Return the total time spent on the process.
This is the sum of user and system time as returned by
systimes().
"""
user, system = systimes()
return user + system
### Testing
def some_workload():
x = 0L
for i in xrange(10000000L):
x = x + 1L
def test_workload():
print 'Testing systimes() under load conditions'
t0 = systimes()
some_workload()
t1 = systimes()
print 'before:', t0
print 'after:', t1
print 'differences:', (t1[0] - t0[0], t1[1] - t0[1])
print
def test_idle():
print 'Testing systimes() under idle conditions'
t0 = systimes()
time.sleep(1)
t1 = systimes()
print 'before:', t0
print 'after:', t1
print 'differences:', (t1[0] - t0[0], t1[1] - t0[1])
print
if __name__ == '__main__':
print 'Using %s as timer' % SYSTIMES_IMPLEMENTATION
print
test_workload()
test_idle()
| apache-2.0 |
Chiru/NVE_Simulation | NS3/src/wifi/bindings/modulegen__gcc_ILP32.py | 12 | 792772 | 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.wifi', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## propagation-environment.h (module 'propagation'): ns3::EnvironmentType [enumeration]
module.add_enum('EnvironmentType', ['UrbanEnvironment', 'SubUrbanEnvironment', 'OpenAreasEnvironment'], import_from_module='ns.propagation')
## qos-utils.h (module 'wifi'): ns3::AcIndex [enumeration]
module.add_enum('AcIndex', ['AC_BE', 'AC_BK', 'AC_VI', 'AC_VO', 'AC_BE_NQOS', 'AC_UNDEF'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacType [enumeration]
module.add_enum('WifiMacType', ['WIFI_MAC_CTL_RTS', 'WIFI_MAC_CTL_CTS', 'WIFI_MAC_CTL_ACK', 'WIFI_MAC_CTL_BACKREQ', 'WIFI_MAC_CTL_BACKRESP', 'WIFI_MAC_MGT_BEACON', 'WIFI_MAC_MGT_ASSOCIATION_REQUEST', 'WIFI_MAC_MGT_ASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_DISASSOCIATION', 'WIFI_MAC_MGT_REASSOCIATION_REQUEST', 'WIFI_MAC_MGT_REASSOCIATION_RESPONSE', 'WIFI_MAC_MGT_PROBE_REQUEST', 'WIFI_MAC_MGT_PROBE_RESPONSE', 'WIFI_MAC_MGT_AUTHENTICATION', 'WIFI_MAC_MGT_DEAUTHENTICATION', 'WIFI_MAC_MGT_ACTION', 'WIFI_MAC_MGT_ACTION_NO_ACK', 'WIFI_MAC_MGT_MULTIHOP_ACTION', 'WIFI_MAC_DATA', 'WIFI_MAC_DATA_CFACK', 'WIFI_MAC_DATA_CFPOLL', 'WIFI_MAC_DATA_CFACK_CFPOLL', 'WIFI_MAC_DATA_NULL', 'WIFI_MAC_DATA_NULL_CFACK', 'WIFI_MAC_DATA_NULL_CFPOLL', 'WIFI_MAC_DATA_NULL_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA', 'WIFI_MAC_QOSDATA_CFACK', 'WIFI_MAC_QOSDATA_CFPOLL', 'WIFI_MAC_QOSDATA_CFACK_CFPOLL', 'WIFI_MAC_QOSDATA_NULL', 'WIFI_MAC_QOSDATA_NULL_CFPOLL', 'WIFI_MAC_QOSDATA_NULL_CFACK_CFPOLL'])
## propagation-environment.h (module 'propagation'): ns3::CitySize [enumeration]
module.add_enum('CitySize', ['SmallCity', 'MediumCity', 'LargeCity'], import_from_module='ns.propagation')
## wifi-preamble.h (module 'wifi'): ns3::WifiPreamble [enumeration]
module.add_enum('WifiPreamble', ['WIFI_PREAMBLE_LONG', 'WIFI_PREAMBLE_SHORT'])
## wifi-mode.h (module 'wifi'): ns3::WifiModulationClass [enumeration]
module.add_enum('WifiModulationClass', ['WIFI_MOD_CLASS_UNKNOWN', 'WIFI_MOD_CLASS_IR', 'WIFI_MOD_CLASS_FHSS', 'WIFI_MOD_CLASS_DSSS', 'WIFI_MOD_CLASS_ERP_PBCC', 'WIFI_MOD_CLASS_DSSS_OFDM', 'WIFI_MOD_CLASS_ERP_OFDM', 'WIFI_MOD_CLASS_OFDM', 'WIFI_MOD_CLASS_HT'])
## wifi-phy-standard.h (module 'wifi'): ns3::WifiPhyStandard [enumeration]
module.add_enum('WifiPhyStandard', ['WIFI_PHY_STANDARD_80211a', 'WIFI_PHY_STANDARD_80211b', 'WIFI_PHY_STANDARD_80211g', 'WIFI_PHY_STANDARD_80211_10MHZ', 'WIFI_PHY_STANDARD_80211_5MHZ', 'WIFI_PHY_STANDARD_holland', 'WIFI_PHY_STANDARD_80211p_CCH', 'WIFI_PHY_STANDARD_80211p_SCH'])
## qos-tag.h (module 'wifi'): ns3::UserPriority [enumeration]
module.add_enum('UserPriority', ['UP_BK', 'UP_BE', 'UP_EE', 'UP_CL', 'UP_VI', 'UP_VO', 'UP_NC'])
## wifi-mode.h (module 'wifi'): ns3::WifiCodeRate [enumeration]
module.add_enum('WifiCodeRate', ['WIFI_CODE_RATE_UNDEFINED', 'WIFI_CODE_RATE_3_4', 'WIFI_CODE_RATE_2_3', 'WIFI_CODE_RATE_1_2'])
## edca-txop-n.h (module 'wifi'): ns3::TypeOfStation [enumeration]
module.add_enum('TypeOfStation', ['STA', 'AP', 'ADHOC_STA', 'MESH'])
## ctrl-headers.h (module 'wifi'): ns3::BlockAckType [enumeration]
module.add_enum('BlockAckType', ['BASIC_BLOCK_ACK', 'COMPRESSED_BLOCK_ACK', 'MULTI_TID_BLOCK_ACK'])
## 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')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class]
module.add_class('AsciiTraceHelper', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class]
module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True, import_from_module='ns.network')
## athstats-helper.h (module 'wifi'): ns3::AthstatsHelper [class]
module.add_class('AthstatsHelper')
## 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'])
## block-ack-manager.h (module 'wifi'): ns3::Bar [struct]
module.add_class('Bar')
## block-ack-agreement.h (module 'wifi'): ns3::BlockAckAgreement [class]
module.add_class('BlockAckAgreement')
## block-ack-cache.h (module 'wifi'): ns3::BlockAckCache [class]
module.add_class('BlockAckCache')
## block-ack-manager.h (module 'wifi'): ns3::BlockAckManager [class]
module.add_class('BlockAckManager')
## 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')
## capability-information.h (module 'wifi'): ns3::CapabilityInformation [class]
module.add_class('CapabilityInformation')
## dcf-manager.h (module 'wifi'): ns3::DcfManager [class]
module.add_class('DcfManager')
## dcf-manager.h (module 'wifi'): ns3::DcfState [class]
module.add_class('DcfState', allow_subclassing=True)
## dsss-error-rate-model.h (module 'wifi'): ns3::DsssErrorRateModel [class]
module.add_class('DsssErrorRateModel')
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId', import_from_module='ns.core')
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper [class]
module.add_class('InterferenceHelper')
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer [struct]
module.add_class('SnrPer', outer_class=root_module['ns3::InterferenceHelper'])
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address', import_from_module='ns.network')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class]
module.add_class('Ipv6Prefix', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
module.add_class('Mac48Address', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
## mac-low.h (module 'wifi'): ns3::MacLowBlockAckEventListener [class]
module.add_class('MacLowBlockAckEventListener', allow_subclassing=True)
## mac-low.h (module 'wifi'): ns3::MacLowDcfListener [class]
module.add_class('MacLowDcfListener', allow_subclassing=True)
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionListener [class]
module.add_class('MacLowTransmissionListener', allow_subclassing=True)
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionParameters [class]
module.add_class('MacLowTransmissionParameters')
## mac-rx-middle.h (module 'wifi'): ns3::MacRxMiddle [class]
module.add_class('MacRxMiddle')
## 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')
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement [class]
module.add_class('OriginatorBlockAckAgreement', parent=root_module['ns3::BlockAckAgreement'])
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement::State [enumeration]
module.add_enum('State', ['PENDING', 'ESTABLISHED', 'INACTIVE', 'UNSUCCESSFUL'], outer_class=root_module['ns3::OriginatorBlockAckAgreement'])
## 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'])
## pcap-file.h (module 'network'): ns3::PcapFile [class]
module.add_class('PcapFile', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelper [class]
module.add_class('PcapHelper', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelper [enumeration]
module.add_enum('', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO'], outer_class=root_module['ns3::PcapHelper'], import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class]
module.add_class('PcapHelperForDevice', allow_subclassing=True, import_from_module='ns.network')
## propagation-cache.h (module 'propagation'): ns3::PropagationCache<ns3::JakesProcess> [class]
module.add_class('PropagationCache', import_from_module='ns.propagation', template_parameters=['ns3::JakesProcess'])
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo [struct]
module.add_class('RateInfo')
## 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')
## status-code.h (module 'wifi'): ns3::StatusCode [class]
module.add_class('StatusCode')
## 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')
## 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'])
## 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')
## wifi-helper.h (module 'wifi'): ns3::WifiHelper [class]
module.add_class('WifiHelper')
## wifi-helper.h (module 'wifi'): ns3::WifiMacHelper [class]
module.add_class('WifiMacHelper', allow_subclassing=True)
## wifi-mode.h (module 'wifi'): ns3::WifiMode [class]
module.add_class('WifiMode')
## wifi-mode.h (module 'wifi'): ns3::WifiModeFactory [class]
module.add_class('WifiModeFactory')
## wifi-helper.h (module 'wifi'): ns3::WifiPhyHelper [class]
module.add_class('WifiPhyHelper', allow_subclassing=True)
## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener [class]
module.add_class('WifiPhyListener', allow_subclassing=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation [struct]
module.add_class('WifiRemoteStation')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo [class]
module.add_class('WifiRemoteStationInfo')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState [struct]
module.add_class('WifiRemoteStationState')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState [enumeration]
module.add_enum('', ['BRAND_NEW', 'DISASSOC', 'WAIT_ASSOC_TX_OK', 'GOT_ASSOC_TX_OK'], outer_class=root_module['ns3::WifiRemoteStationState'])
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiChannelHelper [class]
module.add_class('YansWifiChannelHelper')
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiPhyHelper [class]
module.add_class('YansWifiPhyHelper', parent=[root_module['ns3::WifiPhyHelper'], root_module['ns3::PcapHelperForDevice'], root_module['ns3::AsciiTraceHelperForDevice']])
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiPhyHelper::SupportedPcapDataLinkTypes [enumeration]
module.add_enum('SupportedPcapDataLinkTypes', ['DLT_IEEE802_11', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO'], outer_class=root_module['ns3::YansWifiPhyHelper'])
## 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')
## 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'])
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaRequestHeader [class]
module.add_class('MgtAddBaRequestHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaResponseHeader [class]
module.add_class('MgtAddBaResponseHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtAssocRequestHeader [class]
module.add_class('MgtAssocRequestHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtAssocResponseHeader [class]
module.add_class('MgtAssocResponseHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtDelBaHeader [class]
module.add_class('MgtDelBaHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtProbeRequestHeader [class]
module.add_class('MgtProbeRequestHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::MgtProbeResponseHeader [class]
module.add_class('MgtProbeResponseHeader', parent=root_module['ns3::Header'])
## nqos-wifi-mac-helper.h (module 'wifi'): ns3::NqosWifiMacHelper [class]
module.add_class('NqosWifiMacHelper', parent=root_module['ns3::WifiMacHelper'])
## 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'])
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class]
module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=root_module['ns3::Object'])
## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel [class]
module.add_class('PropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::Object'])
## propagation-loss-model.h (module 'propagation'): ns3::PropagationLossModel [class]
module.add_class('PropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::Object'])
## qos-tag.h (module 'wifi'): ns3::QosTag [class]
module.add_class('QosTag', parent=root_module['ns3::Tag'])
## qos-wifi-mac-helper.h (module 'wifi'): ns3::QosWifiMacHelper [class]
module.add_class('QosWifiMacHelper', parent=root_module['ns3::WifiMacHelper'])
## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel [class]
module.add_class('RandomPropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationDelayModel'])
## propagation-loss-model.h (module 'propagation'): ns3::RandomPropagationLossModel [class]
module.add_class('RandomPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class]
module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object'])
## propagation-loss-model.h (module 'propagation'): ns3::RangePropagationLossModel [class]
module.add_class('RangePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class]
module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::InterferenceHelper::Event', 'ns3::empty', 'ns3::DefaultDeleter<ns3::InterferenceHelper::Event>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::WifiInformationElement', 'ns3::empty', 'ns3::DefaultDeleter<ns3::WifiInformationElement>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## snr-tag.h (module 'wifi'): ns3::SnrTag [class]
module.add_class('SnrTag', parent=root_module['ns3::Tag'])
## propagation-loss-model.h (module 'propagation'): ns3::ThreeLogDistancePropagationLossModel [class]
module.add_class('ThreeLogDistancePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## 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'])
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class]
module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## propagation-loss-model.h (module 'propagation'): ns3::TwoRayGroundPropagationLossModel [class]
module.add_class('TwoRayGroundPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class]
module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class]
module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader [class]
module.add_class('WifiActionHeader', parent=root_module['ns3::Header'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::CategoryValue [enumeration]
module.add_enum('CategoryValue', ['BLOCK_ACK', 'MESH_PEERING_MGT', 'MESH_LINK_METRIC', 'MESH_PATH_SELECTION', 'MESH_INTERWORKING', 'MESH_RESOURCE_COORDINATION', 'MESH_PROXY_FORWARDING'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::PeerLinkMgtActionValue [enumeration]
module.add_enum('PeerLinkMgtActionValue', ['PEER_LINK_OPEN', 'PEER_LINK_CONFIRM', 'PEER_LINK_CLOSE'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::LinkMetricActionValue [enumeration]
module.add_enum('LinkMetricActionValue', ['LINK_METRIC_REQUEST', 'LINK_METRIC_REPORT'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::PathSelectionActionValue [enumeration]
module.add_enum('PathSelectionActionValue', ['PATH_SELECTION'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::InterworkActionValue [enumeration]
module.add_enum('InterworkActionValue', ['PORTAL_ANNOUNCEMENT'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ResourceCoordinationActionValue [enumeration]
module.add_enum('ResourceCoordinationActionValue', ['CONGESTION_CONTROL_NOTIFICATION', 'MDA_SETUP_REQUEST', 'MDA_SETUP_REPLY', 'MDAOP_ADVERTISMENT_REQUEST', 'MDAOP_ADVERTISMENTS', 'MDAOP_SET_TEARDOWN', 'BEACON_TIMING_REQUEST', 'BEACON_TIMING_RESPONSE', 'TBTT_ADJUSTMENT_REQUEST', 'MESH_CHANNEL_SWITCH_ANNOUNCEMENT'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::BlockAckActionValue [enumeration]
module.add_enum('BlockAckActionValue', ['BLOCK_ACK_ADDBA_REQUEST', 'BLOCK_ACK_ADDBA_RESPONSE', 'BLOCK_ACK_DELBA'], outer_class=root_module['ns3::WifiActionHeader'])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue [union]
module.add_class('ActionValue', outer_class=root_module['ns3::WifiActionHeader'])
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElement [class]
module.add_class('WifiInformationElement', parent=root_module['ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >'])
## wifi-information-element-vector.h (module 'wifi'): ns3::WifiInformationElementVector [class]
module.add_class('WifiInformationElementVector', parent=root_module['ns3::Header'])
## wifi-mac.h (module 'wifi'): ns3::WifiMac [class]
module.add_class('WifiMac', parent=root_module['ns3::Object'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader [class]
module.add_class('WifiMacHeader', parent=root_module['ns3::Header'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::QosAckPolicy [enumeration]
module.add_enum('QosAckPolicy', ['NORMAL_ACK', 'NO_ACK', 'NO_EXPLICIT_ACK', 'BLOCK_ACK'], outer_class=root_module['ns3::WifiMacHeader'])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::AddressType [enumeration]
module.add_enum('AddressType', ['ADDR1', 'ADDR2', 'ADDR3', 'ADDR4'], outer_class=root_module['ns3::WifiMacHeader'])
## wifi-mac-queue.h (module 'wifi'): ns3::WifiMacQueue [class]
module.add_class('WifiMacQueue', parent=root_module['ns3::Object'])
## wifi-phy.h (module 'wifi'): ns3::WifiPhy [class]
module.add_class('WifiPhy', parent=root_module['ns3::Object'])
## wifi-phy.h (module 'wifi'): ns3::WifiPhy::State [enumeration]
module.add_enum('State', ['IDLE', 'CCA_BUSY', 'TX', 'RX', 'SWITCHING'], outer_class=root_module['ns3::WifiPhy'])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationManager [class]
module.add_class('WifiRemoteStationManager', parent=root_module['ns3::Object'])
## yans-wifi-phy.h (module 'wifi'): ns3::YansWifiPhy [class]
module.add_class('YansWifiPhy', parent=root_module['ns3::WifiPhy'])
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class]
module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class]
module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## aarf-wifi-manager.h (module 'wifi'): ns3::AarfWifiManager [class]
module.add_class('AarfWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## aarfcd-wifi-manager.h (module 'wifi'): ns3::AarfcdWifiManager [class]
module.add_class('AarfcdWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## amrr-wifi-manager.h (module 'wifi'): ns3::AmrrWifiManager [class]
module.add_class('AmrrWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## amsdu-subframe-header.h (module 'wifi'): ns3::AmsduSubframeHeader [class]
module.add_class('AmsduSubframeHeader', parent=root_module['ns3::Header'])
## arf-wifi-manager.h (module 'wifi'): ns3::ArfWifiManager [class]
module.add_class('ArfWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## athstats-helper.h (module 'wifi'): ns3::AthstatsWifiTraceSink [class]
module.add_class('AthstatsWifiTraceSink', parent=root_module['ns3::Object'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## cara-wifi-manager.h (module 'wifi'): ns3::CaraWifiManager [class]
module.add_class('CaraWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## channel.h (module 'network'): ns3::Channel [class]
module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class]
module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## constant-rate-wifi-manager.h (module 'wifi'): ns3::ConstantRateWifiManager [class]
module.add_class('ConstantRateWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel [class]
module.add_class('ConstantSpeedPropagationDelayModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationDelayModel'])
## cost231-propagation-loss-model.h (module 'propagation'): ns3::Cost231PropagationLossModel [class]
module.add_class('Cost231PropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## cost231-propagation-loss-model.h (module 'propagation'): ns3::Cost231PropagationLossModel::Environment [enumeration]
module.add_enum('Environment', ['SubUrban', 'MediumCity', 'Metropolitan'], outer_class=root_module['ns3::Cost231PropagationLossModel'], import_from_module='ns.propagation')
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckRequestHeader [class]
module.add_class('CtrlBAckRequestHeader', parent=root_module['ns3::Header'])
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckResponseHeader [class]
module.add_class('CtrlBAckResponseHeader', parent=root_module['ns3::Header'])
## dcf.h (module 'wifi'): ns3::Dcf [class]
module.add_class('Dcf', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class]
module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## double.h (module 'core'): ns3::DoubleValue [class]
module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## edca-txop-n.h (module 'wifi'): ns3::EdcaTxopN [class]
module.add_class('EdcaTxopN', parent=root_module['ns3::Dcf'])
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class]
module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class]
module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## error-rate-model.h (module 'wifi'): ns3::ErrorRateModel [class]
module.add_class('ErrorRateModel', parent=root_module['ns3::Object'])
## event-impl.h (module 'core'): ns3::EventImpl [class]
module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class]
module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## supported-rates.h (module 'wifi'): ns3::ExtendedSupportedRatesIE [class]
module.add_class('ExtendedSupportedRatesIE', parent=root_module['ns3::WifiInformationElement'])
## propagation-loss-model.h (module 'propagation'): ns3::FixedRssLossModel [class]
module.add_class('FixedRssLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## propagation-loss-model.h (module 'propagation'): ns3::FriisPropagationLossModel [class]
module.add_class('FriisPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class]
module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## ideal-wifi-manager.h (module 'wifi'): ns3::IdealWifiManager [class]
module.add_class('IdealWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## 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'])
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): ns3::ItuR1411LosPropagationLossModel [class]
module.add_class('ItuR1411LosPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): ns3::ItuR1411NlosOverRooftopPropagationLossModel [class]
module.add_class('ItuR1411NlosOverRooftopPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## jakes-process.h (module 'propagation'): ns3::JakesProcess [class]
module.add_class('JakesProcess', import_from_module='ns.propagation', parent=root_module['ns3::Object'])
## jakes-propagation-loss-model.h (module 'propagation'): ns3::JakesPropagationLossModel [class]
module.add_class('JakesPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): ns3::Kun2600MhzPropagationLossModel [class]
module.add_class('Kun2600MhzPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## propagation-loss-model.h (module 'propagation'): ns3::LogDistancePropagationLossModel [class]
module.add_class('LogDistancePropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class]
module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class]
module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class]
module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## mac-low.h (module 'wifi'): ns3::MacLow [class]
module.add_class('MacLow', parent=root_module['ns3::Object'])
## propagation-loss-model.h (module 'propagation'): ns3::MatrixPropagationLossModel [class]
module.add_class('MatrixPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## mgt-headers.h (module 'wifi'): ns3::MgtBeaconHeader [class]
module.add_class('MgtBeaconHeader', parent=root_module['ns3::MgtProbeResponseHeader'])
## minstrel-wifi-manager.h (module 'wifi'): ns3::MinstrelWifiManager [class]
module.add_class('MinstrelWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## mobility-model.h (module 'mobility'): ns3::MobilityModel [class]
module.add_class('MobilityModel', import_from_module='ns.mobility', parent=root_module['ns3::Object'])
## msdu-aggregator.h (module 'wifi'): ns3::MsduAggregator [class]
module.add_class('MsduAggregator', parent=root_module['ns3::Object'])
## propagation-loss-model.h (module 'propagation'): ns3::NakagamiPropagationLossModel [class]
module.add_class('NakagamiPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## 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')
## nist-error-rate-model.h (module 'wifi'): ns3::NistErrorRateModel [class]
module.add_class('NistErrorRateModel', parent=root_module['ns3::ErrorRateModel'])
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class]
module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## okumura-hata-propagation-loss-model.h (module 'propagation'): ns3::OkumuraHataPropagationLossModel [class]
module.add_class('OkumuraHataPropagationLossModel', import_from_module='ns.propagation', parent=root_module['ns3::PropagationLossModel'])
## onoe-wifi-manager.h (module 'wifi'): ns3::OnoeWifiManager [class]
module.add_class('OnoeWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class]
module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class]
module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## regular-wifi-mac.h (module 'wifi'): ns3::RegularWifiMac [class]
module.add_class('RegularWifiMac', parent=root_module['ns3::WifiMac'])
## rraa-wifi-manager.h (module 'wifi'): ns3::RraaWifiManager [class]
module.add_class('RraaWifiManager', parent=root_module['ns3::WifiRemoteStationManager'])
## ssid.h (module 'wifi'): ns3::Ssid [class]
module.add_class('Ssid', parent=root_module['ns3::WifiInformationElement'])
## ssid.h (module 'wifi'): ns3::SsidChecker [class]
module.add_class('SsidChecker', parent=root_module['ns3::AttributeChecker'])
## ssid.h (module 'wifi'): ns3::SsidValue [class]
module.add_class('SsidValue', parent=root_module['ns3::AttributeValue'])
## sta-wifi-mac.h (module 'wifi'): ns3::StaWifiMac [class]
module.add_class('StaWifiMac', parent=root_module['ns3::RegularWifiMac'])
## supported-rates.h (module 'wifi'): ns3::SupportedRates [class]
module.add_class('SupportedRates', parent=root_module['ns3::WifiInformationElement'])
## 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'])
## 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'])
## wifi-channel.h (module 'wifi'): ns3::WifiChannel [class]
module.add_class('WifiChannel', parent=root_module['ns3::Channel'])
## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker [class]
module.add_class('WifiModeChecker', parent=root_module['ns3::AttributeChecker'])
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue [class]
module.add_class('WifiModeValue', parent=root_module['ns3::AttributeValue'])
## wifi-net-device.h (module 'wifi'): ns3::WifiNetDevice [class]
module.add_class('WifiNetDevice', parent=root_module['ns3::NetDevice'])
## yans-error-rate-model.h (module 'wifi'): ns3::YansErrorRateModel [class]
module.add_class('YansErrorRateModel', parent=root_module['ns3::ErrorRateModel'])
## yans-wifi-channel.h (module 'wifi'): ns3::YansWifiChannel [class]
module.add_class('YansWifiChannel', parent=root_module['ns3::WifiChannel'])
## 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'])
## adhoc-wifi-mac.h (module 'wifi'): ns3::AdhocWifiMac [class]
module.add_class('AdhocWifiMac', parent=root_module['ns3::RegularWifiMac'])
## ap-wifi-mac.h (module 'wifi'): ns3::ApWifiMac [class]
module.add_class('ApWifiMac', parent=root_module['ns3::RegularWifiMac'])
## dca-txop.h (module 'wifi'): ns3::DcaTxop [class]
module.add_class('DcaTxop', parent=root_module['ns3::Dcf'])
module.add_container('ns3::WifiModeList', 'ns3::WifiMode', container_type='vector')
module.add_container('std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::AmsduSubframeHeader > >', 'std::pair< ns3::Ptr< ns3::Packet >, ns3::AmsduSubframeHeader >', container_type='list')
typehandlers.add_type_alias('uint8_t', 'ns3::WifiInformationElementId')
typehandlers.add_type_alias('uint8_t*', 'ns3::WifiInformationElementId*')
typehandlers.add_type_alias('uint8_t&', 'ns3::WifiInformationElementId&')
typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >', 'ns3::WifiModeListIterator')
typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >*', 'ns3::WifiModeListIterator*')
typehandlers.add_type_alias('__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >&', 'ns3::WifiModeListIterator&')
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('std::vector< ns3::RateInfo, std::allocator< ns3::RateInfo > >', 'ns3::MinstrelRate')
typehandlers.add_type_alias('std::vector< ns3::RateInfo, std::allocator< ns3::RateInfo > >*', 'ns3::MinstrelRate*')
typehandlers.add_type_alias('std::vector< ns3::RateInfo, std::allocator< ns3::RateInfo > >&', 'ns3::MinstrelRate&')
typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >', 'ns3::WifiModeList')
typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >*', 'ns3::WifiModeList*')
typehandlers.add_type_alias('std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >&', 'ns3::WifiModeList&')
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('std::vector< std::vector< unsigned int, std::allocator< unsigned int > >, std::allocator< std::vector< unsigned int, std::allocator< unsigned int > > > >', 'ns3::SampleRate')
typehandlers.add_type_alias('std::vector< std::vector< unsigned int, std::allocator< unsigned int > >, std::allocator< std::vector< unsigned int, std::allocator< unsigned int > > > >*', 'ns3::SampleRate*')
typehandlers.add_type_alias('std::vector< std::vector< unsigned int, std::allocator< unsigned int > >, std::allocator< std::vector< unsigned int, std::allocator< unsigned int > > > >&', 'ns3::SampleRate&')
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_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper'])
register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice'])
register_Ns3AthstatsHelper_methods(root_module, root_module['ns3::AthstatsHelper'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3Bar_methods(root_module, root_module['ns3::Bar'])
register_Ns3BlockAckAgreement_methods(root_module, root_module['ns3::BlockAckAgreement'])
register_Ns3BlockAckCache_methods(root_module, root_module['ns3::BlockAckCache'])
register_Ns3BlockAckManager_methods(root_module, root_module['ns3::BlockAckManager'])
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_Ns3CapabilityInformation_methods(root_module, root_module['ns3::CapabilityInformation'])
register_Ns3DcfManager_methods(root_module, root_module['ns3::DcfManager'])
register_Ns3DcfState_methods(root_module, root_module['ns3::DcfState'])
register_Ns3DsssErrorRateModel_methods(root_module, root_module['ns3::DsssErrorRateModel'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3InterferenceHelper_methods(root_module, root_module['ns3::InterferenceHelper'])
register_Ns3InterferenceHelperSnrPer_methods(root_module, root_module['ns3::InterferenceHelper::SnrPer'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask'])
register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address'])
register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3MacLowBlockAckEventListener_methods(root_module, root_module['ns3::MacLowBlockAckEventListener'])
register_Ns3MacLowDcfListener_methods(root_module, root_module['ns3::MacLowDcfListener'])
register_Ns3MacLowTransmissionListener_methods(root_module, root_module['ns3::MacLowTransmissionListener'])
register_Ns3MacLowTransmissionParameters_methods(root_module, root_module['ns3::MacLowTransmissionParameters'])
register_Ns3MacRxMiddle_methods(root_module, root_module['ns3::MacRxMiddle'])
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_Ns3OriginatorBlockAckAgreement_methods(root_module, root_module['ns3::OriginatorBlockAckAgreement'])
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_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile'])
register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper'])
register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice'])
register_Ns3PropagationCache__Ns3JakesProcess_methods(root_module, root_module['ns3::PropagationCache< ns3::JakesProcess >'])
register_Ns3RateInfo_methods(root_module, root_module['ns3::RateInfo'])
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_Ns3StatusCode_methods(root_module, root_module['ns3::StatusCode'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
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_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D'])
register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D'])
register_Ns3WifiHelper_methods(root_module, root_module['ns3::WifiHelper'])
register_Ns3WifiMacHelper_methods(root_module, root_module['ns3::WifiMacHelper'])
register_Ns3WifiMode_methods(root_module, root_module['ns3::WifiMode'])
register_Ns3WifiModeFactory_methods(root_module, root_module['ns3::WifiModeFactory'])
register_Ns3WifiPhyHelper_methods(root_module, root_module['ns3::WifiPhyHelper'])
register_Ns3WifiPhyListener_methods(root_module, root_module['ns3::WifiPhyListener'])
register_Ns3WifiRemoteStation_methods(root_module, root_module['ns3::WifiRemoteStation'])
register_Ns3WifiRemoteStationInfo_methods(root_module, root_module['ns3::WifiRemoteStationInfo'])
register_Ns3WifiRemoteStationState_methods(root_module, root_module['ns3::WifiRemoteStationState'])
register_Ns3YansWifiChannelHelper_methods(root_module, root_module['ns3::YansWifiChannelHelper'])
register_Ns3YansWifiPhyHelper_methods(root_module, root_module['ns3::YansWifiPhyHelper'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3MgtAddBaRequestHeader_methods(root_module, root_module['ns3::MgtAddBaRequestHeader'])
register_Ns3MgtAddBaResponseHeader_methods(root_module, root_module['ns3::MgtAddBaResponseHeader'])
register_Ns3MgtAssocRequestHeader_methods(root_module, root_module['ns3::MgtAssocRequestHeader'])
register_Ns3MgtAssocResponseHeader_methods(root_module, root_module['ns3::MgtAssocResponseHeader'])
register_Ns3MgtDelBaHeader_methods(root_module, root_module['ns3::MgtDelBaHeader'])
register_Ns3MgtProbeRequestHeader_methods(root_module, root_module['ns3::MgtProbeRequestHeader'])
register_Ns3MgtProbeResponseHeader_methods(root_module, root_module['ns3::MgtProbeResponseHeader'])
register_Ns3NqosWifiMacHelper_methods(root_module, root_module['ns3::NqosWifiMacHelper'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper'])
register_Ns3PropagationDelayModel_methods(root_module, root_module['ns3::PropagationDelayModel'])
register_Ns3PropagationLossModel_methods(root_module, root_module['ns3::PropagationLossModel'])
register_Ns3QosTag_methods(root_module, root_module['ns3::QosTag'])
register_Ns3QosWifiMacHelper_methods(root_module, root_module['ns3::QosWifiMacHelper'])
register_Ns3RandomPropagationDelayModel_methods(root_module, root_module['ns3::RandomPropagationDelayModel'])
register_Ns3RandomPropagationLossModel_methods(root_module, root_module['ns3::RandomPropagationLossModel'])
register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream'])
register_Ns3RangePropagationLossModel_methods(root_module, root_module['ns3::RangePropagationLossModel'])
register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable'])
register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
register_Ns3SimpleRefCount__Ns3InterferenceHelperEvent_Ns3Empty_Ns3DefaultDeleter__lt__ns3InterferenceHelperEvent__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> >'])
register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3SimpleRefCount__Ns3WifiInformationElement_Ns3Empty_Ns3DefaultDeleter__lt__ns3WifiInformationElement__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >'])
register_Ns3SnrTag_methods(root_module, root_module['ns3::SnrTag'])
register_Ns3ThreeLogDistancePropagationLossModel_methods(root_module, root_module['ns3::ThreeLogDistancePropagationLossModel'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable'])
register_Ns3TwoRayGroundPropagationLossModel_methods(root_module, root_module['ns3::TwoRayGroundPropagationLossModel'])
register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable'])
register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable'])
register_Ns3WifiActionHeader_methods(root_module, root_module['ns3::WifiActionHeader'])
register_Ns3WifiActionHeaderActionValue_methods(root_module, root_module['ns3::WifiActionHeader::ActionValue'])
register_Ns3WifiInformationElement_methods(root_module, root_module['ns3::WifiInformationElement'])
register_Ns3WifiInformationElementVector_methods(root_module, root_module['ns3::WifiInformationElementVector'])
register_Ns3WifiMac_methods(root_module, root_module['ns3::WifiMac'])
register_Ns3WifiMacHeader_methods(root_module, root_module['ns3::WifiMacHeader'])
register_Ns3WifiMacQueue_methods(root_module, root_module['ns3::WifiMacQueue'])
register_Ns3WifiPhy_methods(root_module, root_module['ns3::WifiPhy'])
register_Ns3WifiRemoteStationManager_methods(root_module, root_module['ns3::WifiRemoteStationManager'])
register_Ns3YansWifiPhy_methods(root_module, root_module['ns3::YansWifiPhy'])
register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable'])
register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable'])
register_Ns3AarfWifiManager_methods(root_module, root_module['ns3::AarfWifiManager'])
register_Ns3AarfcdWifiManager_methods(root_module, root_module['ns3::AarfcdWifiManager'])
register_Ns3AmrrWifiManager_methods(root_module, root_module['ns3::AmrrWifiManager'])
register_Ns3AmsduSubframeHeader_methods(root_module, root_module['ns3::AmsduSubframeHeader'])
register_Ns3ArfWifiManager_methods(root_module, root_module['ns3::ArfWifiManager'])
register_Ns3AthstatsWifiTraceSink_methods(root_module, root_module['ns3::AthstatsWifiTraceSink'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3CaraWifiManager_methods(root_module, root_module['ns3::CaraWifiManager'])
register_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable'])
register_Ns3ConstantRateWifiManager_methods(root_module, root_module['ns3::ConstantRateWifiManager'])
register_Ns3ConstantSpeedPropagationDelayModel_methods(root_module, root_module['ns3::ConstantSpeedPropagationDelayModel'])
register_Ns3Cost231PropagationLossModel_methods(root_module, root_module['ns3::Cost231PropagationLossModel'])
register_Ns3CtrlBAckRequestHeader_methods(root_module, root_module['ns3::CtrlBAckRequestHeader'])
register_Ns3CtrlBAckResponseHeader_methods(root_module, root_module['ns3::CtrlBAckResponseHeader'])
register_Ns3Dcf_methods(root_module, root_module['ns3::Dcf'])
register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3EdcaTxopN_methods(root_module, root_module['ns3::EdcaTxopN'])
register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable'])
register_Ns3ErrorRateModel_methods(root_module, root_module['ns3::ErrorRateModel'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable'])
register_Ns3ExtendedSupportedRatesIE_methods(root_module, root_module['ns3::ExtendedSupportedRatesIE'])
register_Ns3FixedRssLossModel_methods(root_module, root_module['ns3::FixedRssLossModel'])
register_Ns3FriisPropagationLossModel_methods(root_module, root_module['ns3::FriisPropagationLossModel'])
register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable'])
register_Ns3IdealWifiManager_methods(root_module, root_module['ns3::IdealWifiManager'])
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_Ns3ItuR1411LosPropagationLossModel_methods(root_module, root_module['ns3::ItuR1411LosPropagationLossModel'])
register_Ns3ItuR1411NlosOverRooftopPropagationLossModel_methods(root_module, root_module['ns3::ItuR1411NlosOverRooftopPropagationLossModel'])
register_Ns3JakesProcess_methods(root_module, root_module['ns3::JakesProcess'])
register_Ns3JakesPropagationLossModel_methods(root_module, root_module['ns3::JakesPropagationLossModel'])
register_Ns3Kun2600MhzPropagationLossModel_methods(root_module, root_module['ns3::Kun2600MhzPropagationLossModel'])
register_Ns3LogDistancePropagationLossModel_methods(root_module, root_module['ns3::LogDistancePropagationLossModel'])
register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3MacLow_methods(root_module, root_module['ns3::MacLow'])
register_Ns3MatrixPropagationLossModel_methods(root_module, root_module['ns3::MatrixPropagationLossModel'])
register_Ns3MgtBeaconHeader_methods(root_module, root_module['ns3::MgtBeaconHeader'])
register_Ns3MinstrelWifiManager_methods(root_module, root_module['ns3::MinstrelWifiManager'])
register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel'])
register_Ns3MsduAggregator_methods(root_module, root_module['ns3::MsduAggregator'])
register_Ns3NakagamiPropagationLossModel_methods(root_module, root_module['ns3::NakagamiPropagationLossModel'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NistErrorRateModel_methods(root_module, root_module['ns3::NistErrorRateModel'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3OkumuraHataPropagationLossModel_methods(root_module, root_module['ns3::OkumuraHataPropagationLossModel'])
register_Ns3OnoeWifiManager_methods(root_module, root_module['ns3::OnoeWifiManager'])
register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable'])
register_Ns3RegularWifiMac_methods(root_module, root_module['ns3::RegularWifiMac'])
register_Ns3RraaWifiManager_methods(root_module, root_module['ns3::RraaWifiManager'])
register_Ns3Ssid_methods(root_module, root_module['ns3::Ssid'])
register_Ns3SsidChecker_methods(root_module, root_module['ns3::SsidChecker'])
register_Ns3SsidValue_methods(root_module, root_module['ns3::SsidValue'])
register_Ns3StaWifiMac_methods(root_module, root_module['ns3::StaWifiMac'])
register_Ns3SupportedRates_methods(root_module, root_module['ns3::SupportedRates'])
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_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_Ns3WifiChannel_methods(root_module, root_module['ns3::WifiChannel'])
register_Ns3WifiModeChecker_methods(root_module, root_module['ns3::WifiModeChecker'])
register_Ns3WifiModeValue_methods(root_module, root_module['ns3::WifiModeValue'])
register_Ns3WifiNetDevice_methods(root_module, root_module['ns3::WifiNetDevice'])
register_Ns3YansErrorRateModel_methods(root_module, root_module['ns3::YansErrorRateModel'])
register_Ns3YansWifiChannel_methods(root_module, root_module['ns3::YansWifiChannel'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3AdhocWifiMac_methods(root_module, root_module['ns3::AdhocWifiMac'])
register_Ns3ApWifiMac_methods(root_module, root_module['ns3::ApWifiMac'])
register_Ns3DcaTxop_methods(root_module, root_module['ns3::DcaTxop'])
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_Ns3AsciiTraceHelper_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::_Ios_Openmode filemode=std::ios_base::out) [member function]
cls.add_method('CreateFileStream',
'ns3::Ptr< ns3::OutputStreamWrapper >',
[param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode', default_value='std::ios_base::out')])
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDequeueSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDequeueSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDropSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultDropSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultEnqueueSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultEnqueueSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultReceiveSinkWithContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DefaultReceiveSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromDevice',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')])
## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromInterfacePair',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')])
return
def register_Ns3AsciiTraceHelperForDevice_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice(ns3::AsciiTraceHelperForDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AsciiTraceHelperForDevice const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename=false) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::NetDevice> nd) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::NetDevice >', 'nd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, std::string ndName, bool explicitFilename=false) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ndName) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ndName')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NetDeviceContainer', 'd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t deviceid) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(std::string prefix) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('std::string', 'prefix')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function]
cls.add_method('EnableAsciiInternal',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3AthstatsHelper_methods(root_module, cls):
## athstats-helper.h (module 'wifi'): ns3::AthstatsHelper::AthstatsHelper(ns3::AthstatsHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AthstatsHelper const &', 'arg0')])
## athstats-helper.h (module 'wifi'): ns3::AthstatsHelper::AthstatsHelper() [constructor]
cls.add_constructor([])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsHelper::EnableAthstats(std::string filename, uint32_t nodeid, uint32_t deviceid) [member function]
cls.add_method('EnableAthstats',
'void',
[param('std::string', 'filename'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsHelper::EnableAthstats(std::string filename, ns3::Ptr<ns3::NetDevice> nd) [member function]
cls.add_method('EnableAthstats',
'void',
[param('std::string', 'filename'), param('ns3::Ptr< ns3::NetDevice >', 'nd')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsHelper::EnableAthstats(std::string filename, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAthstats',
'void',
[param('std::string', 'filename'), param('ns3::NetDeviceContainer', 'd')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsHelper::EnableAthstats(std::string filename, ns3::NodeContainer n) [member function]
cls.add_method('EnableAthstats',
'void',
[param('std::string', 'filename'), param('ns3::NodeContainer', 'n')])
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_Ns3Bar_methods(root_module, cls):
## block-ack-manager.h (module 'wifi'): ns3::Bar::Bar(ns3::Bar const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Bar const &', 'arg0')])
## block-ack-manager.h (module 'wifi'): ns3::Bar::Bar() [constructor]
cls.add_constructor([])
## block-ack-manager.h (module 'wifi'): ns3::Bar::Bar(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address recipient, uint8_t tid, bool immediate) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('bool', 'immediate')])
## block-ack-manager.h (module 'wifi'): ns3::Bar::bar [variable]
cls.add_instance_attribute('bar', 'ns3::Ptr< ns3::Packet const >', is_const=False)
## block-ack-manager.h (module 'wifi'): ns3::Bar::immediate [variable]
cls.add_instance_attribute('immediate', 'bool', is_const=False)
## block-ack-manager.h (module 'wifi'): ns3::Bar::recipient [variable]
cls.add_instance_attribute('recipient', 'ns3::Mac48Address', is_const=False)
## block-ack-manager.h (module 'wifi'): ns3::Bar::tid [variable]
cls.add_instance_attribute('tid', 'uint8_t', is_const=False)
return
def register_Ns3BlockAckAgreement_methods(root_module, cls):
## block-ack-agreement.h (module 'wifi'): ns3::BlockAckAgreement::BlockAckAgreement(ns3::BlockAckAgreement const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BlockAckAgreement const &', 'arg0')])
## block-ack-agreement.h (module 'wifi'): ns3::BlockAckAgreement::BlockAckAgreement() [constructor]
cls.add_constructor([])
## block-ack-agreement.h (module 'wifi'): ns3::BlockAckAgreement::BlockAckAgreement(ns3::Mac48Address peer, uint8_t tid) [constructor]
cls.add_constructor([param('ns3::Mac48Address', 'peer'), param('uint8_t', 'tid')])
## block-ack-agreement.h (module 'wifi'): uint16_t ns3::BlockAckAgreement::GetBufferSize() const [member function]
cls.add_method('GetBufferSize',
'uint16_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): ns3::Mac48Address ns3::BlockAckAgreement::GetPeer() const [member function]
cls.add_method('GetPeer',
'ns3::Mac48Address',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): uint16_t ns3::BlockAckAgreement::GetStartingSequence() const [member function]
cls.add_method('GetStartingSequence',
'uint16_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): uint16_t ns3::BlockAckAgreement::GetStartingSequenceControl() const [member function]
cls.add_method('GetStartingSequenceControl',
'uint16_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): uint8_t ns3::BlockAckAgreement::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): uint16_t ns3::BlockAckAgreement::GetTimeout() const [member function]
cls.add_method('GetTimeout',
'uint16_t',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): bool ns3::BlockAckAgreement::IsAmsduSupported() const [member function]
cls.add_method('IsAmsduSupported',
'bool',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): bool ns3::BlockAckAgreement::IsImmediateBlockAck() const [member function]
cls.add_method('IsImmediateBlockAck',
'bool',
[],
is_const=True)
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetAmsduSupport(bool supported) [member function]
cls.add_method('SetAmsduSupport',
'void',
[param('bool', 'supported')])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetBufferSize(uint16_t bufferSize) [member function]
cls.add_method('SetBufferSize',
'void',
[param('uint16_t', 'bufferSize')])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetDelayedBlockAck() [member function]
cls.add_method('SetDelayedBlockAck',
'void',
[])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetImmediateBlockAck() [member function]
cls.add_method('SetImmediateBlockAck',
'void',
[])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetStartingSequence(uint16_t seq) [member function]
cls.add_method('SetStartingSequence',
'void',
[param('uint16_t', 'seq')])
## block-ack-agreement.h (module 'wifi'): void ns3::BlockAckAgreement::SetTimeout(uint16_t timeout) [member function]
cls.add_method('SetTimeout',
'void',
[param('uint16_t', 'timeout')])
return
def register_Ns3BlockAckCache_methods(root_module, cls):
## block-ack-cache.h (module 'wifi'): ns3::BlockAckCache::BlockAckCache() [constructor]
cls.add_constructor([])
## block-ack-cache.h (module 'wifi'): ns3::BlockAckCache::BlockAckCache(ns3::BlockAckCache const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BlockAckCache const &', 'arg0')])
## block-ack-cache.h (module 'wifi'): void ns3::BlockAckCache::FillBlockAckBitmap(ns3::CtrlBAckResponseHeader * blockAckHeader) [member function]
cls.add_method('FillBlockAckBitmap',
'void',
[param('ns3::CtrlBAckResponseHeader *', 'blockAckHeader')])
## block-ack-cache.h (module 'wifi'): void ns3::BlockAckCache::Init(uint16_t winStart, uint16_t winSize) [member function]
cls.add_method('Init',
'void',
[param('uint16_t', 'winStart'), param('uint16_t', 'winSize')])
## block-ack-cache.h (module 'wifi'): void ns3::BlockAckCache::UpdateWithBlockAckReq(uint16_t startingSeq) [member function]
cls.add_method('UpdateWithBlockAckReq',
'void',
[param('uint16_t', 'startingSeq')])
## block-ack-cache.h (module 'wifi'): void ns3::BlockAckCache::UpdateWithMpdu(ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('UpdateWithMpdu',
'void',
[param('ns3::WifiMacHeader const *', 'hdr')])
return
def register_Ns3BlockAckManager_methods(root_module, cls):
## block-ack-manager.h (module 'wifi'): ns3::BlockAckManager::BlockAckManager() [constructor]
cls.add_constructor([])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::CreateAgreement(ns3::MgtAddBaRequestHeader const * reqHdr, ns3::Mac48Address recipient) [member function]
cls.add_method('CreateAgreement',
'void',
[param('ns3::MgtAddBaRequestHeader const *', 'reqHdr'), param('ns3::Mac48Address', 'recipient')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::DestroyAgreement(ns3::Mac48Address recipient, uint8_t tid) [member function]
cls.add_method('DestroyAgreement',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')])
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::ExistsAgreement(ns3::Mac48Address recipient, uint8_t tid) const [member function]
cls.add_method('ExistsAgreement',
'bool',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')],
is_const=True)
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::ExistsAgreementInState(ns3::Mac48Address recipient, uint8_t tid, ns3::OriginatorBlockAckAgreement::State state) const [member function]
cls.add_method('ExistsAgreementInState',
'bool',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('ns3::OriginatorBlockAckAgreement::State', 'state')],
is_const=True)
## block-ack-manager.h (module 'wifi'): uint32_t ns3::BlockAckManager::GetNBufferedPackets(ns3::Mac48Address recipient, uint8_t tid) const [member function]
cls.add_method('GetNBufferedPackets',
'uint32_t',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')],
is_const=True)
## block-ack-manager.h (module 'wifi'): uint32_t ns3::BlockAckManager::GetNRetryNeededPackets(ns3::Mac48Address recipient, uint8_t tid) const [member function]
cls.add_method('GetNRetryNeededPackets',
'uint32_t',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')],
is_const=True)
## block-ack-manager.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::BlockAckManager::GetNextPacket(ns3::WifiMacHeader & hdr) [member function]
cls.add_method('GetNextPacket',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader &', 'hdr')])
## block-ack-manager.h (module 'wifi'): uint32_t ns3::BlockAckManager::GetNextPacketSize() const [member function]
cls.add_method('GetNextPacketSize',
'uint32_t',
[],
is_const=True)
## block-ack-manager.h (module 'wifi'): uint16_t ns3::BlockAckManager::GetSeqNumOfNextRetryPacket(ns3::Mac48Address recipient, uint8_t tid) const [member function]
cls.add_method('GetSeqNumOfNextRetryPacket',
'uint16_t',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')],
is_const=True)
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::HasBar(ns3::Bar & bar) [member function]
cls.add_method('HasBar',
'bool',
[param('ns3::Bar &', 'bar')])
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::HasOtherFragments(uint16_t sequenceNumber) const [member function]
cls.add_method('HasOtherFragments',
'bool',
[param('uint16_t', 'sequenceNumber')],
is_const=True)
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::HasPackets() const [member function]
cls.add_method('HasPackets',
'bool',
[],
is_const=True)
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::NotifyAgreementEstablished(ns3::Mac48Address recipient, uint8_t tid, uint16_t startingSeq) [member function]
cls.add_method('NotifyAgreementEstablished',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('uint16_t', 'startingSeq')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::NotifyAgreementUnsuccessful(ns3::Mac48Address recipient, uint8_t tid) [member function]
cls.add_method('NotifyAgreementUnsuccessful',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::NotifyGotBlockAck(ns3::CtrlBAckResponseHeader const * blockAck, ns3::Mac48Address recipient) [member function]
cls.add_method('NotifyGotBlockAck',
'void',
[param('ns3::CtrlBAckResponseHeader const *', 'blockAck'), param('ns3::Mac48Address', 'recipient')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::NotifyMpduTransmission(ns3::Mac48Address recipient, uint8_t tid, uint16_t nextSeqNumber) [member function]
cls.add_method('NotifyMpduTransmission',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('uint16_t', 'nextSeqNumber')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetBlockAckInactivityCallback(ns3::Callback<void, ns3::Mac48Address, unsigned char, bool, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetBlockAckInactivityCallback',
'void',
[param('ns3::Callback< void, ns3::Mac48Address, unsigned char, bool, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetBlockAckThreshold(uint8_t nPackets) [member function]
cls.add_method('SetBlockAckThreshold',
'void',
[param('uint8_t', 'nPackets')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetBlockAckType(ns3::BlockAckType bAckType) [member function]
cls.add_method('SetBlockAckType',
'void',
[param('ns3::BlockAckType', 'bAckType')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetBlockDestinationCallback(ns3::Callback<void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetBlockDestinationCallback',
'void',
[param('ns3::Callback< void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetMaxPacketDelay(ns3::Time maxDelay) [member function]
cls.add_method('SetMaxPacketDelay',
'void',
[param('ns3::Time', 'maxDelay')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetQueue(ns3::Ptr<ns3::WifiMacQueue> queue) [member function]
cls.add_method('SetQueue',
'void',
[param('ns3::Ptr< ns3::WifiMacQueue >', 'queue')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetTxMiddle(ns3::MacTxMiddle * txMiddle) [member function]
cls.add_method('SetTxMiddle',
'void',
[param('ns3::MacTxMiddle *', 'txMiddle')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::SetUnblockDestinationCallback(ns3::Callback<void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetUnblockDestinationCallback',
'void',
[param('ns3::Callback< void, ns3::Mac48Address, unsigned char, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::StorePacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr, ns3::Time tStamp) [member function]
cls.add_method('StorePacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr'), param('ns3::Time', 'tStamp')])
## block-ack-manager.h (module 'wifi'): bool ns3::BlockAckManager::SwitchToBlockAckIfNeeded(ns3::Mac48Address recipient, uint8_t tid, uint16_t startingSeq) [member function]
cls.add_method('SwitchToBlockAckIfNeeded',
'bool',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid'), param('uint16_t', 'startingSeq')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::TearDownBlockAck(ns3::Mac48Address recipient, uint8_t tid) [member function]
cls.add_method('TearDownBlockAck',
'void',
[param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')])
## block-ack-manager.h (module 'wifi'): void ns3::BlockAckManager::UpdateAgreement(ns3::MgtAddBaResponseHeader const * respHdr, ns3::Mac48Address recipient) [member function]
cls.add_method('UpdateAgreement',
'void',
[param('ns3::MgtAddBaResponseHeader const *', 'respHdr'), param('ns3::Mac48Address', 'recipient')])
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_Ns3CapabilityInformation_methods(root_module, cls):
## capability-information.h (module 'wifi'): ns3::CapabilityInformation::CapabilityInformation(ns3::CapabilityInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CapabilityInformation const &', 'arg0')])
## capability-information.h (module 'wifi'): ns3::CapabilityInformation::CapabilityInformation() [constructor]
cls.add_constructor([])
## capability-information.h (module 'wifi'): ns3::Buffer::Iterator ns3::CapabilityInformation::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')])
## capability-information.h (module 'wifi'): uint32_t ns3::CapabilityInformation::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## capability-information.h (module 'wifi'): bool ns3::CapabilityInformation::IsEss() const [member function]
cls.add_method('IsEss',
'bool',
[],
is_const=True)
## capability-information.h (module 'wifi'): bool ns3::CapabilityInformation::IsIbss() const [member function]
cls.add_method('IsIbss',
'bool',
[],
is_const=True)
## capability-information.h (module 'wifi'): ns3::Buffer::Iterator ns3::CapabilityInformation::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## capability-information.h (module 'wifi'): void ns3::CapabilityInformation::SetEss() [member function]
cls.add_method('SetEss',
'void',
[])
## capability-information.h (module 'wifi'): void ns3::CapabilityInformation::SetIbss() [member function]
cls.add_method('SetIbss',
'void',
[])
return
def register_Ns3DcfManager_methods(root_module, cls):
## dcf-manager.h (module 'wifi'): ns3::DcfManager::DcfManager(ns3::DcfManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DcfManager const &', 'arg0')])
## dcf-manager.h (module 'wifi'): ns3::DcfManager::DcfManager() [constructor]
cls.add_constructor([])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::Add(ns3::DcfState * dcf) [member function]
cls.add_method('Add',
'void',
[param('ns3::DcfState *', 'dcf')])
## dcf-manager.h (module 'wifi'): ns3::Time ns3::DcfManager::GetEifsNoDifs() const [member function]
cls.add_method('GetEifsNoDifs',
'ns3::Time',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyAckTimeoutResetNow() [member function]
cls.add_method('NotifyAckTimeoutResetNow',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyAckTimeoutStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyAckTimeoutStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyCtsTimeoutResetNow() [member function]
cls.add_method('NotifyCtsTimeoutResetNow',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyCtsTimeoutStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyCtsTimeoutStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyMaybeCcaBusyStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyMaybeCcaBusyStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyNavResetNow(ns3::Time duration) [member function]
cls.add_method('NotifyNavResetNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyNavStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyNavStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyRxEndErrorNow() [member function]
cls.add_method('NotifyRxEndErrorNow',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyRxEndOkNow() [member function]
cls.add_method('NotifyRxEndOkNow',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyRxStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyRxStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifySwitchingStartNow(ns3::Time duration) [member function]
cls.add_method('NotifySwitchingStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::NotifyTxStartNow(ns3::Time duration) [member function]
cls.add_method('NotifyTxStartNow',
'void',
[param('ns3::Time', 'duration')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::RequestAccess(ns3::DcfState * state) [member function]
cls.add_method('RequestAccess',
'void',
[param('ns3::DcfState *', 'state')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function]
cls.add_method('SetEifsNoDifs',
'void',
[param('ns3::Time', 'eifsNoDifs')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetSifs(ns3::Time sifs) [member function]
cls.add_method('SetSifs',
'void',
[param('ns3::Time', 'sifs')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetSlot(ns3::Time slotTime) [member function]
cls.add_method('SetSlot',
'void',
[param('ns3::Time', 'slotTime')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetupLowListener(ns3::Ptr<ns3::MacLow> low) [member function]
cls.add_method('SetupLowListener',
'void',
[param('ns3::Ptr< ns3::MacLow >', 'low')])
## dcf-manager.h (module 'wifi'): void ns3::DcfManager::SetupPhyListener(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetupPhyListener',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')])
return
def register_Ns3DcfState_methods(root_module, cls):
## dcf-manager.h (module 'wifi'): ns3::DcfState::DcfState(ns3::DcfState const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DcfState const &', 'arg0')])
## dcf-manager.h (module 'wifi'): ns3::DcfState::DcfState() [constructor]
cls.add_constructor([])
## dcf-manager.h (module 'wifi'): uint32_t ns3::DcfState::GetAifsn() const [member function]
cls.add_method('GetAifsn',
'uint32_t',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): uint32_t ns3::DcfState::GetCw() const [member function]
cls.add_method('GetCw',
'uint32_t',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): uint32_t ns3::DcfState::GetCwMax() const [member function]
cls.add_method('GetCwMax',
'uint32_t',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): uint32_t ns3::DcfState::GetCwMin() const [member function]
cls.add_method('GetCwMin',
'uint32_t',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): bool ns3::DcfState::IsAccessRequested() const [member function]
cls.add_method('IsAccessRequested',
'bool',
[],
is_const=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfState::ResetCw() [member function]
cls.add_method('ResetCw',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::SetAifsn(uint32_t aifsn) [member function]
cls.add_method('SetAifsn',
'void',
[param('uint32_t', 'aifsn')])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::SetCwMax(uint32_t maxCw) [member function]
cls.add_method('SetCwMax',
'void',
[param('uint32_t', 'maxCw')])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::SetCwMin(uint32_t minCw) [member function]
cls.add_method('SetCwMin',
'void',
[param('uint32_t', 'minCw')])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::StartBackoffNow(uint32_t nSlots) [member function]
cls.add_method('StartBackoffNow',
'void',
[param('uint32_t', 'nSlots')])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::UpdateFailedCw() [member function]
cls.add_method('UpdateFailedCw',
'void',
[])
## dcf-manager.h (module 'wifi'): void ns3::DcfState::DoNotifyAccessGranted() [member function]
cls.add_method('DoNotifyAccessGranted',
'void',
[],
is_pure_virtual=True, visibility='private', is_virtual=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfState::DoNotifyChannelSwitching() [member function]
cls.add_method('DoNotifyChannelSwitching',
'void',
[],
is_pure_virtual=True, visibility='private', is_virtual=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfState::DoNotifyCollision() [member function]
cls.add_method('DoNotifyCollision',
'void',
[],
is_pure_virtual=True, visibility='private', is_virtual=True)
## dcf-manager.h (module 'wifi'): void ns3::DcfState::DoNotifyInternalCollision() [member function]
cls.add_method('DoNotifyInternalCollision',
'void',
[],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3DsssErrorRateModel_methods(root_module, cls):
## dsss-error-rate-model.h (module 'wifi'): ns3::DsssErrorRateModel::DsssErrorRateModel() [constructor]
cls.add_constructor([])
## dsss-error-rate-model.h (module 'wifi'): ns3::DsssErrorRateModel::DsssErrorRateModel(ns3::DsssErrorRateModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DsssErrorRateModel const &', 'arg0')])
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::DqpskFunction(double x) [member function]
cls.add_method('DqpskFunction',
'double',
[param('double', 'x')],
is_static=True)
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::GetDsssDbpskSuccessRate(double sinr, uint32_t nbits) [member function]
cls.add_method('GetDsssDbpskSuccessRate',
'double',
[param('double', 'sinr'), param('uint32_t', 'nbits')],
is_static=True)
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::GetDsssDqpskCck11SuccessRate(double sinr, uint32_t nbits) [member function]
cls.add_method('GetDsssDqpskCck11SuccessRate',
'double',
[param('double', 'sinr'), param('uint32_t', 'nbits')],
is_static=True)
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::GetDsssDqpskCck5_5SuccessRate(double sinr, uint32_t nbits) [member function]
cls.add_method('GetDsssDqpskCck5_5SuccessRate',
'double',
[param('double', 'sinr'), param('uint32_t', 'nbits')],
is_static=True)
## dsss-error-rate-model.h (module 'wifi'): static double ns3::DsssErrorRateModel::GetDsssDqpskSuccessRate(double sinr, uint32_t nbits) [member function]
cls.add_method('GetDsssDqpskSuccessRate',
'double',
[param('double', 'sinr'), param('uint32_t', 'nbits')],
is_static=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_Ns3InterferenceHelper_methods(root_module, cls):
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::InterferenceHelper() [constructor]
cls.add_constructor([])
## interference-helper.h (module 'wifi'): ns3::Ptr<ns3::InterferenceHelper::Event> ns3::InterferenceHelper::Add(uint32_t size, ns3::WifiMode payloadMode, ns3::WifiPreamble preamble, ns3::Time duration, double rxPower) [member function]
cls.add_method('Add',
'ns3::Ptr< ns3::InterferenceHelper::Event >',
[param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble'), param('ns3::Time', 'duration'), param('double', 'rxPower')])
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer ns3::InterferenceHelper::CalculateSnrPer(ns3::Ptr<ns3::InterferenceHelper::Event> event) [member function]
cls.add_method('CalculateSnrPer',
'ns3::InterferenceHelper::SnrPer',
[param('ns3::Ptr< ns3::InterferenceHelper::Event >', 'event')])
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::EraseEvents() [member function]
cls.add_method('EraseEvents',
'void',
[])
## interference-helper.h (module 'wifi'): ns3::Time ns3::InterferenceHelper::GetEnergyDuration(double energyW) [member function]
cls.add_method('GetEnergyDuration',
'ns3::Time',
[param('double', 'energyW')])
## interference-helper.h (module 'wifi'): ns3::Ptr<ns3::ErrorRateModel> ns3::InterferenceHelper::GetErrorRateModel() const [member function]
cls.add_method('GetErrorRateModel',
'ns3::Ptr< ns3::ErrorRateModel >',
[],
is_const=True)
## interference-helper.h (module 'wifi'): double ns3::InterferenceHelper::GetNoiseFigure() const [member function]
cls.add_method('GetNoiseFigure',
'double',
[],
is_const=True)
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::NotifyRxEnd() [member function]
cls.add_method('NotifyRxEnd',
'void',
[])
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::NotifyRxStart() [member function]
cls.add_method('NotifyRxStart',
'void',
[])
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::SetErrorRateModel(ns3::Ptr<ns3::ErrorRateModel> rate) [member function]
cls.add_method('SetErrorRateModel',
'void',
[param('ns3::Ptr< ns3::ErrorRateModel >', 'rate')])
## interference-helper.h (module 'wifi'): void ns3::InterferenceHelper::SetNoiseFigure(double value) [member function]
cls.add_method('SetNoiseFigure',
'void',
[param('double', 'value')])
return
def register_Ns3InterferenceHelperSnrPer_methods(root_module, cls):
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer::SnrPer() [constructor]
cls.add_constructor([])
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer::SnrPer(ns3::InterferenceHelper::SnrPer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::InterferenceHelper::SnrPer const &', 'arg0')])
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer::per [variable]
cls.add_instance_attribute('per', 'double', is_const=False)
## interference-helper.h (module 'wifi'): ns3::InterferenceHelper::SnrPer::snr [variable]
cls.add_instance_attribute('snr', 'double', is_const=False)
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'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function]
cls.add_method('GetIpv4MappedAddress',
'ns3::Ipv4Address',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Address',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function]
cls.add_method('IsAllHostsMulticast',
'bool',
[],
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::IsIpv4MappedAddress() [member function]
cls.add_method('IsIpv4MappedAddress',
'bool',
[])
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function]
cls.add_method('IsLinkLocal',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function]
cls.add_method('IsLinkLocalMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function]
cls.add_method('IsSolicitedMulticast',
'bool',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::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::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function]
cls.add_method('MakeIpv4MappedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv4Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function]
cls.add_method('MakeSolicitedAddress',
'ns3::Ipv6Address',
[param('ns3::Ipv6Address', 'addr')],
is_static=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function]
cls.add_method('Set',
'void',
[param('uint8_t *', 'address')])
return
def register_Ns3Ipv6Prefix_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor]
cls.add_constructor([])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor]
cls.add_constructor([param('uint8_t *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor]
cls.add_constructor([param('char const *', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor]
cls.add_constructor([param('uint8_t', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor]
cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')])
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function]
cls.add_method('GetBytes',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function]
cls.add_method('GetOnes',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint8_t',
[],
is_const=True)
## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv6Prefix',
[],
is_static=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv6Prefix const &', 'other')],
is_const=True)
## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function]
cls.add_method('IsMatch',
'bool',
[param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')],
is_const=True)
## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
return
def register_Ns3Mac48Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac48Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv4Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv6Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function]
cls.add_method('GetMulticast6Prefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function]
cls.add_method('GetMulticastPrefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function]
cls.add_method('IsGroup',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3MacLowBlockAckEventListener_methods(root_module, cls):
## mac-low.h (module 'wifi'): ns3::MacLowBlockAckEventListener::MacLowBlockAckEventListener(ns3::MacLowBlockAckEventListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLowBlockAckEventListener const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLowBlockAckEventListener::MacLowBlockAckEventListener() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): void ns3::MacLowBlockAckEventListener::BlockAckInactivityTimeout(ns3::Mac48Address originator, uint8_t tid) [member function]
cls.add_method('BlockAckInactivityTimeout',
'void',
[param('ns3::Mac48Address', 'originator'), param('uint8_t', 'tid')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3MacLowDcfListener_methods(root_module, cls):
## mac-low.h (module 'wifi'): ns3::MacLowDcfListener::MacLowDcfListener(ns3::MacLowDcfListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLowDcfListener const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLowDcfListener::MacLowDcfListener() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::AckTimeoutReset() [member function]
cls.add_method('AckTimeoutReset',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::AckTimeoutStart(ns3::Time duration) [member function]
cls.add_method('AckTimeoutStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::CtsTimeoutReset() [member function]
cls.add_method('CtsTimeoutReset',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::CtsTimeoutStart(ns3::Time duration) [member function]
cls.add_method('CtsTimeoutStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::NavReset(ns3::Time duration) [member function]
cls.add_method('NavReset',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowDcfListener::NavStart(ns3::Time duration) [member function]
cls.add_method('NavStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3MacLowTransmissionListener_methods(root_module, cls):
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionListener::MacLowTransmissionListener(ns3::MacLowTransmissionListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLowTransmissionListener const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionListener::MacLowTransmissionListener() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::Cancel() [member function]
cls.add_method('Cancel',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::EndTxNoAck() [member function]
cls.add_method('EndTxNoAck',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::GotAck(double snr, ns3::WifiMode txMode) [member function]
cls.add_method('GotAck',
'void',
[param('double', 'snr'), param('ns3::WifiMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::GotBlockAck(ns3::CtrlBAckResponseHeader const * blockAck, ns3::Mac48Address source) [member function]
cls.add_method('GotBlockAck',
'void',
[param('ns3::CtrlBAckResponseHeader const *', 'blockAck'), param('ns3::Mac48Address', 'source')],
is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::GotCts(double snr, ns3::WifiMode txMode) [member function]
cls.add_method('GotCts',
'void',
[param('double', 'snr'), param('ns3::WifiMode', 'txMode')],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::MissedAck() [member function]
cls.add_method('MissedAck',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::MissedBlockAck() [member function]
cls.add_method('MissedBlockAck',
'void',
[],
is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::MissedCts() [member function]
cls.add_method('MissedCts',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionListener::StartNext() [member function]
cls.add_method('StartNext',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3MacLowTransmissionParameters_methods(root_module, cls):
cls.add_output_stream_operator()
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionParameters::MacLowTransmissionParameters(ns3::MacLowTransmissionParameters const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLowTransmissionParameters const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLowTransmissionParameters::MacLowTransmissionParameters() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::DisableAck() [member function]
cls.add_method('DisableAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::DisableNextData() [member function]
cls.add_method('DisableNextData',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::DisableOverrideDurationId() [member function]
cls.add_method('DisableOverrideDurationId',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::DisableRts() [member function]
cls.add_method('DisableRts',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableAck() [member function]
cls.add_method('EnableAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableBasicBlockAck() [member function]
cls.add_method('EnableBasicBlockAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableCompressedBlockAck() [member function]
cls.add_method('EnableCompressedBlockAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableFastAck() [member function]
cls.add_method('EnableFastAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableMultiTidBlockAck() [member function]
cls.add_method('EnableMultiTidBlockAck',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableNextData(uint32_t size) [member function]
cls.add_method('EnableNextData',
'void',
[param('uint32_t', 'size')])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableOverrideDurationId(ns3::Time durationId) [member function]
cls.add_method('EnableOverrideDurationId',
'void',
[param('ns3::Time', 'durationId')])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableRts() [member function]
cls.add_method('EnableRts',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLowTransmissionParameters::EnableSuperFastAck() [member function]
cls.add_method('EnableSuperFastAck',
'void',
[])
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLowTransmissionParameters::GetDurationId() const [member function]
cls.add_method('GetDurationId',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): uint32_t ns3::MacLowTransmissionParameters::GetNextPacketSize() const [member function]
cls.add_method('GetNextPacketSize',
'uint32_t',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::HasDurationId() const [member function]
cls.add_method('HasDurationId',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::HasNextPacket() const [member function]
cls.add_method('HasNextPacket',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustSendRts() const [member function]
cls.add_method('MustSendRts',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitAck() const [member function]
cls.add_method('MustWaitAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitBasicBlockAck() const [member function]
cls.add_method('MustWaitBasicBlockAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitCompressedBlockAck() const [member function]
cls.add_method('MustWaitCompressedBlockAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitFastAck() const [member function]
cls.add_method('MustWaitFastAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitMultiTidBlockAck() const [member function]
cls.add_method('MustWaitMultiTidBlockAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitNormalAck() const [member function]
cls.add_method('MustWaitNormalAck',
'bool',
[],
is_const=True)
## mac-low.h (module 'wifi'): bool ns3::MacLowTransmissionParameters::MustWaitSuperFastAck() const [member function]
cls.add_method('MustWaitSuperFastAck',
'bool',
[],
is_const=True)
return
def register_Ns3MacRxMiddle_methods(root_module, cls):
## mac-rx-middle.h (module 'wifi'): ns3::MacRxMiddle::MacRxMiddle(ns3::MacRxMiddle const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacRxMiddle const &', 'arg0')])
## mac-rx-middle.h (module 'wifi'): ns3::MacRxMiddle::MacRxMiddle() [constructor]
cls.add_constructor([])
## mac-rx-middle.h (module 'wifi'): void ns3::MacRxMiddle::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')])
## mac-rx-middle.h (module 'wifi'): void ns3::MacRxMiddle::SetForwardCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::WifiMacHeader const*, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetForwardCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::WifiMacHeader const *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
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_Ns3OriginatorBlockAckAgreement_methods(root_module, cls):
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement::OriginatorBlockAckAgreement(ns3::OriginatorBlockAckAgreement const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OriginatorBlockAckAgreement const &', 'arg0')])
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement::OriginatorBlockAckAgreement() [constructor]
cls.add_constructor([])
## originator-block-ack-agreement.h (module 'wifi'): ns3::OriginatorBlockAckAgreement::OriginatorBlockAckAgreement(ns3::Mac48Address recipient, uint8_t tid) [constructor]
cls.add_constructor([param('ns3::Mac48Address', 'recipient'), param('uint8_t', 'tid')])
## originator-block-ack-agreement.h (module 'wifi'): void ns3::OriginatorBlockAckAgreement::CompleteExchange() [member function]
cls.add_method('CompleteExchange',
'void',
[])
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsBlockAckRequestNeeded() const [member function]
cls.add_method('IsBlockAckRequestNeeded',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsEstablished() const [member function]
cls.add_method('IsEstablished',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsInactive() const [member function]
cls.add_method('IsInactive',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsPending() const [member function]
cls.add_method('IsPending',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): bool ns3::OriginatorBlockAckAgreement::IsUnsuccessful() const [member function]
cls.add_method('IsUnsuccessful',
'bool',
[],
is_const=True)
## originator-block-ack-agreement.h (module 'wifi'): void ns3::OriginatorBlockAckAgreement::NotifyMpduTransmission(uint16_t nextSeqNumber) [member function]
cls.add_method('NotifyMpduTransmission',
'void',
[param('uint16_t', 'nextSeqNumber')])
## originator-block-ack-agreement.h (module 'wifi'): void ns3::OriginatorBlockAckAgreement::SetState(ns3::OriginatorBlockAckAgreement::State state) [member function]
cls.add_method('SetState',
'void',
[param('ns3::OriginatorBlockAckAgreement::State', 'state')])
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_Ns3PcapFile_methods(root_module, cls):
## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor]
cls.add_constructor([])
## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT) [member function]
cls.add_method('Diff',
'bool',
[param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint32_t &', 'sec'), param('uint32_t &', 'usec'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT')],
is_static=True)
## pcap-file.h (module 'network'): bool ns3::PcapFile::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## pcap-file.h (module 'network'): bool ns3::PcapFile::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetDataLinkType() [member function]
cls.add_method('GetDataLinkType',
'uint32_t',
[])
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetMagic() [member function]
cls.add_method('GetMagic',
'uint32_t',
[])
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSigFigs() [member function]
cls.add_method('GetSigFigs',
'uint32_t',
[])
## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSnapLen() [member function]
cls.add_method('GetSnapLen',
'uint32_t',
[])
## pcap-file.h (module 'network'): bool ns3::PcapFile::GetSwapMode() [member function]
cls.add_method('GetSwapMode',
'bool',
[])
## pcap-file.h (module 'network'): int32_t ns3::PcapFile::GetTimeZoneOffset() [member function]
cls.add_method('GetTimeZoneOffset',
'int32_t',
[])
## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMajor() [member function]
cls.add_method('GetVersionMajor',
'uint16_t',
[])
## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMinor() [member function]
cls.add_method('GetVersionMinor',
'uint16_t',
[])
## pcap-file.h (module 'network'): void ns3::PcapFile::Init(uint32_t dataLinkType, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT, int32_t timeZoneCorrection=ns3::PcapFile::ZONE_DEFAULT, bool swapMode=false) [member function]
cls.add_method('Init',
'void',
[param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT'), param('int32_t', 'timeZoneCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT'), param('bool', 'swapMode', default_value='false')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Read(uint8_t * const data, uint32_t maxBytes, uint32_t & tsSec, uint32_t & tsUsec, uint32_t & inclLen, uint32_t & origLen, uint32_t & readLen) [member function]
cls.add_method('Read',
'void',
[param('uint8_t * const', 'data'), param('uint32_t', 'maxBytes'), param('uint32_t &', 'tsSec'), param('uint32_t &', 'tsUsec'), param('uint32_t &', 'inclLen'), param('uint32_t &', 'origLen'), param('uint32_t &', 'readLen')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, uint8_t const * const data, uint32_t totalLen) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('uint8_t const * const', 'data'), param('uint32_t', 'totalLen')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Header & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file.h (module 'network'): ns3::PcapFile::SNAPLEN_DEFAULT [variable]
cls.add_static_attribute('SNAPLEN_DEFAULT', 'uint32_t const', is_const=True)
## pcap-file.h (module 'network'): ns3::PcapFile::ZONE_DEFAULT [variable]
cls.add_static_attribute('ZONE_DEFAULT', 'int32_t const', is_const=True)
return
def register_Ns3PcapHelper_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper(ns3::PcapHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PcapHelper const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): ns3::Ptr<ns3::PcapFileWrapper> ns3::PcapHelper::CreateFile(std::string filename, std::_Ios_Openmode filemode, uint32_t dataLinkType, uint32_t snapLen=65535, int32_t tzCorrection=0) [member function]
cls.add_method('CreateFile',
'ns3::Ptr< ns3::PcapFileWrapper >',
[param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode'), param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='65535'), param('int32_t', 'tzCorrection', default_value='0')])
## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromDevice',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')])
## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromInterfacePair',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')])
return
def register_Ns3PcapHelperForDevice_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function]
cls.add_method('EnablePcapAll',
'void',
[param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function]
cls.add_method('EnablePcapInternal',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3PropagationCache__Ns3JakesProcess_methods(root_module, cls):
## propagation-cache.h (module 'propagation'): ns3::PropagationCache<ns3::JakesProcess>::PropagationCache(ns3::PropagationCache<ns3::JakesProcess> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PropagationCache< ns3::JakesProcess > const &', 'arg0')])
## propagation-cache.h (module 'propagation'): ns3::PropagationCache<ns3::JakesProcess>::PropagationCache() [constructor]
cls.add_constructor([])
## propagation-cache.h (module 'propagation'): void ns3::PropagationCache<ns3::JakesProcess>::AddPathData(ns3::Ptr<ns3::JakesProcess> data, ns3::Ptr<ns3::MobilityModel const> a, ns3::Ptr<ns3::MobilityModel const> b, uint32_t modelUid) [member function]
cls.add_method('AddPathData',
'void',
[param('ns3::Ptr< ns3::JakesProcess >', 'data'), param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b'), param('uint32_t', 'modelUid')])
## propagation-cache.h (module 'propagation'): ns3::Ptr<ns3::JakesProcess> ns3::PropagationCache<ns3::JakesProcess>::GetPathData(ns3::Ptr<ns3::MobilityModel const> a, ns3::Ptr<ns3::MobilityModel const> b, uint32_t modelUid) [member function]
cls.add_method('GetPathData',
'ns3::Ptr< ns3::JakesProcess >',
[param('ns3::Ptr< ns3::MobilityModel const >', 'a'), param('ns3::Ptr< ns3::MobilityModel const >', 'b'), param('uint32_t', 'modelUid')])
return
def register_Ns3RateInfo_methods(root_module, cls):
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::RateInfo() [constructor]
cls.add_constructor([])
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::RateInfo(ns3::RateInfo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RateInfo const &', 'arg0')])
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::adjustedRetryCount [variable]
cls.add_instance_attribute('adjustedRetryCount', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::attemptHist [variable]
cls.add_instance_attribute('attemptHist', 'uint64_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::ewmaProb [variable]
cls.add_instance_attribute('ewmaProb', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::numRateAttempt [variable]
cls.add_instance_attribute('numRateAttempt', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::numRateSuccess [variable]
cls.add_instance_attribute('numRateSuccess', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::perfectTxTime [variable]
cls.add_instance_attribute('perfectTxTime', 'ns3::Time', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::prevNumRateAttempt [variable]
cls.add_instance_attribute('prevNumRateAttempt', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::prevNumRateSuccess [variable]
cls.add_instance_attribute('prevNumRateSuccess', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::prob [variable]
cls.add_instance_attribute('prob', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::retryCount [variable]
cls.add_instance_attribute('retryCount', 'uint32_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::successHist [variable]
cls.add_instance_attribute('successHist', 'uint64_t', is_const=False)
## minstrel-wifi-manager.h (module 'wifi'): ns3::RateInfo::throughput [variable]
cls.add_instance_attribute('throughput', 'uint32_t', is_const=False)
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function]
cls.add_method('SetImplementation',
'void',
[param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'time')],
is_static=True)
return
def register_Ns3StatusCode_methods(root_module, cls):
cls.add_output_stream_operator()
## status-code.h (module 'wifi'): ns3::StatusCode::StatusCode(ns3::StatusCode const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StatusCode const &', 'arg0')])
## status-code.h (module 'wifi'): ns3::StatusCode::StatusCode() [constructor]
cls.add_constructor([])
## status-code.h (module 'wifi'): ns3::Buffer::Iterator ns3::StatusCode::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')])
## status-code.h (module 'wifi'): uint32_t ns3::StatusCode::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## status-code.h (module 'wifi'): bool ns3::StatusCode::IsSuccess() const [member function]
cls.add_method('IsSuccess',
'bool',
[],
is_const=True)
## status-code.h (module 'wifi'): ns3::Buffer::Iterator ns3::StatusCode::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## status-code.h (module 'wifi'): void ns3::StatusCode::SetFailure() [member function]
cls.add_method('SetFailure',
'void',
[])
## status-code.h (module 'wifi'): void ns3::StatusCode::SetSuccess() [member function]
cls.add_method('SetSuccess',
'void',
[])
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [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_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', transfer_ownership=False)],
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_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_Ns3WifiHelper_methods(root_module, cls):
## wifi-helper.h (module 'wifi'): ns3::WifiHelper::WifiHelper(ns3::WifiHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiHelper const &', 'arg0')])
## wifi-helper.h (module 'wifi'): ns3::WifiHelper::WifiHelper() [constructor]
cls.add_constructor([])
## wifi-helper.h (module 'wifi'): int64_t ns3::WifiHelper::AssignStreams(ns3::NetDeviceContainer c, int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('ns3::NetDeviceContainer', 'c'), param('int64_t', 'stream')])
## wifi-helper.h (module 'wifi'): static ns3::WifiHelper ns3::WifiHelper::Default() [member function]
cls.add_method('Default',
'ns3::WifiHelper',
[],
is_static=True)
## wifi-helper.h (module 'wifi'): static void ns3::WifiHelper::EnableLogComponents() [member function]
cls.add_method('EnableLogComponents',
'void',
[],
is_static=True)
## wifi-helper.h (module 'wifi'): ns3::NetDeviceContainer ns3::WifiHelper::Install(ns3::WifiPhyHelper const & phy, ns3::WifiMacHelper const & mac, ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::WifiPhyHelper const &', 'phy'), param('ns3::WifiMacHelper const &', 'mac'), param('ns3::NodeContainer', 'c')],
is_const=True)
## wifi-helper.h (module 'wifi'): ns3::NetDeviceContainer ns3::WifiHelper::Install(ns3::WifiPhyHelper const & phy, ns3::WifiMacHelper const & mac, ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::WifiPhyHelper const &', 'phy'), param('ns3::WifiMacHelper const &', 'mac'), param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## wifi-helper.h (module 'wifi'): ns3::NetDeviceContainer ns3::WifiHelper::Install(ns3::WifiPhyHelper const & phy, ns3::WifiMacHelper const & mac, std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::WifiPhyHelper const &', 'phy'), param('ns3::WifiMacHelper const &', 'mac'), param('std::string', 'nodeName')],
is_const=True)
## wifi-helper.h (module 'wifi'): void ns3::WifiHelper::SetRemoteStationManager(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('SetRemoteStationManager',
'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()')])
## wifi-helper.h (module 'wifi'): void ns3::WifiHelper::SetStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('SetStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')])
return
def register_Ns3WifiMacHelper_methods(root_module, cls):
## wifi-helper.h (module 'wifi'): ns3::WifiMacHelper::WifiMacHelper() [constructor]
cls.add_constructor([])
## wifi-helper.h (module 'wifi'): ns3::WifiMacHelper::WifiMacHelper(ns3::WifiMacHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMacHelper const &', 'arg0')])
## wifi-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiMac> ns3::WifiMacHelper::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiMac >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3WifiMode_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode(ns3::WifiMode const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMode const &', 'arg0')])
## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode() [constructor]
cls.add_constructor([])
## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode(std::string name) [constructor]
cls.add_constructor([param('std::string', 'name')])
## wifi-mode.h (module 'wifi'): uint32_t ns3::WifiMode::GetBandwidth() const [member function]
cls.add_method('GetBandwidth',
'uint32_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): ns3::WifiCodeRate ns3::WifiMode::GetCodeRate() const [member function]
cls.add_method('GetCodeRate',
'ns3::WifiCodeRate',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint8_t ns3::WifiMode::GetConstellationSize() const [member function]
cls.add_method('GetConstellationSize',
'uint8_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint64_t ns3::WifiMode::GetDataRate() const [member function]
cls.add_method('GetDataRate',
'uint64_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): ns3::WifiModulationClass ns3::WifiMode::GetModulationClass() const [member function]
cls.add_method('GetModulationClass',
'ns3::WifiModulationClass',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint64_t ns3::WifiMode::GetPhyRate() const [member function]
cls.add_method('GetPhyRate',
'uint64_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): uint32_t ns3::WifiMode::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): std::string ns3::WifiMode::GetUniqueName() const [member function]
cls.add_method('GetUniqueName',
'std::string',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): bool ns3::WifiMode::IsMandatory() const [member function]
cls.add_method('IsMandatory',
'bool',
[],
is_const=True)
return
def register_Ns3WifiModeFactory_methods(root_module, cls):
## wifi-mode.h (module 'wifi'): ns3::WifiModeFactory::WifiModeFactory(ns3::WifiModeFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiModeFactory const &', 'arg0')])
## wifi-mode.h (module 'wifi'): static ns3::WifiMode ns3::WifiModeFactory::CreateWifiMode(std::string uniqueName, ns3::WifiModulationClass modClass, bool isMandatory, uint32_t bandwidth, uint32_t dataRate, ns3::WifiCodeRate codingRate, uint8_t constellationSize) [member function]
cls.add_method('CreateWifiMode',
'ns3::WifiMode',
[param('std::string', 'uniqueName'), param('ns3::WifiModulationClass', 'modClass'), param('bool', 'isMandatory'), param('uint32_t', 'bandwidth'), param('uint32_t', 'dataRate'), param('ns3::WifiCodeRate', 'codingRate'), param('uint8_t', 'constellationSize')],
is_static=True)
return
def register_Ns3WifiPhyHelper_methods(root_module, cls):
## wifi-helper.h (module 'wifi'): ns3::WifiPhyHelper::WifiPhyHelper() [constructor]
cls.add_constructor([])
## wifi-helper.h (module 'wifi'): ns3::WifiPhyHelper::WifiPhyHelper(ns3::WifiPhyHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiPhyHelper const &', 'arg0')])
## wifi-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiPhy> ns3::WifiPhyHelper::Create(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::WifiNetDevice> device) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiPhy >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::WifiNetDevice >', 'device')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3WifiPhyListener_methods(root_module, cls):
## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener::WifiPhyListener() [constructor]
cls.add_constructor([])
## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener::WifiPhyListener(ns3::WifiPhyListener const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiPhyListener const &', 'arg0')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyMaybeCcaBusyStart(ns3::Time duration) [member function]
cls.add_method('NotifyMaybeCcaBusyStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxEndError() [member function]
cls.add_method('NotifyRxEndError',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxEndOk() [member function]
cls.add_method('NotifyRxEndOk',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxStart(ns3::Time duration) [member function]
cls.add_method('NotifyRxStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifySwitchingStart(ns3::Time duration) [member function]
cls.add_method('NotifySwitchingStart',
'void',
[param('ns3::Time', 'duration')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::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_Ns3WifiRemoteStation_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::WifiRemoteStation() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::WifiRemoteStation(ns3::WifiRemoteStation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStation const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_slrc [variable]
cls.add_instance_attribute('m_slrc', 'uint32_t', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_ssrc [variable]
cls.add_instance_attribute('m_ssrc', 'uint32_t', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_state [variable]
cls.add_instance_attribute('m_state', 'ns3::WifiRemoteStationState *', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation::m_tid [variable]
cls.add_instance_attribute('m_tid', 'uint8_t', is_const=False)
return
def register_Ns3WifiRemoteStationInfo_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo::WifiRemoteStationInfo(ns3::WifiRemoteStationInfo const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStationInfo const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo::WifiRemoteStationInfo() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): double ns3::WifiRemoteStationInfo::GetFrameErrorRate() const [member function]
cls.add_method('GetFrameErrorRate',
'double',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationInfo::NotifyTxFailed() [member function]
cls.add_method('NotifyTxFailed',
'void',
[])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationInfo::NotifyTxSuccess(uint32_t retryCounter) [member function]
cls.add_method('NotifyTxSuccess',
'void',
[param('uint32_t', 'retryCounter')])
return
def register_Ns3WifiRemoteStationState_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::WifiRemoteStationState() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::WifiRemoteStationState(ns3::WifiRemoteStationState const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStationState const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::m_address [variable]
cls.add_instance_attribute('m_address', 'ns3::Mac48Address', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::m_info [variable]
cls.add_instance_attribute('m_info', 'ns3::WifiRemoteStationInfo', is_const=False)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationState::m_operationalRateSet [variable]
cls.add_instance_attribute('m_operationalRateSet', 'ns3::WifiModeList', is_const=False)
return
def register_Ns3YansWifiChannelHelper_methods(root_module, cls):
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiChannelHelper::YansWifiChannelHelper(ns3::YansWifiChannelHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::YansWifiChannelHelper const &', 'arg0')])
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiChannelHelper::YansWifiChannelHelper() [constructor]
cls.add_constructor([])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiChannelHelper::AddPropagationLoss(std::string name, 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('AddPropagationLoss',
'void',
[param('std::string', 'name'), 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()')])
## yans-wifi-helper.h (module 'wifi'): int64_t ns3::YansWifiChannelHelper::AssignStreams(ns3::Ptr<ns3::YansWifiChannel> c, int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('ns3::Ptr< ns3::YansWifiChannel >', 'c'), param('int64_t', 'stream')])
## yans-wifi-helper.h (module 'wifi'): ns3::Ptr<ns3::YansWifiChannel> ns3::YansWifiChannelHelper::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::YansWifiChannel >',
[],
is_const=True)
## yans-wifi-helper.h (module 'wifi'): static ns3::YansWifiChannelHelper ns3::YansWifiChannelHelper::Default() [member function]
cls.add_method('Default',
'ns3::YansWifiChannelHelper',
[],
is_static=True)
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiChannelHelper::SetPropagationDelay(std::string name, 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('SetPropagationDelay',
'void',
[param('std::string', 'name'), 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_Ns3YansWifiPhyHelper_methods(root_module, cls):
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiPhyHelper::YansWifiPhyHelper(ns3::YansWifiPhyHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::YansWifiPhyHelper const &', 'arg0')])
## yans-wifi-helper.h (module 'wifi'): ns3::YansWifiPhyHelper::YansWifiPhyHelper() [constructor]
cls.add_constructor([])
## yans-wifi-helper.h (module 'wifi'): static ns3::YansWifiPhyHelper ns3::YansWifiPhyHelper::Default() [member function]
cls.add_method('Default',
'ns3::YansWifiPhyHelper',
[],
is_static=True)
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::Set(std::string name, ns3::AttributeValue const & v) [member function]
cls.add_method('Set',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::SetChannel(ns3::Ptr<ns3::YansWifiChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::YansWifiChannel >', 'channel')])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::SetChannel(std::string channelName) [member function]
cls.add_method('SetChannel',
'void',
[param('std::string', 'channelName')])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::SetErrorRateModel(std::string name, 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('SetErrorRateModel',
'void',
[param('std::string', 'name'), 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()')])
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::SetPcapDataLinkType(ns3::YansWifiPhyHelper::SupportedPcapDataLinkTypes dlt) [member function]
cls.add_method('SetPcapDataLinkType',
'void',
[param('ns3::YansWifiPhyHelper::SupportedPcapDataLinkTypes', 'dlt')])
## yans-wifi-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiPhy> ns3::YansWifiPhyHelper::Create(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::WifiNetDevice> device) const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiPhy >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::WifiNetDevice >', 'device')],
is_const=True, visibility='private', is_virtual=True)
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function]
cls.add_method('EnableAsciiInternal',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')],
visibility='private', is_virtual=True)
## yans-wifi-helper.h (module 'wifi'): void ns3::YansWifiPhyHelper::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function]
cls.add_method('EnablePcapInternal',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')],
visibility='private', is_virtual=True)
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_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right'))
cls.add_binary_comparison_operator('!=')
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_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_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_Ns3MgtAddBaRequestHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaRequestHeader::MgtAddBaRequestHeader(ns3::MgtAddBaRequestHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtAddBaRequestHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaRequestHeader::MgtAddBaRequestHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAddBaRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaRequestHeader::GetBufferSize() const [member function]
cls.add_method('GetBufferSize',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtAddBaRequestHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAddBaRequestHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaRequestHeader::GetStartingSequence() const [member function]
cls.add_method('GetStartingSequence',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint8_t ns3::MgtAddBaRequestHeader::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaRequestHeader::GetTimeout() const [member function]
cls.add_method('GetTimeout',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtAddBaRequestHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtAddBaRequestHeader::IsAmsduSupported() const [member function]
cls.add_method('IsAmsduSupported',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtAddBaRequestHeader::IsImmediateBlockAck() const [member function]
cls.add_method('IsImmediateBlockAck',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetAmsduSupport(bool supported) [member function]
cls.add_method('SetAmsduSupport',
'void',
[param('bool', 'supported')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetBufferSize(uint16_t size) [member function]
cls.add_method('SetBufferSize',
'void',
[param('uint16_t', 'size')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetDelayedBlockAck() [member function]
cls.add_method('SetDelayedBlockAck',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetImmediateBlockAck() [member function]
cls.add_method('SetImmediateBlockAck',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetStartingSequence(uint16_t seq) [member function]
cls.add_method('SetStartingSequence',
'void',
[param('uint16_t', 'seq')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetTid(uint8_t tid) [member function]
cls.add_method('SetTid',
'void',
[param('uint8_t', 'tid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaRequestHeader::SetTimeout(uint16_t timeout) [member function]
cls.add_method('SetTimeout',
'void',
[param('uint16_t', 'timeout')])
return
def register_Ns3MgtAddBaResponseHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaResponseHeader::MgtAddBaResponseHeader(ns3::MgtAddBaResponseHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtAddBaResponseHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtAddBaResponseHeader::MgtAddBaResponseHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAddBaResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaResponseHeader::GetBufferSize() const [member function]
cls.add_method('GetBufferSize',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtAddBaResponseHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAddBaResponseHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::StatusCode ns3::MgtAddBaResponseHeader::GetStatusCode() const [member function]
cls.add_method('GetStatusCode',
'ns3::StatusCode',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint8_t ns3::MgtAddBaResponseHeader::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAddBaResponseHeader::GetTimeout() const [member function]
cls.add_method('GetTimeout',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtAddBaResponseHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtAddBaResponseHeader::IsAmsduSupported() const [member function]
cls.add_method('IsAmsduSupported',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtAddBaResponseHeader::IsImmediateBlockAck() const [member function]
cls.add_method('IsImmediateBlockAck',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetAmsduSupport(bool supported) [member function]
cls.add_method('SetAmsduSupport',
'void',
[param('bool', 'supported')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetBufferSize(uint16_t size) [member function]
cls.add_method('SetBufferSize',
'void',
[param('uint16_t', 'size')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetDelayedBlockAck() [member function]
cls.add_method('SetDelayedBlockAck',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetImmediateBlockAck() [member function]
cls.add_method('SetImmediateBlockAck',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetStatusCode(ns3::StatusCode code) [member function]
cls.add_method('SetStatusCode',
'void',
[param('ns3::StatusCode', 'code')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetTid(uint8_t tid) [member function]
cls.add_method('SetTid',
'void',
[param('uint8_t', 'tid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAddBaResponseHeader::SetTimeout(uint16_t timeout) [member function]
cls.add_method('SetTimeout',
'void',
[param('uint16_t', 'timeout')])
return
def register_Ns3MgtAssocRequestHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtAssocRequestHeader::MgtAssocRequestHeader(ns3::MgtAssocRequestHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtAssocRequestHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtAssocRequestHeader::MgtAssocRequestHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAssocRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtAssocRequestHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint16_t ns3::MgtAssocRequestHeader::GetListenInterval() const [member function]
cls.add_method('GetListenInterval',
'uint16_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAssocRequestHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::Ssid ns3::MgtAssocRequestHeader::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::SupportedRates ns3::MgtAssocRequestHeader::GetSupportedRates() const [member function]
cls.add_method('GetSupportedRates',
'ns3::SupportedRates',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtAssocRequestHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::SetListenInterval(uint16_t interval) [member function]
cls.add_method('SetListenInterval',
'void',
[param('uint16_t', 'interval')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocRequestHeader::SetSupportedRates(ns3::SupportedRates rates) [member function]
cls.add_method('SetSupportedRates',
'void',
[param('ns3::SupportedRates', 'rates')])
return
def register_Ns3MgtAssocResponseHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtAssocResponseHeader::MgtAssocResponseHeader(ns3::MgtAssocResponseHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtAssocResponseHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtAssocResponseHeader::MgtAssocResponseHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAssocResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtAssocResponseHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtAssocResponseHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::StatusCode ns3::MgtAssocResponseHeader::GetStatusCode() [member function]
cls.add_method('GetStatusCode',
'ns3::StatusCode',
[])
## mgt-headers.h (module 'wifi'): ns3::SupportedRates ns3::MgtAssocResponseHeader::GetSupportedRates() [member function]
cls.add_method('GetSupportedRates',
'ns3::SupportedRates',
[])
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtAssocResponseHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocResponseHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocResponseHeader::SetStatusCode(ns3::StatusCode code) [member function]
cls.add_method('SetStatusCode',
'void',
[param('ns3::StatusCode', 'code')])
## mgt-headers.h (module 'wifi'): void ns3::MgtAssocResponseHeader::SetSupportedRates(ns3::SupportedRates rates) [member function]
cls.add_method('SetSupportedRates',
'void',
[param('ns3::SupportedRates', 'rates')])
return
def register_Ns3MgtDelBaHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtDelBaHeader::MgtDelBaHeader(ns3::MgtDelBaHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtDelBaHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtDelBaHeader::MgtDelBaHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtDelBaHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtDelBaHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtDelBaHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint8_t ns3::MgtDelBaHeader::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtDelBaHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): bool ns3::MgtDelBaHeader::IsByOriginator() const [member function]
cls.add_method('IsByOriginator',
'bool',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::SetByOriginator() [member function]
cls.add_method('SetByOriginator',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::SetByRecipient() [member function]
cls.add_method('SetByRecipient',
'void',
[])
## mgt-headers.h (module 'wifi'): void ns3::MgtDelBaHeader::SetTid(uint8_t arg0) [member function]
cls.add_method('SetTid',
'void',
[param('uint8_t', 'arg0')])
return
def register_Ns3MgtProbeRequestHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtProbeRequestHeader::MgtProbeRequestHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): ns3::MgtProbeRequestHeader::MgtProbeRequestHeader(ns3::MgtProbeRequestHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtProbeRequestHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtProbeRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtProbeRequestHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtProbeRequestHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::Ssid ns3::MgtProbeRequestHeader::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::SupportedRates ns3::MgtProbeRequestHeader::GetSupportedRates() const [member function]
cls.add_method('GetSupportedRates',
'ns3::SupportedRates',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtProbeRequestHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeRequestHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeRequestHeader::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeRequestHeader::SetSupportedRates(ns3::SupportedRates rates) [member function]
cls.add_method('SetSupportedRates',
'void',
[param('ns3::SupportedRates', 'rates')])
return
def register_Ns3MgtProbeResponseHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtProbeResponseHeader::MgtProbeResponseHeader(ns3::MgtProbeResponseHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtProbeResponseHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::MgtProbeResponseHeader::MgtProbeResponseHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtProbeResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): uint64_t ns3::MgtProbeResponseHeader::GetBeaconIntervalUs() const [member function]
cls.add_method('GetBeaconIntervalUs',
'uint64_t',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::MgtProbeResponseHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::MgtProbeResponseHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::Ssid ns3::MgtProbeResponseHeader::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): ns3::SupportedRates ns3::MgtProbeResponseHeader::GetSupportedRates() const [member function]
cls.add_method('GetSupportedRates',
'ns3::SupportedRates',
[],
is_const=True)
## mgt-headers.h (module 'wifi'): uint64_t ns3::MgtProbeResponseHeader::GetTimestamp() [member function]
cls.add_method('GetTimestamp',
'uint64_t',
[])
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::MgtProbeResponseHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::SetBeaconIntervalUs(uint64_t us) [member function]
cls.add_method('SetBeaconIntervalUs',
'void',
[param('uint64_t', 'us')])
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')])
## mgt-headers.h (module 'wifi'): void ns3::MgtProbeResponseHeader::SetSupportedRates(ns3::SupportedRates rates) [member function]
cls.add_method('SetSupportedRates',
'void',
[param('ns3::SupportedRates', 'rates')])
return
def register_Ns3NqosWifiMacHelper_methods(root_module, cls):
## nqos-wifi-mac-helper.h (module 'wifi'): ns3::NqosWifiMacHelper::NqosWifiMacHelper(ns3::NqosWifiMacHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NqosWifiMacHelper const &', 'arg0')])
## nqos-wifi-mac-helper.h (module 'wifi'): ns3::NqosWifiMacHelper::NqosWifiMacHelper() [constructor]
cls.add_constructor([])
## nqos-wifi-mac-helper.h (module 'wifi'): static ns3::NqosWifiMacHelper ns3::NqosWifiMacHelper::Default() [member function]
cls.add_method('Default',
'ns3::NqosWifiMacHelper',
[],
is_static=True)
## nqos-wifi-mac-helper.h (module 'wifi'): void ns3::NqosWifiMacHelper::SetType(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('SetType',
'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()')])
## nqos-wifi-mac-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiMac> ns3::NqosWifiMacHelper::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiMac >',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Object_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::Object() [constructor]
cls.add_constructor([])
## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function]
cls.add_method('AggregateObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'other')])
## object.h (module 'core'): void ns3::Object::Dispose() [member function]
cls.add_method('Dispose',
'void',
[])
## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function]
cls.add_method('GetAggregateIterator',
'ns3::Object::AggregateIterator',
[],
is_const=True)
## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object.h (module 'core'): void ns3::Object::Initialize() [member function]
cls.add_method('Initialize',
'void',
[])
## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor]
cls.add_constructor([param('ns3::Object const &', 'o')],
visibility='protected')
## object.h (module 'core'): void ns3::Object::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectAggregateIterator_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')])
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor]
cls.add_constructor([])
## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function]
cls.add_method('Next',
'ns3::Ptr< ns3::Object const >',
[])
return
def register_Ns3PcapFileWrapper_methods(root_module, cls):
## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor]
cls.add_constructor([])
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function]
cls.add_method('Init',
'void',
[param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Header & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function]
cls.add_method('GetMagic',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function]
cls.add_method('GetVersionMajor',
'uint16_t',
[])
## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function]
cls.add_method('GetVersionMinor',
'uint16_t',
[])
## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function]
cls.add_method('GetTimeZoneOffset',
'int32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function]
cls.add_method('GetSigFigs',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function]
cls.add_method('GetSnapLen',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function]
cls.add_method('GetDataLinkType',
'uint32_t',
[])
return
def register_Ns3PropagationDelayModel_methods(root_module, cls):
## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel::PropagationDelayModel() [constructor]
cls.add_constructor([])
## propagation-delay-model.h (module 'propagation'): ns3::PropagationDelayModel::PropagationDelayModel(ns3::PropagationDelayModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PropagationDelayModel const &', 'arg0')])
## propagation-delay-model.h (module 'propagation'): int64_t ns3::PropagationDelayModel::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::PropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::PropagationDelayModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-delay-model.h (module 'propagation'): int64_t ns3::PropagationDelayModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3PropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::PropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::PropagationLossModel::PropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::PropagationLossModel::SetNext(ns3::Ptr<ns3::PropagationLossModel> next) [member function]
cls.add_method('SetNext',
'void',
[param('ns3::Ptr< ns3::PropagationLossModel >', 'next')])
## propagation-loss-model.h (module 'propagation'): ns3::Ptr<ns3::PropagationLossModel> ns3::PropagationLossModel::GetNext() [member function]
cls.add_method('GetNext',
'ns3::Ptr< ns3::PropagationLossModel >',
[])
## propagation-loss-model.h (module 'propagation'): double ns3::PropagationLossModel::CalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('CalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::PropagationLossModel::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## propagation-loss-model.h (module 'propagation'): double ns3::PropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::PropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3QosTag_methods(root_module, cls):
## qos-tag.h (module 'wifi'): ns3::QosTag::QosTag(ns3::QosTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::QosTag const &', 'arg0')])
## qos-tag.h (module 'wifi'): ns3::QosTag::QosTag() [constructor]
cls.add_constructor([])
## qos-tag.h (module 'wifi'): ns3::QosTag::QosTag(uint8_t tid) [constructor]
cls.add_constructor([param('uint8_t', 'tid')])
## qos-tag.h (module 'wifi'): void ns3::QosTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## qos-tag.h (module 'wifi'): ns3::TypeId ns3::QosTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## qos-tag.h (module 'wifi'): uint32_t ns3::QosTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## qos-tag.h (module 'wifi'): uint8_t ns3::QosTag::GetTid() const [member function]
cls.add_method('GetTid',
'uint8_t',
[],
is_const=True)
## qos-tag.h (module 'wifi'): static ns3::TypeId ns3::QosTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## qos-tag.h (module 'wifi'): void ns3::QosTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## qos-tag.h (module 'wifi'): void ns3::QosTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## qos-tag.h (module 'wifi'): void ns3::QosTag::SetTid(uint8_t tid) [member function]
cls.add_method('SetTid',
'void',
[param('uint8_t', 'tid')])
## qos-tag.h (module 'wifi'): void ns3::QosTag::SetUserPriority(ns3::UserPriority up) [member function]
cls.add_method('SetUserPriority',
'void',
[param('ns3::UserPriority', 'up')])
return
def register_Ns3QosWifiMacHelper_methods(root_module, cls):
## qos-wifi-mac-helper.h (module 'wifi'): ns3::QosWifiMacHelper::QosWifiMacHelper(ns3::QosWifiMacHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::QosWifiMacHelper const &', 'arg0')])
## qos-wifi-mac-helper.h (module 'wifi'): ns3::QosWifiMacHelper::QosWifiMacHelper() [constructor]
cls.add_constructor([])
## qos-wifi-mac-helper.h (module 'wifi'): static ns3::QosWifiMacHelper ns3::QosWifiMacHelper::Default() [member function]
cls.add_method('Default',
'ns3::QosWifiMacHelper',
[],
is_static=True)
## qos-wifi-mac-helper.h (module 'wifi'): void ns3::QosWifiMacHelper::SetBlockAckInactivityTimeoutForAc(ns3::AcIndex ac, uint16_t timeout) [member function]
cls.add_method('SetBlockAckInactivityTimeoutForAc',
'void',
[param('ns3::AcIndex', 'ac'), param('uint16_t', 'timeout')])
## qos-wifi-mac-helper.h (module 'wifi'): void ns3::QosWifiMacHelper::SetBlockAckThresholdForAc(ns3::AcIndex ac, uint8_t threshold) [member function]
cls.add_method('SetBlockAckThresholdForAc',
'void',
[param('ns3::AcIndex', 'ac'), param('uint8_t', 'threshold')])
## qos-wifi-mac-helper.h (module 'wifi'): void ns3::QosWifiMacHelper::SetMsduAggregatorForAc(ns3::AcIndex ac, 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()) [member function]
cls.add_method('SetMsduAggregatorForAc',
'void',
[param('ns3::AcIndex', 'ac'), 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()')])
## qos-wifi-mac-helper.h (module 'wifi'): void ns3::QosWifiMacHelper::SetType(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('SetType',
'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()')])
## qos-wifi-mac-helper.h (module 'wifi'): ns3::Ptr<ns3::WifiMac> ns3::QosWifiMacHelper::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::WifiMac >',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3RandomPropagationDelayModel_methods(root_module, cls):
## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel::RandomPropagationDelayModel(ns3::RandomPropagationDelayModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RandomPropagationDelayModel const &', 'arg0')])
## propagation-delay-model.h (module 'propagation'): ns3::RandomPropagationDelayModel::RandomPropagationDelayModel() [constructor]
cls.add_constructor([])
## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::RandomPropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, is_virtual=True)
## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::RandomPropagationDelayModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-delay-model.h (module 'propagation'): int64_t ns3::RandomPropagationDelayModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3RandomPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::RandomPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::RandomPropagationLossModel::RandomPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): double ns3::RandomPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::RandomPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3RandomVariableStream_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function]
cls.add_method('SetStream',
'void',
[param('int64_t', 'stream')])
## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function]
cls.add_method('GetStream',
'int64_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function]
cls.add_method('SetAntithetic',
'void',
[param('bool', 'isAntithetic')])
## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function]
cls.add_method('IsAntithetic',
'bool',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function]
cls.add_method('Peek',
'ns3::RngStream *',
[],
is_const=True, visibility='protected')
return
def register_Ns3RangePropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::RangePropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::RangePropagationLossModel::RangePropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): double ns3::RangePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::RangePropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3SequentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function]
cls.add_method('GetIncrement',
'ns3::Ptr< ns3::RandomVariableStream >',
[],
is_const=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function]
cls.add_method('GetConsecutive',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3InterferenceHelperEvent_Ns3Empty_Ns3DefaultDeleter__lt__ns3InterferenceHelperEvent__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> >::SimpleRefCount(ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter< ns3::InterferenceHelper::Event > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::InterferenceHelper::Event, ns3::empty, ns3::DefaultDeleter<ns3::InterferenceHelper::Event> >::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__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::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_Ns3SimpleRefCount__Ns3WifiInformationElement_Ns3Empty_Ns3DefaultDeleter__lt__ns3WifiInformationElement__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >::SimpleRefCount(ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter< ns3::WifiInformationElement > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::WifiInformationElement, ns3::empty, ns3::DefaultDeleter<ns3::WifiInformationElement> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SnrTag_methods(root_module, cls):
## snr-tag.h (module 'wifi'): ns3::SnrTag::SnrTag(ns3::SnrTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SnrTag const &', 'arg0')])
## snr-tag.h (module 'wifi'): ns3::SnrTag::SnrTag() [constructor]
cls.add_constructor([])
## snr-tag.h (module 'wifi'): ns3::SnrTag::SnrTag(double snr) [constructor]
cls.add_constructor([param('double', 'snr')])
## snr-tag.h (module 'wifi'): void ns3::SnrTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## snr-tag.h (module 'wifi'): double ns3::SnrTag::Get() const [member function]
cls.add_method('Get',
'double',
[],
is_const=True)
## snr-tag.h (module 'wifi'): ns3::TypeId ns3::SnrTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## snr-tag.h (module 'wifi'): uint32_t ns3::SnrTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## snr-tag.h (module 'wifi'): static ns3::TypeId ns3::SnrTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## snr-tag.h (module 'wifi'): void ns3::SnrTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## snr-tag.h (module 'wifi'): void ns3::SnrTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## snr-tag.h (module 'wifi'): void ns3::SnrTag::Set(double snr) [member function]
cls.add_method('Set',
'void',
[param('double', 'snr')])
return
def register_Ns3ThreeLogDistancePropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::ThreeLogDistancePropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::ThreeLogDistancePropagationLossModel::ThreeLogDistancePropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): double ns3::ThreeLogDistancePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::ThreeLogDistancePropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3Time_methods(root_module, cls):
cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right'))
cls.add_binary_comparison_operator('!=')
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_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_Ns3TriangularRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3TwoRayGroundPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::TwoRayGroundPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::TwoRayGroundPropagationLossModel::TwoRayGroundPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetLambda(double frequency, double speed) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'frequency'), param('double', 'speed')])
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetLambda(double lambda) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'lambda')])
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetSystemLoss(double systemLoss) [member function]
cls.add_method('SetSystemLoss',
'void',
[param('double', 'systemLoss')])
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetMinDistance(double minDistance) [member function]
cls.add_method('SetMinDistance',
'void',
[param('double', 'minDistance')])
## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetMinDistance() const [member function]
cls.add_method('GetMinDistance',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::GetSystemLoss() const [member function]
cls.add_method('GetSystemLoss',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): void ns3::TwoRayGroundPropagationLossModel::SetHeightAboveZ(double heightAboveZ) [member function]
cls.add_method('SetHeightAboveZ',
'void',
[param('double', 'heightAboveZ')])
## propagation-loss-model.h (module 'propagation'): double ns3::TwoRayGroundPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::TwoRayGroundPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3UniformRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function]
cls.add_method('GetMin',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function]
cls.add_method('GetMax',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'min'), param('double', 'max')])
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'min'), param('uint32_t', 'max')])
## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3WeibullRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function]
cls.add_method('GetScale',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'scale'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3WifiActionHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::WifiActionHeader(ns3::WifiActionHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiActionHeader const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::WifiActionHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): uint32_t ns3::WifiActionHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue ns3::WifiActionHeader::GetAction() [member function]
cls.add_method('GetAction',
'ns3::WifiActionHeader::ActionValue',
[])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::CategoryValue ns3::WifiActionHeader::GetCategory() [member function]
cls.add_method('GetCategory',
'ns3::WifiActionHeader::CategoryValue',
[])
## mgt-headers.h (module 'wifi'): ns3::TypeId ns3::WifiActionHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): uint32_t ns3::WifiActionHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): static ns3::TypeId ns3::WifiActionHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mgt-headers.h (module 'wifi'): void ns3::WifiActionHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::WifiActionHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## mgt-headers.h (module 'wifi'): void ns3::WifiActionHeader::SetAction(ns3::WifiActionHeader::CategoryValue type, ns3::WifiActionHeader::ActionValue action) [member function]
cls.add_method('SetAction',
'void',
[param('ns3::WifiActionHeader::CategoryValue', 'type'), param('ns3::WifiActionHeader::ActionValue', 'action')])
return
def register_Ns3WifiActionHeaderActionValue_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::ActionValue() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::ActionValue(ns3::WifiActionHeader::ActionValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiActionHeader::ActionValue const &', 'arg0')])
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::blockAck [variable]
cls.add_instance_attribute('blockAck', 'ns3::WifiActionHeader::BlockAckActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::interwork [variable]
cls.add_instance_attribute('interwork', 'ns3::WifiActionHeader::InterworkActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::linkMetrtic [variable]
cls.add_instance_attribute('linkMetrtic', 'ns3::WifiActionHeader::LinkMetricActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::pathSelection [variable]
cls.add_instance_attribute('pathSelection', 'ns3::WifiActionHeader::PathSelectionActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::peerLink [variable]
cls.add_instance_attribute('peerLink', 'ns3::WifiActionHeader::PeerLinkMgtActionValue', is_const=False)
## mgt-headers.h (module 'wifi'): ns3::WifiActionHeader::ActionValue::resourceCoordination [variable]
cls.add_instance_attribute('resourceCoordination', 'ns3::WifiActionHeader::ResourceCoordinationActionValue', is_const=False)
return
def register_Ns3WifiInformationElement_methods(root_module, cls):
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('==')
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElement::WifiInformationElement() [constructor]
cls.add_constructor([])
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElement::WifiInformationElement(ns3::WifiInformationElement const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiInformationElement const &', 'arg0')])
## wifi-information-element.h (module 'wifi'): ns3::Buffer::Iterator ns3::WifiInformationElement::Deserialize(ns3::Buffer::Iterator i) [member function]
cls.add_method('Deserialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'i')])
## wifi-information-element.h (module 'wifi'): ns3::Buffer::Iterator ns3::WifiInformationElement::DeserializeIfPresent(ns3::Buffer::Iterator i) [member function]
cls.add_method('DeserializeIfPresent',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'i')])
## wifi-information-element.h (module 'wifi'): uint8_t ns3::WifiInformationElement::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_pure_virtual=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): ns3::WifiInformationElementId ns3::WifiInformationElement::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): uint8_t ns3::WifiInformationElement::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): uint16_t ns3::WifiInformationElement::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint16_t',
[],
is_const=True)
## wifi-information-element.h (module 'wifi'): void ns3::WifiInformationElement::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## wifi-information-element.h (module 'wifi'): ns3::Buffer::Iterator ns3::WifiInformationElement::Serialize(ns3::Buffer::Iterator i) const [member function]
cls.add_method('Serialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'i')],
is_const=True)
## wifi-information-element.h (module 'wifi'): void ns3::WifiInformationElement::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3WifiInformationElementVector_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
## wifi-information-element-vector.h (module 'wifi'): ns3::WifiInformationElementVector::WifiInformationElementVector(ns3::WifiInformationElementVector const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiInformationElementVector const &', 'arg0')])
## wifi-information-element-vector.h (module 'wifi'): ns3::WifiInformationElementVector::WifiInformationElementVector() [constructor]
cls.add_constructor([])
## wifi-information-element-vector.h (module 'wifi'): bool ns3::WifiInformationElementVector::AddInformationElement(ns3::Ptr<ns3::WifiInformationElement> element) [member function]
cls.add_method('AddInformationElement',
'bool',
[param('ns3::Ptr< ns3::WifiInformationElement >', 'element')])
## wifi-information-element-vector.h (module 'wifi'): __gnu_cxx::__normal_iterator<ns3::Ptr<ns3::WifiInformationElement>*,std::vector<ns3::Ptr<ns3::WifiInformationElement>, std::allocator<ns3::Ptr<ns3::WifiInformationElement> > > > ns3::WifiInformationElementVector::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::WifiInformationElement >, std::vector< ns3::Ptr< ns3::WifiInformationElement > > >',
[])
## wifi-information-element-vector.h (module 'wifi'): uint32_t ns3::WifiInformationElementVector::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): uint32_t ns3::WifiInformationElementVector::DeserializeSingleIe(ns3::Buffer::Iterator start) [member function]
cls.add_method('DeserializeSingleIe',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): __gnu_cxx::__normal_iterator<ns3::Ptr<ns3::WifiInformationElement>*,std::vector<ns3::Ptr<ns3::WifiInformationElement>, std::allocator<ns3::Ptr<ns3::WifiInformationElement> > > > ns3::WifiInformationElementVector::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::WifiInformationElement >, std::vector< ns3::Ptr< ns3::WifiInformationElement > > >',
[])
## wifi-information-element-vector.h (module 'wifi'): ns3::Ptr<ns3::WifiInformationElement> ns3::WifiInformationElementVector::FindFirst(ns3::WifiInformationElementId id) const [member function]
cls.add_method('FindFirst',
'ns3::Ptr< ns3::WifiInformationElement >',
[param('ns3::WifiInformationElementId', 'id')],
is_const=True)
## wifi-information-element-vector.h (module 'wifi'): ns3::TypeId ns3::WifiInformationElementVector::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): uint32_t ns3::WifiInformationElementVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): static ns3::TypeId ns3::WifiInformationElementVector::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-information-element-vector.h (module 'wifi'): void ns3::WifiInformationElementVector::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): void ns3::WifiInformationElementVector::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## wifi-information-element-vector.h (module 'wifi'): void ns3::WifiInformationElementVector::SetMaxSize(uint16_t size) [member function]
cls.add_method('SetMaxSize',
'void',
[param('uint16_t', 'size')])
## wifi-information-element-vector.h (module 'wifi'): uint32_t ns3::WifiInformationElementVector::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True, visibility='protected')
return
def register_Ns3WifiMac_methods(root_module, cls):
## wifi-mac.h (module 'wifi'): ns3::WifiMac::WifiMac() [constructor]
cls.add_constructor([])
## wifi-mac.h (module 'wifi'): ns3::WifiMac::WifiMac(ns3::WifiMac const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMac const &', 'arg0')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::ConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('ConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetAckTimeout() const [member function]
cls.add_method('GetAckTimeout',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::WifiMac::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Mac48Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetBasicBlockAckTimeout() const [member function]
cls.add_method('GetBasicBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::WifiMac::GetBssid() const [member function]
cls.add_method('GetBssid',
'ns3::Mac48Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetCompressedBlockAckTimeout() const [member function]
cls.add_method('GetCompressedBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetCtsTimeout() const [member function]
cls.add_method('GetCtsTimeout',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetEifsNoDifs() const [member function]
cls.add_method('GetEifsNoDifs',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetMaxPropagationDelay() const [member function]
cls.add_method('GetMaxPropagationDelay',
'ns3::Time',
[],
is_const=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetMsduLifetime() const [member function]
cls.add_method('GetMsduLifetime',
'ns3::Time',
[],
is_const=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetPifs() const [member function]
cls.add_method('GetPifs',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetSifs() const [member function]
cls.add_method('GetSifs',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Time ns3::WifiMac::GetSlot() const [member function]
cls.add_method('GetSlot',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): ns3::Ssid ns3::WifiMac::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::WifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyPromiscRx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyPromiscRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyRx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyRxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyTx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::NotifyTxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function]
cls.add_method('SetAckTimeout',
'void',
[param('ns3::Time', 'ackTimeout')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetAddress(ns3::Mac48Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetBasicBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetCompressedBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function]
cls.add_method('SetCtsTimeout',
'void',
[param('ns3::Time', 'ctsTimeout')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function]
cls.add_method('SetEifsNoDifs',
'void',
[param('ns3::Time', 'eifsNoDifs')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function]
cls.add_method('SetForwardUpCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function]
cls.add_method('SetLinkDownCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function]
cls.add_method('SetLinkUpCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetMaxPropagationDelay(ns3::Time delay) [member function]
cls.add_method('SetMaxPropagationDelay',
'void',
[param('ns3::Time', 'delay')])
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetPifs(ns3::Time pifs) [member function]
cls.add_method('SetPifs',
'void',
[param('ns3::Time', 'pifs')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetPromisc() [member function]
cls.add_method('SetPromisc',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetSifs(ns3::Time sifs) [member function]
cls.add_method('SetSifs',
'void',
[param('ns3::Time', 'sifs')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetSlot(ns3::Time slotTime) [member function]
cls.add_method('SetSlot',
'void',
[param('ns3::Time', 'slotTime')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetWifiPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')],
is_pure_virtual=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): bool ns3::WifiMac::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::ConfigureCCHDcf(ns3::Ptr<ns3::Dcf> dcf, uint32_t cwmin, uint32_t cwmax, ns3::AcIndex ac) [member function]
cls.add_method('ConfigureCCHDcf',
'void',
[param('ns3::Ptr< ns3::Dcf >', 'dcf'), param('uint32_t', 'cwmin'), param('uint32_t', 'cwmax'), param('ns3::AcIndex', 'ac')],
visibility='protected')
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::ConfigureDcf(ns3::Ptr<ns3::Dcf> dcf, uint32_t cwmin, uint32_t cwmax, ns3::AcIndex ac) [member function]
cls.add_method('ConfigureDcf',
'void',
[param('ns3::Ptr< ns3::Dcf >', 'dcf'), param('uint32_t', 'cwmin'), param('uint32_t', 'cwmax'), param('ns3::AcIndex', 'ac')],
visibility='protected')
## wifi-mac.h (module 'wifi'): void ns3::WifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('FinishConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3WifiMacHeader_methods(root_module, cls):
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::WifiMacHeader(ns3::WifiMacHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMacHeader const &', 'arg0')])
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::WifiMacHeader() [constructor]
cls.add_constructor([])
## wifi-mac-header.h (module 'wifi'): uint32_t ns3::WifiMacHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr1() const [member function]
cls.add_method('GetAddr1',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr2() const [member function]
cls.add_method('GetAddr2',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr3() const [member function]
cls.add_method('GetAddr3',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Mac48Address ns3::WifiMacHeader::GetAddr4() const [member function]
cls.add_method('GetAddr4',
'ns3::Mac48Address',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::Time ns3::WifiMacHeader::GetDuration() const [member function]
cls.add_method('GetDuration',
'ns3::Time',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetFragmentNumber() const [member function]
cls.add_method('GetFragmentNumber',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::TypeId ns3::WifiMacHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacHeader::QosAckPolicy ns3::WifiMacHeader::GetQosAckPolicy() const [member function]
cls.add_method('GetQosAckPolicy',
'ns3::WifiMacHeader::QosAckPolicy',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint8_t ns3::WifiMacHeader::GetQosTid() const [member function]
cls.add_method('GetQosTid',
'uint8_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint8_t ns3::WifiMacHeader::GetQosTxopLimit() const [member function]
cls.add_method('GetQosTxopLimit',
'uint8_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetRawDuration() const [member function]
cls.add_method('GetRawDuration',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetSequenceControl() const [member function]
cls.add_method('GetSequenceControl',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint16_t ns3::WifiMacHeader::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): uint32_t ns3::WifiMacHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): uint32_t ns3::WifiMacHeader::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): ns3::WifiMacType ns3::WifiMacHeader::GetType() const [member function]
cls.add_method('GetType',
'ns3::WifiMacType',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): static ns3::TypeId ns3::WifiMacHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-mac-header.h (module 'wifi'): char const * ns3::WifiMacHeader::GetTypeString() const [member function]
cls.add_method('GetTypeString',
'char const *',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAck() const [member function]
cls.add_method('IsAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAction() const [member function]
cls.add_method('IsAction',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAssocReq() const [member function]
cls.add_method('IsAssocReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAssocResp() const [member function]
cls.add_method('IsAssocResp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsAuthentication() const [member function]
cls.add_method('IsAuthentication',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsBeacon() const [member function]
cls.add_method('IsBeacon',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsBlockAck() const [member function]
cls.add_method('IsBlockAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsBlockAckReq() const [member function]
cls.add_method('IsBlockAckReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsCfpoll() const [member function]
cls.add_method('IsCfpoll',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsCtl() const [member function]
cls.add_method('IsCtl',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsCts() const [member function]
cls.add_method('IsCts',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsData() const [member function]
cls.add_method('IsData',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsDeauthentication() const [member function]
cls.add_method('IsDeauthentication',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsDisassociation() const [member function]
cls.add_method('IsDisassociation',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsFromDs() const [member function]
cls.add_method('IsFromDs',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsMgt() const [member function]
cls.add_method('IsMgt',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsMoreFragments() const [member function]
cls.add_method('IsMoreFragments',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsMultihopAction() const [member function]
cls.add_method('IsMultihopAction',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsProbeReq() const [member function]
cls.add_method('IsProbeReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsProbeResp() const [member function]
cls.add_method('IsProbeResp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosAck() const [member function]
cls.add_method('IsQosAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosAmsdu() const [member function]
cls.add_method('IsQosAmsdu',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosBlockAck() const [member function]
cls.add_method('IsQosBlockAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosData() const [member function]
cls.add_method('IsQosData',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosEosp() const [member function]
cls.add_method('IsQosEosp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsQosNoAck() const [member function]
cls.add_method('IsQosNoAck',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsReassocReq() const [member function]
cls.add_method('IsReassocReq',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsReassocResp() const [member function]
cls.add_method('IsReassocResp',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsRetry() const [member function]
cls.add_method('IsRetry',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsRts() const [member function]
cls.add_method('IsRts',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): bool ns3::WifiMacHeader::IsToDs() const [member function]
cls.add_method('IsToDs',
'bool',
[],
is_const=True)
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAction() [member function]
cls.add_method('SetAction',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr1(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr1',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr2(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr2',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr3(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr3',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAddr4(ns3::Mac48Address address) [member function]
cls.add_method('SetAddr4',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAssocReq() [member function]
cls.add_method('SetAssocReq',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetAssocResp() [member function]
cls.add_method('SetAssocResp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetBeacon() [member function]
cls.add_method('SetBeacon',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetBlockAck() [member function]
cls.add_method('SetBlockAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetBlockAckReq() [member function]
cls.add_method('SetBlockAckReq',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsFrom() [member function]
cls.add_method('SetDsFrom',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsNotFrom() [member function]
cls.add_method('SetDsNotFrom',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsNotTo() [member function]
cls.add_method('SetDsNotTo',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDsTo() [member function]
cls.add_method('SetDsTo',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetDuration(ns3::Time duration) [member function]
cls.add_method('SetDuration',
'void',
[param('ns3::Time', 'duration')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetFragmentNumber(uint8_t frag) [member function]
cls.add_method('SetFragmentNumber',
'void',
[param('uint8_t', 'frag')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetId(uint16_t id) [member function]
cls.add_method('SetId',
'void',
[param('uint16_t', 'id')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetMoreFragments() [member function]
cls.add_method('SetMoreFragments',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetMultihopAction() [member function]
cls.add_method('SetMultihopAction',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetNoMoreFragments() [member function]
cls.add_method('SetNoMoreFragments',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetNoRetry() [member function]
cls.add_method('SetNoRetry',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetProbeReq() [member function]
cls.add_method('SetProbeReq',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetProbeResp() [member function]
cls.add_method('SetProbeResp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosAckPolicy(ns3::WifiMacHeader::QosAckPolicy arg0) [member function]
cls.add_method('SetQosAckPolicy',
'void',
[param('ns3::WifiMacHeader::QosAckPolicy', 'arg0')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosAmsdu() [member function]
cls.add_method('SetQosAmsdu',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosBlockAck() [member function]
cls.add_method('SetQosBlockAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosEosp() [member function]
cls.add_method('SetQosEosp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNoAck() [member function]
cls.add_method('SetQosNoAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNoAmsdu() [member function]
cls.add_method('SetQosNoAmsdu',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNoEosp() [member function]
cls.add_method('SetQosNoEosp',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosNormalAck() [member function]
cls.add_method('SetQosNormalAck',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosTid(uint8_t tid) [member function]
cls.add_method('SetQosTid',
'void',
[param('uint8_t', 'tid')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetQosTxopLimit(uint8_t txop) [member function]
cls.add_method('SetQosTxopLimit',
'void',
[param('uint8_t', 'txop')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetRawDuration(uint16_t duration) [member function]
cls.add_method('SetRawDuration',
'void',
[param('uint16_t', 'duration')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetRetry() [member function]
cls.add_method('SetRetry',
'void',
[])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetSequenceNumber(uint16_t seq) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'seq')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetType(ns3::WifiMacType type) [member function]
cls.add_method('SetType',
'void',
[param('ns3::WifiMacType', 'type')])
## wifi-mac-header.h (module 'wifi'): void ns3::WifiMacHeader::SetTypeData() [member function]
cls.add_method('SetTypeData',
'void',
[])
return
def register_Ns3WifiMacQueue_methods(root_module, cls):
## wifi-mac-queue.h (module 'wifi'): ns3::WifiMacQueue::WifiMacQueue(ns3::WifiMacQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiMacQueue const &', 'arg0')])
## wifi-mac-queue.h (module 'wifi'): ns3::WifiMacQueue::WifiMacQueue() [constructor]
cls.add_constructor([])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::Dequeue(ns3::WifiMacHeader * hdr) [member function]
cls.add_method('Dequeue',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr')])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::DequeueByTidAndAddress(ns3::WifiMacHeader * hdr, uint8_t tid, ns3::WifiMacHeader::AddressType type, ns3::Mac48Address addr) [member function]
cls.add_method('DequeueByTidAndAddress',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr'), param('uint8_t', 'tid'), param('ns3::WifiMacHeader::AddressType', 'type'), param('ns3::Mac48Address', 'addr')])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::DequeueFirstAvailable(ns3::WifiMacHeader * hdr, ns3::Time & tStamp, ns3::QosBlockedDestinations const * blockedPackets) [member function]
cls.add_method('DequeueFirstAvailable',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr'), param('ns3::Time &', 'tStamp'), param('ns3::QosBlockedDestinations const *', 'blockedPackets')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::Flush() [member function]
cls.add_method('Flush',
'void',
[])
## wifi-mac-queue.h (module 'wifi'): ns3::Time ns3::WifiMacQueue::GetMaxDelay() const [member function]
cls.add_method('GetMaxDelay',
'ns3::Time',
[],
is_const=True)
## wifi-mac-queue.h (module 'wifi'): uint32_t ns3::WifiMacQueue::GetMaxSize() const [member function]
cls.add_method('GetMaxSize',
'uint32_t',
[],
is_const=True)
## wifi-mac-queue.h (module 'wifi'): uint32_t ns3::WifiMacQueue::GetNPacketsByTidAndAddress(uint8_t tid, ns3::WifiMacHeader::AddressType type, ns3::Mac48Address addr) [member function]
cls.add_method('GetNPacketsByTidAndAddress',
'uint32_t',
[param('uint8_t', 'tid'), param('ns3::WifiMacHeader::AddressType', 'type'), param('ns3::Mac48Address', 'addr')])
## wifi-mac-queue.h (module 'wifi'): uint32_t ns3::WifiMacQueue::GetSize() [member function]
cls.add_method('GetSize',
'uint32_t',
[])
## wifi-mac-queue.h (module 'wifi'): static ns3::TypeId ns3::WifiMacQueue::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-mac-queue.h (module 'wifi'): bool ns3::WifiMacQueue::IsEmpty() [member function]
cls.add_method('IsEmpty',
'bool',
[])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::Peek(ns3::WifiMacHeader * hdr) [member function]
cls.add_method('Peek',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr')])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::PeekByTidAndAddress(ns3::WifiMacHeader * hdr, uint8_t tid, ns3::WifiMacHeader::AddressType type, ns3::Mac48Address addr) [member function]
cls.add_method('PeekByTidAndAddress',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr'), param('uint8_t', 'tid'), param('ns3::WifiMacHeader::AddressType', 'type'), param('ns3::Mac48Address', 'addr')])
## wifi-mac-queue.h (module 'wifi'): ns3::Ptr<ns3::Packet const> ns3::WifiMacQueue::PeekFirstAvailable(ns3::WifiMacHeader * hdr, ns3::Time & tStamp, ns3::QosBlockedDestinations const * blockedPackets) [member function]
cls.add_method('PeekFirstAvailable',
'ns3::Ptr< ns3::Packet const >',
[param('ns3::WifiMacHeader *', 'hdr'), param('ns3::Time &', 'tStamp'), param('ns3::QosBlockedDestinations const *', 'blockedPackets')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::PushFront(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## wifi-mac-queue.h (module 'wifi'): bool ns3::WifiMacQueue::Remove(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::SetMaxDelay(ns3::Time delay) [member function]
cls.add_method('SetMaxDelay',
'void',
[param('ns3::Time', 'delay')])
## wifi-mac-queue.h (module 'wifi'): void ns3::WifiMacQueue::SetMaxSize(uint32_t maxSize) [member function]
cls.add_method('SetMaxSize',
'void',
[param('uint32_t', 'maxSize')])
return
def register_Ns3WifiPhy_methods(root_module, cls):
## wifi-phy.h (module 'wifi'): ns3::WifiPhy::WifiPhy(ns3::WifiPhy const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiPhy const &', 'arg0')])
## wifi-phy.h (module 'wifi'): ns3::WifiPhy::WifiPhy() [constructor]
cls.add_constructor([])
## wifi-phy.h (module 'wifi'): int64_t ns3::WifiPhy::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function]
cls.add_method('CalculateSnr',
'double',
[param('ns3::WifiMode', 'txMode'), param('double', 'ber')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::Time ns3::WifiPhy::CalculateTxDuration(uint32_t size, ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('CalculateTxDuration',
'ns3::Time',
[param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::ConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('ConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::WifiChannel> ns3::WifiPhy::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::WifiChannel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): uint16_t ns3::WifiPhy::GetChannelNumber() const [member function]
cls.add_method('GetChannelNumber',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetDelayUntilIdle() [member function]
cls.add_method('GetDelayUntilIdle',
'ns3::Time',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate11Mbps() [member function]
cls.add_method('GetDsssRate11Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate1Mbps() [member function]
cls.add_method('GetDsssRate1Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate2Mbps() [member function]
cls.add_method('GetDsssRate2Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate5_5Mbps() [member function]
cls.add_method('GetDsssRate5_5Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate12Mbps() [member function]
cls.add_method('GetErpOfdmRate12Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate18Mbps() [member function]
cls.add_method('GetErpOfdmRate18Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate24Mbps() [member function]
cls.add_method('GetErpOfdmRate24Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate36Mbps() [member function]
cls.add_method('GetErpOfdmRate36Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate48Mbps() [member function]
cls.add_method('GetErpOfdmRate48Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate54Mbps() [member function]
cls.add_method('GetErpOfdmRate54Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate6Mbps() [member function]
cls.add_method('GetErpOfdmRate6Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate9Mbps() [member function]
cls.add_method('GetErpOfdmRate9Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetLastRxStartTime() const [member function]
cls.add_method('GetLastRxStartTime',
'ns3::Time',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): ns3::WifiMode ns3::WifiPhy::GetMode(uint32_t mode) const [member function]
cls.add_method('GetMode',
'ns3::WifiMode',
[param('uint32_t', 'mode')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNModes() const [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNTxPower() const [member function]
cls.add_method('GetNTxPower',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12Mbps() [member function]
cls.add_method('GetOfdmRate12Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate12MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate12MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate13_5MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate13_5MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18Mbps() [member function]
cls.add_method('GetOfdmRate18Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate18MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate1_5MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate1_5MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24Mbps() [member function]
cls.add_method('GetOfdmRate24Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate24MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate27MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate27MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate2_25MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate2_25MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate36Mbps() [member function]
cls.add_method('GetOfdmRate36Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate3MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate3MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate48Mbps() [member function]
cls.add_method('GetOfdmRate48Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate4_5MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate4_5MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate54Mbps() [member function]
cls.add_method('GetOfdmRate54Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6Mbps() [member function]
cls.add_method('GetOfdmRate6Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate6MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate6MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9Mbps() [member function]
cls.add_method('GetOfdmRate9Mbps',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW10MHz() [member function]
cls.add_method('GetOfdmRate9MbpsBW10MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW5MHz() [member function]
cls.add_method('GetOfdmRate9MbpsBW5MHz',
'ns3::WifiMode',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPayloadDurationMicroSeconds(uint32_t size, ns3::WifiMode payloadMode) [member function]
cls.add_method('GetPayloadDurationMicroSeconds',
'uint32_t',
[param('uint32_t', 'size'), param('ns3::WifiMode', 'payloadMode')],
is_static=True)
## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpHeaderDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('GetPlcpHeaderDurationMicroSeconds',
'uint32_t',
[param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetPlcpHeaderMode(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('GetPlcpHeaderMode',
'ns3::WifiMode',
[param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpPreambleDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('GetPlcpPreambleDurationMicroSeconds',
'uint32_t',
[param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')],
is_static=True)
## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetStateDuration() [member function]
cls.add_method('GetStateDuration',
'ns3::Time',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::GetTxPowerEnd() const [member function]
cls.add_method('GetTxPowerEnd',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::GetTxPowerStart() const [member function]
cls.add_method('GetTxPowerStart',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): static ns3::TypeId ns3::WifiPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateSwitching() [member function]
cls.add_method('IsStateSwitching',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyMonitorSniffRx(ns3::Ptr<ns3::Packet const> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble, double signalDbm, double noiseDbm) [member function]
cls.add_method('NotifyMonitorSniffRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble'), param('double', 'signalDbm'), param('double', 'noiseDbm')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyMonitorSniffTx(ns3::Ptr<ns3::Packet const> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble) [member function]
cls.add_method('NotifyMonitorSniffTx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxBegin(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxBegin',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxEnd(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyRxEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxBegin(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxBegin',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxDrop(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxDrop',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxEnd(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NotifyTxEnd',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::RegisterListener(ns3::WifiPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::WifiPhyListener *', 'listener')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SendPacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, uint8_t txPowerLevel) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('uint8_t', 'txPowerLevel')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetChannelNumber(uint16_t id) [member function]
cls.add_method('SetChannelNumber',
'void',
[param('uint16_t', 'id')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetReceiveErrorCallback(ns3::Callback<void,ns3::Ptr<const ns3::Packet>,double,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetReceiveOkCallback(ns3::Callback<void,ns3::Ptr<ns3::Packet>,double,ns3::WifiMode,ns3::WifiPreamble,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::WifiMode, ns3::WifiPreamble, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3WifiRemoteStationManager_methods(root_module, cls):
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationManager::WifiRemoteStationManager(ns3::WifiRemoteStationManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiRemoteStationManager const &', 'arg0')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationManager::WifiRemoteStationManager() [constructor]
cls.add_constructor([])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::AddBasicMode(ns3::WifiMode mode) [member function]
cls.add_method('AddBasicMode',
'void',
[param('ns3::WifiMode', 'mode')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::AddSupportedMode(ns3::Mac48Address address, ns3::WifiMode mode) [member function]
cls.add_method('AddSupportedMode',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'mode')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetAckMode(ns3::Mac48Address address, ns3::WifiMode dataMode) [member function]
cls.add_method('GetAckMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'dataMode')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetBasicMode(uint32_t i) const [member function]
cls.add_method('GetBasicMode',
'ns3::WifiMode',
[param('uint32_t', 'i')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetCtsMode(ns3::Mac48Address address, ns3::WifiMode rtsMode) [member function]
cls.add_method('GetCtsMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMode', 'rtsMode')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetDataMode(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fullPacketSize) [member function]
cls.add_method('GetDataMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fullPacketSize')])
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetDefaultMode() const [member function]
cls.add_method('GetDefaultMode',
'ns3::WifiMode',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetFragmentOffset(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function]
cls.add_method('GetFragmentOffset',
'uint32_t',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')])
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetFragmentSize(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function]
cls.add_method('GetFragmentSize',
'uint32_t',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')])
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetFragmentationThreshold() const [member function]
cls.add_method('GetFragmentationThreshold',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStationInfo ns3::WifiRemoteStationManager::GetInfo(ns3::Mac48Address address) [member function]
cls.add_method('GetInfo',
'ns3::WifiRemoteStationInfo',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetMaxSlrc() const [member function]
cls.add_method('GetMaxSlrc',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetMaxSsrc() const [member function]
cls.add_method('GetMaxSsrc',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetNBasicModes() const [member function]
cls.add_method('GetNBasicModes',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetNonUnicastMode() const [member function]
cls.add_method('GetNonUnicastMode',
'ns3::WifiMode',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetRtsCtsThreshold() const [member function]
cls.add_method('GetRtsCtsThreshold',
'uint32_t',
[],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetRtsMode(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('GetRtsMode',
'ns3::WifiMode',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): static ns3::TypeId ns3::WifiRemoteStationManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsAssociated(ns3::Mac48Address address) const [member function]
cls.add_method('IsAssociated',
'bool',
[param('ns3::Mac48Address', 'address')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsBrandNew(ns3::Mac48Address address) const [member function]
cls.add_method('IsBrandNew',
'bool',
[param('ns3::Mac48Address', 'address')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsLastFragment(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fragmentNumber) [member function]
cls.add_method('IsLastFragment',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fragmentNumber')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsWaitAssocTxOk(ns3::Mac48Address address) const [member function]
cls.add_method('IsWaitAssocTxOk',
'bool',
[param('ns3::Mac48Address', 'address')],
is_const=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedDataRetransmission(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedDataRetransmission',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedFragmentation(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedFragmentation',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedRts(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedRts',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::NeedRtsRetransmission(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('NeedRtsRetransmission',
'bool',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::PrepareForQueue(ns3::Mac48Address address, ns3::WifiMacHeader const * header, ns3::Ptr<ns3::Packet const> packet, uint32_t fullPacketSize) [member function]
cls.add_method('PrepareForQueue',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint32_t', 'fullPacketSize')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordDisassociated(ns3::Mac48Address address) [member function]
cls.add_method('RecordDisassociated',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordGotAssocTxFailed(ns3::Mac48Address address) [member function]
cls.add_method('RecordGotAssocTxFailed',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordGotAssocTxOk(ns3::Mac48Address address) [member function]
cls.add_method('RecordGotAssocTxOk',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::RecordWaitAssocTxOk(ns3::Mac48Address address) [member function]
cls.add_method('RecordWaitAssocTxOk',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportDataFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportDataFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportDataOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('ReportDataOk',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportFinalDataFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportFinalDataFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportFinalRtsFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportFinalRtsFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportRtsFailed(ns3::Mac48Address address, ns3::WifiMacHeader const * header) [member function]
cls.add_method('ReportRtsFailed',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportRtsOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('ReportRtsOk',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::ReportRxOk(ns3::Mac48Address address, ns3::WifiMacHeader const * header, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('ReportRxOk',
'void',
[param('ns3::Mac48Address', 'address'), param('ns3::WifiMacHeader const *', 'header'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::Reset() [member function]
cls.add_method('Reset',
'void',
[])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::Reset(ns3::Mac48Address address) [member function]
cls.add_method('Reset',
'void',
[param('ns3::Mac48Address', 'address')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetFragmentationThreshold(uint32_t threshold) [member function]
cls.add_method('SetFragmentationThreshold',
'void',
[param('uint32_t', 'threshold')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetMaxSlrc(uint32_t maxSlrc) [member function]
cls.add_method('SetMaxSlrc',
'void',
[param('uint32_t', 'maxSlrc')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetMaxSsrc(uint32_t maxSsrc) [member function]
cls.add_method('SetMaxSsrc',
'void',
[param('uint32_t', 'maxSsrc')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetRtsCtsThreshold(uint32_t threshold) [member function]
cls.add_method('SetRtsCtsThreshold',
'void',
[param('uint32_t', 'threshold')])
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetupPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): uint32_t ns3::WifiRemoteStationManager::GetNSupported(ns3::WifiRemoteStation const * station) const [member function]
cls.add_method('GetNSupported',
'uint32_t',
[param('ns3::WifiRemoteStation const *', 'station')],
is_const=True, visibility='protected')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::GetSupported(ns3::WifiRemoteStation const * station, uint32_t i) const [member function]
cls.add_method('GetSupported',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation const *', 'station'), param('uint32_t', 'i')],
is_const=True, visibility='protected')
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::WifiRemoteStationManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): ns3::WifiMode ns3::WifiRemoteStationManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedDataRetransmission(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedDataRetransmission',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedFragmentation(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedFragmentation',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRts',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::DoNeedRtsRetransmission(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRtsRetransmission',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): void ns3::WifiRemoteStationManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
is_pure_virtual=True, visibility='private', is_virtual=True)
## wifi-remote-station-manager.h (module 'wifi'): bool ns3::WifiRemoteStationManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3YansWifiPhy_methods(root_module, cls):
## yans-wifi-phy.h (module 'wifi'): static ns3::TypeId ns3::YansWifiPhy::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## yans-wifi-phy.h (module 'wifi'): ns3::YansWifiPhy::YansWifiPhy() [constructor]
cls.add_constructor([])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetChannel(ns3::Ptr<ns3::YansWifiChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::YansWifiChannel >', 'channel')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetChannelNumber(uint16_t id) [member function]
cls.add_method('SetChannelNumber',
'void',
[param('uint16_t', 'id')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): uint16_t ns3::YansWifiPhy::GetChannelNumber() const [member function]
cls.add_method('GetChannelNumber',
'uint16_t',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetChannelFrequencyMhz() const [member function]
cls.add_method('GetChannelFrequencyMhz',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::StartReceivePacket(ns3::Ptr<ns3::Packet> packet, double rxPowerDbm, ns3::WifiMode mode, ns3::WifiPreamble preamble) [member function]
cls.add_method('StartReceivePacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxPowerDbm'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetRxNoiseFigure(double noiseFigureDb) [member function]
cls.add_method('SetRxNoiseFigure',
'void',
[param('double', 'noiseFigureDb')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetTxPowerStart(double start) [member function]
cls.add_method('SetTxPowerStart',
'void',
[param('double', 'start')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetTxPowerEnd(double end) [member function]
cls.add_method('SetTxPowerEnd',
'void',
[param('double', 'end')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetNTxPower(uint32_t n) [member function]
cls.add_method('SetNTxPower',
'void',
[param('uint32_t', 'n')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetTxGain(double gain) [member function]
cls.add_method('SetTxGain',
'void',
[param('double', 'gain')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetRxGain(double gain) [member function]
cls.add_method('SetRxGain',
'void',
[param('double', 'gain')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetEdThreshold(double threshold) [member function]
cls.add_method('SetEdThreshold',
'void',
[param('double', 'threshold')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetCcaMode1Threshold(double threshold) [member function]
cls.add_method('SetCcaMode1Threshold',
'void',
[param('double', 'threshold')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetErrorRateModel(ns3::Ptr<ns3::ErrorRateModel> rate) [member function]
cls.add_method('SetErrorRateModel',
'void',
[param('ns3::Ptr< ns3::ErrorRateModel >', 'rate')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetDevice(ns3::Ptr<ns3::Object> device) [member function]
cls.add_method('SetDevice',
'void',
[param('ns3::Ptr< ns3::Object >', 'device')])
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetMobility(ns3::Ptr<ns3::Object> mobility) [member function]
cls.add_method('SetMobility',
'void',
[param('ns3::Ptr< ns3::Object >', 'mobility')])
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetRxNoiseFigure() const [member function]
cls.add_method('GetRxNoiseFigure',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetTxGain() const [member function]
cls.add_method('GetTxGain',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetRxGain() const [member function]
cls.add_method('GetRxGain',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetEdThreshold() const [member function]
cls.add_method('GetEdThreshold',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetCcaMode1Threshold() const [member function]
cls.add_method('GetCcaMode1Threshold',
'double',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::ErrorRateModel> ns3::YansWifiPhy::GetErrorRateModel() const [member function]
cls.add_method('GetErrorRateModel',
'ns3::Ptr< ns3::ErrorRateModel >',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::Object> ns3::YansWifiPhy::GetDevice() const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::Object >',
[],
is_const=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::Object> ns3::YansWifiPhy::GetMobility() [member function]
cls.add_method('GetMobility',
'ns3::Ptr< ns3::Object >',
[])
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetTxPowerStart() const [member function]
cls.add_method('GetTxPowerStart',
'double',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::GetTxPowerEnd() const [member function]
cls.add_method('GetTxPowerEnd',
'double',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): uint32_t ns3::YansWifiPhy::GetNTxPower() const [member function]
cls.add_method('GetNTxPower',
'uint32_t',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetReceiveOkCallback(ns3::Callback<void,ns3::Ptr<ns3::Packet>,double,ns3::WifiMode,ns3::WifiPreamble,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveOkCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::WifiMode, ns3::WifiPreamble, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SetReceiveErrorCallback(ns3::Callback<void,ns3::Ptr<const ns3::Packet>,double,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('SetReceiveErrorCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::SendPacket(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, uint8_t txPowerLevel) [member function]
cls.add_method('SendPacket',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('uint8_t', 'txPowerLevel')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::RegisterListener(ns3::WifiPhyListener * listener) [member function]
cls.add_method('RegisterListener',
'void',
[param('ns3::WifiPhyListener *', 'listener')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateCcaBusy() [member function]
cls.add_method('IsStateCcaBusy',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateIdle() [member function]
cls.add_method('IsStateIdle',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateBusy() [member function]
cls.add_method('IsStateBusy',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateRx() [member function]
cls.add_method('IsStateRx',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateTx() [member function]
cls.add_method('IsStateTx',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): bool ns3::YansWifiPhy::IsStateSwitching() [member function]
cls.add_method('IsStateSwitching',
'bool',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Time ns3::YansWifiPhy::GetStateDuration() [member function]
cls.add_method('GetStateDuration',
'ns3::Time',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Time ns3::YansWifiPhy::GetDelayUntilIdle() [member function]
cls.add_method('GetDelayUntilIdle',
'ns3::Time',
[],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Time ns3::YansWifiPhy::GetLastRxStartTime() const [member function]
cls.add_method('GetLastRxStartTime',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): uint32_t ns3::YansWifiPhy::GetNModes() const [member function]
cls.add_method('GetNModes',
'uint32_t',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::WifiMode ns3::YansWifiPhy::GetMode(uint32_t mode) const [member function]
cls.add_method('GetMode',
'ns3::WifiMode',
[param('uint32_t', 'mode')],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): double ns3::YansWifiPhy::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function]
cls.add_method('CalculateSnr',
'double',
[param('ns3::WifiMode', 'txMode'), param('double', 'ber')],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::WifiChannel> ns3::YansWifiPhy::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::WifiChannel >',
[],
is_const=True, is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::ConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('ConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): int64_t ns3::YansWifiPhy::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')],
is_virtual=True)
## yans-wifi-phy.h (module 'wifi'): void ns3::YansWifiPhy::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3ZetaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ZipfRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'n'), param('double', 'alpha')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'n'), param('uint32_t', 'alpha')])
## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3AarfWifiManager_methods(root_module, cls):
## aarf-wifi-manager.h (module 'wifi'): ns3::AarfWifiManager::AarfWifiManager(ns3::AarfWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AarfWifiManager const &', 'arg0')])
## aarf-wifi-manager.h (module 'wifi'): ns3::AarfWifiManager::AarfWifiManager() [constructor]
cls.add_constructor([])
## aarf-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::AarfWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aarf-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::AarfWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AarfWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AarfWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): void ns3::AarfWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## aarf-wifi-manager.h (module 'wifi'): bool ns3::AarfWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AarfcdWifiManager_methods(root_module, cls):
## aarfcd-wifi-manager.h (module 'wifi'): ns3::AarfcdWifiManager::AarfcdWifiManager(ns3::AarfcdWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AarfcdWifiManager const &', 'arg0')])
## aarfcd-wifi-manager.h (module 'wifi'): ns3::AarfcdWifiManager::AarfcdWifiManager() [constructor]
cls.add_constructor([])
## aarfcd-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::AarfcdWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## aarfcd-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::AarfcdWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AarfcdWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AarfcdWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): bool ns3::AarfcdWifiManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRts',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): void ns3::AarfcdWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## aarfcd-wifi-manager.h (module 'wifi'): bool ns3::AarfcdWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AmrrWifiManager_methods(root_module, cls):
## amrr-wifi-manager.h (module 'wifi'): ns3::AmrrWifiManager::AmrrWifiManager(ns3::AmrrWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AmrrWifiManager const &', 'arg0')])
## amrr-wifi-manager.h (module 'wifi'): ns3::AmrrWifiManager::AmrrWifiManager() [constructor]
cls.add_constructor([])
## amrr-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::AmrrWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## amrr-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::AmrrWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AmrrWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::AmrrWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): void ns3::AmrrWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## amrr-wifi-manager.h (module 'wifi'): bool ns3::AmrrWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AmsduSubframeHeader_methods(root_module, cls):
## amsdu-subframe-header.h (module 'wifi'): ns3::AmsduSubframeHeader::AmsduSubframeHeader(ns3::AmsduSubframeHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AmsduSubframeHeader const &', 'arg0')])
## amsdu-subframe-header.h (module 'wifi'): ns3::AmsduSubframeHeader::AmsduSubframeHeader() [constructor]
cls.add_constructor([])
## amsdu-subframe-header.h (module 'wifi'): uint32_t ns3::AmsduSubframeHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): ns3::Mac48Address ns3::AmsduSubframeHeader::GetDestinationAddr() const [member function]
cls.add_method('GetDestinationAddr',
'ns3::Mac48Address',
[],
is_const=True)
## amsdu-subframe-header.h (module 'wifi'): ns3::TypeId ns3::AmsduSubframeHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): uint16_t ns3::AmsduSubframeHeader::GetLength() const [member function]
cls.add_method('GetLength',
'uint16_t',
[],
is_const=True)
## amsdu-subframe-header.h (module 'wifi'): uint32_t ns3::AmsduSubframeHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): ns3::Mac48Address ns3::AmsduSubframeHeader::GetSourceAddr() const [member function]
cls.add_method('GetSourceAddr',
'ns3::Mac48Address',
[],
is_const=True)
## amsdu-subframe-header.h (module 'wifi'): static ns3::TypeId ns3::AmsduSubframeHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::SetDestinationAddr(ns3::Mac48Address to) [member function]
cls.add_method('SetDestinationAddr',
'void',
[param('ns3::Mac48Address', 'to')])
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::SetLength(uint16_t arg0) [member function]
cls.add_method('SetLength',
'void',
[param('uint16_t', 'arg0')])
## amsdu-subframe-header.h (module 'wifi'): void ns3::AmsduSubframeHeader::SetSourceAddr(ns3::Mac48Address to) [member function]
cls.add_method('SetSourceAddr',
'void',
[param('ns3::Mac48Address', 'to')])
return
def register_Ns3ArfWifiManager_methods(root_module, cls):
## arf-wifi-manager.h (module 'wifi'): ns3::ArfWifiManager::ArfWifiManager(ns3::ArfWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ArfWifiManager const &', 'arg0')])
## arf-wifi-manager.h (module 'wifi'): ns3::ArfWifiManager::ArfWifiManager() [constructor]
cls.add_constructor([])
## arf-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::ArfWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## arf-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::ArfWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::ArfWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::ArfWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): void ns3::ArfWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## arf-wifi-manager.h (module 'wifi'): bool ns3::ArfWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3AthstatsWifiTraceSink_methods(root_module, cls):
## athstats-helper.h (module 'wifi'): ns3::AthstatsWifiTraceSink::AthstatsWifiTraceSink(ns3::AthstatsWifiTraceSink const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AthstatsWifiTraceSink const &', 'arg0')])
## athstats-helper.h (module 'wifi'): ns3::AthstatsWifiTraceSink::AthstatsWifiTraceSink() [constructor]
cls.add_constructor([])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::DevRxTrace(std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DevRxTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::DevTxTrace(std::string context, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('DevTxTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## athstats-helper.h (module 'wifi'): static ns3::TypeId ns3::AthstatsWifiTraceSink::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::Open(std::string const & name) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'name')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::PhyRxErrorTrace(std::string context, ns3::Ptr<ns3::Packet const> packet, double snr) [member function]
cls.add_method('PhyRxErrorTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'snr')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::PhyRxOkTrace(std::string context, ns3::Ptr<ns3::Packet const> packet, double snr, ns3::WifiMode mode, ns3::WifiPreamble preamble) [member function]
cls.add_method('PhyRxOkTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'snr'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::PhyStateTrace(std::string context, ns3::Time start, ns3::Time duration, ns3::WifiPhy::State state) [member function]
cls.add_method('PhyStateTrace',
'void',
[param('std::string', 'context'), param('ns3::Time', 'start'), param('ns3::Time', 'duration'), param('ns3::WifiPhy::State', 'state')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::PhyTxTrace(std::string context, ns3::Ptr<ns3::Packet const> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, uint8_t txPower) [member function]
cls.add_method('PhyTxTrace',
'void',
[param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('uint8_t', 'txPower')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::TxDataFailedTrace(std::string context, ns3::Mac48Address address) [member function]
cls.add_method('TxDataFailedTrace',
'void',
[param('std::string', 'context'), param('ns3::Mac48Address', 'address')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::TxFinalDataFailedTrace(std::string context, ns3::Mac48Address address) [member function]
cls.add_method('TxFinalDataFailedTrace',
'void',
[param('std::string', 'context'), param('ns3::Mac48Address', 'address')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::TxFinalRtsFailedTrace(std::string context, ns3::Mac48Address address) [member function]
cls.add_method('TxFinalRtsFailedTrace',
'void',
[param('std::string', 'context'), param('ns3::Mac48Address', 'address')])
## athstats-helper.h (module 'wifi'): void ns3::AthstatsWifiTraceSink::TxRtsFailedTrace(std::string context, ns3::Mac48Address address) [member function]
cls.add_method('TxRtsFailedTrace',
'void',
[param('std::string', 'context'), param('ns3::Mac48Address', 'address')])
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_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_Ns3CaraWifiManager_methods(root_module, cls):
## cara-wifi-manager.h (module 'wifi'): ns3::CaraWifiManager::CaraWifiManager(ns3::CaraWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CaraWifiManager const &', 'arg0')])
## cara-wifi-manager.h (module 'wifi'): ns3::CaraWifiManager::CaraWifiManager() [constructor]
cls.add_constructor([])
## cara-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::CaraWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## cara-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::CaraWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::CaraWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::CaraWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): bool ns3::CaraWifiManager::DoNeedRts(ns3::WifiRemoteStation * station, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRts',
'bool',
[param('ns3::WifiRemoteStation *', 'station'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): void ns3::CaraWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## cara-wifi-manager.h (module 'wifi'): bool ns3::CaraWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Channel_methods(root_module, cls):
## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Channel const &', 'arg0')])
## channel.h (module 'network'): ns3::Channel::Channel() [constructor]
cls.add_constructor([])
## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3ConstantRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function]
cls.add_method('GetConstant',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'constant')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'constant')])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ConstantRateWifiManager_methods(root_module, cls):
## constant-rate-wifi-manager.h (module 'wifi'): ns3::ConstantRateWifiManager::ConstantRateWifiManager(ns3::ConstantRateWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ConstantRateWifiManager const &', 'arg0')])
## constant-rate-wifi-manager.h (module 'wifi'): ns3::ConstantRateWifiManager::ConstantRateWifiManager() [constructor]
cls.add_constructor([])
## constant-rate-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::ConstantRateWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## constant-rate-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::ConstantRateWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::ConstantRateWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::ConstantRateWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): void ns3::ConstantRateWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## constant-rate-wifi-manager.h (module 'wifi'): bool ns3::ConstantRateWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3ConstantSpeedPropagationDelayModel_methods(root_module, cls):
## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel::ConstantSpeedPropagationDelayModel(ns3::ConstantSpeedPropagationDelayModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ConstantSpeedPropagationDelayModel const &', 'arg0')])
## propagation-delay-model.h (module 'propagation'): ns3::ConstantSpeedPropagationDelayModel::ConstantSpeedPropagationDelayModel() [constructor]
cls.add_constructor([])
## propagation-delay-model.h (module 'propagation'): ns3::Time ns3::ConstantSpeedPropagationDelayModel::GetDelay(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetDelay',
'ns3::Time',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, is_virtual=True)
## propagation-delay-model.h (module 'propagation'): double ns3::ConstantSpeedPropagationDelayModel::GetSpeed() const [member function]
cls.add_method('GetSpeed',
'double',
[],
is_const=True)
## propagation-delay-model.h (module 'propagation'): static ns3::TypeId ns3::ConstantSpeedPropagationDelayModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-delay-model.h (module 'propagation'): void ns3::ConstantSpeedPropagationDelayModel::SetSpeed(double speed) [member function]
cls.add_method('SetSpeed',
'void',
[param('double', 'speed')])
## propagation-delay-model.h (module 'propagation'): int64_t ns3::ConstantSpeedPropagationDelayModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3Cost231PropagationLossModel_methods(root_module, cls):
## cost231-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::Cost231PropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## cost231-propagation-loss-model.h (module 'propagation'): ns3::Cost231PropagationLossModel::Cost231PropagationLossModel() [constructor]
cls.add_constructor([])
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetBSAntennaHeight(double height) [member function]
cls.add_method('SetBSAntennaHeight',
'void',
[param('double', 'height')])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetSSAntennaHeight(double height) [member function]
cls.add_method('SetSSAntennaHeight',
'void',
[param('double', 'height')])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetEnvironment(ns3::Cost231PropagationLossModel::Environment env) [member function]
cls.add_method('SetEnvironment',
'void',
[param('ns3::Cost231PropagationLossModel::Environment', 'env')])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetLambda(double lambda) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'lambda')])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetMinDistance(double minDistance) [member function]
cls.add_method('SetMinDistance',
'void',
[param('double', 'minDistance')])
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetBSAntennaHeight() const [member function]
cls.add_method('GetBSAntennaHeight',
'double',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetSSAntennaHeight() const [member function]
cls.add_method('GetSSAntennaHeight',
'double',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): ns3::Cost231PropagationLossModel::Environment ns3::Cost231PropagationLossModel::GetEnvironment() const [member function]
cls.add_method('GetEnvironment',
'ns3::Cost231PropagationLossModel::Environment',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetMinDistance() const [member function]
cls.add_method('GetMinDistance',
'double',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetLambda(double frequency, double speed) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'frequency'), param('double', 'speed')])
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::GetShadowing() [member function]
cls.add_method('GetShadowing',
'double',
[])
## cost231-propagation-loss-model.h (module 'propagation'): void ns3::Cost231PropagationLossModel::SetShadowing(double shadowing) [member function]
cls.add_method('SetShadowing',
'void',
[param('double', 'shadowing')])
## cost231-propagation-loss-model.h (module 'propagation'): double ns3::Cost231PropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## cost231-propagation-loss-model.h (module 'propagation'): int64_t ns3::Cost231PropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3CtrlBAckRequestHeader_methods(root_module, cls):
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckRequestHeader::CtrlBAckRequestHeader(ns3::CtrlBAckRequestHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CtrlBAckRequestHeader const &', 'arg0')])
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckRequestHeader::CtrlBAckRequestHeader() [constructor]
cls.add_constructor([])
## ctrl-headers.h (module 'wifi'): uint32_t ns3::CtrlBAckRequestHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ctrl-headers.h (module 'wifi'): ns3::TypeId ns3::CtrlBAckRequestHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint32_t ns3::CtrlBAckRequestHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint16_t ns3::CtrlBAckRequestHeader::GetStartingSequence() const [member function]
cls.add_method('GetStartingSequence',
'uint16_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint16_t ns3::CtrlBAckRequestHeader::GetStartingSequenceControl() const [member function]
cls.add_method('GetStartingSequenceControl',
'uint16_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint8_t ns3::CtrlBAckRequestHeader::GetTidInfo() const [member function]
cls.add_method('GetTidInfo',
'uint8_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): static ns3::TypeId ns3::CtrlBAckRequestHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckRequestHeader::IsBasic() const [member function]
cls.add_method('IsBasic',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckRequestHeader::IsCompressed() const [member function]
cls.add_method('IsCompressed',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckRequestHeader::IsMultiTid() const [member function]
cls.add_method('IsMultiTid',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckRequestHeader::MustSendHtImmediateAck() const [member function]
cls.add_method('MustSendHtImmediateAck',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::SetHtImmediateAck(bool immediateAck) [member function]
cls.add_method('SetHtImmediateAck',
'void',
[param('bool', 'immediateAck')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::SetStartingSequence(uint16_t seq) [member function]
cls.add_method('SetStartingSequence',
'void',
[param('uint16_t', 'seq')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::SetTidInfo(uint8_t tid) [member function]
cls.add_method('SetTidInfo',
'void',
[param('uint8_t', 'tid')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckRequestHeader::SetType(ns3::BlockAckType type) [member function]
cls.add_method('SetType',
'void',
[param('ns3::BlockAckType', 'type')])
return
def register_Ns3CtrlBAckResponseHeader_methods(root_module, cls):
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckResponseHeader::CtrlBAckResponseHeader(ns3::CtrlBAckResponseHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CtrlBAckResponseHeader const &', 'arg0')])
## ctrl-headers.h (module 'wifi'): ns3::CtrlBAckResponseHeader::CtrlBAckResponseHeader() [constructor]
cls.add_constructor([])
## ctrl-headers.h (module 'wifi'): uint32_t ns3::CtrlBAckResponseHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint16_t const * ns3::CtrlBAckResponseHeader::GetBitmap() const [member function]
cls.add_method('GetBitmap',
'uint16_t const *',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint64_t ns3::CtrlBAckResponseHeader::GetCompressedBitmap() const [member function]
cls.add_method('GetCompressedBitmap',
'uint64_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): ns3::TypeId ns3::CtrlBAckResponseHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint32_t ns3::CtrlBAckResponseHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): uint16_t ns3::CtrlBAckResponseHeader::GetStartingSequence() const [member function]
cls.add_method('GetStartingSequence',
'uint16_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint16_t ns3::CtrlBAckResponseHeader::GetStartingSequenceControl() const [member function]
cls.add_method('GetStartingSequenceControl',
'uint16_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): uint8_t ns3::CtrlBAckResponseHeader::GetTidInfo() const [member function]
cls.add_method('GetTidInfo',
'uint8_t',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): static ns3::TypeId ns3::CtrlBAckResponseHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsBasic() const [member function]
cls.add_method('IsBasic',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsCompressed() const [member function]
cls.add_method('IsCompressed',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsFragmentReceived(uint16_t seq, uint8_t frag) const [member function]
cls.add_method('IsFragmentReceived',
'bool',
[param('uint16_t', 'seq'), param('uint8_t', 'frag')],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsMultiTid() const [member function]
cls.add_method('IsMultiTid',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::IsPacketReceived(uint16_t seq) const [member function]
cls.add_method('IsPacketReceived',
'bool',
[param('uint16_t', 'seq')],
is_const=True)
## ctrl-headers.h (module 'wifi'): bool ns3::CtrlBAckResponseHeader::MustSendHtImmediateAck() const [member function]
cls.add_method('MustSendHtImmediateAck',
'bool',
[],
is_const=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::ResetBitmap() [member function]
cls.add_method('ResetBitmap',
'void',
[])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetHtImmediateAck(bool immeadiateAck) [member function]
cls.add_method('SetHtImmediateAck',
'void',
[param('bool', 'immeadiateAck')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetReceivedFragment(uint16_t seq, uint8_t frag) [member function]
cls.add_method('SetReceivedFragment',
'void',
[param('uint16_t', 'seq'), param('uint8_t', 'frag')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetReceivedPacket(uint16_t seq) [member function]
cls.add_method('SetReceivedPacket',
'void',
[param('uint16_t', 'seq')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetStartingSequence(uint16_t seq) [member function]
cls.add_method('SetStartingSequence',
'void',
[param('uint16_t', 'seq')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetStartingSequenceControl(uint16_t seqControl) [member function]
cls.add_method('SetStartingSequenceControl',
'void',
[param('uint16_t', 'seqControl')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetTidInfo(uint8_t tid) [member function]
cls.add_method('SetTidInfo',
'void',
[param('uint8_t', 'tid')])
## ctrl-headers.h (module 'wifi'): void ns3::CtrlBAckResponseHeader::SetType(ns3::BlockAckType type) [member function]
cls.add_method('SetType',
'void',
[param('ns3::BlockAckType', 'type')])
return
def register_Ns3Dcf_methods(root_module, cls):
## dcf.h (module 'wifi'): ns3::Dcf::Dcf() [constructor]
cls.add_constructor([])
## dcf.h (module 'wifi'): ns3::Dcf::Dcf(ns3::Dcf const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Dcf const &', 'arg0')])
## dcf.h (module 'wifi'): uint32_t ns3::Dcf::GetAifsn() const [member function]
cls.add_method('GetAifsn',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## dcf.h (module 'wifi'): uint32_t ns3::Dcf::GetMaxCw() const [member function]
cls.add_method('GetMaxCw',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## dcf.h (module 'wifi'): uint32_t ns3::Dcf::GetMinCw() const [member function]
cls.add_method('GetMinCw',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## dcf.h (module 'wifi'): static ns3::TypeId ns3::Dcf::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dcf.h (module 'wifi'): void ns3::Dcf::SetAifsn(uint32_t aifsn) [member function]
cls.add_method('SetAifsn',
'void',
[param('uint32_t', 'aifsn')],
is_pure_virtual=True, is_virtual=True)
## dcf.h (module 'wifi'): void ns3::Dcf::SetMaxCw(uint32_t maxCw) [member function]
cls.add_method('SetMaxCw',
'void',
[param('uint32_t', 'maxCw')],
is_pure_virtual=True, is_virtual=True)
## dcf.h (module 'wifi'): void ns3::Dcf::SetMinCw(uint32_t minCw) [member function]
cls.add_method('SetMinCw',
'void',
[param('uint32_t', 'minCw')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3DeterministicRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function]
cls.add_method('SetValueArray',
'void',
[param('double *', 'values'), param('uint64_t', 'length')])
## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_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_Ns3EdcaTxopN_methods(root_module, cls):
## edca-txop-n.h (module 'wifi'): static ns3::TypeId ns3::EdcaTxopN::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## edca-txop-n.h (module 'wifi'): ns3::EdcaTxopN::EdcaTxopN() [constructor]
cls.add_constructor([])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetLow(ns3::Ptr<ns3::MacLow> low) [member function]
cls.add_method('SetLow',
'void',
[param('ns3::Ptr< ns3::MacLow >', 'low')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetTxMiddle(ns3::MacTxMiddle * txMiddle) [member function]
cls.add_method('SetTxMiddle',
'void',
[param('ns3::MacTxMiddle *', 'txMiddle')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetManager(ns3::DcfManager * manager) [member function]
cls.add_method('SetManager',
'void',
[param('ns3::DcfManager *', 'manager')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetTxOkCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetTxOkCallback',
'void',
[param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetTxFailedCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetTxFailedCallback',
'void',
[param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> remoteManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'remoteManager')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetTypeOfStation(ns3::TypeOfStation type) [member function]
cls.add_method('SetTypeOfStation',
'void',
[param('ns3::TypeOfStation', 'type')])
## edca-txop-n.h (module 'wifi'): ns3::TypeOfStation ns3::EdcaTxopN::GetTypeOfStation() const [member function]
cls.add_method('GetTypeOfStation',
'ns3::TypeOfStation',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): ns3::Ptr<ns3::WifiMacQueue> ns3::EdcaTxopN::GetQueue() const [member function]
cls.add_method('GetQueue',
'ns3::Ptr< ns3::WifiMacQueue >',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetMinCw(uint32_t minCw) [member function]
cls.add_method('SetMinCw',
'void',
[param('uint32_t', 'minCw')],
is_virtual=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetMaxCw(uint32_t maxCw) [member function]
cls.add_method('SetMaxCw',
'void',
[param('uint32_t', 'maxCw')],
is_virtual=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetAifsn(uint32_t aifsn) [member function]
cls.add_method('SetAifsn',
'void',
[param('uint32_t', 'aifsn')],
is_virtual=True)
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetMinCw() const [member function]
cls.add_method('GetMinCw',
'uint32_t',
[],
is_const=True, is_virtual=True)
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetMaxCw() const [member function]
cls.add_method('GetMaxCw',
'uint32_t',
[],
is_const=True, is_virtual=True)
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetAifsn() const [member function]
cls.add_method('GetAifsn',
'uint32_t',
[],
is_const=True, is_virtual=True)
## edca-txop-n.h (module 'wifi'): ns3::Ptr<ns3::MacLow> ns3::EdcaTxopN::Low() [member function]
cls.add_method('Low',
'ns3::Ptr< ns3::MacLow >',
[])
## edca-txop-n.h (module 'wifi'): ns3::Ptr<ns3::MsduAggregator> ns3::EdcaTxopN::GetMsduAggregator() const [member function]
cls.add_method('GetMsduAggregator',
'ns3::Ptr< ns3::MsduAggregator >',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedsAccess() const [member function]
cls.add_method('NeedsAccess',
'bool',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NotifyAccessGranted() [member function]
cls.add_method('NotifyAccessGranted',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NotifyInternalCollision() [member function]
cls.add_method('NotifyInternalCollision',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NotifyCollision() [member function]
cls.add_method('NotifyCollision',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NotifyChannelSwitching() [member function]
cls.add_method('NotifyChannelSwitching',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotCts(double snr, ns3::WifiMode txMode) [member function]
cls.add_method('GotCts',
'void',
[param('double', 'snr'), param('ns3::WifiMode', 'txMode')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::MissedCts() [member function]
cls.add_method('MissedCts',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotAck(double snr, ns3::WifiMode txMode) [member function]
cls.add_method('GotAck',
'void',
[param('double', 'snr'), param('ns3::WifiMode', 'txMode')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotBlockAck(ns3::CtrlBAckResponseHeader const * blockAck, ns3::Mac48Address recipient) [member function]
cls.add_method('GotBlockAck',
'void',
[param('ns3::CtrlBAckResponseHeader const *', 'blockAck'), param('ns3::Mac48Address', 'recipient')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::MissedBlockAck() [member function]
cls.add_method('MissedBlockAck',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotAddBaResponse(ns3::MgtAddBaResponseHeader const * respHdr, ns3::Mac48Address recipient) [member function]
cls.add_method('GotAddBaResponse',
'void',
[param('ns3::MgtAddBaResponseHeader const *', 'respHdr'), param('ns3::Mac48Address', 'recipient')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::GotDelBaFrame(ns3::MgtDelBaHeader const * delBaHdr, ns3::Mac48Address recipient) [member function]
cls.add_method('GotDelBaFrame',
'void',
[param('ns3::MgtDelBaHeader const *', 'delBaHdr'), param('ns3::Mac48Address', 'recipient')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::MissedAck() [member function]
cls.add_method('MissedAck',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::StartNext() [member function]
cls.add_method('StartNext',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::EndTxNoAck() [member function]
cls.add_method('EndTxNoAck',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::RestartAccessIfNeeded() [member function]
cls.add_method('RestartAccessIfNeeded',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::StartAccessIfNeeded() [member function]
cls.add_method('StartAccessIfNeeded',
'void',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedRts() [member function]
cls.add_method('NeedRts',
'bool',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedRtsRetransmission() [member function]
cls.add_method('NeedRtsRetransmission',
'bool',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedDataRetransmission() [member function]
cls.add_method('NeedDataRetransmission',
'bool',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::NeedFragmentation() const [member function]
cls.add_method('NeedFragmentation',
'bool',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetNextFragmentSize() [member function]
cls.add_method('GetNextFragmentSize',
'uint32_t',
[])
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetFragmentSize() [member function]
cls.add_method('GetFragmentSize',
'uint32_t',
[])
## edca-txop-n.h (module 'wifi'): uint32_t ns3::EdcaTxopN::GetFragmentOffset() [member function]
cls.add_method('GetFragmentOffset',
'uint32_t',
[])
## edca-txop-n.h (module 'wifi'): bool ns3::EdcaTxopN::IsLastFragment() const [member function]
cls.add_method('IsLastFragment',
'bool',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::NextFragment() [member function]
cls.add_method('NextFragment',
'void',
[])
## edca-txop-n.h (module 'wifi'): ns3::Ptr<ns3::Packet> ns3::EdcaTxopN::GetFragmentPacket(ns3::WifiMacHeader * hdr) [member function]
cls.add_method('GetFragmentPacket',
'ns3::Ptr< ns3::Packet >',
[param('ns3::WifiMacHeader *', 'hdr')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetAccessCategory(ns3::AcIndex ac) [member function]
cls.add_method('SetAccessCategory',
'void',
[param('ns3::AcIndex', 'ac')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::Queue(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('Queue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetMsduAggregator(ns3::Ptr<ns3::MsduAggregator> aggr) [member function]
cls.add_method('SetMsduAggregator',
'void',
[param('ns3::Ptr< ns3::MsduAggregator >', 'aggr')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::PushFront(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::CompleteConfig() [member function]
cls.add_method('CompleteConfig',
'void',
[])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetBlockAckThreshold(uint8_t threshold) [member function]
cls.add_method('SetBlockAckThreshold',
'void',
[param('uint8_t', 'threshold')])
## edca-txop-n.h (module 'wifi'): uint8_t ns3::EdcaTxopN::GetBlockAckThreshold() const [member function]
cls.add_method('GetBlockAckThreshold',
'uint8_t',
[],
is_const=True)
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SetBlockAckInactivityTimeout(uint16_t timeout) [member function]
cls.add_method('SetBlockAckInactivityTimeout',
'void',
[param('uint16_t', 'timeout')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::SendDelbaFrame(ns3::Mac48Address addr, uint8_t tid, bool byOriginator) [member function]
cls.add_method('SendDelbaFrame',
'void',
[param('ns3::Mac48Address', 'addr'), param('uint8_t', 'tid'), param('bool', 'byOriginator')])
## edca-txop-n.h (module 'wifi'): int64_t ns3::EdcaTxopN::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## edca-txop-n.h (module 'wifi'): void ns3::EdcaTxopN::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EmpiricalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function]
cls.add_method('CDF',
'void',
[param('double', 'v'), param('double', 'c')])
## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double arg0, double arg1, double arg2, double arg3, double arg4) [member function]
cls.add_method('Interpolate',
'double',
[param('double', 'arg0'), param('double', 'arg1'), param('double', 'arg2'), param('double', 'arg3'), param('double', 'arg4')],
visibility='private', is_virtual=True)
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function]
cls.add_method('Validate',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3EmptyAttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, visibility='private', is_virtual=True)
## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
visibility='private', is_virtual=True)
## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3ErlangRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function]
cls.add_method('GetK',
'uint32_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function]
cls.add_method('GetValue',
'double',
[param('uint32_t', 'k'), param('double', 'lambda')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'k'), param('uint32_t', 'lambda')])
## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ErrorRateModel_methods(root_module, cls):
## error-rate-model.h (module 'wifi'): ns3::ErrorRateModel::ErrorRateModel() [constructor]
cls.add_constructor([])
## error-rate-model.h (module 'wifi'): ns3::ErrorRateModel::ErrorRateModel(ns3::ErrorRateModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ErrorRateModel const &', 'arg0')])
## error-rate-model.h (module 'wifi'): double ns3::ErrorRateModel::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function]
cls.add_method('CalculateSnr',
'double',
[param('ns3::WifiMode', 'txMode'), param('double', 'ber')],
is_const=True)
## error-rate-model.h (module 'wifi'): double ns3::ErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function]
cls.add_method('GetChunkSuccessRate',
'double',
[param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## error-rate-model.h (module 'wifi'): static ns3::TypeId ns3::ErrorRateModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3EventImpl_methods(root_module, cls):
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventImpl const &', 'arg0')])
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor]
cls.add_constructor([])
## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[])
## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function]
cls.add_method('IsCancelled',
'bool',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function]
cls.add_method('Notify',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3ExponentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ExtendedSupportedRatesIE_methods(root_module, cls):
## supported-rates.h (module 'wifi'): ns3::ExtendedSupportedRatesIE::ExtendedSupportedRatesIE(ns3::ExtendedSupportedRatesIE const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ExtendedSupportedRatesIE const &', 'arg0')])
## supported-rates.h (module 'wifi'): ns3::ExtendedSupportedRatesIE::ExtendedSupportedRatesIE() [constructor]
cls.add_constructor([])
## supported-rates.h (module 'wifi'): ns3::ExtendedSupportedRatesIE::ExtendedSupportedRatesIE(ns3::SupportedRates * rates) [constructor]
cls.add_constructor([param('ns3::SupportedRates *', 'rates')])
## supported-rates.h (module 'wifi'): uint8_t ns3::ExtendedSupportedRatesIE::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_virtual=True)
## supported-rates.h (module 'wifi'): ns3::WifiInformationElementId ns3::ExtendedSupportedRatesIE::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): uint8_t ns3::ExtendedSupportedRatesIE::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): uint16_t ns3::ExtendedSupportedRatesIE::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint16_t',
[],
is_const=True)
## supported-rates.h (module 'wifi'): ns3::Buffer::Iterator ns3::ExtendedSupportedRatesIE::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'ns3::Buffer::Iterator',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True)
## supported-rates.h (module 'wifi'): void ns3::ExtendedSupportedRatesIE::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
return
def register_Ns3FixedRssLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::FixedRssLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::FixedRssLossModel::FixedRssLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::FixedRssLossModel::SetRss(double rss) [member function]
cls.add_method('SetRss',
'void',
[param('double', 'rss')])
## propagation-loss-model.h (module 'propagation'): double ns3::FixedRssLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::FixedRssLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3FriisPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::FriisPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::FriisPropagationLossModel::FriisPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetLambda(double frequency, double speed) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'frequency'), param('double', 'speed')])
## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetLambda(double lambda) [member function]
cls.add_method('SetLambda',
'void',
[param('double', 'lambda')])
## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetSystemLoss(double systemLoss) [member function]
cls.add_method('SetSystemLoss',
'void',
[param('double', 'systemLoss')])
## propagation-loss-model.h (module 'propagation'): void ns3::FriisPropagationLossModel::SetMinDistance(double minDistance) [member function]
cls.add_method('SetMinDistance',
'void',
[param('double', 'minDistance')])
## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetMinDistance() const [member function]
cls.add_method('GetMinDistance',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetLambda() const [member function]
cls.add_method('GetLambda',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::GetSystemLoss() const [member function]
cls.add_method('GetSystemLoss',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): double ns3::FriisPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::FriisPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3GammaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function]
cls.add_method('GetBeta',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha'), param('double', 'beta')])
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha'), param('uint32_t', 'beta')])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3IdealWifiManager_methods(root_module, cls):
## ideal-wifi-manager.h (module 'wifi'): ns3::IdealWifiManager::IdealWifiManager(ns3::IdealWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IdealWifiManager const &', 'arg0')])
## ideal-wifi-manager.h (module 'wifi'): ns3::IdealWifiManager::IdealWifiManager() [constructor]
cls.add_constructor([])
## ideal-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::IdealWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetupPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::IdealWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::IdealWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::IdealWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): void ns3::IdealWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## ideal-wifi-manager.h (module 'wifi'): bool ns3::IdealWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Ipv4AddressChecker_methods(root_module, cls):
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [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_Ns3ItuR1411LosPropagationLossModel_methods(root_module, cls):
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): ns3::ItuR1411LosPropagationLossModel::ItuR1411LosPropagationLossModel() [constructor]
cls.add_constructor([])
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::ItuR1411LosPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): void ns3::ItuR1411LosPropagationLossModel::SetFrequency(double freq) [member function]
cls.add_method('SetFrequency',
'void',
[param('double', 'freq')])
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): double ns3::ItuR1411LosPropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): double ns3::ItuR1411LosPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## itu-r-1411-los-propagation-loss-model.h (module 'propagation'): int64_t ns3::ItuR1411LosPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3ItuR1411NlosOverRooftopPropagationLossModel_methods(root_module, cls):
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): ns3::ItuR1411NlosOverRooftopPropagationLossModel::ItuR1411NlosOverRooftopPropagationLossModel() [constructor]
cls.add_constructor([])
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::ItuR1411NlosOverRooftopPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): void ns3::ItuR1411NlosOverRooftopPropagationLossModel::SetFrequency(double freq) [member function]
cls.add_method('SetFrequency',
'void',
[param('double', 'freq')])
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): double ns3::ItuR1411NlosOverRooftopPropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): double ns3::ItuR1411NlosOverRooftopPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## itu-r-1411-nlos-over-rooftop-propagation-loss-model.h (module 'propagation'): int64_t ns3::ItuR1411NlosOverRooftopPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3JakesProcess_methods(root_module, cls):
## jakes-process.h (module 'propagation'): ns3::JakesProcess::JakesProcess(ns3::JakesProcess const & arg0) [copy constructor]
cls.add_constructor([param('ns3::JakesProcess const &', 'arg0')])
## jakes-process.h (module 'propagation'): ns3::JakesProcess::JakesProcess() [constructor]
cls.add_constructor([])
## jakes-process.h (module 'propagation'): void ns3::JakesProcess::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
is_virtual=True)
## jakes-process.h (module 'propagation'): double ns3::JakesProcess::GetChannelGainDb() const [member function]
cls.add_method('GetChannelGainDb',
'double',
[],
is_const=True)
## jakes-process.h (module 'propagation'): std::complex<double> ns3::JakesProcess::GetComplexGain() const [member function]
cls.add_method('GetComplexGain',
'std::complex< double >',
[],
is_const=True)
## jakes-process.h (module 'propagation'): static ns3::TypeId ns3::JakesProcess::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## jakes-process.h (module 'propagation'): void ns3::JakesProcess::SetPropagationLossModel(ns3::Ptr<const ns3::PropagationLossModel> arg0) [member function]
cls.add_method('SetPropagationLossModel',
'void',
[param('ns3::Ptr< ns3::PropagationLossModel const >', 'arg0')])
return
def register_Ns3JakesPropagationLossModel_methods(root_module, cls):
## jakes-propagation-loss-model.h (module 'propagation'): ns3::JakesPropagationLossModel::PI [variable]
cls.add_static_attribute('PI', 'double const', is_const=True)
## jakes-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::JakesPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## jakes-propagation-loss-model.h (module 'propagation'): ns3::JakesPropagationLossModel::JakesPropagationLossModel() [constructor]
cls.add_constructor([])
## jakes-propagation-loss-model.h (module 'propagation'): double ns3::JakesPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## jakes-propagation-loss-model.h (module 'propagation'): int64_t ns3::JakesPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3Kun2600MhzPropagationLossModel_methods(root_module, cls):
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): ns3::Kun2600MhzPropagationLossModel::Kun2600MhzPropagationLossModel() [constructor]
cls.add_constructor([])
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::Kun2600MhzPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): double ns3::Kun2600MhzPropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): double ns3::Kun2600MhzPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## kun-2600-mhz-propagation-loss-model.h (module 'propagation'): int64_t ns3::Kun2600MhzPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3LogDistancePropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::LogDistancePropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::LogDistancePropagationLossModel::LogDistancePropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::LogDistancePropagationLossModel::SetPathLossExponent(double n) [member function]
cls.add_method('SetPathLossExponent',
'void',
[param('double', 'n')])
## propagation-loss-model.h (module 'propagation'): double ns3::LogDistancePropagationLossModel::GetPathLossExponent() const [member function]
cls.add_method('GetPathLossExponent',
'double',
[],
is_const=True)
## propagation-loss-model.h (module 'propagation'): void ns3::LogDistancePropagationLossModel::SetReference(double referenceDistance, double referenceLoss) [member function]
cls.add_method('SetReference',
'void',
[param('double', 'referenceDistance'), param('double', 'referenceLoss')])
## propagation-loss-model.h (module 'propagation'): double ns3::LogDistancePropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::LogDistancePropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3LogNormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function]
cls.add_method('GetMu',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function]
cls.add_method('GetSigma',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mu'), param('double', 'sigma')])
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mu'), param('uint32_t', 'sigma')])
## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3Mac48AddressChecker_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')])
return
def register_Ns3Mac48AddressValue_methods(root_module, cls):
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'value')])
## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac48Address',
[],
is_const=True)
## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac48Address const &', 'value')])
return
def register_Ns3MacLow_methods(root_module, cls):
## mac-low.h (module 'wifi'): ns3::MacLow::MacLow(ns3::MacLow const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MacLow const &', 'arg0')])
## mac-low.h (module 'wifi'): ns3::MacLow::MacLow() [constructor]
cls.add_constructor([])
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::CalculateTransmissionTime(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const * hdr, ns3::MacLowTransmissionParameters const & parameters) const [member function]
cls.add_method('CalculateTransmissionTime',
'ns3::Time',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr'), param('ns3::MacLowTransmissionParameters const &', 'parameters')],
is_const=True)
## mac-low.h (module 'wifi'): void ns3::MacLow::CreateBlockAckAgreement(ns3::MgtAddBaResponseHeader const * respHdr, ns3::Mac48Address originator, uint16_t startingSeq) [member function]
cls.add_method('CreateBlockAckAgreement',
'void',
[param('ns3::MgtAddBaResponseHeader const *', 'respHdr'), param('ns3::Mac48Address', 'originator'), param('uint16_t', 'startingSeq')])
## mac-low.h (module 'wifi'): void ns3::MacLow::DestroyBlockAckAgreement(ns3::Mac48Address originator, uint8_t tid) [member function]
cls.add_method('DestroyBlockAckAgreement',
'void',
[param('ns3::Mac48Address', 'originator'), param('uint8_t', 'tid')])
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetAckTimeout() const [member function]
cls.add_method('GetAckTimeout',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Mac48Address ns3::MacLow::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Mac48Address',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetBasicBlockAckTimeout() const [member function]
cls.add_method('GetBasicBlockAckTimeout',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Mac48Address ns3::MacLow::GetBssid() const [member function]
cls.add_method('GetBssid',
'ns3::Mac48Address',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetCompressedBlockAckTimeout() const [member function]
cls.add_method('GetCompressedBlockAckTimeout',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetCtsTimeout() const [member function]
cls.add_method('GetCtsTimeout',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetPifs() const [member function]
cls.add_method('GetPifs',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetSifs() const [member function]
cls.add_method('GetSifs',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): ns3::Time ns3::MacLow::GetSlotTime() const [member function]
cls.add_method('GetSlotTime',
'ns3::Time',
[],
is_const=True)
## mac-low.h (module 'wifi'): void ns3::MacLow::NotifySwitchingStartNow(ns3::Time duration) [member function]
cls.add_method('NotifySwitchingStartNow',
'void',
[param('ns3::Time', 'duration')])
## mac-low.h (module 'wifi'): void ns3::MacLow::ReceiveError(ns3::Ptr<ns3::Packet const> packet, double rxSnr) [member function]
cls.add_method('ReceiveError',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'rxSnr')])
## mac-low.h (module 'wifi'): void ns3::MacLow::ReceiveOk(ns3::Ptr<ns3::Packet> packet, double rxSnr, ns3::WifiMode txMode, ns3::WifiPreamble preamble) [member function]
cls.add_method('ReceiveOk',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode'), param('ns3::WifiPreamble', 'preamble')])
## mac-low.h (module 'wifi'): void ns3::MacLow::RegisterBlockAckListenerForAc(ns3::AcIndex ac, ns3::MacLowBlockAckEventListener * listener) [member function]
cls.add_method('RegisterBlockAckListenerForAc',
'void',
[param('ns3::AcIndex', 'ac'), param('ns3::MacLowBlockAckEventListener *', 'listener')])
## mac-low.h (module 'wifi'): void ns3::MacLow::RegisterDcfListener(ns3::MacLowDcfListener * listener) [member function]
cls.add_method('RegisterDcfListener',
'void',
[param('ns3::MacLowDcfListener *', 'listener')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetAckTimeout(ns3::Time ackTimeout) [member function]
cls.add_method('SetAckTimeout',
'void',
[param('ns3::Time', 'ackTimeout')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetAddress(ns3::Mac48Address ad) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'ad')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetBasicBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetBssid(ns3::Mac48Address ad) [member function]
cls.add_method('SetBssid',
'void',
[param('ns3::Mac48Address', 'ad')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetCompressedBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetCtsTimeout(ns3::Time ctsTimeout) [member function]
cls.add_method('SetCtsTimeout',
'void',
[param('ns3::Time', 'ctsTimeout')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetPifs(ns3::Time pifs) [member function]
cls.add_method('SetPifs',
'void',
[param('ns3::Time', 'pifs')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetPromisc() [member function]
cls.add_method('SetPromisc',
'void',
[])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetRxCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::WifiMacHeader const*, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetRxCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::WifiMacHeader const *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetSifs(ns3::Time sifs) [member function]
cls.add_method('SetSifs',
'void',
[param('ns3::Time', 'sifs')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetSlotTime(ns3::Time slotTime) [member function]
cls.add_method('SetSlotTime',
'void',
[param('ns3::Time', 'slotTime')])
## mac-low.h (module 'wifi'): void ns3::MacLow::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> manager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'manager')])
## mac-low.h (module 'wifi'): void ns3::MacLow::StartTransmission(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const * hdr, ns3::MacLowTransmissionParameters parameters, ns3::MacLowTransmissionListener * listener) [member function]
cls.add_method('StartTransmission',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr'), param('ns3::MacLowTransmissionParameters', 'parameters'), param('ns3::MacLowTransmissionListener *', 'listener')])
## mac-low.h (module 'wifi'): void ns3::MacLow::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3MatrixPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::MatrixPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::MatrixPropagationLossModel::MatrixPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): void ns3::MatrixPropagationLossModel::SetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b, double loss, bool symmetric=true) [member function]
cls.add_method('SetLoss',
'void',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b'), param('double', 'loss'), param('bool', 'symmetric', default_value='true')])
## propagation-loss-model.h (module 'propagation'): void ns3::MatrixPropagationLossModel::SetDefaultLoss(double arg0) [member function]
cls.add_method('SetDefaultLoss',
'void',
[param('double', 'arg0')])
## propagation-loss-model.h (module 'propagation'): double ns3::MatrixPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::MatrixPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3MgtBeaconHeader_methods(root_module, cls):
## mgt-headers.h (module 'wifi'): ns3::MgtBeaconHeader::MgtBeaconHeader() [constructor]
cls.add_constructor([])
## mgt-headers.h (module 'wifi'): ns3::MgtBeaconHeader::MgtBeaconHeader(ns3::MgtBeaconHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MgtBeaconHeader const &', 'arg0')])
return
def register_Ns3MinstrelWifiManager_methods(root_module, cls):
## minstrel-wifi-manager.h (module 'wifi'): ns3::MinstrelWifiManager::MinstrelWifiManager(ns3::MinstrelWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MinstrelWifiManager const &', 'arg0')])
## minstrel-wifi-manager.h (module 'wifi'): ns3::MinstrelWifiManager::MinstrelWifiManager() [constructor]
cls.add_constructor([])
## minstrel-wifi-manager.h (module 'wifi'): int64_t ns3::MinstrelWifiManager::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## minstrel-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::MinstrelWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::SetupPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetupPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::MinstrelWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::MinstrelWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::MinstrelWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): void ns3::MinstrelWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## minstrel-wifi-manager.h (module 'wifi'): bool ns3::MinstrelWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3MobilityModel_methods(root_module, cls):
## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel(ns3::MobilityModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MobilityModel const &', 'arg0')])
## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel() [constructor]
cls.add_constructor([])
## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr<ns3::MobilityModel const> 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<ns3::MobilityModel const> other) const [member function]
cls.add_method('GetRelativeSpeed',
'double',
[param('ns3::Ptr< ns3::MobilityModel const >', 'other')],
is_const=True)
## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function]
cls.add_method('GetVelocity',
'ns3::Vector',
[],
is_const=True)
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function]
cls.add_method('SetPosition',
'void',
[param('ns3::Vector const &', 'position')])
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function]
cls.add_method('NotifyCourseChange',
'void',
[],
is_const=True, visibility='protected')
## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::DoAssignStreams(int64_t start) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'start')],
visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function]
cls.add_method('DoGetPosition',
'ns3::Vector',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function]
cls.add_method('DoGetVelocity',
'ns3::Vector',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function]
cls.add_method('DoSetPosition',
'void',
[param('ns3::Vector const &', 'position')],
is_pure_virtual=True, visibility='private', is_virtual=True)
return
def register_Ns3MsduAggregator_methods(root_module, cls):
## msdu-aggregator.h (module 'wifi'): ns3::MsduAggregator::MsduAggregator() [constructor]
cls.add_constructor([])
## msdu-aggregator.h (module 'wifi'): ns3::MsduAggregator::MsduAggregator(ns3::MsduAggregator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MsduAggregator const &', 'arg0')])
## msdu-aggregator.h (module 'wifi'): bool ns3::MsduAggregator::Aggregate(ns3::Ptr<ns3::Packet const> packet, ns3::Ptr<ns3::Packet> aggregatedPacket, ns3::Mac48Address src, ns3::Mac48Address dest) [member function]
cls.add_method('Aggregate',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket'), param('ns3::Mac48Address', 'src'), param('ns3::Mac48Address', 'dest')],
is_pure_virtual=True, is_virtual=True)
## msdu-aggregator.h (module 'wifi'): static std::list<std::pair<ns3::Ptr<ns3::Packet>, ns3::AmsduSubframeHeader>, std::allocator<std::pair<ns3::Ptr<ns3::Packet>, ns3::AmsduSubframeHeader> > > ns3::MsduAggregator::Deaggregate(ns3::Ptr<ns3::Packet> aggregatedPacket) [member function]
cls.add_method('Deaggregate',
'std::list< std::pair< ns3::Ptr< ns3::Packet >, ns3::AmsduSubframeHeader > >',
[param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket')],
is_static=True)
## msdu-aggregator.h (module 'wifi'): static ns3::TypeId ns3::MsduAggregator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3NakagamiPropagationLossModel_methods(root_module, cls):
## propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::NakagamiPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## propagation-loss-model.h (module 'propagation'): ns3::NakagamiPropagationLossModel::NakagamiPropagationLossModel() [constructor]
cls.add_constructor([])
## propagation-loss-model.h (module 'propagation'): double ns3::NakagamiPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## propagation-loss-model.h (module 'propagation'): int64_t ns3::NakagamiPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
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<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, 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 >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::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_Ns3NistErrorRateModel_methods(root_module, cls):
## nist-error-rate-model.h (module 'wifi'): ns3::NistErrorRateModel::NistErrorRateModel(ns3::NistErrorRateModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NistErrorRateModel const &', 'arg0')])
## nist-error-rate-model.h (module 'wifi'): ns3::NistErrorRateModel::NistErrorRateModel() [constructor]
cls.add_constructor([])
## nist-error-rate-model.h (module 'wifi'): double ns3::NistErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function]
cls.add_method('GetChunkSuccessRate',
'double',
[param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')],
is_const=True, is_virtual=True)
## nist-error-rate-model.h (module 'wifi'): static ns3::TypeId ns3::NistErrorRateModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=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::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3NormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable]
cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function]
cls.add_method('GetVariance',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')])
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ObjectFactoryChecker_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')])
return
def register_Ns3ObjectFactoryValue_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'value')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function]
cls.add_method('Get',
'ns3::ObjectFactory',
[],
is_const=True)
## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::ObjectFactory const &', 'value')])
return
def register_Ns3OkumuraHataPropagationLossModel_methods(root_module, cls):
## okumura-hata-propagation-loss-model.h (module 'propagation'): ns3::OkumuraHataPropagationLossModel::OkumuraHataPropagationLossModel() [constructor]
cls.add_constructor([])
## okumura-hata-propagation-loss-model.h (module 'propagation'): static ns3::TypeId ns3::OkumuraHataPropagationLossModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## okumura-hata-propagation-loss-model.h (module 'propagation'): double ns3::OkumuraHataPropagationLossModel::GetLoss(ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('GetLoss',
'double',
[param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True)
## okumura-hata-propagation-loss-model.h (module 'propagation'): double ns3::OkumuraHataPropagationLossModel::DoCalcRxPower(double txPowerDbm, ns3::Ptr<ns3::MobilityModel> a, ns3::Ptr<ns3::MobilityModel> b) const [member function]
cls.add_method('DoCalcRxPower',
'double',
[param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::MobilityModel >', 'a'), param('ns3::Ptr< ns3::MobilityModel >', 'b')],
is_const=True, visibility='private', is_virtual=True)
## okumura-hata-propagation-loss-model.h (module 'propagation'): int64_t ns3::OkumuraHataPropagationLossModel::DoAssignStreams(int64_t stream) [member function]
cls.add_method('DoAssignStreams',
'int64_t',
[param('int64_t', 'stream')],
visibility='private', is_virtual=True)
return
def register_Ns3OnoeWifiManager_methods(root_module, cls):
## onoe-wifi-manager.h (module 'wifi'): ns3::OnoeWifiManager::OnoeWifiManager(ns3::OnoeWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OnoeWifiManager const &', 'arg0')])
## onoe-wifi-manager.h (module 'wifi'): ns3::OnoeWifiManager::OnoeWifiManager() [constructor]
cls.add_constructor([])
## onoe-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::OnoeWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## onoe-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::OnoeWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::OnoeWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::OnoeWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): void ns3::OnoeWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## onoe-wifi-manager.h (module 'wifi'): bool ns3::OnoeWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3OutputStreamWrapper_methods(root_module, cls):
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor]
cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor]
cls.add_constructor([param('std::ostream *', 'os')])
## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function]
cls.add_method('GetStream',
'std::ostream *',
[])
return
def register_Ns3Packet_methods(root_module, cls):
cls.add_output_stream_operator()
## packet.h (module 'network'): ns3::Packet::Packet() [constructor]
cls.add_constructor([])
## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [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<ns3::Packet const> 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_Ns3ParetoRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3RegularWifiMac_methods(root_module, cls):
## regular-wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::RegularWifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## regular-wifi-mac.h (module 'wifi'): ns3::RegularWifiMac::RegularWifiMac() [constructor]
cls.add_constructor([])
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetSlot(ns3::Time slotTime) [member function]
cls.add_method('SetSlot',
'void',
[param('ns3::Time', 'slotTime')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetSifs(ns3::Time sifs) [member function]
cls.add_method('SetSifs',
'void',
[param('ns3::Time', 'sifs')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetEifsNoDifs(ns3::Time eifsNoDifs) [member function]
cls.add_method('SetEifsNoDifs',
'void',
[param('ns3::Time', 'eifsNoDifs')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetPifs(ns3::Time pifs) [member function]
cls.add_method('SetPifs',
'void',
[param('ns3::Time', 'pifs')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetCtsTimeout(ns3::Time ctsTimeout) [member function]
cls.add_method('SetCtsTimeout',
'void',
[param('ns3::Time', 'ctsTimeout')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetAckTimeout(ns3::Time ackTimeout) [member function]
cls.add_method('SetAckTimeout',
'void',
[param('ns3::Time', 'ackTimeout')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetPifs() const [member function]
cls.add_method('GetPifs',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetSifs() const [member function]
cls.add_method('GetSifs',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetSlot() const [member function]
cls.add_method('GetSlot',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetEifsNoDifs() const [member function]
cls.add_method('GetEifsNoDifs',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetCtsTimeout() const [member function]
cls.add_method('GetCtsTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetAckTimeout() const [member function]
cls.add_method('GetAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::RegularWifiMac::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Mac48Address',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Ssid ns3::RegularWifiMac::GetSsid() const [member function]
cls.add_method('GetSsid',
'ns3::Ssid',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetAddress(ns3::Mac48Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'address')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetSsid(ns3::Ssid ssid) [member function]
cls.add_method('SetSsid',
'void',
[param('ns3::Ssid', 'ssid')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetBssid(ns3::Mac48Address bssid) [member function]
cls.add_method('SetBssid',
'void',
[param('ns3::Mac48Address', 'bssid')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Mac48Address ns3::RegularWifiMac::GetBssid() const [member function]
cls.add_method('GetBssid',
'ns3::Mac48Address',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetPromisc() [member function]
cls.add_method('SetPromisc',
'void',
[],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): bool ns3::RegularWifiMac::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_pure_virtual=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetWifiPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetWifiPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Ptr<ns3::WifiPhy> ns3::RegularWifiMac::GetWifiPhy() const [member function]
cls.add_method('GetWifiPhy',
'ns3::Ptr< ns3::WifiPhy >',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Ptr<ns3::WifiRemoteStationManager> ns3::RegularWifiMac::GetWifiRemoteStationManager() const [member function]
cls.add_method('GetWifiRemoteStationManager',
'ns3::Ptr< ns3::WifiRemoteStationManager >',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetForwardUpCallback(ns3::Callback<void, ns3::Ptr<ns3::Packet>, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> upCallback) [member function]
cls.add_method('SetForwardUpCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Mac48Address, ns3::Mac48Address, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'upCallback')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function]
cls.add_method('SetLinkUpCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetLinkDownCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkDown) [member function]
cls.add_method('SetLinkDownCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkDown')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetBasicBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetBasicBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetBasicBlockAckTimeout() const [member function]
cls.add_method('GetBasicBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetCompressedBlockAckTimeout(ns3::Time blockAckTimeout) [member function]
cls.add_method('SetCompressedBlockAckTimeout',
'void',
[param('ns3::Time', 'blockAckTimeout')],
is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): ns3::Time ns3::RegularWifiMac::GetCompressedBlockAckTimeout() const [member function]
cls.add_method('GetCompressedBlockAckTimeout',
'ns3::Time',
[],
is_const=True, is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::FinishConfigureStandard(ns3::WifiPhyStandard standard) [member function]
cls.add_method('FinishConfigureStandard',
'void',
[param('ns3::WifiPhyStandard', 'standard')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetTypeOfStation(ns3::TypeOfStation type) [member function]
cls.add_method('SetTypeOfStation',
'void',
[param('ns3::TypeOfStation', 'type')],
visibility='protected')
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::TxOk(ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('TxOk',
'void',
[param('ns3::WifiMacHeader const &', 'hdr')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::TxFailed(ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('TxFailed',
'void',
[param('ns3::WifiMacHeader const &', 'hdr')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::ForwardUp(ns3::Ptr<ns3::Packet> packet, ns3::Mac48Address from, ns3::Mac48Address to) [member function]
cls.add_method('ForwardUp',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Mac48Address', 'from'), param('ns3::Mac48Address', 'to')],
visibility='protected')
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::DeaggregateAmsduAndForward(ns3::Ptr<ns3::Packet> aggregatedPacket, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('DeaggregateAmsduAndForward',
'void',
[param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SendAddBaResponse(ns3::MgtAddBaRequestHeader const * reqHdr, ns3::Mac48Address originator) [member function]
cls.add_method('SendAddBaResponse',
'void',
[param('ns3::MgtAddBaRequestHeader const *', 'reqHdr'), param('ns3::Mac48Address', 'originator')],
visibility='protected', is_virtual=True)
## regular-wifi-mac.h (module 'wifi'): void ns3::RegularWifiMac::SetQosSupported(bool enable) [member function]
cls.add_method('SetQosSupported',
'void',
[param('bool', 'enable')],
visibility='protected')
## regular-wifi-mac.h (module 'wifi'): bool ns3::RegularWifiMac::GetQosSupported() const [member function]
cls.add_method('GetQosSupported',
'bool',
[],
is_const=True, visibility='protected')
return
def register_Ns3RraaWifiManager_methods(root_module, cls):
## rraa-wifi-manager.h (module 'wifi'): ns3::RraaWifiManager::RraaWifiManager(ns3::RraaWifiManager const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RraaWifiManager const &', 'arg0')])
## rraa-wifi-manager.h (module 'wifi'): ns3::RraaWifiManager::RraaWifiManager() [constructor]
cls.add_constructor([])
## rraa-wifi-manager.h (module 'wifi'): static ns3::TypeId ns3::RraaWifiManager::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## rraa-wifi-manager.h (module 'wifi'): ns3::WifiRemoteStation * ns3::RraaWifiManager::DoCreateStation() const [member function]
cls.add_method('DoCreateStation',
'ns3::WifiRemoteStation *',
[],
is_const=True, visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::RraaWifiManager::DoGetDataMode(ns3::WifiRemoteStation * station, uint32_t size) [member function]
cls.add_method('DoGetDataMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station'), param('uint32_t', 'size')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): ns3::WifiMode ns3::RraaWifiManager::DoGetRtsMode(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoGetRtsMode',
'ns3::WifiMode',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): bool ns3::RraaWifiManager::DoNeedRts(ns3::WifiRemoteStation * st, ns3::Ptr<ns3::Packet const> packet, bool normally) [member function]
cls.add_method('DoNeedRts',
'bool',
[param('ns3::WifiRemoteStation *', 'st'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('bool', 'normally')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportDataOk(ns3::WifiRemoteStation * station, double ackSnr, ns3::WifiMode ackMode, double dataSnr) [member function]
cls.add_method('DoReportDataOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ackSnr'), param('ns3::WifiMode', 'ackMode'), param('double', 'dataSnr')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportFinalDataFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalDataFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportFinalRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportFinalRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportRtsFailed(ns3::WifiRemoteStation * station) [member function]
cls.add_method('DoReportRtsFailed',
'void',
[param('ns3::WifiRemoteStation *', 'station')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportRtsOk(ns3::WifiRemoteStation * station, double ctsSnr, ns3::WifiMode ctsMode, double rtsSnr) [member function]
cls.add_method('DoReportRtsOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'ctsSnr'), param('ns3::WifiMode', 'ctsMode'), param('double', 'rtsSnr')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): void ns3::RraaWifiManager::DoReportRxOk(ns3::WifiRemoteStation * station, double rxSnr, ns3::WifiMode txMode) [member function]
cls.add_method('DoReportRxOk',
'void',
[param('ns3::WifiRemoteStation *', 'station'), param('double', 'rxSnr'), param('ns3::WifiMode', 'txMode')],
visibility='private', is_virtual=True)
## rraa-wifi-manager.h (module 'wifi'): bool ns3::RraaWifiManager::IsLowLatency() const [member function]
cls.add_method('IsLowLatency',
'bool',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3Ssid_methods(root_module, cls):
cls.add_output_stream_operator()
## ssid.h (module 'wifi'): ns3::Ssid::Ssid(ns3::Ssid const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ssid const &', 'arg0')])
## ssid.h (module 'wifi'): ns3::Ssid::Ssid() [constructor]
cls.add_constructor([])
## ssid.h (module 'wifi'): ns3::Ssid::Ssid(std::string s) [constructor]
cls.add_constructor([param('std::string', 's')])
## ssid.h (module 'wifi'): ns3::Ssid::Ssid(char const * ssid, uint8_t length) [constructor]
cls.add_constructor([param('char const *', 'ssid'), param('uint8_t', 'length')])
## ssid.h (module 'wifi'): uint8_t ns3::Ssid::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_virtual=True)
## ssid.h (module 'wifi'): ns3::WifiInformationElementId ns3::Ssid::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): uint8_t ns3::Ssid::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): bool ns3::Ssid::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ssid.h (module 'wifi'): bool ns3::Ssid::IsEqual(ns3::Ssid const & o) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ssid const &', 'o')],
is_const=True)
## ssid.h (module 'wifi'): char * ns3::Ssid::PeekString() const [member function]
cls.add_method('PeekString',
'char *',
[],
is_const=True)
## ssid.h (module 'wifi'): void ns3::Ssid::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
return
def register_Ns3SsidChecker_methods(root_module, cls):
## ssid.h (module 'wifi'): ns3::SsidChecker::SsidChecker() [constructor]
cls.add_constructor([])
## ssid.h (module 'wifi'): ns3::SsidChecker::SsidChecker(ns3::SsidChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SsidChecker const &', 'arg0')])
return
def register_Ns3SsidValue_methods(root_module, cls):
## ssid.h (module 'wifi'): ns3::SsidValue::SsidValue() [constructor]
cls.add_constructor([])
## ssid.h (module 'wifi'): ns3::SsidValue::SsidValue(ns3::SsidValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SsidValue const &', 'arg0')])
## ssid.h (module 'wifi'): ns3::SsidValue::SsidValue(ns3::Ssid const & value) [constructor]
cls.add_constructor([param('ns3::Ssid const &', 'value')])
## ssid.h (module 'wifi'): ns3::Ptr<ns3::AttributeValue> ns3::SsidValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## ssid.h (module 'wifi'): bool ns3::SsidValue::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)
## ssid.h (module 'wifi'): ns3::Ssid ns3::SsidValue::Get() const [member function]
cls.add_method('Get',
'ns3::Ssid',
[],
is_const=True)
## ssid.h (module 'wifi'): std::string ns3::SsidValue::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)
## ssid.h (module 'wifi'): void ns3::SsidValue::Set(ns3::Ssid const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Ssid const &', 'value')])
return
def register_Ns3StaWifiMac_methods(root_module, cls):
## sta-wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::StaWifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## sta-wifi-mac.h (module 'wifi'): ns3::StaWifiMac::StaWifiMac() [constructor]
cls.add_constructor([])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_virtual=True)
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::SetMaxMissedBeacons(uint32_t missed) [member function]
cls.add_method('SetMaxMissedBeacons',
'void',
[param('uint32_t', 'missed')])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::SetProbeRequestTimeout(ns3::Time timeout) [member function]
cls.add_method('SetProbeRequestTimeout',
'void',
[param('ns3::Time', 'timeout')])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::SetAssocRequestTimeout(ns3::Time timeout) [member function]
cls.add_method('SetAssocRequestTimeout',
'void',
[param('ns3::Time', 'timeout')])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::StartActiveAssociation() [member function]
cls.add_method('StartActiveAssociation',
'void',
[])
## sta-wifi-mac.h (module 'wifi'): void ns3::StaWifiMac::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='private', is_virtual=True)
return
def register_Ns3SupportedRates_methods(root_module, cls):
cls.add_output_stream_operator()
## supported-rates.h (module 'wifi'): ns3::SupportedRates::SupportedRates(ns3::SupportedRates const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SupportedRates const &', 'arg0')])
## supported-rates.h (module 'wifi'): ns3::SupportedRates::SupportedRates() [constructor]
cls.add_constructor([])
## supported-rates.h (module 'wifi'): void ns3::SupportedRates::AddSupportedRate(uint32_t bs) [member function]
cls.add_method('AddSupportedRate',
'void',
[param('uint32_t', 'bs')])
## supported-rates.h (module 'wifi'): uint8_t ns3::SupportedRates::DeserializeInformationField(ns3::Buffer::Iterator start, uint8_t length) [member function]
cls.add_method('DeserializeInformationField',
'uint8_t',
[param('ns3::Buffer::Iterator', 'start'), param('uint8_t', 'length')],
is_virtual=True)
## supported-rates.h (module 'wifi'): ns3::WifiInformationElementId ns3::SupportedRates::ElementId() const [member function]
cls.add_method('ElementId',
'ns3::WifiInformationElementId',
[],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): uint8_t ns3::SupportedRates::GetInformationFieldSize() const [member function]
cls.add_method('GetInformationFieldSize',
'uint8_t',
[],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): uint8_t ns3::SupportedRates::GetNRates() const [member function]
cls.add_method('GetNRates',
'uint8_t',
[],
is_const=True)
## supported-rates.h (module 'wifi'): uint32_t ns3::SupportedRates::GetRate(uint8_t i) const [member function]
cls.add_method('GetRate',
'uint32_t',
[param('uint8_t', 'i')],
is_const=True)
## supported-rates.h (module 'wifi'): bool ns3::SupportedRates::IsBasicRate(uint32_t bs) const [member function]
cls.add_method('IsBasicRate',
'bool',
[param('uint32_t', 'bs')],
is_const=True)
## supported-rates.h (module 'wifi'): bool ns3::SupportedRates::IsSupportedRate(uint32_t bs) const [member function]
cls.add_method('IsSupportedRate',
'bool',
[param('uint32_t', 'bs')],
is_const=True)
## supported-rates.h (module 'wifi'): void ns3::SupportedRates::SerializeInformationField(ns3::Buffer::Iterator start) const [member function]
cls.add_method('SerializeInformationField',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## supported-rates.h (module 'wifi'): void ns3::SupportedRates::SetBasicRate(uint32_t bs) [member function]
cls.add_method('SetBasicRate',
'void',
[param('uint32_t', 'bs')])
## supported-rates.h (module 'wifi'): ns3::SupportedRates::extended [variable]
cls.add_instance_attribute('extended', 'ns3::ExtendedSupportedRatesIE', is_const=False)
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_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_Ns3WifiChannel_methods(root_module, cls):
## wifi-channel.h (module 'wifi'): ns3::WifiChannel::WifiChannel() [constructor]
cls.add_constructor([])
## wifi-channel.h (module 'wifi'): ns3::WifiChannel::WifiChannel(ns3::WifiChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiChannel const &', 'arg0')])
## wifi-channel.h (module 'wifi'): static ns3::TypeId ns3::WifiChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3WifiModeChecker_methods(root_module, cls):
## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker::WifiModeChecker() [constructor]
cls.add_constructor([])
## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker::WifiModeChecker(ns3::WifiModeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiModeChecker const &', 'arg0')])
return
def register_Ns3WifiModeValue_methods(root_module, cls):
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue() [constructor]
cls.add_constructor([])
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue(ns3::WifiModeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiModeValue const &', 'arg0')])
## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue(ns3::WifiMode const & value) [constructor]
cls.add_constructor([param('ns3::WifiMode const &', 'value')])
## wifi-mode.h (module 'wifi'): ns3::Ptr<ns3::AttributeValue> ns3::WifiModeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## wifi-mode.h (module 'wifi'): bool ns3::WifiModeValue::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)
## wifi-mode.h (module 'wifi'): ns3::WifiMode ns3::WifiModeValue::Get() const [member function]
cls.add_method('Get',
'ns3::WifiMode',
[],
is_const=True)
## wifi-mode.h (module 'wifi'): std::string ns3::WifiModeValue::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)
## wifi-mode.h (module 'wifi'): void ns3::WifiModeValue::Set(ns3::WifiMode const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::WifiMode const &', 'value')])
return
def register_Ns3WifiNetDevice_methods(root_module, cls):
## wifi-net-device.h (module 'wifi'): ns3::WifiNetDevice::WifiNetDevice(ns3::WifiNetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::WifiNetDevice const &', 'arg0')])
## wifi-net-device.h (module 'wifi'): ns3::WifiNetDevice::WifiNetDevice() [constructor]
cls.add_constructor([])
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::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)
## wifi-net-device.h (module 'wifi'): ns3::Address ns3::WifiNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Address ns3::WifiNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::Channel> ns3::WifiNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): uint32_t ns3::WifiNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::WifiMac> ns3::WifiNetDevice::GetMac() const [member function]
cls.add_method('GetMac',
'ns3::Ptr< ns3::WifiMac >',
[],
is_const=True)
## wifi-net-device.h (module 'wifi'): uint16_t ns3::WifiNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Address ns3::WifiNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Address ns3::WifiNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::Node> ns3::WifiNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::WifiPhy> ns3::WifiNetDevice::GetPhy() const [member function]
cls.add_method('GetPhy',
'ns3::Ptr< ns3::WifiPhy >',
[],
is_const=True)
## wifi-net-device.h (module 'wifi'): ns3::Ptr<ns3::WifiRemoteStationManager> ns3::WifiNetDevice::GetRemoteStationManager() const [member function]
cls.add_method('GetRemoteStationManager',
'ns3::Ptr< ns3::WifiRemoteStationManager >',
[],
is_const=True)
## wifi-net-device.h (module 'wifi'): static ns3::TypeId ns3::WifiNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::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)
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::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)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetMac(ns3::Ptr<ns3::WifiMac> mac) [member function]
cls.add_method('SetMac',
'void',
[param('ns3::Ptr< ns3::WifiMac >', 'mac')])
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetPhy(ns3::Ptr<ns3::WifiPhy> phy) [member function]
cls.add_method('SetPhy',
'void',
[param('ns3::Ptr< ns3::WifiPhy >', 'phy')])
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::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)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::SetRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> manager) [member function]
cls.add_method('SetRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'manager')])
## wifi-net-device.h (module 'wifi'): bool ns3::WifiNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## wifi-net-device.h (module 'wifi'): void ns3::WifiNetDevice::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3YansErrorRateModel_methods(root_module, cls):
## yans-error-rate-model.h (module 'wifi'): ns3::YansErrorRateModel::YansErrorRateModel(ns3::YansErrorRateModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::YansErrorRateModel const &', 'arg0')])
## yans-error-rate-model.h (module 'wifi'): ns3::YansErrorRateModel::YansErrorRateModel() [constructor]
cls.add_constructor([])
## yans-error-rate-model.h (module 'wifi'): double ns3::YansErrorRateModel::GetChunkSuccessRate(ns3::WifiMode mode, double snr, uint32_t nbits) const [member function]
cls.add_method('GetChunkSuccessRate',
'double',
[param('ns3::WifiMode', 'mode'), param('double', 'snr'), param('uint32_t', 'nbits')],
is_const=True, is_virtual=True)
## yans-error-rate-model.h (module 'wifi'): static ns3::TypeId ns3::YansErrorRateModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3YansWifiChannel_methods(root_module, cls):
## yans-wifi-channel.h (module 'wifi'): static ns3::TypeId ns3::YansWifiChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## yans-wifi-channel.h (module 'wifi'): ns3::YansWifiChannel::YansWifiChannel() [constructor]
cls.add_constructor([])
## yans-wifi-channel.h (module 'wifi'): uint32_t ns3::YansWifiChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## yans-wifi-channel.h (module 'wifi'): ns3::Ptr<ns3::NetDevice> ns3::YansWifiChannel::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)
## yans-wifi-channel.h (module 'wifi'): void ns3::YansWifiChannel::Add(ns3::Ptr<ns3::YansWifiPhy> phy) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::YansWifiPhy >', 'phy')])
## yans-wifi-channel.h (module 'wifi'): void ns3::YansWifiChannel::SetPropagationLossModel(ns3::Ptr<ns3::PropagationLossModel> loss) [member function]
cls.add_method('SetPropagationLossModel',
'void',
[param('ns3::Ptr< ns3::PropagationLossModel >', 'loss')])
## yans-wifi-channel.h (module 'wifi'): void ns3::YansWifiChannel::SetPropagationDelayModel(ns3::Ptr<ns3::PropagationDelayModel> delay) [member function]
cls.add_method('SetPropagationDelayModel',
'void',
[param('ns3::Ptr< ns3::PropagationDelayModel >', 'delay')])
## yans-wifi-channel.h (module 'wifi'): void ns3::YansWifiChannel::Send(ns3::Ptr<ns3::YansWifiPhy> sender, ns3::Ptr<ns3::Packet const> packet, double txPowerDbm, ns3::WifiMode wifiMode, ns3::WifiPreamble preamble) const [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::YansWifiPhy >', 'sender'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('double', 'txPowerDbm'), param('ns3::WifiMode', 'wifiMode'), param('ns3::WifiPreamble', 'preamble')],
is_const=True)
## yans-wifi-channel.h (module 'wifi'): int64_t ns3::YansWifiChannel::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
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_Ns3AdhocWifiMac_methods(root_module, cls):
## adhoc-wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::AdhocWifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## adhoc-wifi-mac.h (module 'wifi'): ns3::AdhocWifiMac::AdhocWifiMac() [constructor]
cls.add_constructor([])
## adhoc-wifi-mac.h (module 'wifi'): void ns3::AdhocWifiMac::SetAddress(ns3::Mac48Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'address')],
is_virtual=True)
## adhoc-wifi-mac.h (module 'wifi'): void ns3::AdhocWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function]
cls.add_method('SetLinkUpCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')],
is_virtual=True)
## adhoc-wifi-mac.h (module 'wifi'): void ns3::AdhocWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_virtual=True)
## adhoc-wifi-mac.h (module 'wifi'): void ns3::AdhocWifiMac::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='private', is_virtual=True)
return
def register_Ns3ApWifiMac_methods(root_module, cls):
## ap-wifi-mac.h (module 'wifi'): static ns3::TypeId ns3::ApWifiMac::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ap-wifi-mac.h (module 'wifi'): ns3::ApWifiMac::ApWifiMac() [constructor]
cls.add_constructor([])
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> stationManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'stationManager')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::SetLinkUpCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> linkUp) [member function]
cls.add_method('SetLinkUpCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'linkUp')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::Enqueue(ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Enqueue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): bool ns3::ApWifiMac::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::SetAddress(ns3::Mac48Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Mac48Address', 'address')],
is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::SetBeaconInterval(ns3::Time interval) [member function]
cls.add_method('SetBeaconInterval',
'void',
[param('ns3::Time', 'interval')])
## ap-wifi-mac.h (module 'wifi'): ns3::Time ns3::ApWifiMac::GetBeaconInterval() const [member function]
cls.add_method('GetBeaconInterval',
'ns3::Time',
[],
is_const=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::StartBeaconing() [member function]
cls.add_method('StartBeaconing',
'void',
[])
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::Receive(ns3::Ptr<ns3::Packet> packet, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::TxOk(ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('TxOk',
'void',
[param('ns3::WifiMacHeader const &', 'hdr')],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::TxFailed(ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('TxFailed',
'void',
[param('ns3::WifiMacHeader const &', 'hdr')],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::DeaggregateAmsduAndForward(ns3::Ptr<ns3::Packet> aggregatedPacket, ns3::WifiMacHeader const * hdr) [member function]
cls.add_method('DeaggregateAmsduAndForward',
'void',
[param('ns3::Ptr< ns3::Packet >', 'aggregatedPacket'), param('ns3::WifiMacHeader const *', 'hdr')],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## ap-wifi-mac.h (module 'wifi'): void ns3::ApWifiMac::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3DcaTxop_methods(root_module, cls):
## dca-txop.h (module 'wifi'): static ns3::TypeId ns3::DcaTxop::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dca-txop.h (module 'wifi'): ns3::DcaTxop::DcaTxop() [constructor]
cls.add_constructor([])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetLow(ns3::Ptr<ns3::MacLow> low) [member function]
cls.add_method('SetLow',
'void',
[param('ns3::Ptr< ns3::MacLow >', 'low')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetManager(ns3::DcfManager * manager) [member function]
cls.add_method('SetManager',
'void',
[param('ns3::DcfManager *', 'manager')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetWifiRemoteStationManager(ns3::Ptr<ns3::WifiRemoteStationManager> remoteManager) [member function]
cls.add_method('SetWifiRemoteStationManager',
'void',
[param('ns3::Ptr< ns3::WifiRemoteStationManager >', 'remoteManager')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetTxOkCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetTxOkCallback',
'void',
[param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetTxFailedCallback(ns3::Callback<void, ns3::WifiMacHeader const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('SetTxFailedCallback',
'void',
[param('ns3::Callback< void, ns3::WifiMacHeader const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')])
## dca-txop.h (module 'wifi'): ns3::Ptr<ns3::WifiMacQueue> ns3::DcaTxop::GetQueue() const [member function]
cls.add_method('GetQueue',
'ns3::Ptr< ns3::WifiMacQueue >',
[],
is_const=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetMinCw(uint32_t minCw) [member function]
cls.add_method('SetMinCw',
'void',
[param('uint32_t', 'minCw')],
is_virtual=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetMaxCw(uint32_t maxCw) [member function]
cls.add_method('SetMaxCw',
'void',
[param('uint32_t', 'maxCw')],
is_virtual=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::SetAifsn(uint32_t aifsn) [member function]
cls.add_method('SetAifsn',
'void',
[param('uint32_t', 'aifsn')],
is_virtual=True)
## dca-txop.h (module 'wifi'): uint32_t ns3::DcaTxop::GetMinCw() const [member function]
cls.add_method('GetMinCw',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dca-txop.h (module 'wifi'): uint32_t ns3::DcaTxop::GetMaxCw() const [member function]
cls.add_method('GetMaxCw',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dca-txop.h (module 'wifi'): uint32_t ns3::DcaTxop::GetAifsn() const [member function]
cls.add_method('GetAifsn',
'uint32_t',
[],
is_const=True, is_virtual=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::Queue(ns3::Ptr<ns3::Packet const> packet, ns3::WifiMacHeader const & hdr) [member function]
cls.add_method('Queue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMacHeader const &', 'hdr')])
## dca-txop.h (module 'wifi'): int64_t ns3::DcaTxop::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='private', is_virtual=True)
## dca-txop.h (module 'wifi'): void ns3::DcaTxop::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_functions(root_module):
module = root_module
## ssid.h (module 'wifi'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeSsidChecker() [free function]
module.add_function('MakeSsidChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## wifi-mode.h (module 'wifi'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeWifiModeChecker() [free function]
module.add_function('MakeWifiModeChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## qos-utils.h (module 'wifi'): extern uint8_t ns3::QosUtilsGetTidForPacket(ns3::Ptr<ns3::Packet const> packet) [free function]
module.add_function('QosUtilsGetTidForPacket',
'uint8_t',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## qos-utils.h (module 'wifi'): extern bool ns3::QosUtilsIsOldPacket(uint16_t startingSeq, uint16_t seqNumber) [free function]
module.add_function('QosUtilsIsOldPacket',
'bool',
[param('uint16_t', 'startingSeq'), param('uint16_t', 'seqNumber')])
## qos-utils.h (module 'wifi'): extern uint32_t ns3::QosUtilsMapSeqControlToUniqueInteger(uint16_t seqControl, uint16_t endSequence) [free function]
module.add_function('QosUtilsMapSeqControlToUniqueInteger',
'uint32_t',
[param('uint16_t', 'seqControl'), param('uint16_t', 'endSequence')])
## qos-utils.h (module 'wifi'): extern ns3::AcIndex ns3::QosUtilsMapTidToAc(uint8_t tid) [free function]
module.add_function('QosUtilsMapTidToAc',
'ns3::AcIndex',
[param('uint8_t', 'tid')])
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()
| bsd-3-clause |
MatthewCox/dotfiles | weechat/python/theme.py | 5 | 49092 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2011-2015 Sébastien Helleu <flashcode@flashtux.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# WeeChat theme manager.
# (this script requires WeeChat 0.3.7 or newer)
#
# History:
#
# 2015-07-13, Sébastien Helleu <flashcode@flashtux.org>:
# version 0.1: dev snapshot
# 2011-02-22, Sébastien Helleu <flashcode@flashtux.org>:
# start dev
#
SCRIPT_NAME = 'theme'
SCRIPT_AUTHOR = 'Sébastien Helleu <flashcode@flashtux.org>'
SCRIPT_VERSION = '0.1-dev'
SCRIPT_LICENSE = 'GPL3'
SCRIPT_DESC = 'WeeChat theme manager'
SCRIPT_COMMAND = 'theme'
import_weechat_ok = True
import_other_ok = True
try:
import weechat
except ImportError:
import_weechat_ok = False
try:
import sys
import os
import re
import datetime
import time
import cgi
import tarfile
import traceback
import xml.dom.minidom
except ImportError as e:
print('Missing package(s) for {0}: {1}'.format(SCRIPT_NAME, e))
import_other_ok = False
THEME_CONFIG_FILENAME = 'theme'
THEME_URL = 'https://weechat.org/files/themes.tar.bz2'
# color attributes (in weechat color options)
COLOR_ATTRIBUTES = ('*', '_', '/', '!')
# timeout for download of themes.tar.bz2
TIMEOUT_UPDATE = 120 * 1000
# hook process and stdout
theme_hook_process = ''
theme_stdout = ''
# themes read from themes.xml
theme_themes = {}
# config file and options
theme_cfg_file = ''
theme_cfg = {}
theme_bars = 'input|nicklist|status|title'
theme_plugins = 'weechat|alias|aspell|charset|fifo|irc|logger|relay|'\
'rmodifier|xfer'
theme_options_include_re = (
r'^weechat\.bar\.({0})\.color.*'.format(theme_bars),
r'^weechat\.look\.buffer_time_format$',
r'^({0})\.color\..*'.format(theme_plugins),
r'^({0})\.look\..*color.*'.format(theme_plugins),
)
theme_options_exclude_re = (
r'^weechat.look.color_pairs_auto_reset$',
r'^weechat.look.color_real_white$',
r'^weechat.look.color_basic_force_bold$',
r'^irc\.look\.',
)
# =================================[ config ]=================================
def theme_config_init():
"""Initialization of configuration file. Sections: color, themes."""
global theme_cfg_file, theme_cfg
theme_cfg_file = weechat.config_new(THEME_CONFIG_FILENAME,
'theme_config_reload_cb', '')
# section "color"
section = weechat.config_new_section(
theme_cfg_file, 'color', 0, 0,
'', '', '', '', '', '', '', '', '', '')
theme_cfg['color_script'] = weechat.config_new_option(
theme_cfg_file, section, 'script', 'color',
'Color for script names', '', 0, 0,
'cyan', 'cyan', 0, '', '', '', '', '', '')
theme_cfg['color_installed'] = weechat.config_new_option(
theme_cfg_file, section, 'installed', 'color',
'Color for "installed" indicator', '', 0, 0,
'yellow', 'yellow', 0, '', '', '', '', '', '')
theme_cfg['color_running'] = weechat.config_new_option(
theme_cfg_file, section, 'running', 'color',
'Color for "running" indicator', '', 0, 0,
'lightgreen', 'lightgreen', 0, '', '', '', '', '', '')
theme_cfg['color_obsolete'] = weechat.config_new_option(
theme_cfg_file, section, 'obsolete', 'color',
'Color for "obsolete" indicator', '', 0, 0,
'lightmagenta', 'lightmagenta', 0, '', '', '', '', '', '')
theme_cfg['color_unknown'] = weechat.config_new_option(
theme_cfg_file, section, 'unknown', 'color',
'Color for "unknown status" indicator', '', 0, 0,
'lightred', 'lightred', 0, '', '', '', '', '', '')
theme_cfg['color_language'] = weechat.config_new_option(
theme_cfg_file, section, 'language', 'color',
'Color for language names', '', 0, 0,
'lightblue', 'lightblue', 0, '', '', '', '', '', '')
# section "themes"
section = weechat.config_new_section(
theme_cfg_file, 'themes', 0, 0,
'', '', '', '', '', '', '', '', '', '')
theme_cfg['themes_url'] = weechat.config_new_option(
theme_cfg_file, section,
'url', 'string', 'URL for file with themes (.tar.bz2 file)', '', 0, 0,
THEME_URL, THEME_URL, 0, '', '', '', '', '', '')
theme_cfg['themes_cache_expire'] = weechat.config_new_option(
theme_cfg_file, section,
'cache_expire', 'integer', 'Local cache expiration time, in minutes '
'(-1 = never expires, 0 = always expires)', '',
-1, 60 * 24 * 365, '60', '60', 0, '', '', '', '', '', '')
theme_cfg['themes_dir'] = weechat.config_new_option(
theme_cfg_file, section,
'dir', 'string', 'Local directory for themes', '', 0, 0,
'%h/themes', '%h/themes', 0, '', '', '', '', '', '')
def theme_config_reload_cb(data, config_file):
"""Reload configuration file."""
return weechat.config_read(config_file)
def theme_config_read():
"""Read configuration file."""
return weechat.config_read(theme_cfg_file)
def theme_config_write():
"""Write configuration file."""
return weechat.config_write(theme_cfg_file)
def theme_config_color(color):
"""Get a color from configuration."""
option = theme_cfg.get('color_' + color, '')
if not option:
return ''
return weechat.color(weechat.config_string(option))
def theme_config_get_dir():
"""Return themes directory, with expanded WeeChat home dir."""
return weechat.config_string(
theme_cfg['themes_dir']).replace('%h',
weechat.info_get('weechat_dir', ''))
def theme_config_get_backup():
"""
Return name of backup theme
(by default "~/.weechat/themes/_backup.theme").
"""
return theme_config_get_dir() + '/_backup.theme'
def theme_config_get_undo():
"""
Return name of undo file
(by default "~/.weechat/themes/_undo.theme").
"""
return theme_config_get_dir() + '/_undo.theme'
def theme_config_create_dir():
"""Create "themes" directory."""
directory = theme_config_get_dir()
if not os.path.isdir(directory):
os.makedirs(directory, mode=0o700)
def theme_config_get_tarball_filename():
"""Get local tarball filename, based on URL."""
return theme_config_get_dir() + '/' + \
os.path.basename(weechat.config_string(theme_cfg['themes_url']))
def theme_config_get_xml_filename():
"""Get XML filename."""
return theme_config_get_dir() + '/themes.xml'
# =================================[ themes ]=================================
class Theme:
def __init__(self, filename=None):
self.filename = filename
self.props = {}
self.listprops = []
self.options = {}
self.theme_ok = True
if self.filename:
self.theme_ok = self.load(self.filename)
else:
self.init_weechat()
self.nick_prefixes = self._get_nick_prefixes()
def isok(self):
return self.theme_ok
def _option_is_used(self, option):
global theme_options_include_re, theme_options_exclude_re
for regex in theme_options_exclude_re:
if re.search(regex, option):
return False
for regex in theme_options_include_re:
if re.search(regex, option):
return True
return False
def _get_nick_prefixes(self):
"""Get dict with nick prefixes."""
prefixes = {}
nick_prefixes = self.options.get('irc.color.nick_prefixes', '')
for prefix in nick_prefixes.split(';'):
values = prefix.split(':', 1)
if len(values) == 2:
prefixes[values[0]] = values[1]
return prefixes
def _get_attr_color(self, color):
"""Return tuple with attributes and color."""
m = re.match('([*_!]*)(.*)', color)
if m:
return m.group(1), m.group(2)
return '', color
def _get_color_without_alias(self, color):
"""
Return color without alias (color can be "fg", "fg,bg" or "fg:bg").
"""
pos = color.find(',')
if pos < 0:
pos = color.find(':')
if pos > 0:
fg = color[0:pos]
bg = color[pos + 1:]
else:
fg = color
bg = ''
attr, col = self._get_attr_color(fg)
fg = attr + self.palette.get(col, col)
attr, col = self._get_attr_color(bg)
bg = attr + self.palette.get(col, col)
if bg:
return fg + color[pos:pos + 1] + bg
return fg
def _replace_color_alias(self, match):
value = match.group()[8:-1]
if value in self.palette:
value = self.palette[value]
return '${color:' + value + '}'
def init_weechat(self):
"""
Initialize theme using current WeeChat options (aliases are
replaced with their values from palette).
"""
# get palette options
self.palette = {}
infolist = weechat.infolist_get('option', '', 'weechat.palette.*')
while weechat.infolist_next(infolist):
option_name = weechat.infolist_string(infolist, 'option_name')
value = weechat.infolist_string(infolist, 'value')
self.palette[value] = option_name
weechat.infolist_free(infolist)
# get color options (replace aliases by values from palette)
self.options = {}
infolist = weechat.infolist_get('option', '', '')
while weechat.infolist_next(infolist):
full_name = weechat.infolist_string(infolist, 'full_name')
if self._option_is_used(full_name):
value = weechat.infolist_string(infolist, 'value')
self.options[full_name] = self._get_color_without_alias(value)
weechat.infolist_free(infolist)
# replace aliases in chat_nick_colors
option = 'weechat.color.chat_nick_colors'
colors = []
for color in self.options.get(option, '').split(','):
colors.append(self._get_color_without_alias(color))
if colors:
self.options[option] = ','.join(colors)
# replace aliases in buffer_time_format
option = 'weechat.look.buffer_time_format'
if option in self.options:
value = re.compile(r'\$\{color:[^\}]+\}').sub(
self._replace_color_alias, self.options[option])
if value:
self.options[option] = value
# build dict with nick prefixes (and replace alisases)
prefixes = []
option = 'irc.color.nick_prefixes'
for prefix in self.options.get(option, '').split(';'):
values = prefix.split(':', 1)
if len(values) == 2:
prefixes.append(values[0] + ':' +
self._get_color_without_alias(values[1]))
if prefixes:
self.options[option] = ';'.join(prefixes)
# delete palette
del self.palette
def prnt(self, message):
try:
weechat.prnt('', message)
except:
print(message)
def prnt_error(self, message):
try:
weechat.prnt('', weechat.prefix('error') + message)
except:
print(message)
def load(self, filename):
self.options = {}
try:
lines = open(filename, 'rb').readlines()
for line in lines:
line = str(line.strip().decode('utf-8'))
if line.startswith('#'):
m = re.match('^# \\$([A-Za-z]+): (.*)', line)
if m:
self.props[m.group(1)] = m.group(2)
self.listprops.append(m.group(1))
else:
items = line.split('=', 1)
if len(items) == 2:
value = items[1].strip()
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
self.options[items[0].strip()] = value
return True
except:
self.prnt('Error loading theme "{0}"'.format(filename))
return False
def save(self, filename):
names = sorted(self.options)
try:
f = open(filename, 'w')
version = weechat.info_get('version', '')
pos = version.find('-')
if pos > 0:
version = version[0:pos]
header = ('#',
'# -- WeeChat theme --',
'# $name: {0}'.format(os.path.basename(filename)),
'# $date: {0}'.format(datetime.date.today()),
'# $weechat: {0}'.format(version),
'# $script: {0}.py {1}'.format(SCRIPT_NAME,
SCRIPT_VERSION),
'#\n')
f.write('\n'.join(header))
for option in names:
f.write('{0} = "{1}"\n'.format(option, self.options[option]))
f.close()
self.prnt('Theme saved to "{0}"'.format(filename))
except:
self.prnt_error('Error writing theme to "{0}"'.format(filename))
raise
def show(self, header):
"""Display content of theme."""
names = sorted(self.options)
self.prnt('')
self.prnt(header)
for name in names:
self.prnt(' {0} {1}= {2}{3}'
''.format(name,
weechat.color('chat_delimiters'),
weechat.color('chat_value'),
self.options[name]))
def info(self, header):
"""Display info about theme."""
self.prnt('')
self.prnt(header)
for prop in self.listprops:
self.prnt(' {0}: {1}{2}'
''.format(prop,
weechat.color('chat_value'),
self.props[prop]))
numerrors = 0
for name in self.options:
if not weechat.config_get(name):
numerrors += 1
if numerrors == 0:
text = 'all OK'
else:
text = ('WARNING: {0} option(s) not found in your WeeChat'
''.format(numerrors))
self.prnt(' options: {0}{1}{2} ({3})'
''.format(weechat.color('chat_value'),
len(self.options),
weechat.color('reset'),
text))
def install(self):
try:
numset = 0
numerrors = 0
for name in self.options:
option = weechat.config_get(name)
if option:
rc = weechat.config_option_set(option,
self.options[name], 1)
if rc == weechat.WEECHAT_CONFIG_OPTION_SET_ERROR:
self.prnt_error('Error setting option "{0}" to value '
'"{1}" (running an old WeeChat?)'
''.format(name, self.options[name]))
numerrors += 1
else:
numset += 1
else:
self.prnt('Warning: option not found: "{0}" '
'(running an old WeeChat?)'.format(name))
numerrors += 1
errors = ''
if numerrors > 0:
errors = ', {0} error(s)'.format(numerrors)
if self.filename:
self.prnt('Theme "{0}" installed ({1} options set{2})'
''.format(self.filename, numset, errors))
else:
self.prnt('Theme installed ({0} options set{1})'
''.format(numset, errors))
except:
if self.filename:
self.prnt_error('Failed to install theme "{0}"'
''.format(self.filename))
else:
self.prnt_error('Failed to install theme')
def nick_prefix_color(self, prefix):
"""Get color for a nick prefix."""
modes = 'qaohv'
prefixes = '~&@%+'
pos = prefixes.find(prefix)
if pos < 0:
return ''
while pos < len(modes):
if modes[pos] in self.nick_prefixes:
return self.nick_prefixes[modes[pos]]
pos += 1
return self.nick_prefixes.get('*', '')
# =============================[ themes / html ]==============================
class HtmlTheme(Theme):
def __init__(self, filename=None, chat_width=85, chat_height=25,
prefix_width=10, nicklist_width=10):
Theme.__init__(self, filename)
self.chat_width = chat_width
self.chat_height = chat_height
self.prefix_width = prefix_width
self.nicklist_width = nicklist_width
def html_color(self, index):
"""Return HTML color with index in table of 256 colors."""
terminal_colors = (
'000000cd000000cd00cdcd000000cdcd00cd00cdcde5e5e54d4d4dff0000'
'00ff00ffff000000ffff00ff00ffffffffff00000000002a000055000080'
'0000aa0000d4002a00002a2a002a55002a80002aaa002ad400550000552a'
'0055550055800055aa0055d400800000802a0080550080800080aa0080d4'
'00aa0000aa2a00aa5500aa8000aaaa00aad400d40000d42a00d45500d480'
'00d4aa00d4d42a00002a002a2a00552a00802a00aa2a00d42a2a002a2a2a'
'2a2a552a2a802a2aaa2a2ad42a55002a552a2a55552a55802a55aa2a55d4'
'2a80002a802a2a80552a80802a80aa2a80d42aaa002aaa2a2aaa552aaa80'
'2aaaaa2aaad42ad4002ad42a2ad4552ad4802ad4aa2ad4d455000055002a'
'5500555500805500aa5500d4552a00552a2a552a55552a80552aaa552ad4'
'55550055552a5555555555805555aa5555d455800055802a558055558080'
'5580aa5580d455aa0055aa2a55aa5555aa8055aaaa55aad455d40055d42a'
'55d45555d48055d4aa55d4d480000080002a8000558000808000aa8000d4'
'802a00802a2a802a55802a80802aaa802ad480550080552a805555805580'
'8055aa8055d480800080802a8080558080808080aa8080d480aa0080aa2a'
'80aa5580aa8080aaaa80aad480d40080d42a80d45580d48080d4aa80d4d4'
'aa0000aa002aaa0055aa0080aa00aaaa00d4aa2a00aa2a2aaa2a55aa2a80'
'aa2aaaaa2ad4aa5500aa552aaa5555aa5580aa55aaaa55d4aa8000aa802a'
'aa8055aa8080aa80aaaa80d4aaaa00aaaa2aaaaa55aaaa80aaaaaaaaaad4'
'aad400aad42aaad455aad480aad4aaaad4d4d40000d4002ad40055d40080'
'd400aad400d4d42a00d42a2ad42a55d42a80d42aaad42ad4d45500d4552a'
'd45555d45580d455aad455d4d48000d4802ad48055d48080d480aad480d4'
'd4aa00d4aa2ad4aa55d4aa80d4aaaad4aad4d4d400d4d42ad4d455d4d480'
'd4d4aad4d4d40808081212121c1c1c2626263030303a3a3a4444444e4e4e'
'5858586262626c6c6c7676768080808a8a8a9494949e9e9ea8a8a8b2b2b2'
'bcbcbcc6c6c6d0d0d0dadadae4e4e4eeeeee')
color = terminal_colors[index * 6:(index * 6) + 6]
#if color in ('000000', 'e5e5e5'): # keep black or 'default' (gray)
# return color
r = int(color[0:2], 16)
g = int(color[2:4], 16)
b = int(color[4:6], 16)
r = int(min(r * (1.5 - (r / 510.0)), 255))
g = int(min(g * (1.5 - (r / 510.0)), 255))
b = int(min(b * (1.5 - (r / 510.0)), 255))
return '{0:02x}{1:02x}{2:02x}'.format(r, g, b)
def html_style(self, fg, bg):
"""Return HTML style with WeeChat fg and bg colors."""
weechat_basic_colors = {
'default': 7, 'black': 0, 'darkgray': 8, 'red': 1, 'lightred': 9,
'green': 2, 'lightgreen': 10, 'brown': 3, 'yellow': 11, 'blue': 4,
'lightblue': 12, 'magenta': 5, 'lightmagenta': 13, 'cyan': 6,
'lightcyan': 14, 'gray': 7, 'white': 15}
delim = max(fg.find(','), fg.find(':'))
if delim > 0:
bg = fg[delim + 1:]
fg = fg[0:delim]
bold = ''
underline = ''
reverse = False
while fg[0] in COLOR_ATTRIBUTES:
if fg[0] == '*':
bold = '; font-weight: bold'
elif fg[0] == '_':
underline = '; text-decoration: underline'
elif fg[0] == '!':
reverse = True
fg = fg[1:]
while bg[0] in COLOR_ATTRIBUTES:
bg = bg[1:]
if fg == 'default':
fg = self.options['fg']
if bg == 'default':
bg = self.options['bg']
if bold and fg in ('black', '0'):
fg = 'darkgray'
reverse = ''
if reverse:
fg2 = bg
bg = fg
fg = fg2
if fg == 'white' and self.whitebg:
fg = 'black'
num_fg = 0
num_bg = 0
if fg in weechat_basic_colors:
num_fg = weechat_basic_colors[fg]
else:
try:
num_fg = int(fg)
except:
self.prnt('Warning: unknown fg color "{0}", '
'using "default" instead'.format(fg))
num_fg = weechat_basic_colors['default']
if bg in weechat_basic_colors:
num_bg = weechat_basic_colors[bg]
else:
try:
num_bg = int(bg)
except:
self.prnt('Warning: unknown bg color "{0}", '
'using "default" instead'.format(bg))
num_bg = weechat_basic_colors['default']
style = ('color: #{0}; background-color: #{1}{2}{3}'
''.format(self.html_color(num_fg),
self.html_color(num_bg),
bold,
underline))
return style
def html_string(self, string, maxlen, optfg='fg', optbg='bg', escape=True):
"""Write html string using fg/bg colors."""
fg = optfg
bg = optbg
if fg in self.options:
fg = self.options[optfg]
if bg in self.options:
bg = self.options[optbg]
if maxlen >= 0:
string = string.ljust(maxlen)
else:
string = string.rjust(maxlen * -1)
if escape:
string = cgi.escape(string)
return '<span style="{0}">{1}</span>'.format(self.html_style(fg, bg),
string)
def html_nick(self, nicks, index, prefix, usecolor, highlight, maxlen,
optfg='fg', optbg='bg'):
"""Print a nick."""
nick = nicks[index]
nickfg = optfg
if usecolor and optfg != 'weechat.color.nicklist_away':
nick_colors = \
self.options['weechat.color.chat_nick_colors'].split(',')
nickfg = nick_colors[index % len(nick_colors)]
if usecolor and nick == self.html_nick_self:
nickfg = 'weechat.color.chat_nick_self'
if nick[0] in ('@', '%', '+'):
color = self.nick_prefix_color(nick[0]) or optfg
str_prefix = self.html_string(nick[0], 1, color, optbg)
nick = nick[1:]
else:
str_prefix = self.html_string(' ', 1, optfg, optbg)
length = 1 + len(nick)
if not prefix:
str_prefix = ''
maxlen += 1
length -= 1
padding = ''
if length < abs(maxlen):
padding = self.html_string('', abs(maxlen) - length, optfg, optbg)
if highlight:
nickfg = 'weechat.color.chat_highlight'
optbg = 'weechat.color.chat_highlight_bg'
string = str_prefix + self.html_string(nick, 0, nickfg, optbg)
if maxlen < 0:
return padding + string
return string + padding
def html_concat(self, messages, width, optfg, optbg):
"""Concatenate some messages with colors."""
string = ''
remaining = width
for msg in messages:
if msg[0] != '':
string += self.html_string(msg[1], 0, msg[0], optbg)
remaining -= len(msg[1])
else:
string += self.html_nick((msg[1],), 0, False, True, False, 0,
optfg, optbg)
remaining -= len(msg[1])
if msg[1][0] in ('@', '%', '+'):
remaining += 1
string += self.html_string('', remaining, optfg, optbg)
return string
def _html_apply_colors(self, match):
string = match.group()
end = string.find('}')
if end < 0:
return string
color = string[8:end]
text = string[end + 1:]
return self.html_string(text, 0, color)
def _html_apply_color_chat_time_delimiters(self, match):
return self.html_string(match.group(), 0,
'weechat.color.chat_time_delimiters')
def html_chat_time(self, msgtime):
"""Return formatted time with colors."""
option = 'weechat.look.buffer_time_format'
if self.options[option].find('${') >= 0:
str_without_colors = re.sub(r'\$\{color:[^\}]+\}', '',
self.options[option])
length = len(time.strftime(str_without_colors, msgtime))
value = re.compile(r'\$\{color:[^\}]+\}[^\$]*').sub(
self._html_apply_colors, self.options[option])
else:
value = time.strftime(self.options[option], msgtime)
length = len(value)
value = re.compile(r'[^0-9]+').sub(
self._html_apply_color_chat_time_delimiters, value)
value = self.html_string(value, 0, 'weechat.color.chat_time',
escape=False)
return (time.strftime(value, msgtime), length)
def html_chat(self, hhmmss, prefix, messages):
"""Print a message in chat area."""
delimiter = self.html_string(':', 0,
'weechat.color.chat_time_delimiters',
'weechat.color.chat_bg')
str_datetime = ('2010-12-25 {0:02d}:{1:02d}:{2:02d}'
''.format(hhmmss[0], hhmmss[1], hhmmss[2]))
t = time.strptime(str_datetime, '%Y-%m-%d %H:%M:%S')
(str_time, length_time) = self.html_chat_time(t)
return (str_time + prefix +
self.html_string(' │ ', 0,
'weechat.color.chat_prefix_suffix',
'weechat.color.chat_bg', escape=False) +
self.html_concat(messages,
self.chat_width - length_time -
self.prefix_width - 3,
'weechat.color.chat',
'weechat.color.chat_bg'))
def to_html(self):
"""Print HTML version of theme."""
self.html_nick_self = 'mario'
channel = '#weechat'
oldtopic = 'Welcome'
newtopic = 'Welcome to ' + channel + ' - help channel for WeeChat'
nicks = ('@carl', '@jessika', '@louise', '%Diego', '%Melody', '+Max',
'celia', 'Eva', 'freddy', 'Harold^', 'henry4', 'jimmy17',
'jodie', 'lee', 'madeleine', self.html_nick_self, 'mark',
'peter', 'Rachel', 'richard', 'sheryl', 'Vince', 'warren',
'zack')
nicks_hosts = ('test@foo.com', 'something@host.com')
chat_msgs = ('Hello!',
'hi mario, I just tested your patch',
'I would like to ask something',
'just ask!',
'WeeChat is great?',
'yes',
'indeed',
'sure',
'of course!',
'affirmative',
'all right',
'obviously...',
'certainly!')
html = []
#html.append('<pre style="line-height: 1.2em">')
html.append('<pre>')
width = self.chat_width + 1 + self.nicklist_width
# title bar
html.append(self.html_string(newtopic, width,
'weechat.bar.title.color_fg',
'weechat.bar.title.color_bg'))
# chat
chat = []
str_prefix_join = self.html_string(
'-->', self.prefix_width * -1,
'weechat.color.chat_prefix_join', 'weechat.color.chat_bg')
str_prefix_quit = self.html_string(
'<--', self.prefix_width * -1,
'weechat.color.chat_prefix_quit', 'weechat.color.chat_bg')
str_prefix_network = self.html_string(
'--', self.prefix_width * -1,
'weechat.color.chat_prefix_network', 'weechat.color.chat_bg')
str_prefix_empty = self.html_string(
'', self.prefix_width * -1,
'weechat.color.chat', 'weechat.color.chat_bg')
chat.append(
self.html_chat(
(9, 10, 00),
str_prefix_join,
(('', self.html_nick_self),
('weechat.color.chat_delimiters', ' ('),
('weechat.color.chat_host', nicks_hosts[0]),
('weechat.color.chat_delimiters', ')'),
('irc.color.message_join', ' has joined '),
('weechat.color.chat_channel', channel))))
chat.append(
self.html_chat(
(9, 10, 25),
self.html_nick(nicks, 8, True, True, False,
self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[0]),)))
chat.append(
self.html_chat(
(9, 11, 2),
str_prefix_network,
(('', nicks[0]),
('weechat.color.chat', ' has changed topic for '),
('weechat.color.chat_channel', channel),
('weechat.color.chat', ' from "'),
('irc.color.topic_old', oldtopic),
('weechat.color.chat', '"'))))
chat.append(
self.html_chat(
(9, 11, 2),
str_prefix_empty,
(('weechat.color.chat', 'to "'),
('irc.color.topic_new', newtopic),
('weechat.color.chat', '"'))))
chat.append(
self.html_chat(
(9, 11, 36),
self.html_nick(nicks, 16, True, True, True,
self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[1]),)))
chat.append(
self.html_chat(
(9, 12, 4),
str_prefix_quit,
(('', 'joe'),
('weechat.color.chat_delimiters', ' ('),
('weechat.color.chat_host', nicks_hosts[1]),
('weechat.color.chat_delimiters', ')'),
('irc.color.message_quit', ' has left '),
('weechat.color.chat_channel', channel),
('weechat.color.chat_delimiters', ' ('),
('irc.color.reason_quit', 'bye!'),
('weechat.color.chat_delimiters', ')'))))
chat.append(
self.html_chat(
(9, 15, 58),
self.html_nick(nicks, 12, True, True, False,
self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[2]),)))
chat.append(
self.html_chat(
(9, 16, 12),
self.html_nick(nicks, 0, True, True, False,
self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[3]),)))
chat.append(
self.html_chat(
(9, 16, 27),
self.html_nick(nicks, 12, True, True, False,
self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[4]),)))
for i in range(5, len(chat_msgs)):
chat.append(
self.html_chat(
(9, 17, (i - 5) * 4),
self.html_nick(nicks, i - 2, True, True,
False, self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[i]),)))
chat_empty = self.html_string(' ', self.chat_width,
'weechat.color.chat',
'weechat.color.chat_bg')
# separator (between chat and nicklist)
str_separator = self.html_string(
'│', 0, 'weechat.color.separator', 'weechat.color.chat_bg',
escape=False)
# nicklist
nicklist = []
for index in range(0, len(nicks)):
fg = 'weechat.bar.nicklist.color_fg'
if nicks[index].endswith('a'):
fg = 'weechat.color.nicklist_away'
nicklist.append(self.html_nick(nicks, index, True, True, False,
self.nicklist_width, fg,
'weechat.bar.nicklist.color_bg'))
nicklist_empty = self.html_string('', self.nicklist_width,
'weechat.bar.nicklist.color_fg',
'weechat.bar.nicklist.color_bg')
# print chat + nicklist
for i in range(0, self.chat_height):
if i < len(chat):
str1 = chat[i]
else:
str1 = chat_empty
if i < len(nicklist):
str2 = nicklist[i]
else:
str2 = nicklist_empty
html.append(str1 + str_separator + str2)
# status
html.append(
self.html_concat(
(('weechat.bar.status.color_delim', '['),
('weechat.color.status_time', '12:34'),
('weechat.bar.status.color_delim', '] ['),
('weechat.bar.status.color_fg', '18'),
('weechat.bar.status.color_delim', '] ['),
('weechat.bar.status.color_fg', 'irc'),
('weechat.bar.status.color_delim', '/'),
('weechat.bar.status.color_fg', 'freenode'),
('weechat.bar.status.color_delim', '] '),
('weechat.color.status_number', '2'),
('weechat.bar.status.color_delim', ':'),
('weechat.color.status_name', '#weechat'),
('weechat.bar.status.color_delim', '('),
('irc.color.item_channel_modes', '+nt'),
('weechat.bar.status.color_delim', '){'),
('weechat.bar.status.color_fg', str(len(nicks))),
('weechat.bar.status.color_delim', '} ['),
('weechat.bar.status.color_fg', 'Act: '),
('weechat.color.status_data_highlight', '3'),
('weechat.bar.status.color_delim', ':'),
('weechat.bar.status.color_fg', '#linux'),
('weechat.bar.status.color_delim', ','),
('weechat.color.status_data_private', '18'),
('weechat.bar.status.color_delim', ','),
('weechat.color.status_data_msg', '4'),
('weechat.bar.status.color_delim', ','),
('weechat.color.status_data_other', '5'),
('weechat.bar.status.color_delim', ','),
('weechat.color.status_data_other', '6'),
('weechat.bar.status.color_delim', ']')),
width, 'weechat.bar.status.color_fg',
'weechat.bar.status.color_bg'))
# input
html.append(
self.html_concat(
(('weechat.bar.input.color_delim', '['),
(self.nick_prefix_color('+'), '+'),
('irc.color.input_nick', self.html_nick_self),
('weechat.bar.input.color_delim', '('),
('weechat.bar.input.color_fg', 'i'),
('weechat.bar.input.color_delim', ')] '),
('weechat.bar.input.color_fg', 'this is misspelled '),
('aspell.color.misspelled', 'woord'),
('weechat.bar.input.color_fg', ' '),
('cursor', ' ')),
width, 'weechat.bar.input.color_fg',
'weechat.bar.input.color_bg'))
# end
html.append('</pre>')
del self.html_nick_self
return '\n'.join(html)
def get_html(self, whitebg=False):
if whitebg:
self.options['fg'] = 'black'
self.options['bg'] = 'white'
self.options['cursor'] = '!black'
else:
self.options['fg'] = '250'
self.options['bg'] = 'black'
self.options['cursor'] = '!yellow'
self.whitebg = whitebg
html = self.to_html()
del self.whitebg
del self.options['fg']
del self.options['bg']
del self.options['cursor']
return html
def save_html(self, filename, whitebg=False):
html = self.get_html(whitebg)
try:
f = open(filename, 'w')
f.write(html)
f.close()
self.prnt('Theme exported as HTML to "{0}"'.format(filename))
except:
self.prnt_error('Error writing HTML to "{0}"'.format(filename))
raise
# =============================[ themes package ]=============================
def theme_parse_xml():
"""
Parse XML themes list and return dictionary with list, with key 'id'.
Example of item return in dictionary :
'15': { 'name': 'flashcode.theme',
'version': '0.4.0',
'url': 'http://www.weechat.org/files/themes/flashcode.theme',
'md5sum': '172d3b9c99e3a8720e8a40abd768092a',
'desc': 'My theme.',
'author': 'FlashCode',
'mail': 'flashcode [at] flashtux [dot] org',
'added': '2011-09-27 18:12:57',
'updated': '2012-12-11 14:28:17' }
"""
global theme_themes
theme_themes = {}
try:
f = open(theme_config_get_xml_filename(), 'rb')
string = f.read()
f.close()
except:
weechat.prnt('',
'{0}{1}: unable to read xml file'
''.format(weechat.prefix('error'), SCRIPT_NAME))
else:
try:
dom = xml.dom.minidom.parseString(string)
except:
weechat.prnt('',
'{0}{1}: unable to parse xml list of themes: {2}'
''.format(weechat.prefix('error'),
SCRIPT_NAME,
traceback.format_exc()))
else:
for scriptNode in dom.getElementsByTagName('theme'):
id = scriptNode.getAttribute('id')
themedata = {}
for node in scriptNode.childNodes:
if node.nodeType == node.ELEMENT_NODE:
if node.firstChild is not None:
nodename = node.nodeName.encode('utf-8')
value = node.firstChild.data.encode('utf-8')
themedata[nodename] = value
theme_themes[id] = themedata
def theme_unpack():
"""Unpack theme file (themes.tar.bz2)."""
filename = theme_config_get_tarball_filename()
if not os.path.isfile(filename):
weechat.prnt('',
'{0}{1}: file not found: {1}'
''.format(weechat.prefix('error'),
SCRIPT_NAME,
filename))
return False
try:
tar = tarfile.open(filename, 'r:bz2')
tar.extractall(path=theme_config_get_dir())
tar.close()
except (tarfile.ReadError, tarfile.CompressionError, IOError):
weechat.prnt('',
'{0}{1}: invalid file (format .tar.bz2 expected): {2}'
''.format(weechat.prefix('error'),
SCRIPT_NAME,
filename))
weechat.prnt('',
'{0}{1}: try /unset theme.themes.url'
''.format(weechat.prefix('error'), SCRIPT_NAME))
return False
return True
def theme_process_update_cb(data, command, rc, stdout, stderr):
"""Callback when reading themes.tar.bz2 from website."""
global theme_hook_process, theme_stdout, theme_themes
if stdout:
theme_stdout += stdout
if stderr:
theme_stdout += stderr
if int(rc) >= 0:
if theme_stdout.startswith('error:'):
weechat.prnt('',
'{0}{1}: error downloading themes ({2})'
''.format(weechat.prefix('error'),
SCRIPT_NAME,
theme_stdout[6:].strip()))
else:
if theme_unpack():
theme_parse_xml()
weechat.prnt('',
'{0}: {1} themes loaded'
''.format(SCRIPT_NAME, len(theme_themes)))
theme_hook_process = ''
return weechat.WEECHAT_RC_OK
def theme_update():
"""Download themes (themes.tar.bz2)."""
global theme_hook_process, theme_stdout
# get data from website, via hook_process
if theme_hook_process:
weechat.unhook(theme_hook_process)
theme_hook_process = ''
weechat.prnt('', SCRIPT_NAME + ': downloading themes...')
theme_config_create_dir()
theme_stdout = ''
theme_hook_process = (
weechat.hook_process_hashtable(
'url:' + weechat.config_string(theme_cfg['themes_url']),
{'file_out': theme_config_get_tarball_filename()},
TIMEOUT_UPDATE,
'theme_process_update_cb', ''))
def theme_list(search):
"""List themes."""
global theme_themes
if (len(theme_themes) > 0):
weechat.prnt('', '')
weechat.prnt('', '{0} themes:'.format(len(theme_themes)))
for idtheme, theme in theme_themes.items():
weechat.prnt('', ' ' + theme['name'])
else:
weechat.prnt('', 'No theme loaded')
# ================================[ command ]=================================
def theme_cmd(data, buffer, args):
"""Callback for /theme command."""
if args == '':
weechat.command('', '/help ' + SCRIPT_COMMAND)
return weechat.WEECHAT_RC_OK
argv = args.strip().split(' ', 1)
if len(argv) == 0:
return weechat.WEECHAT_RC_OK
if argv[0] in ('install',):
weechat.prnt('',
'{0}: action "{1}" not developed'
''.format(SCRIPT_NAME, argv[0]))
return weechat.WEECHAT_RC_OK
# check arguments
if len(argv) < 2:
if argv[0] in ('install', 'installfile', 'save', 'export'):
weechat.prnt('',
'{0}: too few arguments for action "{1}"'
''.format(SCRIPT_NAME, argv[0]))
return weechat.WEECHAT_RC_OK
# execute asked action
if argv[0] == 'list':
theme_list(argv[1] if len(argv) >= 2 else '')
elif argv[0] == 'info':
filename = None
if len(argv) >= 2:
filename = argv[1]
theme = Theme(filename)
if filename:
theme.info('Info about theme "{0}":'.format(filename))
else:
theme.info('Info about current theme:')
elif argv[0] == 'show':
filename = None
if len(argv) >= 2:
filename = argv[1]
theme = Theme(filename)
if filename:
theme.show('Content of theme "{0}":'.format(filename))
else:
theme.show('Content of current theme:')
elif argv[0] == 'installfile':
theme = Theme()
theme.save(theme_config_get_undo())
theme = Theme(argv[1])
if theme.isok():
theme.install()
elif argv[0] == 'update':
theme_update()
elif argv[0] == 'undo':
theme = Theme(theme_config_get_undo())
if theme.isok():
theme.install()
elif argv[0] == 'save':
theme = Theme()
theme.save(argv[1])
elif argv[0] == 'backup':
theme = Theme()
theme.save(theme_config_get_backup())
elif argv[0] == 'restore':
theme = Theme(theme_config_get_backup())
if theme.isok():
theme.install()
elif argv[0] == 'export':
htheme = HtmlTheme()
whitebg = False
htmlfile = argv[1]
argv2 = args.strip().split(' ', 2)
if len(argv2) >= 3 and argv2[1] == 'white':
whitebg = True
htmlfile = argv2[2]
htheme.save_html(htmlfile, whitebg)
return weechat.WEECHAT_RC_OK
# ==================================[ main ]==================================
def theme_init():
"""Called when script is loaded."""
theme_config_create_dir()
filename = theme_config_get_backup()
if not os.path.isfile(filename):
theme = Theme()
theme.save(filename)
def main_weechat():
"""Main function, called only in WeeChat."""
if not weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
SCRIPT_LICENSE, SCRIPT_DESC, '', ''):
return
theme_config_init()
theme_config_read()
theme_init()
weechat.hook_command(
SCRIPT_COMMAND,
'WeeChat theme manager',
'list [<text>] || info|show [<theme>] || install <theme>'
' || installfile <file> || update || undo || backup || save <file>'
' || restore || export [-white] <file>',
' list: list themes (search text if given)\n'
' info: show info about theme (without argument: for current '
'theme)\n'
' show: show all options in theme (without argument: for '
'current theme)\n'
' install: install a theme from repository\n'
'installfile: load theme from a file\n'
' update: download and unpack themes in themes directory\n'
' undo: undo last theme install\n'
' backup: backup current theme (by default in '
'~/.weechat/themes/_backup.theme); this is done the first time script '
'is loaded\n'
' save: save current theme in a file\n'
' restore: restore theme backuped by script\n'
' export: save current theme as HTML in a file (with "-white": '
'use white background in HTML)\n\n'
'Examples:\n'
' /' + SCRIPT_COMMAND + ' save /tmp/flashcode.theme => save current '
'theme',
'list'
' || info %(filename)'
' || show %(filename)'
' || install %(themes)'
' || installfile %(filename)'
' || update'
' || undo'
' || save %(filename)'
' || backup'
' || restore'
' || export -white|%(filename) %(filename)',
'theme_cmd', '')
def theme_usage():
"""Display usage."""
padding = ' ' * len(sys.argv[0])
print('')
print('Usage: {0} --export <themefile> <htmlfile> [white]'
''.format(sys.argv[0]))
print(' {0} --info <filename>'.format(padding))
print(' {0} --help'.format(padding))
print('')
print(' -e, --export export a theme file to HTML')
print(' -i, --info display info about a theme')
print(' -h, --help display this help')
print('')
sys.exit(0)
def main_cmdline():
"""Main function, called only outside WeeChat."""
if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
theme_usage()
elif len(sys.argv) > 1:
if sys.argv[1] in ('-e', '--export'):
if len(sys.argv) < 4:
theme_usage()
whitebg = 'white' in sys.argv[4:]
htheme = HtmlTheme(sys.argv[2])
htheme.save_html(sys.argv[3], whitebg)
elif sys.argv[1] in ('-i', '--info'):
if len(sys.argv) < 3:
theme_usage()
theme = Theme(sys.argv[2])
theme.info('Info about theme "{0}":'.format(sys.argv[2]))
else:
theme_usage()
if __name__ == '__main__' and import_other_ok:
if import_weechat_ok:
main_weechat()
else:
main_cmdline()
| mit |
chouseknecht/ansible | lib/ansible/modules/cloud/ovirt/ovirt_scheduling_policy_info.py | 20 | 4760 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ovirt_scheduling_policy_info
short_description: Retrieve information about one or more oVirt scheduling policies
author: "Ondra Machacek (@machacekondra)"
version_added: "2.4"
description:
- "Retrieve information about one or more oVirt scheduling policies."
- This module was called C(ovirt_scheduling_policy_facts) before Ansible 2.9, returning C(ansible_facts).
Note that the M(ovirt_scheduling_policy_info) module no longer returns C(ansible_facts)!
notes:
- "This module returns a variable C(ovirt_scheduling_policies),
which contains a list of scheduling policies. You need to register the result with
the I(register) keyword to use it."
options:
id:
description:
- "ID of the scheduling policy."
required: true
name:
description:
- "Name of the scheduling policy, can be used as glob expression."
extends_documentation_fragment: ovirt_info
'''
EXAMPLES = '''
# Examples don't contain auth parameter for simplicity,
# look at ovirt_auth module to see how to reuse authentication:
# Gather information about all scheduling policies with name InClusterUpgrade:
- ovirt_scheduling_policy_info:
name: InClusterUpgrade
register: result
- debug:
msg: "{{ result.ovirt_scheduling_policies }}"
'''
RETURN = '''
ovirt_scheduling_policies:
description: "List of dictionaries describing the scheduling policies.
Scheduling policies attributes are mapped to dictionary keys,
all scheduling policies attributes can be found at following
url: https://ovirt.example.com/ovirt-engine/api/model#types/scheduling_policy."
returned: On success.
type: list
'''
import fnmatch
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_of_struct,
ovirt_info_full_argument_spec,
)
def main():
argument_spec = ovirt_info_full_argument_spec(
id=dict(default=None),
name=dict(default=None),
)
module = AnsibleModule(argument_spec)
is_old_facts = module._name == 'ovirt_scheduling_policy_facts'
if is_old_facts:
module.deprecate("The 'ovirt_scheduling_policy_facts' module has been renamed to 'ovirt_scheduling_policy_info', "
"and the renamed one no longer returns ansible_facts", version='2.13')
check_sdk(module)
try:
auth = module.params.pop('auth')
connection = create_connection(auth)
system_service = connection.system_service()
sched_policies_service = system_service.scheduling_policies_service()
if module.params['name']:
sched_policies = [
e for e in sched_policies_service.list()
if fnmatch.fnmatch(e.name, module.params['name'])
]
elif module.params['id']:
sched_policies = [
sched_policies_service.service(module.params['id']).get()
]
else:
sched_policies = sched_policies_service.list()
result = dict(
ovirt_scheduling_policies=[
get_dict_of_struct(
struct=c,
connection=connection,
fetch_nested=module.params.get('fetch_nested'),
attributes=module.params.get('nested_attributes'),
) for c in sched_policies
],
)
if is_old_facts:
module.exit_json(changed=False, ansible_facts=result)
else:
module.exit_json(changed=False, **result)
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
finally:
connection.close(logout=auth.get('token') is None)
if __name__ == '__main__':
main()
| gpl-3.0 |
fichter/grpc | src/python/grpcio/grpc/framework/foundation/__init__.py | 1496 | 1530 | # Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| bsd-3-clause |
luceatnobis/youtube-dl | youtube_dl/extractor/vidbit.py | 64 | 2917 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
int_or_none,
js_to_json,
remove_end,
unified_strdate,
)
class VidbitIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?vidbit\.co/(?:watch|embed)\?.*?\bv=(?P<id>[\da-zA-Z]+)'
_TESTS = [{
'url': 'http://www.vidbit.co/watch?v=jkL2yDOEq2',
'md5': '1a34b7f14defe3b8fafca9796892924d',
'info_dict': {
'id': 'jkL2yDOEq2',
'ext': 'mp4',
'title': 'Intro to VidBit',
'description': 'md5:5e0d6142eec00b766cbf114bfd3d16b7',
'thumbnail': r're:https?://.*\.jpg$',
'upload_date': '20160618',
'view_count': int,
'comment_count': int,
}
}, {
'url': 'http://www.vidbit.co/embed?v=jkL2yDOEq2&auto=0&water=0',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(
compat_urlparse.urljoin(url, '/watch?v=%s' % video_id), video_id)
video_url, title = [None] * 2
config = self._parse_json(self._search_regex(
r'(?s)\.setup\(({.+?})\);', webpage, 'setup', default='{}'),
video_id, transform_source=js_to_json)
if config:
if config.get('file'):
video_url = compat_urlparse.urljoin(url, config['file'])
title = config.get('title')
if not video_url:
video_url = compat_urlparse.urljoin(url, self._search_regex(
r'file\s*:\s*(["\'])(?P<url>(?:(?!\1).)+)\1',
webpage, 'video URL', group='url'))
if not title:
title = remove_end(
self._html_search_regex(
(r'<h1>(.+?)</h1>', r'<title>(.+?)</title>'),
webpage, 'title', default=None) or self._og_search_title(webpage),
' - VidBit')
description = self._html_search_meta(
('description', 'og:description', 'twitter:description'),
webpage, 'description')
upload_date = unified_strdate(self._html_search_meta(
'datePublished', webpage, 'upload date'))
view_count = int_or_none(self._search_regex(
r'<strong>(\d+)</strong> views',
webpage, 'view count', fatal=False))
comment_count = int_or_none(self._search_regex(
r'id=["\']cmt_num["\'][^>]*>\((\d+)\)',
webpage, 'comment count', fatal=False))
return {
'id': video_id,
'url': video_url,
'title': title,
'description': description,
'thumbnail': self._og_search_thumbnail(webpage),
'upload_date': upload_date,
'view_count': view_count,
'comment_count': comment_count,
}
| unlicense |
P0cL4bs/3vilTwinAttacker | plugins/external/Responder/servers/MSSQL.py | 5 | 5677 | #!/usr/bin/env python
# This file is part of Responder
# Original work by Laurent Gaffie - Trustwave Holdings
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from SocketServer import BaseRequestHandler
from packets import MSSQLPreLoginAnswer, MSSQLNTLMChallengeAnswer
from utils import *
import struct
class TDS_Login_Packet:
def __init__(self, data):
ClientNameOff = struct.unpack('<h', data[44:46])[0]
ClientNameLen = struct.unpack('<h', data[46:48])[0]
UserNameOff = struct.unpack('<h', data[48:50])[0]
UserNameLen = struct.unpack('<h', data[50:52])[0]
PasswordOff = struct.unpack('<h', data[52:54])[0]
PasswordLen = struct.unpack('<h', data[54:56])[0]
AppNameOff = struct.unpack('<h', data[56:58])[0]
AppNameLen = struct.unpack('<h', data[58:60])[0]
ServerNameOff = struct.unpack('<h', data[60:62])[0]
ServerNameLen = struct.unpack('<h', data[62:64])[0]
Unknown1Off = struct.unpack('<h', data[64:66])[0]
Unknown1Len = struct.unpack('<h', data[66:68])[0]
LibraryNameOff = struct.unpack('<h', data[68:70])[0]
LibraryNameLen = struct.unpack('<h', data[70:72])[0]
LocaleOff = struct.unpack('<h', data[72:74])[0]
LocaleLen = struct.unpack('<h', data[74:76])[0]
DatabaseNameOff = struct.unpack('<h', data[76:78])[0]
DatabaseNameLen = struct.unpack('<h', data[78:80])[0]
self.ClientName = data[8+ClientNameOff:8+ClientNameOff+ClientNameLen*2].replace('\x00', '')
self.UserName = data[8+UserNameOff:8+UserNameOff+UserNameLen*2].replace('\x00', '')
self.Password = data[8+PasswordOff:8+PasswordOff+PasswordLen*2].replace('\x00', '')
self.AppName = data[8+AppNameOff:8+AppNameOff+AppNameLen*2].replace('\x00', '')
self.ServerName = data[8+ServerNameOff:8+ServerNameOff+ServerNameLen*2].replace('\x00', '')
self.Unknown1 = data[8+Unknown1Off:8+Unknown1Off+Unknown1Len*2].replace('\x00', '')
self.LibraryName = data[8+LibraryNameOff:8+LibraryNameOff+LibraryNameLen*2].replace('\x00', '')
self.Locale = data[8+LocaleOff:8+LocaleOff+LocaleLen*2].replace('\x00', '')
self.DatabaseName = data[8+DatabaseNameOff:8+DatabaseNameOff+DatabaseNameLen*2].replace('\x00', '')
def ParseSQLHash(data, client):
SSPIStart = data[8:]
LMhashLen = struct.unpack('<H',data[20:22])[0]
LMhashOffset = struct.unpack('<H',data[24:26])[0]
LMHash = SSPIStart[LMhashOffset:LMhashOffset+LMhashLen].encode("hex").upper()
NthashLen = struct.unpack('<H',data[30:32])[0]
NthashOffset = struct.unpack('<H',data[32:34])[0]
NTHash = SSPIStart[NthashOffset:NthashOffset+NthashLen].encode("hex").upper()
DomainLen = struct.unpack('<H',data[36:38])[0]
DomainOffset = struct.unpack('<H',data[40:42])[0]
Domain = SSPIStart[DomainOffset:DomainOffset+DomainLen].replace('\x00','')
UserLen = struct.unpack('<H',data[44:46])[0]
UserOffset = struct.unpack('<H',data[48:50])[0]
User = SSPIStart[UserOffset:UserOffset+UserLen].replace('\x00','')
if NthashLen == 24:
WriteHash = '%s::%s:%s:%s:%s' % (User, Domain, LMHash, NTHash, settings.Config.NumChal)
SaveToDb({
'module': 'MSSQL',
'type': 'NTLMv1',
'client': client,
'user': Domain+'\\'+User,
'hash': LMHash+":"+NTHash,
'fullhash': WriteHash,
})
if NthashLen > 60:
WriteHash = '%s::%s:%s:%s:%s' % (User, Domain, settings.Config.NumChal, NTHash[:32], NTHash[32:])
SaveToDb({
'module': 'MSSQL',
'type': 'NTLMv2',
'client': client,
'user': Domain+'\\'+User,
'hash': NTHash[:32]+":"+NTHash[32:],
'fullhash': WriteHash,
})
def ParseSqlClearTxtPwd(Pwd):
Pwd = map(ord,Pwd.replace('\xa5',''))
Pw = ''
for x in Pwd:
Pw += hex(x ^ 0xa5)[::-1][:2].replace("x", "0").decode('hex')
return Pw
def ParseClearTextSQLPass(data, client):
TDS = TDS_Login_Packet(data)
SaveToDb({
'module': 'MSSQL',
'type': 'Cleartext',
'client': client,
'hostname': "%s (%s)" % (TDS.ServerName, TDS.DatabaseName),
'user': TDS.UserName,
'cleartext': ParseSqlClearTxtPwd(TDS.Password),
'fullhash': TDS.UserName +':'+ ParseSqlClearTxtPwd(TDS.Password),
})
# MSSQL Server class
class MSSQL(BaseRequestHandler):
def handle(self):
if settings.Config.Verbose:
print text("[MSSQL] Received connection from %s" % self.client_address[0])
try:
while True:
data = self.request.recv(1024)
self.request.settimeout(0.1)
if data[0] == "\x12": # Pre-Login Message
Buffer = str(MSSQLPreLoginAnswer())
self.request.send(Buffer)
data = self.request.recv(1024)
if data[0] == "\x10": # NegoSSP
if re.search("NTLMSSP",data):
Packet = MSSQLNTLMChallengeAnswer(ServerChallenge=settings.Config.Challenge)
Packet.calculate()
Buffer = str(Packet)
self.request.send(Buffer)
data = self.request.recv(1024)
else:
ParseClearTextSQLPass(data,self.client_address[0])
if data[0] == "\x11": # NegoSSP Auth
ParseSQLHash(data,self.client_address[0])
except socket.timeout:
self.request.close()
| gpl-3.0 |
shackra/thomas-aquinas | tests/test_rich_label.py | 1 | 1040 | # This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
testinfo = "s, t 5, s, t 10.1, s, q"
tags = "RichLabel"
import summa
from summa.director import director
from summa.sprite import Sprite
from summa.actions import *
from summa.text import *
class TestLayer(summa.layer.Layer):
def __init__(self):
super( TestLayer, self ).__init__()
x,y = director.get_window_size()
self.text = RichLabel(
"Hello {color (255, 0, 0, 255)}World!",
(x/2, y/2))
self.text.element.document.set_style(0, 5, dict(bold = True))
self.text.element.document.set_style(6, 11, dict(italic = True))
self.text.do( Rotate( 360, 10 ) )
self.text.do( ScaleTo( 10, 10 ) )
self.add( self.text )
def main():
director.init()
test_layer = TestLayer ()
main_scene = summa.scene.Scene (test_layer)
director.run (main_scene)
if __name__ == '__main__':
main()
| bsd-3-clause |
zammitjames/pyo | examples/sequencing/01_starttime_duration.py | 12 | 1082 | #!/usr/bin/env python
# encoding: utf-8
"""
Show how to use `dur` and `delay` parameters of play() and out()
methods to sequence events over time.
"""
from pyo import *
s = Server(sr=44100, nchnls=2, buffersize=512, duplex=0).boot()
num = 70
freqs = [random.uniform(100,1000) for i in range(num)]
start1 = [i*.5 for i in range(num)]
fade1 = Fader([1]*num, 1, 5, mul=.03).play(dur=5, delay=start1)
a = SineLoop(freqs, feedback=.05, mul=fade1).out(dur=5, delay=start1)
start2 = 30
dur2 = 40
snds = ['../snds/alum1.wav', '../snds/alum2.wav', '../snds/alum3.wav', '../snds/alum4.wav']
tabs = SndTable(snds)
fade2 = Fader(.05, 10, dur2, mul=.7).play(dur=dur2, delay=start2)
b = Beat(time=.125, w1=[90,30,30,20], w2=[30,90,50,40], w3=[0,30,30,40], poly=1).play(dur=dur2, delay=start2)
out = TrigEnv(b, tabs, b['dur'], mul=b['amp']*fade2).out(dur=dur2, delay=start2)
start3 = 45
dur3 = 30
fade3 = Fader(15, 15, dur3, mul=.02).play(dur=dur3, delay=start3)
fm = FM(carrier=[149,100,151,50]*3, ratio=[.2499,.501,.75003], index=10, mul=fade3).out(dur=dur3, delay=start3)
s.gui(locals()) | gpl-3.0 |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/tensorflow/python/ops/linalg_ops.py | 17 | 16241 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Operations for linear algebra."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_linalg_ops
from tensorflow.python.ops import math_ops
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.ops.gen_linalg_ops import *
# pylint: enable=wildcard-import
# Names below are lower_case.
# pylint: disable=invalid-name
def cholesky_solve(chol, rhs, name=None):
"""Solves systems of linear eqns `A X = RHS`, given Cholesky factorizations.
```python
# Solve 10 separate 2x2 linear systems:
A = ... # shape 10 x 2 x 2
RHS = ... # shape 10 x 2 x 1
chol = tf.cholesky(A) # shape 10 x 2 x 2
X = tf.cholesky_solve(chol, RHS) # shape 10 x 2 x 1
# tf.matmul(A, X) ~ RHS
X[3, :, 0] # Solution to the linear system A[3, :, :] x = RHS[3, :, 0]
# Solve five linear systems (K = 5) for every member of the length 10 batch.
A = ... # shape 10 x 2 x 2
RHS = ... # shape 10 x 2 x 5
...
X[3, :, 2] # Solution to the linear system A[3, :, :] x = RHS[3, :, 2]
```
Args:
chol: A `Tensor`. Must be `float32` or `float64`, shape is `[..., M, M]`.
Cholesky factorization of `A`, e.g. `chol = tf.cholesky(A)`.
For that reason, only the lower triangular parts (including the diagonal)
of the last two dimensions of `chol` are used. The strictly upper part is
assumed to be zero and not accessed.
rhs: A `Tensor`, same type as `chol`, shape is `[..., M, K]`.
name: A name to give this `Op`. Defaults to `cholesky_solve`.
Returns:
Solution to `A x = rhs`, shape `[..., M, K]`.
"""
# To solve C C^* x = rhs, we
# 1. Solve C y = rhs for y, thus y = C^* x
# 2. Solve C^* x = y for x
with ops.name_scope(name, 'cholesky_solve', [chol, rhs]):
y = gen_linalg_ops.matrix_triangular_solve(
chol, rhs, adjoint=False, lower=True)
x = gen_linalg_ops.matrix_triangular_solve(
chol, y, adjoint=True, lower=True)
return x
def eye(num_rows,
num_columns=None,
batch_shape=None,
dtype=dtypes.float32,
name=None):
"""Construct an identity matrix, or a batch of matrices.
```python
# Construct one identity matrix.
tf.eye(2)
==> [[1., 0.],
[0., 1.]]
# Construct a batch of 3 identity matricies, each 2 x 2.
# batch_identity[i, :, :] is a 2 x 2 identity matrix, i = 0, 1, 2.
batch_identity = tf.eye(2, batch_shape=[3])
# Construct one 2 x 3 "identity" matrix
tf.eye(2, num_columns=3)
==> [[ 1., 0., 0.],
[ 0., 1., 0.]]
```
Args:
num_rows: Non-negative `int32` scalar `Tensor` giving the number of rows
in each batch matrix.
num_columns: Optional non-negative `int32` scalar `Tensor` giving the number
of columns in each batch matrix. Defaults to `num_rows`.
batch_shape: `int32` `Tensor`. If provided, returned `Tensor` will have
leading batch dimensions of this shape.
dtype: The type of an element in the resulting `Tensor`
name: A name for this `Op`. Defaults to "eye".
Returns:
A `Tensor` of shape `batch_shape + [num_rows, num_columns]`
"""
with ops.name_scope(
name, default_name='eye', values=[num_rows, num_columns, batch_shape]):
batch_shape = [] if batch_shape is None else batch_shape
batch_shape = ops.convert_to_tensor(
batch_shape, name='shape', dtype=dtypes.int32)
if num_columns is None:
diag_size = num_rows
else:
diag_size = math_ops.minimum(num_rows, num_columns)
diag_shape = array_ops.concat((batch_shape, [diag_size]), 0)
diag_ones = array_ops.ones(diag_shape, dtype=dtype)
if num_columns is None:
return array_ops.matrix_diag(diag_ones)
else:
shape = array_ops.concat((batch_shape, [num_rows, num_columns]), 0)
zero_matrix = array_ops.zeros(shape, dtype=dtype)
return array_ops.matrix_set_diag(zero_matrix, diag_ones)
def matrix_solve_ls(matrix, rhs, l2_regularizer=0.0, fast=True, name=None):
r"""Solves one or more linear least-squares problems.
`matrix` is a tensor of shape `[..., M, N]` whose inner-most 2 dimensions
form `M`-by-`N` matrices. Rhs is a tensor of shape `[..., M, K]` whose
inner-most 2 dimensions form `M`-by-`K` matrices. The computed output is a
`Tensor` of shape `[..., N, K]` whose inner-most 2 dimensions form `M`-by-`K`
matrices that solve the equations
`matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]` in the least squares
sense.
Below we will use the following notation for each pair of matrix and
right-hand sides in the batch:
`matrix`=\\(A \in \Re^{m \times n}\\),
`rhs`=\\(B \in \Re^{m \times k}\\),
`output`=\\(X \in \Re^{n \times k}\\),
`l2_regularizer`=\\(\lambda\\).
If `fast` is `True`, then the solution is computed by solving the normal
equations using Cholesky decomposition. Specifically, if \\(m \ge n\\) then
\\(X = (A^T A + \lambda I)^{-1} A^T B\\), which solves the least-squares
problem \\(X = \mathrm{argmin}_{Z \in \Re^{n \times k}} ||A Z - B||_F^2 +
\lambda ||Z||_F^2\\). If \\(m \lt n\\) then `output` is computed as
\\(X = A^T (A A^T + \lambda I)^{-1} B\\), which (for \\(\lambda = 0\\)) is
the minimum-norm solution to the under-determined linear system, i.e.
\\(X = \mathrm{argmin}_{Z \in \Re^{n \times k}} ||Z||_F^2 \\), subject to
\\(A Z = B\\). Notice that the fast path is only numerically stable when
\\(A\\) is numerically full rank and has a condition number
\\(\mathrm{cond}(A) \lt \frac{1}{\sqrt{\epsilon_{mach}}}\\) or\\(\lambda\\)
is sufficiently large.
If `fast` is `False` an algorithm based on the numerically robust complete
orthogonal decomposition is used. This computes the minimum-norm
least-squares solution, even when \\(A\\) is rank deficient. This path is
typically 6-7 times slower than the fast path. If `fast` is `False` then
`l2_regularizer` is ignored.
Args:
matrix: `Tensor` of shape `[..., M, N]`.
rhs: `Tensor` of shape `[..., M, K]`.
l2_regularizer: 0-D `double` `Tensor`. Ignored if `fast=False`.
fast: bool. Defaults to `True`.
name: string, optional name of the operation.
Returns:
output: `Tensor` of shape `[..., N, K]` whose inner-most 2 dimensions form
`M`-by-`K` matrices that solve the equations
`matrix[..., :, :] * output[..., :, :] = rhs[..., :, :]` in the least
squares sense.
"""
# pylint: disable=protected-access
return gen_linalg_ops._matrix_solve_ls(
matrix, rhs, l2_regularizer, fast=fast, name=name)
def self_adjoint_eig(tensor, name=None):
"""Computes the eigen decomposition of a batch of self-adjoint matrices.
Computes the eigenvalues and eigenvectors of the innermost N-by-N matrices
in `tensor` such that
`tensor[...,:,:] * v[..., :,i] = e[..., i] * v[...,:,i]`, for i=0...N-1.
Args:
tensor: `Tensor` of shape `[..., N, N]`. Only the lower triangular part of
each inner inner matrix is referenced.
name: string, optional name of the operation.
Returns:
e: Eigenvalues. Shape is `[..., N]`.
v: Eigenvectors. Shape is `[..., N, N]`. The columns of the inner most
matrices contain eigenvectors of the corresponding matrices in `tensor`
"""
# pylint: disable=protected-access
e, v = gen_linalg_ops._self_adjoint_eig_v2(tensor, compute_v=True, name=name)
return e, v
def self_adjoint_eigvals(tensor, name=None):
"""Computes the eigenvalues of one or more self-adjoint matrices.
Args:
tensor: `Tensor` of shape `[..., N, N]`.
name: string, optional name of the operation.
Returns:
e: Eigenvalues. Shape is `[..., N]`. The vector `e[..., :]` contains the `N`
eigenvalues of `tensor[..., :, :]`.
"""
# pylint: disable=protected-access
e, _ = gen_linalg_ops._self_adjoint_eig_v2(tensor, compute_v=False, name=name)
return e
def svd(tensor, full_matrices=False, compute_uv=True, name=None):
"""Computes the singular value decompositions of one or more matrices.
Computes the SVD of each inner matrix in `tensor` such that
`tensor[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * transpose(v[..., :,
:])`
```prettyprint
# a is a tensor.
# s is a tensor of singular values.
# u is a tensor of left singular vectors.
# v is a tensor of right singular vectors.
s, u, v = svd(a)
s = svd(a, compute_uv=False)
```
Args:
tensor: `Tensor` of shape `[..., M, N]`. Let `P` be the minimum of `M` and
`N`.
full_matrices: If true, compute full-sized `u` and `v`. If false
(the default), compute only the leading `P` singular vectors.
Ignored if `compute_uv` is `False`.
compute_uv: If `True` then left and right singular vectors will be
computed and returned in `u` and `v`, respectively. Otherwise, only the
singular values will be computed, which can be significantly faster.
name: string, optional name of the operation.
Returns:
s: Singular values. Shape is `[..., P]`. The values are sorted in reverse
order of magnitude, so s[..., 0] is the largest value, s[..., 1] is the
second largest, etc.
u: Left singular vectors. If `full_matrices` is `False` (default) then
shape is `[..., M, P]`; if `full_matrices` is `True` then shape is
`[..., M, M]`. Not returned if `compute_uv` is `False`.
v: Right singular vectors. If `full_matrices` is `False` (default) then
shape is `[..., N, P]`. If `full_matrices` is `True` then shape is
`[..., N, N]`. Not returned if `compute_uv` is `False`.
@compatibility(numpy)
Mostly equivalent to numpy.linalg.svd, except that the order of output
arguments here is `s`, `u`, `v` when `compute_uv` is `True`, as opposed to
`u`, `s`, `v` for numpy.linalg.svd.
@end_compatibility
"""
# pylint: disable=protected-access
s, u, v = gen_linalg_ops._svd(
tensor, compute_uv=compute_uv, full_matrices=full_matrices)
# pylint: enable=protected-access
if compute_uv:
return math_ops.real(s), u, v
else:
return math_ops.real(s)
# pylint: disable=redefined-builtin
def norm(tensor, ord='euclidean', axis=None, keep_dims=False, name=None):
r"""Computes the norm of vectors, matrices, and tensors.
This function can compute several different vector norms (the 1-norm, the
Euclidean or 2-norm, the inf-norm, and in general the p-norm for p > 0) and
matrix norms (Frobenius, 1-norm, and inf-norm).
Args:
tensor: `Tensor` of types `float32`, `float64`, `complex64`, `complex128`
ord: Order of the norm. Supported values are 'fro', 'euclidean', `0`,
`1`, `2`, `np.inf` and any positive real number yielding the corresponding
p-norm. Default is 'euclidean' which is equivalent to Frobenius norm if
`tensor` is a matrix and equivalent to 2-norm for vectors.
Some restrictions apply:
a) The Frobenius norm `fro` is not defined for vectors,
b) If axis is a 2-tuple (matrix norm), only 'euclidean', 'fro', `1`,
`np.inf` are supported.
See the description of `axis` on how to compute norms for a batch of
vectors or matrices stored in a tensor.
axis: If `axis` is `None` (the default), the input is considered a vector
and a single vector norm is computed over the entire set of values in the
tensor, i.e. `norm(tensor, ord=ord)` is equivalent to
`norm(reshape(tensor, [-1]), ord=ord)`.
If `axis` is a Python integer, the input is considered a batch of vectors,
and `axis` determines the axis in `tensor` over which to compute vector
norms.
If `axis` is a 2-tuple of Python integers it is considered a batch of
matrices and `axis` determines the axes in `tensor` over which to compute
a matrix norm.
Negative indices are supported. Example: If you are passing a tensor that
can be either a matrix or a batch of matrices at runtime, pass
`axis=[-2,-1]` instead of `axis=None` to make sure that matrix norms are
computed.
keep_dims: If True, the axis indicated in `axis` are kept with size 1.
Otherwise, the dimensions in `axis` are removed from the output shape.
name: The name of the op.
Returns:
output: A `Tensor` of the same type as tensor, containing the vector or
matrix norms. If `keep_dims` is True then the rank of output is equal to
the rank of `tensor`. Otherwise, if `axis` is none the output is a scalar,
if `axis` is an integer, the rank of `output` is one less than the rank
of `tensor`, if `axis` is a 2-tuple the rank of `output` is two less
than the rank of `tensor`.
Raises:
ValueError: If `ord` or `axis` is invalid.
@compatibility(numpy)
Mostly equivalent to numpy.linalg.norm.
Not supported: ord <= 0, 2-norm for matrices, nuclear norm.
Other differences:
a) If axis is `None`, treats the flattened `tensor` as a vector
regardless of rank.
b) Explicitly supports 'euclidean' norm as the default, including for
higher order tensors.
@end_compatibility
"""
is_matrix_norm = ((isinstance(axis, tuple) or isinstance(axis, list)) and
len(axis) == 2)
if is_matrix_norm:
axis = tuple(axis)
if (not isinstance(axis[0], int) or not isinstance(axis[1], int) or
axis[0] == axis[1]):
raise ValueError(
"'axis' must be None, an integer, or a tuple of 2 unique integers")
# TODO(rmlarsen): Implement matrix 2-norm using tf.svd().
supported_matrix_norms = ['euclidean', 'fro', 1, np.inf]
if ord not in supported_matrix_norms:
raise ValueError("'ord' must be a supported matrix norm in %s, got %s" %
(supported_matrix_norms, ord))
else:
if not (isinstance(axis, int) or axis is None):
raise ValueError(
"'axis' must be None, an integer, or a tuple of 2 unique integers")
supported_vector_norms = ['euclidean', 1, 2, np.inf]
if (not np.isreal(ord) or ord <= 0) and ord not in supported_vector_norms:
raise ValueError("'ord' must be a supported vector norm, got %s" % ord)
if axis is not None:
axis = (axis,)
with ops.name_scope(name, 'norm', [tensor]):
tensor = ops.convert_to_tensor(tensor)
if ord in ['fro', 'euclidean', 2, 2.0]:
# TODO(rmlarsen): Move 2-norm to a separate clause once we support it for
# matrices.
result = math_ops.sqrt(
math_ops.reduce_sum(
math_ops.square(tensor), axis, keep_dims=True))
else:
result = math_ops.abs(tensor)
if ord == 1:
sum_axis = None if axis is None else axis[0]
result = math_ops.reduce_sum(result, sum_axis, keep_dims=True)
if is_matrix_norm:
result = math_ops.reduce_max(result, axis[-1], keep_dims=True)
elif ord == np.inf:
if is_matrix_norm:
result = math_ops.reduce_sum(result, axis[1], keep_dims=True)
max_axis = None if axis is None else axis[0]
result = math_ops.reduce_max(result, max_axis, keep_dims=True)
else:
# General p-norms (positive p only)
result = math_ops.pow(math_ops.reduce_sum(
math_ops.pow(result, ord), axis, keep_dims=True),
1.0 / ord)
if not keep_dims:
result = array_ops.squeeze(result, axis)
return result
# pylint: enable=invalid-name,redefined-builtin
| bsd-2-clause |
waynenilsen/statsmodels | statsmodels/stats/base.py | 33 | 3643 | # -*- coding: utf-8 -*-
"""Base classes for statistical test results
Created on Mon Apr 22 14:03:21 2013
Author: Josef Perktold
"""
from statsmodels.compat.python import lzip, zip
import numpy as np
class AllPairsResults(object):
'''Results class for pairwise comparisons, based on p-values
Parameters
----------
pvals_raw : array_like, 1-D
p-values from a pairwise comparison test
all_pairs : list of tuples
list of indices, one pair for each comparison
multitest_method : string
method that is used by default for p-value correction. This is used
as default by the methods like if the multiple-testing method is not
specified as argument.
levels : None or list of strings
optional names of the levels or groups
n_levels : None or int
If None, then the number of levels or groups is inferred from the
other arguments. It can be explicitly specified, if the inferred
number is incorrect.
Notes
-----
This class can also be used for other pairwise comparisons, for example
comparing several treatments to a control (as in Dunnet's test).
'''
def __init__(self, pvals_raw, all_pairs, multitest_method='hs',
levels=None, n_levels=None):
self.pvals_raw = pvals_raw
self.all_pairs = all_pairs
if n_levels is None:
# for all_pairs nobs*(nobs-1)/2
#self.n_levels = (1. + np.sqrt(1 + 8 * len(all_pairs))) * 0.5
self.n_levels = np.max(all_pairs) + 1
else:
self.n_levels = n_levels
self.multitest_method = multitest_method
self.levels = levels
if levels is None:
self.all_pairs_names = ['%r' % (pairs,) for pairs in all_pairs]
else:
self.all_pairs_names = ['%s-%s' % (levels[pairs[0]],
levels[pairs[1]])
for pairs in all_pairs]
def pval_corrected(self, method=None):
'''p-values corrected for multiple testing problem
This uses the default p-value correction of the instance stored in
``self.multitest_method`` if method is None.
'''
import statsmodels.stats.multitest as smt
if method is None:
method = self.multitest_method
#TODO: breaks with method=None
return smt.multipletests(self.pvals_raw, method=method)[1]
def __str__(self):
return self.summary()
def pval_table(self):
'''create a (n_levels, n_levels) array with corrected p_values
this needs to improve, similar to R pairwise output
'''
k = self.n_levels
pvals_mat = np.zeros((k, k))
# if we don't assume we have all pairs
pvals_mat[lzip(*self.all_pairs)] = self.pval_corrected()
#pvals_mat[np.triu_indices(k, 1)] = self.pval_corrected()
return pvals_mat
def summary(self):
'''returns text summarizing the results
uses the default pvalue correction of the instance stored in
``self.multitest_method``
'''
import statsmodels.stats.multitest as smt
maxlevel = max((len(ss) for ss in self.all_pairs_names))
text = 'Corrected p-values using %s p-value correction\n\n' % \
smt.multitest_methods_names[self.multitest_method]
text += 'Pairs' + (' ' * (maxlevel - 5 + 1)) + 'p-values\n'
text += '\n'.join(('%s %6.4g' % (pairs, pv) for (pairs, pv) in
zip(self.all_pairs_names, self.pval_corrected())))
return text
| bsd-3-clause |
virajkanwade/rk3188_android_kernel | tools/perf/scripts/python/sched-migration.py | 11215 | 11670 | #!/usr/bin/python
#
# Cpu task migration overview toy
#
# Copyright (C) 2010 Frederic Weisbecker <fweisbec@gmail.com>
#
# perf script event handlers have been generated by perf script -g python
#
# This software is distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
import os
import sys
from collections import defaultdict
from UserList import UserList
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
sys.path.append('scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from SchedGui import *
threads = { 0 : "idle"}
def thread_name(pid):
return "%s:%d" % (threads[pid], pid)
class RunqueueEventUnknown:
@staticmethod
def color():
return None
def __repr__(self):
return "unknown"
class RunqueueEventSleep:
@staticmethod
def color():
return (0, 0, 0xff)
def __init__(self, sleeper):
self.sleeper = sleeper
def __repr__(self):
return "%s gone to sleep" % thread_name(self.sleeper)
class RunqueueEventWakeup:
@staticmethod
def color():
return (0xff, 0xff, 0)
def __init__(self, wakee):
self.wakee = wakee
def __repr__(self):
return "%s woke up" % thread_name(self.wakee)
class RunqueueEventFork:
@staticmethod
def color():
return (0, 0xff, 0)
def __init__(self, child):
self.child = child
def __repr__(self):
return "new forked task %s" % thread_name(self.child)
class RunqueueMigrateIn:
@staticmethod
def color():
return (0, 0xf0, 0xff)
def __init__(self, new):
self.new = new
def __repr__(self):
return "task migrated in %s" % thread_name(self.new)
class RunqueueMigrateOut:
@staticmethod
def color():
return (0xff, 0, 0xff)
def __init__(self, old):
self.old = old
def __repr__(self):
return "task migrated out %s" % thread_name(self.old)
class RunqueueSnapshot:
def __init__(self, tasks = [0], event = RunqueueEventUnknown()):
self.tasks = tuple(tasks)
self.event = event
def sched_switch(self, prev, prev_state, next):
event = RunqueueEventUnknown()
if taskState(prev_state) == "R" and next in self.tasks \
and prev in self.tasks:
return self
if taskState(prev_state) != "R":
event = RunqueueEventSleep(prev)
next_tasks = list(self.tasks[:])
if prev in self.tasks:
if taskState(prev_state) != "R":
next_tasks.remove(prev)
elif taskState(prev_state) == "R":
next_tasks.append(prev)
if next not in next_tasks:
next_tasks.append(next)
return RunqueueSnapshot(next_tasks, event)
def migrate_out(self, old):
if old not in self.tasks:
return self
next_tasks = [task for task in self.tasks if task != old]
return RunqueueSnapshot(next_tasks, RunqueueMigrateOut(old))
def __migrate_in(self, new, event):
if new in self.tasks:
self.event = event
return self
next_tasks = self.tasks[:] + tuple([new])
return RunqueueSnapshot(next_tasks, event)
def migrate_in(self, new):
return self.__migrate_in(new, RunqueueMigrateIn(new))
def wake_up(self, new):
return self.__migrate_in(new, RunqueueEventWakeup(new))
def wake_up_new(self, new):
return self.__migrate_in(new, RunqueueEventFork(new))
def load(self):
""" Provide the number of tasks on the runqueue.
Don't count idle"""
return len(self.tasks) - 1
def __repr__(self):
ret = self.tasks.__repr__()
ret += self.origin_tostring()
return ret
class TimeSlice:
def __init__(self, start, prev):
self.start = start
self.prev = prev
self.end = start
# cpus that triggered the event
self.event_cpus = []
if prev is not None:
self.total_load = prev.total_load
self.rqs = prev.rqs.copy()
else:
self.rqs = defaultdict(RunqueueSnapshot)
self.total_load = 0
def __update_total_load(self, old_rq, new_rq):
diff = new_rq.load() - old_rq.load()
self.total_load += diff
def sched_switch(self, ts_list, prev, prev_state, next, cpu):
old_rq = self.prev.rqs[cpu]
new_rq = old_rq.sched_switch(prev, prev_state, next)
if old_rq is new_rq:
return
self.rqs[cpu] = new_rq
self.__update_total_load(old_rq, new_rq)
ts_list.append(self)
self.event_cpus = [cpu]
def migrate(self, ts_list, new, old_cpu, new_cpu):
if old_cpu == new_cpu:
return
old_rq = self.prev.rqs[old_cpu]
out_rq = old_rq.migrate_out(new)
self.rqs[old_cpu] = out_rq
self.__update_total_load(old_rq, out_rq)
new_rq = self.prev.rqs[new_cpu]
in_rq = new_rq.migrate_in(new)
self.rqs[new_cpu] = in_rq
self.__update_total_load(new_rq, in_rq)
ts_list.append(self)
if old_rq is not out_rq:
self.event_cpus.append(old_cpu)
self.event_cpus.append(new_cpu)
def wake_up(self, ts_list, pid, cpu, fork):
old_rq = self.prev.rqs[cpu]
if fork:
new_rq = old_rq.wake_up_new(pid)
else:
new_rq = old_rq.wake_up(pid)
if new_rq is old_rq:
return
self.rqs[cpu] = new_rq
self.__update_total_load(old_rq, new_rq)
ts_list.append(self)
self.event_cpus = [cpu]
def next(self, t):
self.end = t
return TimeSlice(t, self)
class TimeSliceList(UserList):
def __init__(self, arg = []):
self.data = arg
def get_time_slice(self, ts):
if len(self.data) == 0:
slice = TimeSlice(ts, TimeSlice(-1, None))
else:
slice = self.data[-1].next(ts)
return slice
def find_time_slice(self, ts):
start = 0
end = len(self.data)
found = -1
searching = True
while searching:
if start == end or start == end - 1:
searching = False
i = (end + start) / 2
if self.data[i].start <= ts and self.data[i].end >= ts:
found = i
end = i
continue
if self.data[i].end < ts:
start = i
elif self.data[i].start > ts:
end = i
return found
def set_root_win(self, win):
self.root_win = win
def mouse_down(self, cpu, t):
idx = self.find_time_slice(t)
if idx == -1:
return
ts = self[idx]
rq = ts.rqs[cpu]
raw = "CPU: %d\n" % cpu
raw += "Last event : %s\n" % rq.event.__repr__()
raw += "Timestamp : %d.%06d\n" % (ts.start / (10 ** 9), (ts.start % (10 ** 9)) / 1000)
raw += "Duration : %6d us\n" % ((ts.end - ts.start) / (10 ** 6))
raw += "Load = %d\n" % rq.load()
for t in rq.tasks:
raw += "%s \n" % thread_name(t)
self.root_win.update_summary(raw)
def update_rectangle_cpu(self, slice, cpu):
rq = slice.rqs[cpu]
if slice.total_load != 0:
load_rate = rq.load() / float(slice.total_load)
else:
load_rate = 0
red_power = int(0xff - (0xff * load_rate))
color = (0xff, red_power, red_power)
top_color = None
if cpu in slice.event_cpus:
top_color = rq.event.color()
self.root_win.paint_rectangle_zone(cpu, color, top_color, slice.start, slice.end)
def fill_zone(self, start, end):
i = self.find_time_slice(start)
if i == -1:
return
for i in xrange(i, len(self.data)):
timeslice = self.data[i]
if timeslice.start > end:
return
for cpu in timeslice.rqs:
self.update_rectangle_cpu(timeslice, cpu)
def interval(self):
if len(self.data) == 0:
return (0, 0)
return (self.data[0].start, self.data[-1].end)
def nr_rectangles(self):
last_ts = self.data[-1]
max_cpu = 0
for cpu in last_ts.rqs:
if cpu > max_cpu:
max_cpu = cpu
return max_cpu
class SchedEventProxy:
def __init__(self):
self.current_tsk = defaultdict(lambda : -1)
self.timeslices = TimeSliceList()
def sched_switch(self, headers, prev_comm, prev_pid, prev_prio, prev_state,
next_comm, next_pid, next_prio):
""" Ensure the task we sched out this cpu is really the one
we logged. Otherwise we may have missed traces """
on_cpu_task = self.current_tsk[headers.cpu]
if on_cpu_task != -1 and on_cpu_task != prev_pid:
print "Sched switch event rejected ts: %s cpu: %d prev: %s(%d) next: %s(%d)" % \
(headers.ts_format(), headers.cpu, prev_comm, prev_pid, next_comm, next_pid)
threads[prev_pid] = prev_comm
threads[next_pid] = next_comm
self.current_tsk[headers.cpu] = next_pid
ts = self.timeslices.get_time_slice(headers.ts())
ts.sched_switch(self.timeslices, prev_pid, prev_state, next_pid, headers.cpu)
def migrate(self, headers, pid, prio, orig_cpu, dest_cpu):
ts = self.timeslices.get_time_slice(headers.ts())
ts.migrate(self.timeslices, pid, orig_cpu, dest_cpu)
def wake_up(self, headers, comm, pid, success, target_cpu, fork):
if success == 0:
return
ts = self.timeslices.get_time_slice(headers.ts())
ts.wake_up(self.timeslices, pid, target_cpu, fork)
def trace_begin():
global parser
parser = SchedEventProxy()
def trace_end():
app = wx.App(False)
timeslices = parser.timeslices
frame = RootFrame(timeslices, "Migration")
app.MainLoop()
def sched__sched_stat_runtime(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, runtime, vruntime):
pass
def sched__sched_stat_iowait(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, delay):
pass
def sched__sched_stat_sleep(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, delay):
pass
def sched__sched_stat_wait(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, delay):
pass
def sched__sched_process_fork(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
parent_comm, parent_pid, child_comm, child_pid):
pass
def sched__sched_process_wait(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio):
pass
def sched__sched_process_exit(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio):
pass
def sched__sched_process_free(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio):
pass
def sched__sched_migrate_task(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio, orig_cpu,
dest_cpu):
headers = EventHeaders(common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
parser.migrate(headers, pid, prio, orig_cpu, dest_cpu)
def sched__sched_switch(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
prev_comm, prev_pid, prev_prio, prev_state,
next_comm, next_pid, next_prio):
headers = EventHeaders(common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
parser.sched_switch(headers, prev_comm, prev_pid, prev_prio, prev_state,
next_comm, next_pid, next_prio)
def sched__sched_wakeup_new(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio, success,
target_cpu):
headers = EventHeaders(common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
parser.wake_up(headers, comm, pid, success, target_cpu, 1)
def sched__sched_wakeup(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio, success,
target_cpu):
headers = EventHeaders(common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
parser.wake_up(headers, comm, pid, success, target_cpu, 0)
def sched__sched_wait_task(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio):
pass
def sched__sched_kthread_stop_ret(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
ret):
pass
def sched__sched_kthread_stop(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid):
pass
def trace_unhandled(event_name, context, common_cpu, common_secs, common_nsecs,
common_pid, common_comm):
pass
| gpl-2.0 |
samboiki/smap-data | python/smap/driver.py | 4 | 10510 | """
Copyright (c) 2011, 2012, Regents of the University of California
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
"""
"""
@author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
"""
import uuid
import datetime
import time
import sys
import urlparse
import urllib2
from twisted.internet import reactor, threads, defer
from twisted.python.util import println
from twisted.python import log
from zope.interface import implements
from interface import *
import core
import util
import loader
import server
from smap.contrib import dtutil
class SmapDriver(object):
# this is actually a shim layer which presents a ISmapInstance to
# drivers
implements(ISmapInstance)
load_chunk_size = datetime.timedelta(days=1)
@classmethod
def get_driver(cls, inst, name, attach_point, namespace):
"""Create a managed driver which will manage a driver whose
implementation is named by "name"
"""
cmps = name.split('.')
assert len(cmps) > 1
(mod_name, class_name) = ('.'.join(cmps[:-1]), cmps[-1])
if mod_name in sys.modules:
mod = sys.modules[mod_name]
else:
mod = __import__(mod_name, globals(), locals(), [class_name])
klass = getattr(mod, class_name)
driver = klass(inst, attach_point, namespace)
inst.add_driver(attach_point, driver)
return driver
flush = lambda self: self.__inst.reports.flush()
_flush = lambda self: self.__inst.reports._flush()
def __init__(self, smap_instance, attach_point, namespace):
self.__inst = smap_instance
self.__attach_point = attach_point
self.namespace = namespace
self.statslog = core.LoggingTimeseries()
def __join_id(self, id):
if util.is_string(id) and id.startswith('/'):
return util.norm_path(self.__attach_point + '/' + id)
else:
return id
# override
def setup(self, opts={}):
pass
# override
def start(self):
pass
# override
def stop(self):
pass
# ISmapInstance implementation
# drivers get a pass-through version of the SmapInstance which
# knows where they are attached in the tree. Drivers may, for the
# most part, assume that they have the instance to themselves.
# However, the main exception to this is that their names are
# still in a global namespace. Therefore they should either
# generate their own uuids for their streams based on the uuid in
# their root collection (inst.get_collection('/')['uuid'])
def lookup(self, id, **kwargs):
return self.__inst.lookup(self.__join_id(id), **kwargs)
def get_timeseries(self, id):
return self.__inst.get_timeseries(self.__join_id(id))
def get_collection(self, id):
return self.__inst.get_collection(self.__join_id(id))
def add_timeseries(self, path, *args, **kwargs):
kwargs['namespace'] = self.namespace
if ITimeseries.providedBy(args[0]) or IActuator.providedBy(args[0]):
key = args[0]
elif len(args) <= 1:
key = path
elif len(args) == 2:
key = args[0]
args = args[1:]
return self.__inst.add_timeseries(self.__join_id(path), key, *args, **kwargs)
def add_actuator(self, path, unit, klass, **kwargs):
return self.__inst.add_actuator(self.__join_id(path), unit, klass, **kwargs)
def add_collection(self, path, *args):
self.__inst.add_collection(self.__join_id(path), *args)
def set_metadata(self, id, *metadata):
return self.__inst.set_metadata(self.__join_id(id), *metadata)
def add(self, id, *args):
self.statslog.mark()
return self.__inst.add(self.__join_id(id), *args)
def _add(self, id, *args):
self.statslog.mark()
return self.__inst._add(self.__join_id(id), *args)
def uuid(self, key):
return self.__inst.uuid(key, namespace=self.namespace)
def pause_reporting(self):
return self.__inst.pause_reporting()
def unpause_reporting(self):
return self.__inst.unpause_reporting()
# let drivers optimize loading a lot of points
def _get_loading(self):
return self.__inst.loading
def _set_loading(self, val):
if val:
print "starting load"
self.__inst.loading = True
else:
print "finishing load"
self.__inst.reports.update_subscriptions()
self.__inst.loading = False
loading = property(_get_loading, _set_loading)
def load(self, startdt, enddt):
"""Default load method tries to call update with one-day chunks"""
self.start_dt = startdt
self.end_dt = enddt
return self._load_time_chunk(self)
def _load_time_chunk(self, *args):
if self.start_dt >= self.end_dt:
return None
# pick a new window
start = self.start_dt
end = self.start_dt + self.load_chunk_size
if end > self.end_dt: end = self.end_dt
print "loading", self.start_dt, '-', self.end_dt
self.start_dt = self.start_dt + self.load_chunk_size
print start, end
d = defer.maybeDeferred(self.update, start, end)
d.addCallback(self.update)
d.addCallback(lambda _: self._flush())
d.addCallback(self._load_time_chunk)
def err(e):
print e
d.addErrback(err)
return d
class FetchDriver(SmapDriver):
"""Driver class implementing flexible getting from multiple URI
schemes. This is a virtual class and should be subclassed by a
driver implementing a method named process(self, data).
Options:
Uri: required. URI of data source. supported schemes are http,
https, file, and python. The python uri should specify a
python function which will load the data and return it as a
string; for instance, python://loaders.pge_loader schemes.
The http and https schemes support including a username and
password in the url
Rate: how often to check the source
"""
def setup(self, opts):
self.uri = opts.get('Uri') # url to load
self.rate = int(opts.get('Rate', 30)) # rate in seconds
self.timeout = int(opts.get('Timeout', 30)) # timeout for IO operations
# load known URI schemes
scheme = urlparse.urlparse(self.uri).scheme
if scheme == 'http' or scheme == 'https':
# load a page over http
self.update = self.update_http
elif scheme == 'file':
# load data from a file
self.update = self.update_file
elif scheme == 'python':
# load data by calling a python function
u = util.import_module(urlparse.urlparse(self.uri).netloc)
self.update = lambda: self.process(u(opts))
else:
raise ValueError("Unknown URI scheme: " + scheme)
def start(self):
util.periodicCallInThread(self.update).start(self.rate)
def open_url(self):
"""Open a URL using urllib2, potentially sending HTTP authentication"""
mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
url_p = urlparse.urlparse(self.uri)
# parse out the username and password (if present) and
# reconstruct a url which urllib2 will accept
if url_p.username and url_p.password:
mgr.add_password(None, url_p.hostname, url_p.username, url_p.password)
handler = urllib2.HTTPBasicAuthHandler(mgr)
opener = urllib2.build_opener(handler)
dest = urlparse.urlunparse((url_p.scheme, url_p.hostname, url_p.path,
url_p.params, url_p.query, url_p.fragment))
try:
# try the open but mask errors
fp = opener.open(dest,
timeout=self.timeout)
data = fp.read()
fp.close()
except:
log.err()
return None
else:
return data
def update_http(self):
d = threads.deferToThread(self.open_url)
d.addCallback(self.process)
d.addErrback(println)
def update_file(self):
with open(urlparse.urlparse(self.uri).path, "r") as fp:
self.process(fp.read())
class BaseDriver(SmapDriver):
def setup(self, opts={}):
self.t = self.add_timeseries('/sensor0', 'mytimeseries', 'SDH')
self.set_metadata('/sensor0', {
'Instrument/ModelName' : 'ExampleInstrument',
'Extra/ModbusAddr' : opts.get('ModbusAddr', '')
})
self.counter = int(opts.get('StartVal', 0))
def start(self):
self.counter = 0
util.periodicSequentialCall(self.read).start(1)
def read(self):
# print "Add", self.counter
self.t.add(self.counter)
self.counter += 1
# print self.counter
if __name__ == '__main__':
# inst = loader.load('default.ini', autoflush=False)
# d = SmapDriverManager.get_driver('driver.BaseDriver', '/newsensor')
# d.setup(inst)
import uuid
inst = core.SmapInstance(uuid.uuid1())
bd = SmapDriver.get_driver(inst, 'driver.BaseDriver', '/newsensor', None)
bd.setup()
server.run(inst)
| bsd-2-clause |
ahu-odoo/odoo | addons/portal/portal.py | 386 | 1361 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2011 OpenERP S.A (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class portal(osv.osv):
""" A portal is simply a group of users with the flag 'is_portal' set to True.
The flag 'is_portal' makes a user group usable as a portal.
"""
_inherit = 'res.groups'
_columns = {
'is_portal': fields.boolean('Portal', help="If checked, this group is usable as a portal."),
}
| agpl-3.0 |
blaquee/crits | crits/raw_data/views.py | 15 | 19549 | import json
from django.contrib.auth.decorators import user_passes_test
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from crits.core.handlers import get_item_names
from crits.core.user_tools import user_can_view_data
from crits.core.user_tools import user_is_admin
from crits.raw_data.forms import UploadRawDataFileForm, UploadRawDataForm
from crits.raw_data.forms import NewRawDataTypeForm
from crits.raw_data.handlers import update_raw_data_tool_details
from crits.raw_data.handlers import update_raw_data_tool_name
from crits.raw_data.handlers import update_raw_data_type
from crits.raw_data.handlers import handle_raw_data_file
from crits.raw_data.handlers import delete_raw_data, get_raw_data_details
from crits.raw_data.handlers import generate_raw_data_jtable
from crits.raw_data.handlers import generate_raw_data_csv, new_inline_comment
from crits.raw_data.handlers import generate_inline_comments
from crits.raw_data.handlers import generate_raw_data_versions
from crits.raw_data.handlers import get_id_from_link_and_version
from crits.raw_data.handlers import add_new_raw_data_type, new_highlight
from crits.raw_data.handlers import update_raw_data_highlight_comment
from crits.raw_data.handlers import delete_highlight
from crits.raw_data.handlers import update_raw_data_highlight_date
from crits.raw_data.raw_data import RawDataType
@user_passes_test(user_can_view_data)
def raw_data_listing(request,option=None):
"""
Generate RawData Listing template.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param option: Whether or not we should generate a CSV (yes if option is "csv")
:type option: str
:returns: :class:`django.http.HttpResponse`
"""
if option == "csv":
return generate_raw_data_csv(request)
return generate_raw_data_jtable(request, option)
@user_passes_test(user_can_view_data)
def set_raw_data_tool_details(request, _id):
"""
Set the RawData tool details. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
details = request.POST['details']
analyst = request.user.username
return HttpResponse(json.dumps(update_raw_data_tool_details(_id,
details,
analyst)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def set_raw_data_tool_name(request, _id):
"""
Set the RawData tool name. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
name = request.POST['name']
analyst = request.user.username
return HttpResponse(json.dumps(update_raw_data_tool_name(_id,
name,
analyst)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def set_raw_data_type(request, _id):
"""
Set the RawData datatype. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
data_type = request.POST['data_type']
analyst = request.user.username
return HttpResponse(json.dumps(update_raw_data_type(_id,
data_type,
analyst)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def set_raw_data_highlight_comment(request, _id):
"""
Set a highlight comment in RawData. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
comment = request.POST['comment']
line = request.POST['line']
analyst = request.user.username
return HttpResponse(json.dumps(update_raw_data_highlight_comment(_id,
comment,
line,
analyst)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def set_raw_data_highlight_date(request, _id):
"""
Set a highlight date in RawData. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
date = request.POST['date']
line = request.POST['line']
analyst = request.user.username
return HttpResponse(json.dumps(update_raw_data_highlight_date(_id,
date,
line,
analyst)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def add_inline_comment(request, _id):
"""
Add an inline comment to RawData. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
comment = request.POST['comment']
analyst = request.user.username
line_num = request.GET.get('line', 1)
return HttpResponse(json.dumps(new_inline_comment(_id,
comment,
line_num,
analyst)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def add_highlight(request, _id):
"""
Set a line as highlighted for RawData. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
analyst = request.user.username
line_num = request.POST.get('line', 1)
line_data = request.POST.get('line_data', None)
return HttpResponse(json.dumps(new_highlight(_id,
line_num,
line_data,
analyst)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def remove_highlight(request, _id):
"""
Remove a line highlight from RawData. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
analyst = request.user.username
line_num = request.POST.get('line', 1)
return HttpResponse(json.dumps(delete_highlight(_id,
line_num,
analyst)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def get_inline_comments(request, _id):
"""
Get inline comments for RawData. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
return HttpResponse(json.dumps(generate_inline_comments(_id)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def get_raw_data_versions(request, _id):
"""
Get a list of versions for RawData. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
return HttpResponse(json.dumps(generate_raw_data_versions(_id)),
mimetype="application/json")
else:
error = "Expected POST"
return render_to_response("error.html",
{"error" : error },
RequestContext(request))
@user_passes_test(user_can_view_data)
def raw_data_details(request, _id):
"""
Generate RawData details page.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
template = 'raw_data_details.html'
analyst = request.user.username
(new_template, args) = get_raw_data_details(_id, analyst)
if new_template:
template = new_template
return render_to_response(template,
args,
RequestContext(request))
@user_passes_test(user_can_view_data)
def details_by_link(request, link):
"""
Generate RawData details page by link.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param link: The LinkId of the RawData.
:type link: str
:returns: :class:`django.http.HttpResponse`
"""
version = request.GET.get('version', 1)
return raw_data_details(request,
get_id_from_link_and_version(link, version))
@user_passes_test(user_can_view_data)
def upload_raw_data(request, link_id=None):
"""
Upload new RawData to CRITs.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param link_id: The LinkId of RawData if this is a new version upload.
:type link_id: str
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST':
if 'filedata' in request.FILES:
form = UploadRawDataFileForm(request.user,
request.POST,
request.FILES)
filedata = request.FILES['filedata']
data = filedata.read() # XXX: Should be using chunks here.
has_file = True
else:
form = UploadRawDataForm(request.user,request.POST)
data = request.POST.get('data', None)
has_file = False
if form.is_valid():
source = form.cleaned_data.get('source')
user = request.user.username
description = form.cleaned_data.get('description', '')
title = form.cleaned_data.get('title', None)
tool_name = form.cleaned_data.get('tool_name', '')
tool_version = form.cleaned_data.get('tool_version', '')
tool_details = form.cleaned_data.get('tool_details', '')
data_type = form.cleaned_data.get('data_type', None)
copy_rels = request.POST.get('copy_relationships', False)
link_id = link_id
bucket_list = form.cleaned_data.get('bucket_list')
ticket = form.cleaned_data.get('ticket')
method = form.cleaned_data.get('method', '') or 'Upload'
reference = form.cleaned_data.get('reference', '')
status = handle_raw_data_file(data, source, user,
description, title, data_type,
tool_name, tool_version, tool_details,
link_id,
method=method,
reference=reference,
copy_rels=copy_rels,
bucket_list=bucket_list,
ticket=ticket)
if status['success']:
jdump = json.dumps({
'message': 'raw_data uploaded successfully! <a href="%s">View raw_data</a>'
% reverse('crits.raw_data.views.raw_data_details',
args=[status['_id']]), 'success': True})
if not has_file:
return HttpResponse(jdump, mimetype="application/json")
return render_to_response('file_upload_response.html',
{'response': jdump},
RequestContext(request))
else:
jdump = json.dumps({'success': False,
'message': status['message']})
if not has_file:
return HttpResponse(jdump, mimetype="application/json")
return render_to_response('file_upload_response.html',
{'response': jdump},
RequestContext(request))
else:
jdump = json.dumps({'success': False,
'form': form.as_table()})
if not has_file:
return HttpResponse(jdump, mimetype="application/json")
return render_to_response('file_upload_response.html',
{'response': jdump},
RequestContext(request))
else:
return render_to_response('error.html',
{'error': "Expected POST."},
RequestContext(request))
@user_passes_test(user_is_admin)
def remove_raw_data(request, _id):
"""
Remove RawData from CRITs.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the RawData to remove.
:type _id: str
:returns: :class:`django.http.HttpResponse`
"""
result = delete_raw_data(_id, '%s' % request.user.username)
if result:
return HttpResponseRedirect(reverse('crits.raw_data.views.raw_data_listing'))
else:
return render_to_response('error.html',
{'error': "Could not delete raw_data"})
@user_passes_test(user_can_view_data)
def new_raw_data_type(request):
"""
Add a new RawData datatype to CRITs. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST' and request.is_ajax():
form = NewRawDataTypeForm(request.POST)
analyst = request.user.username
if form.is_valid():
result = add_new_raw_data_type(form.cleaned_data['data_type'],
analyst)
if result:
message = {'message': '<div>Raw Data Type added successfully!</div>',
'success': True}
else:
message = {'message': '<div>Raw Data Type addition failed!</div>',
'success': False}
else:
message = {'form': form.as_table()}
return HttpResponse(json.dumps(message),
mimetype="application/json")
return render_to_response('error.html',
{'error':'Expected AJAX POST'})
@user_passes_test(user_can_view_data)
def get_raw_data_type_dropdown(request):
"""
Generate RawData datetypes dropdown information. Should be an AJAX POST.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
if request.method == 'POST' and request.is_ajax():
dt_types = get_item_names(RawDataType)
dt_final = []
for dt in dt_types:
dt_final.append(dt.name)
result = {'data': dt_final}
return HttpResponse(json.dumps(result),
mimetype="application/json")
else:
error = "Expected AJAX POST"
return render_to_response("error.html",
{'error': error},
RequestContext(request))
| mit |
patrickm/chromium.src | chrome/app/nibs/PRESUBMIT.py | 126 | 3062 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script to verify that XIB changes are done with the right version.
See http://dev.chromium.org/developers/design-documents/mac-xib-files for more
information.
"""
import re
# Minimum is Mac OS X 10.8.1 (12B19).
HUMAN_DARWIN_VERSION = '10.8.x, x >= 1'
ALLOWED_DARWIN_VERSION = 12 # Darwin 12 = 10.8.
MINIMUM_DARWIN_RELEASE = 'B' # Release B = 10.8.1.
MINIMUM_IB_VERSION = 2549 # Xcode 4.4.1.
MAXIMUM_IB_VERSION = 3084 # Xcode 4.6.x.
HUMAN_IB_VERSION = '>= 4.4.1, <= 4.6.x'
SYSTEM_VERSION_RE = r'<string key="IBDocument\.SystemVersion">' + \
'([0-9]{,2})([A-Z])([0-9]+)</string>'
IB_VERSION_RE = \
r'<string key="IBDocument\.InterfaceBuilderVersion">([0-9]+)</string>'
def _CheckXIBSystemAndXcodeVersions(input_api, output_api, error_type):
affected_xibs = [x for x in input_api.AffectedFiles()
if x.LocalPath().endswith('.xib')]
incorrect_system_versions = []
incorrect_ib_versions = []
for xib in affected_xibs:
if len(xib.NewContents()) == 0:
continue
system_version = None
ib_version = None
new_contents = xib.NewContents()
if not new_contents:
# Deleting files is always fine.
continue
for line in new_contents:
m = re.search(SYSTEM_VERSION_RE, line)
if m:
system_version = (m.group(1), m.group(2), m.group(3))
m = re.search(IB_VERSION_RE, line)
if m:
ib_version = m.group(1)
if system_version is not None and ib_version is not None:
break
if system_version is None:
incorrect_system_versions.append(xib.LocalPath())
continue
if int(system_version[0]) != ALLOWED_DARWIN_VERSION:
incorrect_system_versions.append(xib.LocalPath())
continue
if system_version[1] < MINIMUM_DARWIN_RELEASE:
incorrect_system_versions.append(xib.LocalPath())
continue
if ib_version is None or int(ib_version) < MINIMUM_IB_VERSION or \
int(ib_version) > MAXIMUM_IB_VERSION:
incorrect_ib_versions.append(xib.LocalPath())
continue
problems = []
if incorrect_system_versions:
problems.append(error_type(
'XIB files need to be saved on Mac OS X ' + HUMAN_DARWIN_VERSION,
items=incorrect_system_versions))
if incorrect_ib_versions:
problems.append(error_type(
'XIB files need to be saved using Xcode version ' + HUMAN_IB_VERSION,
items=incorrect_ib_versions))
return problems
def CheckChangeOnUpload(input_api, output_api):
# Allow uploads to happen even if the presubmit fails, so that contributors
# can ask their reviewer or another person to re-save the XIBs for them.
return _CheckXIBSystemAndXcodeVersions(input_api, output_api,
error_type=output_api.PresubmitPromptWarning)
def CheckChangeOnCommit(input_api, output_api):
return _CheckXIBSystemAndXcodeVersions(input_api, output_api,
error_type=output_api.PresubmitError)
| bsd-3-clause |
richard-willowit/sale-workflow | __unported__/sale_multi_picking/sale.py | 37 | 2758 | # -*- coding: utf-8 -*-
#
#
# Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>)
# Copyright (C) 2012 Domsense srl (<http://www.domsense.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU 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, orm
class sale_order_line_group(orm.Model):
_name = 'sale.order.line.group'
_columns = {
'name': fields.char('Group', size=64, required=True),
'company_id': fields.many2one(
'res.company', 'Company', required=True, select=1),
}
_defaults = {
'company_id': lambda self, cr, uid, c: self.pool.get(
'res.company')._company_default_get(
cr, uid, 'sale.order.line.group', context=c),
}
class sale_order_line(orm.Model):
_inherit = 'sale.order.line'
_columns = {
'picking_group_id': fields.many2one(
'sale.order.line.group', 'Group',
help="This is used by 'multi-picking' to group order lines in one "
"picking"),
}
class sale_order(orm.Model):
_inherit = 'sale.order'
def action_ship_create(self, cr, uid, ids, context=None):
picking_pool = self.pool.get('stock.picking')
for order in self.browse(cr, uid, ids, context=context):
lines_by_group = {}
for line in order.order_line:
group_id = (
line.picking_group_id.id if line.picking_group_id else 0)
lines_by_group.setdefault(group_id, []).append(line)
for group in lines_by_group:
if not group:
picking_id = None
else:
picking_vals = super(
sale_order, self)._prepare_order_picking(
cr, uid, order, context=context)
picking_id = picking_pool.create(
cr, uid, picking_vals, context=context)
super(sale_order, self)._create_pickings_and_procurements(
cr, uid, order, lines_by_group[group], picking_id,
context=context)
return True
| agpl-3.0 |
tanzquotient/tq_website | payment/payment_processor.py | 2 | 5779 | import logging
import re
from courses.models import Subscribe, PaymentMethod, SubscribeState
from payment.models import Payment, SubscriptionPayment
from payment.models.choices import State, CreditDebit, Type
log = logging.getLogger('payment')
USI_PREFIX = "USI-"
# also accept USL since I is often typed as L
RE_USI_STRICT = re.compile(r"[USILusil]{3,3}[\- _](?P<usi>[a-zA-Z0-9]{6,6})")
class PaymentProcessor:
def process_payments(self, queryset=Payment.objects):
self.detect_irrelevant_payments()
self.match_payments(queryset)
self.finalize_payments(queryset)
def detect_irrelevant_payments(self, queryset=Payment.objects):
new_payments = queryset.filter(state=State.NEW, credit_debit=CreditDebit.DEBIT).all()
for payment in new_payments:
payment.type = Type.IRRELEVANT
payment.save()
def match_payments(self, queryset=Payment.objects):
new_payments = queryset.filter(state=State.NEW, credit_debit=CreditDebit.CREDIT).all()
for payment in new_payments:
if payment.remittance_user_string:
matches = RE_USI_STRICT.findall(payment.remittance_user_string)
# if no matches, try removing all spaces first
if not matches:
matches = RE_USI_STRICT.findall(payment.remittance_user_string.replace(" ", ""))
if matches:
payment.type = Type.SUBSCRIPTION_PAYMENT
payment.save()
for usi in matches:
subscription_query = Subscribe.objects.filter(usi=usi, state=SubscribeState.CONFIRMED)
if subscription_query.count() == 1:
matched_subscription = subscription_query.first()
# check if payment amount sufficient
to_pay = matched_subscription.get_price_to_pay()
if to_pay is None:
log.warning(
"Received payment {} which is related to a course with undefined prices.".format(
payment))
payment.state = State.MANUAL
payment.save()
break
sp = SubscriptionPayment(payment=payment, subscription=matched_subscription,
amount=to_pay)
sp.save()
log.info('Matched payment {0} to subscription {1}'.format(payment, subscription_query))
elif subscription_query.count() > 1:
# should never happen since USI is unique
log.error(
"Implementation Error: Payment {0} is not related to a unique Subscription".format(
payment))
break
# elif course_query.count() == 1:
# course = course_query.first()
# log.info("Matched payment to course payment {}".format(course))
# CoursePayment(course=course, payment=payment, amount=payment.amount).save()
# payment.type = Type.COURSE_PAYMENT_TRANSFER
# payment.state = State.PROCESSED
# payment.save()
# break
else:
log.warning("USI {0} was not found for payment {1}.".format(usi, payment))
self._check_balance(payment)
else:
log.info("No USI was recognized in payment {0}.".format(payment))
# try to detect if it is a teacher transfer
# TODO improve this with a code for teachers when they transfer course payments
payment.state = State.MANUAL
payment.save()
else:
log.warning("No user remittance was found for payment {0}.".format(payment))
payment.state = State.MANUAL
payment.save()
def finalize_payments(self, queryset=Payment.objects):
matched_payments = queryset.filter(state=State.MATCHED).all()
for payment in matched_payments:
for s in payment.subscriptions.all():
s.mark_as_paid(PaymentMethod.ONLINE)
payment.state = State.PROCESSED
payment.save()
def check_balance(self, payments):
for payment in payments.filter(state__in=[State.NEW, State.MANUAL]).all():
self._check_balance(payment)
def _check_balance(self, payment):
"""
Updates the payment according to currently linked subscriptions.
Returns true if the payment's amount is equals to the sum of the matched subscriptions.
"""
if payment.state in [State.NEW,
State.MANUAL] and payment.type == Type.SUBSCRIPTION_PAYMENT:
remaining_amount = payment.amount - payment.subscription_payments_amount_sum()
if remaining_amount == 0:
payment.state = State.MATCHED
payment.amount_to_reimburse = 0
payment.save()
return True
elif remaining_amount > 0:
payment.amount_to_reimburse = remaining_amount
payment.state = State.MANUAL
payment.save()
return False
else:
payment.state = State.MANUAL
payment.save()
return False
| gpl-2.0 |
kittiu/odoo | addons/crm/wizard/crm_lead_to_opportunity.py | 146 | 13701 | # -*- 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 re
class crm_lead2opportunity_partner(osv.osv_memory):
_name = 'crm.lead2opportunity.partner'
_description = 'Lead To Opportunity Partner'
_inherit = 'crm.partner.binding'
_columns = {
'name': fields.selection([
('convert', 'Convert to opportunity'),
('merge', 'Merge with existing opportunities')
], 'Conversion Action', required=True),
'opportunity_ids': fields.many2many('crm.lead', string='Opportunities'),
'user_id': fields.many2one('res.users', 'Salesperson', select=True),
'section_id': fields.many2one('crm.case.section', 'Sales Team', select=True),
}
def onchange_action(self, cr, uid, ids, action, context=None):
return {'value': {'partner_id': False if action != 'exist' else self._find_matching_partner(cr, uid, context=context)}}
def _get_duplicated_leads(self, cr, uid, partner_id, email, include_lost=False, context=None):
"""
Search for opportunities that have the same partner and that arent done or cancelled
"""
return self.pool.get('crm.lead')._get_duplicated_leads_by_emails(cr, uid, partner_id, email, include_lost=include_lost, context=context)
def default_get(self, cr, uid, fields, context=None):
"""
Default get for name, opportunity_ids.
If there is an exisitng partner link to the lead, find all existing
opportunities links with this partner to merge all information together
"""
lead_obj = self.pool.get('crm.lead')
res = super(crm_lead2opportunity_partner, self).default_get(cr, uid, fields, context=context)
if context.get('active_id'):
tomerge = [int(context['active_id'])]
partner_id = res.get('partner_id')
lead = lead_obj.browse(cr, uid, int(context['active_id']), context=context)
email = lead.partner_id and lead.partner_id.email or lead.email_from
tomerge.extend(self._get_duplicated_leads(cr, uid, partner_id, email, include_lost=True, context=context))
tomerge = list(set(tomerge))
if 'action' in fields and not res.get('action'):
res.update({'action' : partner_id and 'exist' or 'create'})
if 'partner_id' in fields:
res.update({'partner_id' : partner_id})
if 'name' in fields:
res.update({'name' : len(tomerge) >= 2 and 'merge' or 'convert'})
if 'opportunity_ids' in fields and len(tomerge) >= 2:
res.update({'opportunity_ids': tomerge})
if lead.user_id:
res.update({'user_id': lead.user_id.id})
if lead.section_id:
res.update({'section_id': lead.section_id.id})
return res
def on_change_user(self, cr, uid, ids, user_id, section_id, context=None):
""" When changing the user, also set a section_id or restrict section id
to the ones user_id is member of. """
if user_id:
if section_id:
user_in_section = self.pool.get('crm.case.section').search(cr, uid, [('id', '=', section_id), '|', ('user_id', '=', user_id), ('member_ids', '=', user_id)], context=context, count=True)
else:
user_in_section = False
if not user_in_section:
result = self.pool['crm.lead'].on_change_user(cr, uid, ids, user_id, context=context)
section_id = result.get('value') and result['value'].get('section_id') and result['value']['section_id'] or False
return {'value': {'section_id': section_id}}
def view_init(self, cr, uid, fields, context=None):
"""
Check some preconditions before the wizard executes.
"""
if context is None:
context = {}
lead_obj = self.pool.get('crm.lead')
for lead in lead_obj.browse(cr, uid, context.get('active_ids', []), context=context):
if lead.probability == 100:
raise osv.except_osv(_("Warning!"), _("Closed/Dead leads cannot be converted into opportunities."))
return False
def _convert_opportunity(self, cr, uid, ids, vals, context=None):
if context is None:
context = {}
lead = self.pool.get('crm.lead')
res = False
lead_ids = vals.get('lead_ids', [])
team_id = vals.get('section_id', False)
partner_id = vals.get('partner_id')
data = self.browse(cr, uid, ids, context=context)[0]
leads = lead.browse(cr, uid, lead_ids, context=context)
for lead_id in leads:
partner_id = self._create_partner(cr, uid, lead_id.id, data.action, partner_id or lead_id.partner_id.id, context=context)
res = lead.convert_opportunity(cr, uid, [lead_id.id], partner_id, [], False, context=context)
user_ids = vals.get('user_ids', False)
if context.get('no_force_assignation'):
leads_to_allocate = [lead_id.id for lead_id in leads if not lead_id.user_id]
else:
leads_to_allocate = lead_ids
if user_ids:
lead.allocate_salesman(cr, uid, leads_to_allocate, user_ids, team_id=team_id, context=context)
return res
def action_apply(self, cr, uid, ids, context=None):
"""
Convert lead to opportunity or merge lead and opportunity and open
the freshly created opportunity view.
"""
if context is None:
context = {}
lead_obj = self.pool['crm.lead']
w = self.browse(cr, uid, ids, context=context)[0]
opp_ids = [o.id for o in w.opportunity_ids]
vals = {
'section_id': w.section_id.id,
}
if w.partner_id:
vals['partner_id'] = w.partner_id.id
if w.name == 'merge':
lead_id = lead_obj.merge_opportunity(cr, uid, opp_ids, context=context)
lead_ids = [lead_id]
lead = lead_obj.read(cr, uid, lead_id, ['type', 'user_id'], context=context)
if lead['type'] == "lead":
context = dict(context, active_ids=lead_ids)
vals.update({'lead_ids': lead_ids, 'user_ids': [w.user_id.id]})
self._convert_opportunity(cr, uid, ids, vals, context=context)
elif not context.get('no_force_assignation') or not lead['user_id']:
vals.update({'user_id': w.user_id.id})
lead_obj.write(cr, uid, lead_id, vals, context=context)
else:
lead_ids = context.get('active_ids', [])
vals.update({'lead_ids': lead_ids, 'user_ids': [w.user_id.id]})
self._convert_opportunity(cr, uid, ids, vals, context=context)
return self.pool.get('crm.lead').redirect_opportunity_view(cr, uid, lead_ids[0], context=context)
def _create_partner(self, cr, uid, lead_id, action, partner_id, context=None):
"""
Create partner based on action.
:return dict: dictionary organized as followed: {lead_id: partner_assigned_id}
"""
#TODO this method in only called by crm_lead2opportunity_partner
#wizard and would probably diserve to be refactored or at least
#moved to a better place
if context is None:
context = {}
lead = self.pool.get('crm.lead')
if action == 'each_exist_or_create':
ctx = dict(context)
ctx['active_id'] = lead_id
partner_id = self._find_matching_partner(cr, uid, context=ctx)
action = 'create'
res = lead.handle_partner_assignation(cr, uid, [lead_id], action, partner_id, context=context)
return res.get(lead_id)
class crm_lead2opportunity_mass_convert(osv.osv_memory):
_name = 'crm.lead2opportunity.partner.mass'
_description = 'Mass Lead To Opportunity Partner'
_inherit = 'crm.lead2opportunity.partner'
_columns = {
'user_ids': fields.many2many('res.users', string='Salesmen'),
'section_id': fields.many2one('crm.case.section', 'Sales Team', select=True),
'deduplicate': fields.boolean('Apply deduplication', help='Merge with existing leads/opportunities of each partner'),
'action': fields.selection([
('each_exist_or_create', 'Use existing partner or create'),
('nothing', 'Do not link to a customer')
], 'Related Customer', required=True),
'force_assignation': fields.boolean('Force assignation', help='If unchecked, this will leave the salesman of duplicated opportunities'),
}
_defaults = {
'deduplicate': True,
}
def default_get(self, cr, uid, fields, context=None):
res = super(crm_lead2opportunity_mass_convert, self).default_get(cr, uid, fields, context)
if 'partner_id' in fields:
# avoid forcing the partner of the first lead as default
res['partner_id'] = False
if 'action' in fields:
res['action'] = 'each_exist_or_create'
if 'name' in fields:
res['name'] = 'convert'
if 'opportunity_ids' in fields:
res['opportunity_ids'] = False
return res
def on_change_action(self, cr, uid, ids, action, context=None):
vals = {}
if action != 'exist':
vals = {'value': {'partner_id': False}}
return vals
def on_change_deduplicate(self, cr, uid, ids, deduplicate, context=None):
if context is None:
context = {}
active_leads = self.pool['crm.lead'].browse(cr, uid, context['active_ids'], context=context)
partner_ids = [(lead.partner_id.id, lead.partner_id and lead.partner_id.email or lead.email_from) for lead in active_leads]
partners_duplicated_leads = {}
for partner_id, email in partner_ids:
duplicated_leads = self._get_duplicated_leads(cr, uid, partner_id, email)
if len(duplicated_leads) > 1:
partners_duplicated_leads.setdefault((partner_id, email), []).extend(duplicated_leads)
leads_with_duplicates = []
for lead in active_leads:
lead_tuple = (lead.partner_id.id, lead.partner_id.email if lead.partner_id else lead.email_from)
if len(partners_duplicated_leads.get(lead_tuple, [])) > 1:
leads_with_duplicates.append(lead.id)
return {'value': {'opportunity_ids': leads_with_duplicates}}
def _convert_opportunity(self, cr, uid, ids, vals, context=None):
"""
When "massively" (more than one at a time) converting leads to
opportunities, check the salesteam_id and salesmen_ids and update
the values before calling super.
"""
if context is None:
context = {}
data = self.browse(cr, uid, ids, context=context)[0]
salesteam_id = data.section_id and data.section_id.id or False
salesmen_ids = []
if data.user_ids:
salesmen_ids = [x.id for x in data.user_ids]
vals.update({'user_ids': salesmen_ids, 'section_id': salesteam_id})
return super(crm_lead2opportunity_mass_convert, self)._convert_opportunity(cr, uid, ids, vals, context=context)
def mass_convert(self, cr, uid, ids, context=None):
data = self.browse(cr, uid, ids, context=context)[0]
ctx = dict(context)
if data.name == 'convert' and data.deduplicate:
merged_lead_ids = []
remaining_lead_ids = []
lead_selected = context.get('active_ids', [])
for lead_id in lead_selected:
if lead_id not in merged_lead_ids:
lead = self.pool['crm.lead'].browse(cr, uid, lead_id, context=context)
duplicated_lead_ids = self._get_duplicated_leads(cr, uid, lead.partner_id.id, lead.partner_id and lead.partner_id.email or lead.email_from)
if len(duplicated_lead_ids) > 1:
lead_id = self.pool.get('crm.lead').merge_opportunity(cr, uid, duplicated_lead_ids, False, False, context=context)
merged_lead_ids.extend(duplicated_lead_ids)
remaining_lead_ids.append(lead_id)
active_ids = set(context.get('active_ids', []))
active_ids = active_ids.difference(merged_lead_ids)
active_ids = active_ids.union(remaining_lead_ids)
ctx['active_ids'] = list(active_ids)
ctx['no_force_assignation'] = context.get('no_force_assignation', not data.force_assignation)
return self.action_apply(cr, uid, ids, context=ctx)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
damdam-s/connector-magento | magentoerpconnect/tests/data_guest_order.py | 11 | 29105 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2015 Camptocamp SA
#
# 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/>.
#
##############################################################################
# flake8: noqa : ignore style in this file because it is a data file
# only
"""
Magento responses for calls done by the connector.
This set of responses has been recorded for the synchronizations
with a Magento 1.7 version with demo data.
It has been recorded using ``magentoerpconnect.unit.backend_adapter.record``
and ``magentoerpconnect.unit.backend_adapter.output_recorder``
"""
import time
FMT = "%Y-%m-%d %H:%M:%S"
guest_order_responses = \
{('sales_order.info', (900000700,)): {'adjustment_negative': None,
'adjustment_positive': None,
'applied_rule_ids': None,
'base_adjustment_negative': None,
'base_adjustment_positive': None,
'base_currency_code': 'EUR',
'base_custbalance_amount': None,
'base_discount_amount': '0.0000',
'base_discount_canceled': None,
'base_discount_invoiced': None,
'base_discount_refunded': None,
'base_grand_total': '166.9400',
'base_hidden_tax_amount': '0.0000',
'base_hidden_tax_invoiced': None,
'base_hidden_tax_refunded': None,
'base_shipping_amount': '5.0000',
'base_shipping_canceled': None,
'base_shipping_discount_amount': '0.0000',
'base_shipping_hidden_tax_amnt': '0.0000',
'base_shipping_hidden_tax_amount': '0.0000',
'base_shipping_incl_tax': '5.0000',
'base_shipping_invoiced': None,
'base_shipping_refunded': None,
'base_shipping_tax_amount': '0.0000',
'base_shipping_tax_refunded': None,
'base_subtotal': '161.9400',
'base_subtotal_canceled': None,
'base_subtotal_incl_tax': '161.9400',
'base_subtotal_invoiced': None,
'base_subtotal_refunded': None,
'base_tax_amount': '0.0000',
'base_tax_canceled': None,
'base_tax_invoiced': None,
'base_tax_refunded': None,
'base_to_global_rate': '1.0000',
'base_to_order_rate': '1.0000',
'base_total_canceled': None,
'base_total_due': None,
'base_total_invoiced': None,
'base_total_invoiced_cost': None,
'base_total_offline_refunded': None,
'base_total_online_refunded': None,
'base_total_paid': None,
'base_total_qty_ordered': None,
'base_total_refunded': None,
'billing_address': {'address_id': '15',
'address_type': 'billing',
'city': 'Oberehrendingen',
'company': None,
'country_id': 'CH',
'customer_address_id': None,
'customer_id': None,
'email': 'chtrokatoral@example.com',
'fax': None,
'firstname': "Ch'Troka",
'gift_message_id': None,
'lastname': 'Toral',
'middlename': None,
'parent_id': '8',
'postcode': '5420',
'prefix': None,
'quote_address_id': None,
'region': 'Aargau',
'region_id': '104',
'street': 'Clius 25',
'suffix': None,
'tax_id': None,
'telephone': '056 524 10 76',
'vat_id': None,
'vat_is_valid': None,
'vat_request_date': None,
'vat_request_id': None,
'vat_request_success': None},
'billing_address_id': '15',
'can_ship_partially': None,
'can_ship_partially_item': None,
'coupon_code': None,
'coupon_rule_name': None,
'created_at': time.strftime(FMT),
'currency_base_id': None,
'currency_code': None,
'currency_rate': None,
'custbalance_amount': None,
'customer_dob': None,
'customer_email': 'ChTrokaToral@rhyta.com',
'customer_firstname': "Ch'Troka",
'customer_gender': None,
'customer_group_id': '0',
'customer_id': 'guestorder:900000700',
'customer_is_guest': True,
'customer_lastname': 'Toral',
'customer_middlename': None,
'customer_note': None,
'customer_note_notify': '1',
'customer_prefix': None,
'customer_suffix': None,
'customer_taxvat': None,
'discount_amount': '0.0000',
'discount_canceled': None,
'discount_description': None,
'discount_invoiced': None,
'discount_refunded': None,
'edit_increment': None,
'email_sent': '1',
'ext_customer_id': None,
'ext_order_id': None,
'forced_do_shipment_with_invoice': None,
'forced_shipment_with_invoice': None,
'gift_message_id': None,
'global_currency_code': 'EUR',
'grand_total': '166.9400',
'hidden_tax_amount': '0.0000',
'hidden_tax_invoiced': None,
'hidden_tax_refunded': None,
'hold_before_state': None,
'hold_before_status': None,
'imported': '0',
'increment_id': '900000700',
'is_hold': None,
'is_multi_payment': None,
'is_virtual': '0',
'items': [{'additional_data': None,
'amount_refunded': '0.0000',
'applied_rule_ids': None,
'base_amount_refunded': '0.0000',
'base_cost': '29.9900',
'base_discount_amount': '0.0000',
'base_discount_invoiced': '0.0000',
'base_discount_refunded': None,
'base_hidden_tax_amount': None,
'base_hidden_tax_invoiced': None,
'base_hidden_tax_refunded': None,
'base_original_price': '161.9400',
'base_price': '161.9400',
'base_price_incl_tax': '161.9400',
'base_row_invoiced': '0.0000',
'base_row_total': '161.9400',
'base_row_total_incl_tax': '161.9400',
'base_tax_amount': '0.0000',
'base_tax_before_discount': None,
'base_tax_invoiced': '0.0000',
'base_tax_refunded': None,
'base_weee_tax_applied_amount': '0.0000',
'base_weee_tax_applied_row_amnt': '0.0000',
'base_weee_tax_applied_row_amount': '0.0000',
'base_weee_tax_disposition': '0.0000',
'base_weee_tax_row_disposition': '0.0000',
'created_at': time.strftime(FMT),
'description': None,
'discount_amount': '0.0000',
'discount_invoiced': '0.0000',
'discount_percent': '0.0000',
'discount_refunded': None,
'ext_order_item_id': None,
'free_shipping': '0',
'gift_message_available': None,
'gift_message_id': None,
'hidden_tax_amount': None,
'hidden_tax_canceled': None,
'hidden_tax_invoiced': None,
'hidden_tax_refunded': None,
'is_nominal': '0',
'is_qty_decimal': '0',
'is_virtual': '0',
'item_id': '11',
'locked_do_invoice': None,
'locked_do_ship': None,
'name': ' Olympus Stylus 750 7.1MP Digital Camera',
'no_discount': '0',
'order_id': '8',
'original_price': '161.9400',
'parent_item_id': None,
'price': '161.9400',
'price_incl_tax': '161.9400',
'product_id': '46',
'product_options': 'a:1:{s:15:"info_buyRequest";a:4:{s:4:"uenc";s:116:"aHR0cDovL2xvY2FsaG9zdDo5MTAwL2luZGV4LnBocC9vbHltcHVzLXN0eWx1cy03NTAtNy0xbXAtZGlnaXRhbC1jYW1lcmEuaHRtbD9fX19TSUQ9VQ,,";s:7:"product";s:2:"46";s:15:"related_product";s:0:"";s:3:"qty";s:1:"1";}}',
'product_type': 'simple',
'qty_backordered': None,
'qty_canceled': '0.0000',
'qty_invoiced': '0.0000',
'qty_ordered': '1.0000',
'qty_refunded': '0.0000',
'qty_shipped': '0.0000',
'quote_item_id': '11',
'row_invoiced': '0.0000',
'row_total': '161.9400',
'row_total_incl_tax': '161.9400',
'row_weight': '2.0000',
'sku': '750',
'store_id': '1',
'tax_amount': '0.0000',
'tax_before_discount': None,
'tax_canceled': None,
'tax_invoiced': '0.0000',
'tax_percent': '0.0000',
'tax_refunded': None,
'updated_at': '2015-03-19 12:57:14',
'weee_tax_applied': 'a:0:{}',
'weee_tax_applied_amount': '0.0000',
'weee_tax_applied_row_amount': '0.0000',
'weee_tax_disposition': '0.0000',
'weee_tax_row_disposition': '0.0000',
'weight': '2.0000'}],
'order_currency_code': 'EUR',
'order_id': '8',
'original_increment_id': None,
'payment': {'account_status': None,
'additional_data': None,
'additional_information': [],
'address_status': None,
'amount': None,
'amount_authorized': None,
'amount_canceled': None,
'amount_ordered': '166.9400',
'amount_paid': None,
'amount_refunded': None,
'anet_trans_method': None,
'base_amount_authorized': None,
'base_amount_canceled': None,
'base_amount_ordered': '166.9400',
'base_amount_paid': None,
'base_amount_paid_online': None,
'base_amount_refunded': None,
'base_amount_refunded_online': None,
'base_shipping_amount': '5.0000',
'base_shipping_captured': None,
'base_shipping_refunded': None,
'cc_approval': None,
'cc_avs_status': None,
'cc_cid_status': None,
'cc_debug_request_body': None,
'cc_debug_response_body': None,
'cc_debug_response_serialized': None,
'cc_exp_month': '0',
'cc_exp_year': '0',
'cc_last4': None,
'cc_number_enc': None,
'cc_owner': None,
'cc_raw_request': None,
'cc_raw_response': None,
'cc_secure_verify': None,
'cc_ss_issue': None,
'cc_ss_start_month': '0',
'cc_ss_start_year': '0',
'cc_status': None,
'cc_status_description': None,
'cc_trans_id': None,
'cc_type': None,
'customer_payment_id': None,
'cybersource_token': None,
'echeck_account_name': None,
'echeck_account_type': None,
'echeck_bank_name': None,
'echeck_routing_number': None,
'echeck_type': None,
'flo2cash_account_id': None,
'ideal_issuer_id': None,
'ideal_issuer_title': None,
'ideal_transaction_checked': None,
'last_trans_id': None,
'method': 'checkmo',
'parent_id': '8',
'paybox_question_number': None,
'paybox_request_number': None,
'payment_id': '8',
'po_number': None,
'protection_eligibility': None,
'quote_payment_id': None,
'shipping_amount': '5.0000',
'shipping_captured': None,
'shipping_refunded': None},
'payment_auth_expiration': None,
'payment_authorization_amount': None,
'payment_authorization_expiration': None,
'paypal_ipn_customer_notified': None,
'protect_code': 'db6fd3',
'quote_address_id': None,
'quote_id': '9',
'real_order_id': None,
'relation_child_id': None,
'relation_child_real_id': None,
'relation_parent_id': None,
'relation_parent_real_id': None,
'remote_ip': '10.0.2.2',
'shipping_address': {'address_id': '16',
'address_type': 'shipping',
'city': 'Oberehrendingen',
'company': None,
'country_id': 'CH',
'customer_address_id': None,
'customer_id': None,
'email': 'ChTrokaToral@rhyta.com',
'fax': None,
'firstname': "Ch'Troka",
'gift_message_id': None,
'lastname': 'Toral',
'middlename': None,
'parent_id': '8',
'postcode': '5420',
'prefix': None,
'quote_address_id': None,
'region': 'Aargau',
'region_id': '104',
'street': 'Clius 25',
'suffix': None,
'tax_id': None,
'telephone': '056 524 10 76',
'vat_id': None,
'vat_is_valid': None,
'vat_request_date': None,
'vat_request_id': None,
'vat_request_success': None},
'shipping_address_id': '16',
'shipping_amount': '5.0000',
'shipping_canceled': None,
'shipping_description': 'Flat Rate - Fixed',
'shipping_discount_amount': '0.0000',
'shipping_hidden_tax_amount': '0.0000',
'shipping_incl_tax': '5.0000',
'shipping_invoiced': None,
'shipping_method': 'flatrate_flatrate',
'shipping_refunded': None,
'shipping_tax_amount': '0.0000',
'shipping_tax_refunded': None,
'state': 'new',
'status': 'pending',
'status_history': [{'comment': None,
'created_at': time.strftime(FMT),
'entity_name': 'order',
'is_customer_notified': '1',
'is_visible_on_front': '0',
'parent_id': '8',
'status': 'pending',
'store_id': '1'}],
'store_currency_code': 'EUR',
'store_id': '1',
'store_name': 'Main Website\nMain Store\nEnglish',
'store_to_base_rate': '1.0000',
'store_to_order_rate': '1.0000',
'subtotal': '161.9400',
'subtotal_canceled': None,
'subtotal_incl_tax': '161.9400',
'subtotal_invoiced': None,
'subtotal_refunded': None,
'tax_amount': '0.0000',
'tax_canceled': None,
'tax_invoiced': None,
'tax_percent': None,
'tax_refunded': None,
'total_canceled': None,
'total_due': None,
'total_invoiced': None,
'total_item_count': '1',
'total_offline_refunded': None,
'total_online_refunded': None,
'total_paid': None,
'total_qty_ordered': '1.0000',
'total_refunded': None,
'tracking_numbers': None,
'updated_at': '2015-03-19 12:57:14',
'website_id': u'1',
'weight': '2.0000',
'x_forwarded_for': None},
}
| agpl-3.0 |
encukou/freeipa | ipaserver/install/dns.py | 1 | 19778 | #
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
"""
DNS installer module
"""
from __future__ import absolute_import
from __future__ import print_function
import enum
import logging
import os
import sys
import six
from subprocess import CalledProcessError
from ipalib import api
from ipalib import errors
from ipalib import util
from ipalib.install import hostname, sysrestore
from ipalib.install.service import enroll_only, prepare_only
from ipaplatform.paths import paths
from ipaplatform.constants import constants
from ipaplatform import services
from ipapython import ipautil
from ipapython import dnsutil
from ipapython.dn import DN
from ipapython.dnsutil import check_zone_overlap
from ipapython.install import typing
from ipapython.install.core import group, knob
from ipapython.admintool import ScriptError
from ipapython.ipautil import user_input
from ipaserver.install.installutils import get_server_ip_address
from ipaserver.install.installutils import read_dns_forwarders
from ipaserver.install.installutils import update_hosts_file
from ipaserver.install import bindinstance
from ipaserver.install import dnskeysyncinstance
from ipaserver.install import odsexporterinstance
from ipaserver.install import opendnssecinstance
from ipaserver.install import service
if six.PY3:
unicode = str
logger = logging.getLogger(__name__)
ip_addresses = []
reverse_zones = []
def _find_dnssec_enabled_zones(conn):
search_kw = {'idnssecinlinesigning': True}
dnssec_enabled_filter = conn.make_filter(search_kw)
dn = DN('cn=dns', api.env.basedn)
try:
entries, _truncated = conn.find_entries(
base_dn=dn, filter=dnssec_enabled_filter, attrs_list=['idnsname'])
except errors.NotFound:
return []
else:
return [entry.single_value['idnsname'] for entry in entries
if 'idnsname' in entry]
def _is_master():
# test if server is DNSSEC key master
masters = opendnssecinstance.get_dnssec_key_masters(api.Backend.ldap2)
if api.env.host not in masters:
raise RuntimeError("Current server is not DNSSEC key master")
def _disable_dnssec():
fstore = sysrestore.FileStore(paths.SYSRESTORE)
ods = opendnssecinstance.OpenDNSSECInstance(fstore)
ods.realm = api.env.realm
ods_exporter = odsexporterinstance.ODSExporterInstance(fstore)
ods_exporter.realm = api.env.realm
# unconfigure services first
ods.uninstall() # needs keytab to flush the latest ods database
ods_exporter.uninstall()
ods.ldap_disable('DNSSEC', api.env.host, api.env.basedn)
ods.ldap_remove_service_container('DNSSEC', api.env.host, api.env.basedn)
ods_exporter.ldap_disable('DNSKeyExporter', api.env.host, api.env.basedn)
ods_exporter.remove_service()
ods_exporter.ldap_remove_service_container('DNSKeyExporter', api.env.host,
api.env.basedn)
conn = api.Backend.ldap2
dn = DN(('cn', 'DNSSEC'), ('cn', api.env.host),
api.env.container_masters, api.env.basedn)
try:
entry = conn.get_entry(dn)
except errors.NotFound:
pass
else:
ipa_config = entry.get('ipaConfigString', [])
if opendnssecinstance.KEYMASTER in ipa_config:
ipa_config.remove(opendnssecinstance.KEYMASTER)
conn.update_entry(entry)
def package_check(exception):
if not os.path.isfile(paths.IPA_DNS_INSTALL):
raise exception(
"Integrated DNS requires '%s' package"
% constants.IPA_DNS_PACKAGE_NAME
)
def install_check(standalone, api, replica, options, hostname):
global ip_addresses
global reverse_zones
fstore = sysrestore.FileStore(paths.SYSRESTORE)
package_check(RuntimeError)
# when installing first DNS instance we need to check zone overlap
if replica or standalone:
already_enabled = api.Command.dns_is_enabled()['result']
else:
already_enabled = False
if not already_enabled:
domain = dnsutil.DNSName(util.normalize_zone(api.env.domain))
try:
dnsutil.check_zone_overlap(domain, raise_on_error=False)
except dnsutil.DNSZoneAlreadyExists as e:
if options.force or options.allow_zone_overlap:
logger.warning("%s Please make sure that the domain is "
"properly delegated to this IPA server.",
e)
else:
hst = dnsutil.DNSName(hostname).make_absolute().to_text()
if hst not in e.kwargs['ns']:
raise ValueError(str(e))
for reverse_zone in options.reverse_zones:
try:
dnsutil.check_zone_overlap(reverse_zone)
except dnsutil.DNSZoneAlreadyExists as e:
if options.force or options.allow_zone_overlap:
logger.warning('%s', str(e))
else:
raise e
if standalone:
print("==============================================================================")
print("This program will setup DNS for the FreeIPA Server.")
print("")
print("This includes:")
print(" * Configure DNS (bind)")
print(" * Configure SoftHSM (required by DNSSEC)")
print(" * Configure ipa-dnskeysyncd (required by DNSSEC)")
if options.dnssec_master:
print(" * Configure ipa-ods-exporter (required by DNSSEC key master)")
print(" * Configure OpenDNSSEC (required by DNSSEC key master)")
print(" * Generate DNSSEC master key (required by DNSSEC key master)")
elif options.disable_dnssec_master:
print(" * Unconfigure ipa-ods-exporter")
print(" * Unconfigure OpenDNSSEC")
print("")
print("No new zones will be signed without DNSSEC key master IPA server.")
print("")
print(("Please copy file from %s after uninstallation. This file is needed "
"on new DNSSEC key " % paths.IPA_KASP_DB_BACKUP))
print("master server")
print("")
print("NOTE: DNSSEC zone signing is not enabled by default")
print("")
if options.dnssec_master:
print("Plan carefully, replacing DNSSEC key master is not recommended")
print("")
print("")
print("To accept the default shown in brackets, press the Enter key.")
print("")
if (options.dnssec_master and not options.unattended and not
ipautil.user_input(
"Do you want to setup this IPA server as DNSSEC key master?",
False)):
sys.exit("Aborted")
elif (options.disable_dnssec_master and not options.unattended and not
ipautil.user_input(
"Do you want to disable current DNSSEC key master?",
False)):
sys.exit("Aborted")
if options.disable_dnssec_master:
_is_master()
if options.disable_dnssec_master or options.dnssec_master:
dnssec_zones = _find_dnssec_enabled_zones(api.Backend.ldap2)
if options.disable_dnssec_master:
if dnssec_zones and not options.force:
raise RuntimeError(
"Cannot disable DNSSEC key master, DNSSEC signing is still "
"enabled for following zone(s):\n"
"%s\n"
"It is possible to move DNSSEC key master role to a different "
"server by using --force option to skip this check.\n\n"
"WARNING: You have to immediately copy kasp.db file to a new "
"server and run command 'ipa-dns-install --dnssec-master "
"--kasp-db'.\n"
"Your DNS zones will become unavailable if you "
"do not reinstall the DNSSEC key master role immediately." %
", ".join([str(zone) for zone in dnssec_zones]))
elif options.dnssec_master:
ods = opendnssecinstance.OpenDNSSECInstance(fstore)
ods.realm = api.env.realm
dnssec_masters = ods.get_masters()
# we can reinstall current server if it is dnssec master
if dnssec_masters and api.env.host not in dnssec_masters:
print("DNSSEC key master(s):", u','.join(dnssec_masters))
raise ScriptError(
"Only one DNSSEC key master is supported in current version.")
if options.kasp_db_file:
dnskeysyncd = services.service('ipa-dnskeysyncd', api)
if not dnskeysyncd.is_installed():
raise RuntimeError("ipa-dnskeysyncd is not configured on this "
"server, you cannot reuse OpenDNSSEC "
"database (kasp.db file)")
# check if replica can be the DNSSEC master
cmd = [paths.IPA_DNSKEYSYNCD_REPLICA]
environment = {
"SOFTHSM2_CONF": paths.DNSSEC_SOFTHSM2_CONF,
}
# stop dnskeysyncd before test
dnskeysyncd_running = dnskeysyncd.is_running()
dnskeysyncd.stop()
try:
ipautil.run(cmd, env=environment,
runas=constants.ODS_USER,
suplementary_groups=[constants.NAMED_GROUP])
except CalledProcessError as e:
logger.debug("%s", e)
raise RuntimeError("This IPA server cannot be promoted to "
"DNSSEC master role because some keys were "
"not replicated from the original "
"DNSSEC master server")
finally:
if dnskeysyncd_running:
dnskeysyncd.start()
elif dnssec_zones and not options.force:
# some zones have --dnssec=true, make sure a user really want to
# install new database
raise RuntimeError(
"DNSSEC signing is already enabled for following zone(s): %s\n"
"Installation cannot continue without the OpenDNSSEC database "
"file from the original DNSSEC master server.\n"
"Please use option --kasp-db to specify location "
"of the kasp.db file copied from the original "
"DNSSEC master server.\n"
"WARNING: Zones will become unavailable if you do not provide "
"the original kasp.db file." %
", ".join([str(zone) for zone in dnssec_zones]))
ip_addresses = get_server_ip_address(hostname, options.unattended,
True, options.ip_addresses)
util.no_matching_interface_for_ip_address_warning(ip_addresses)
if not options.forward_policy:
# user did not specify policy, derive it: default is 'first' but
# if any of local IP addresses belongs to private ranges use 'only'
options.forward_policy = 'first'
for ip in ip_addresses:
if dnsutil.inside_auto_empty_zone(dnsutil.DNSName(ip.reverse_dns)):
options.forward_policy = 'only'
logger.debug('IP address %s belongs to a private range, '
'using forward policy only', ip)
break
if options.no_forwarders:
options.forwarders = []
elif options.forwarders or options.auto_forwarders:
if not options.forwarders:
options.forwarders = []
if options.auto_forwarders:
options.forwarders += dnsutil.get_ipa_resolver().nameservers
elif standalone or not replica:
options.forwarders = read_dns_forwarders()
# test DNSSEC forwarders
if options.forwarders:
if not options.no_dnssec_validation \
and not bindinstance.check_forwarders(options.forwarders):
options.no_dnssec_validation = True
print("WARNING: DNSSEC validation will be disabled")
logger.debug("will use DNS forwarders: %s\n", options.forwarders)
if not standalone:
search_reverse_zones = False
else:
search_reverse_zones = True
if not standalone and replica:
reverse_zones_unattended_check = True
else:
reverse_zones_unattended_check = options.unattended
reverse_zones = bindinstance.check_reverse_zones(
ip_addresses, options.reverse_zones, options,
reverse_zones_unattended_check, search_reverse_zones
)
if reverse_zones:
print("Using reverse zone(s) %s" % ', '.join(reverse_zones))
def install(standalone, replica, options, api=api):
fstore = sysrestore.FileStore(paths.SYSRESTORE)
if standalone:
# otherwise this is done by server/replica installer
update_hosts_file(ip_addresses, api.env.host, fstore)
bind = bindinstance.BindInstance(fstore, api=api)
bind.setup(api.env.host, ip_addresses, api.env.realm, api.env.domain,
options.forwarders, options.forward_policy,
reverse_zones, zonemgr=options.zonemgr,
no_dnssec_validation=options.no_dnssec_validation)
if standalone and not options.unattended:
print("")
print("The following operations may take some minutes to complete.")
print("Please wait until the prompt is returned.")
print("")
bind.create_instance()
print("Restarting the web server to pick up resolv.conf changes")
services.knownservices.httpd.restart(capture_output=True)
# on dnssec master this must be installed last
dnskeysyncd = dnskeysyncinstance.DNSKeySyncInstance(fstore)
dnskeysyncd.create_instance(api.env.host, api.env.realm)
if options.dnssec_master:
ods = opendnssecinstance.OpenDNSSECInstance(fstore)
ods_exporter = odsexporterinstance.ODSExporterInstance(fstore)
ods_exporter.create_instance(api.env.host, api.env.realm)
ods.create_instance(api.env.host, api.env.realm,
kasp_db_file=options.kasp_db_file)
elif options.disable_dnssec_master:
_disable_dnssec()
dnskeysyncd.start_dnskeysyncd()
bind.start_named()
# Enable configured services for standalone check_global_configuration()
if standalone:
service.enable_services(api.env.host)
# this must be done when bind is started and operational
bind.update_system_records()
if standalone:
print("==============================================================================")
print("Setup complete")
print("")
bind.check_global_configuration()
print("")
print("")
print("\tYou must make sure these network ports are open:")
print("\t\tTCP Ports:")
print("\t\t * 53: bind")
print("\t\tUDP Ports:")
print("\t\t * 53: bind")
elif not standalone and replica:
print("")
bind.check_global_configuration()
print("")
def uninstall_check(options):
# test if server is DNSSEC key master
masters = opendnssecinstance.get_dnssec_key_masters(api.Backend.ldap2)
if api.env.host in masters:
print("This server is active DNSSEC key master. Uninstall could break your DNS system.")
if not (options.unattended or user_input(
"Are you sure you want to continue with the uninstall "
"procedure?", False)):
print("")
print("Aborting uninstall operation.")
sys.exit(1)
def uninstall():
fstore = sysrestore.FileStore(paths.SYSRESTORE)
ods = opendnssecinstance.OpenDNSSECInstance(fstore)
if ods.is_configured():
ods.uninstall()
ods_exporter = odsexporterinstance.ODSExporterInstance(fstore)
if ods_exporter.is_configured():
ods_exporter.uninstall()
bind = bindinstance.BindInstance(fstore)
if bind.is_configured():
bind.uninstall()
dnskeysync = dnskeysyncinstance.DNSKeySyncInstance(fstore)
if dnskeysync.is_configured():
dnskeysync.uninstall()
class DNSForwardPolicy(enum.Enum):
ONLY = 'only'
FIRST = 'first'
@group
class DNSInstallInterface(hostname.HostNameInstallInterface):
"""
Interface of the DNS installer
Knobs defined here will be available in:
* ipa-server-install
* ipa-replica-prepare
* ipa-replica-install
* ipa-dns-install
"""
description = "DNS"
allow_zone_overlap = knob(
None,
description="Create DNS zone even if it already exists",
)
allow_zone_overlap = prepare_only(allow_zone_overlap)
reverse_zones = knob(
# pylint: disable=invalid-sequence-index
typing.List[str], [],
description=("The reverse DNS zone to use. This option can be used "
"multiple times"),
cli_names='--reverse-zone',
cli_metavar='REVERSE_ZONE',
)
reverse_zones = prepare_only(reverse_zones)
@reverse_zones.validator
def reverse_zones(self, values):
if not self.allow_zone_overlap:
for zone in values:
check_zone_overlap(zone)
no_reverse = knob(
None,
description="Do not create new reverse DNS zone",
)
no_reverse = prepare_only(no_reverse)
auto_reverse = knob(
None,
description="Create necessary reverse zones",
)
auto_reverse = prepare_only(auto_reverse)
zonemgr = knob(
str, None,
description=("DNS zone manager e-mail address. Defaults to "
"hostmaster@DOMAIN"),
)
zonemgr = prepare_only(zonemgr)
@zonemgr.validator
def zonemgr(self, value):
# validate the value first
if six.PY3:
bindinstance.validate_zonemgr_str(value)
else:
try:
# IDNA support requires unicode
encoding = getattr(sys.stdin, 'encoding', None)
if encoding is None:
encoding = 'utf-8'
# value is string in py2 and py3
if not isinstance(value, unicode):
value = value.decode(encoding)
bindinstance.validate_zonemgr_str(value)
except ValueError as e:
# FIXME we can do this in better way
# https://fedorahosted.org/freeipa/ticket/4804
# decode to proper stderr encoding
stderr_encoding = getattr(sys.stderr, 'encoding', None)
if stderr_encoding is None:
stderr_encoding = 'utf-8'
error = unicode(e).encode(stderr_encoding)
raise ValueError(error)
forwarders = knob(
# pylint: disable=invalid-sequence-index
typing.List[ipautil.CheckedIPAddressLoopback], None,
description=("Add a DNS forwarder. This option can be used multiple "
"times"),
cli_names='--forwarder',
)
forwarders = enroll_only(forwarders)
no_forwarders = knob(
None,
description="Do not add any DNS forwarders, use root servers instead",
)
no_forwarders = enroll_only(no_forwarders)
auto_forwarders = knob(
None,
description="Use DNS forwarders configured in /etc/resolv.conf",
)
auto_forwarders = enroll_only(auto_forwarders)
forward_policy = knob(
DNSForwardPolicy, None,
description=("DNS forwarding policy for global forwarders"),
)
forward_policy = enroll_only(forward_policy)
no_dnssec_validation = knob(
None,
description="Disable DNSSEC validation",
)
no_dnssec_validation = enroll_only(no_dnssec_validation)
dnssec_master = False
disable_dnssec_master = False
kasp_db_file = None
force = False
| gpl-3.0 |
peterwittek/qml-rg | Archiv_Session_Spring_2017/Exercises/04_another_agent.py | 2 | 5829 |
''' This agent is based on the Bellman equation, used to create a matrix which will help the agent to find the
suitable move, given a certain position. The learning function constructs the matrix from random games. This matrix has
an element for each reward position, agent position and move. There is an option at the end of the program to let the initial
position of the agent not be only the center, to make things trickier! '''
import numpy as np
import random
Q = np.zeros(shape = (2,3,2)) # We shape the Q matrix from Bellman equation for 2 reward states, 3 agent states, 2 actions
Agent_state = [[1,0,0],[0,1,0],[0,0,1]] #possible agent positions
# An easy way to save the different states of the game is as follows: the reward can only have two
# positions, so we assign 0 for left and 1 for right. For the agent, we can have three different
# positions so 0 = left, 1 = center, 2 = right. Putting the reward + agent together, we can have 6
# possible states, that we can number from 0 to 5 using S=position_agent+3*position_reward. Then
# we can build a reward matrix, where for the states where there is a coincidence (S=0+0=0 and
# S=2+3*1=5) we assing value one, and for the non coinciding states we assing 0:
Reward=[1, 0, 0, 0, 0, 1] # Reward matrix from Bellman equation.
state = [0,0,0] # empty state
# Copy paste from rl_toy_example.py + comments from Patrick--------------------
def moveto(position,agent_position, status):
agent_position += position # x += y adds y to the variable x
if agent_position < 0: #since we always add 1 or -1 randomly to the position it can happen, that we get negative indices
agent_position = 0 #position -1 therefore is always set to 0
#agent_position = self.agent_position if we set this it will be found in max 2 steps (CHEAT)
elif agent_position > 2: #same for to big values. indices bigger than 2 are not in the state vector anymore
agent_position = 2
if status == "running" and state[agent_position] == 1: #if the agent is positioned at the same index as we initially set the reward
status = "win"
return 1, status, agent_position
else:
return 0, status, agent_position
def next_move():
return random.randint(0, 1)*2-1 #gives randomly either 1 or -1
# ----------------------------------------------------------------------------
# Learning function ----------------------------------------------------------
def learning(idx_reward,agent_position,agent_move,gamma): # This function construct the matrix Q by means of the Bellman equation
position_agent_0 = agent_position # Position of the Agent at time t
position_agent_1 = moveto(agent_move, agent_position, status)[2] # Position of the Agent at time t+1
if agent_move == -1: # we assing the value 0 for a left move (agent_move=-1) and 1 for a right move
a_move = 0
else:
a_move = 1
if idx_reward == 2: # we assign 1 to the right position for the reward (idx_reward=2) and 0 for left position
n_idx_reward = 1
else:
n_idx_reward = 0
# Bellman equation:
Q[n_idx_reward, position_agent_0, a_move] = Reward[position_agent_1 + 3*n_idx_reward] + gamma*np.max([Q[n_idx_reward, position_agent_1, i] for i in [0,1]])
# -----------------------------------------------------------------------------
# Teached agent ---------------------------------------------------------------
def cleverplayer(idx_reward,agent_position):
if idx_reward == 2: # we assign 1 to the right position for the reward (idx_reward=2) and 0 for left position
n_idx_reward = 1
else:
n_idx_reward = 0
# We compare the value of Q for the given state and the two possible movements. The highest value
# gives us the move to do! In the (rare) case the values are equal, we choose randomly
if Q[n_idx_reward, agent_position, 0] > Q[n_idx_reward, agent_position, 1]:
return +1
elif Q[n_idx_reward, agent_position, 0] < Q[n_idx_reward, agent_position, 1]:
return -1
else:
return random.randint(0, 1)*2-1
# -----------------------------------------------------------------------------
# Learning phase: the goal is to construct the matrix Q by playing random games
iterations=100 # Number of iterations of the learning process
gamma=0.9 # gamma of the Bellman equation. Roughly, this parameter tells you how much you want to take in account from future moves
for ii in range(0,iterations):
idx_reward=random.randint(0, 1)*2
state[idx_reward] = 1 #places reward randomly in state
agent_position = 1
agent_position = random.randint(0, 2) # Uncomment for random initial position (harder for the agent)
status = "running"
while status == "running":
agent_move = next_move()
learning(idx_reward, agent_position, agent_move,gamma)
reward, status, agent_position = moveto(agent_move, agent_position, status)
# -----------------------------------------------------------------------------
# Play! -----------------------------------------------------------------------
iterations_play=100
number_steps = 0
for jj in range(0,iterations_play):
idx_reward=random.randint(0, 1)*2
state[idx_reward] = 1
agent_position = 1
agent_position = random.randint(0, 2) # Uncomment for random initial position (harder for the agent)
status = "running"
while status == "running":
number_steps += 1 #saving number of steps
agent_move = cleverplayer(idx_reward,agent_position)
reward, status, agent_position = moveto(agent_move, agent_position, status)
print('\n The mean number of steps is ' + repr(number_steps / iterations_play) + '\n')
| gpl-3.0 |
junmin-zhu/chromium-rivertrail | chrome/test/pyautolib/bookmark_model.py | 80 | 3206 | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""BookmarkModel: python representation of the bookmark model.
Obtain one of these from PyUITestSuite::GetBookmarkModel() call.
"""
import os
import simplejson as json
import sys
class BookmarkModel(object):
def __init__(self, json_string):
"""Initialize a BookmarkModel from a string of json.
The JSON representation is the same as used by the bookmark model
to save to disk.
Args:
json_string: a string of JSON.
"""
self.bookdict = json.loads(json_string)
def BookmarkBar(self):
"""Return the bookmark bar node as a dict."""
return self.bookdict['roots']['bookmark_bar']
def Other(self):
"""Return the 'other' node (e.g. parent of "Other Bookmarks")"""
return self.bookdict['roots']['other']
def NodeCount(self, node=None):
"""Return a count of bookmark nodes, including folders.
The root node itself is included in the count.
Args:
node: the root to start with. If not specified, count all."""
if node == None:
return reduce(lambda x, y: x + y,
[self.NodeCount(x)
for x in self.bookdict['roots'].values()])
total = 1
children = node.get('children', None)
if children:
total = total + reduce(lambda x,y: x + y,
[self.NodeCount(x) for x in children])
return total
def FindByID(self, id, nodes=None):
"""Find the bookmark by id. Return the dict or None.
Args:
id: the id to look for.
nodes: an iterable of nodes to start with. If not specified, search all.
'Not specified' means None, not [].
"""
# Careful; we may get an empty list which is different than not
# having specified a list.
if nodes == None:
nodes = self.bookdict['roots'].values()
# Check each item. If it matches, return. If not, check each of
# their kids.
for node in nodes:
if node['id'] == id:
return node
for child in node.get('children', []):
found_node = self.FindByID(id, [child])
if found_node:
return found_node
# Not found at all.
return None
def FindByTitle(self, title, nodes=None):
"""Return a tuple of all nodes which have |title| in their title.
Args:
title: the title to look for.
node: an iterable of nodes to start with. If not specified, search all.
'Not specified' means None, not [].
"""
# Careful; we may get an empty list which is different than not
# having specified a list.
if nodes == None:
nodes = self.bookdict['roots'].values()
# Check each item. If it matches, return. If not, check each of
# their kids.
results = []
for node in nodes:
node_title = node.get('title', None) or node.get('name', None)
if title == node_title:
results.append(node)
# Note we check everything; unlike the FindByID, we do not stop early.
for child in node.get('children', []):
results += self.FindByTitle(title, [child])
return results
| bsd-3-clause |
konstruktoid/ansible-upstream | lib/ansible/modules/cloud/misc/rhevm.py | 25 | 51097 | #!/usr/bin/python
# (c) 2016, Timothy Vandenbrande <timothy.vandenbrande@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: rhevm
author: Timothy Vandenbrande
short_description: RHEV/oVirt automation
description:
- This module only supports oVirt/RHEV version 3. A newer module M(ovirt_vms) supports oVirt/RHV version 4.
- Allows you to create/remove/update or powermanage virtual machines on a RHEV/oVirt platform.
version_added: "2.2"
requirements:
- ovirtsdk
options:
user:
description:
- The user to authenticate with.
default: "admin@internal"
server:
description:
- The name/ip of your RHEV-m/oVirt instance.
default: "127.0.0.1"
port:
description:
- The port on which the API is reacheable.
default: "443"
insecure_api:
description:
- A boolean switch to make a secure or insecure connection to the server.
type: bool
default: 'no'
name:
description:
- The name of the VM.
cluster:
description:
- The rhev/ovirt cluster in which you want you VM to start.
datacenter:
description:
- The rhev/ovirt datacenter in which you want you VM to start.
default: "Default"
state:
description:
- This serves to create/remove/update or powermanage your VM.
default: "present"
choices: ['ping', 'present', 'absent', 'up', 'down', 'restarted', 'cd', 'info']
image:
description:
- The template to use for the VM.
type:
description:
- To define if the VM is a server or desktop.
default: server
choices: [ 'server', 'desktop', 'host' ]
vmhost:
description:
- The host you wish your VM to run on.
vmcpu:
description:
- The number of CPUs you want in your VM.
default: "2"
cpu_share:
description:
- This parameter is used to configure the cpu share.
default: "0"
vmmem:
description:
- The amount of memory you want your VM to use (in GB).
default: "1"
osver:
description:
- The operationsystem option in RHEV/oVirt.
default: "rhel_6x64"
mempol:
description:
- The minimum amount of memory you wish to reserve for this system.
default: "1"
vm_ha:
description:
- To make your VM High Available.
type: bool
default: 'yes'
disks:
description:
- This option uses complex arguments and is a list of disks with the options name, size and domain.
ifaces:
description:
- This option uses complex arguments and is a list of interfaces with the options name and vlan.
aliases: ['nics', 'interfaces']
boot_order:
description:
- This option uses complex arguments and is a list of items that specify the bootorder.
default: ["network","hd"]
del_prot:
description:
- This option sets the delete protection checkbox.
type: bool
default: yes
cd_drive:
description:
- The CD you wish to have mounted on the VM when I(state = 'CD').
timeout:
description:
- The timeout you wish to define for power actions.
- When I(state = 'up')
- When I(state = 'down')
- When I(state = 'restarted')
'''
RETURN = '''
vm:
description: Returns all of the VMs variables and execution.
returned: always
type: dict
sample: '{
"boot_order": [
"hd",
"network"
],
"changed": true,
"changes": [
"Delete Protection"
],
"cluster": "C1",
"cpu_share": "0",
"created": false,
"datacenter": "Default",
"del_prot": true,
"disks": [
{
"domain": "ssd-san",
"name": "OS",
"size": 40
}
],
"eth0": "00:00:5E:00:53:00",
"eth1": "00:00:5E:00:53:01",
"eth2": "00:00:5E:00:53:02",
"exists": true,
"failed": false,
"ifaces": [
{
"name": "eth0",
"vlan": "Management"
},
{
"name": "eth1",
"vlan": "Internal"
},
{
"name": "eth2",
"vlan": "External"
}
],
"image": false,
"mempol": "0",
"msg": [
"VM exists",
"cpu_share was already set to 0",
"VM high availability was already set to True",
"The boot order has already been set",
"VM delete protection has been set to True",
"Disk web2_Disk0_OS already exists",
"The VM starting host was already set to host416"
],
"name": "web2",
"type": "server",
"uuid": "4ba5a1be-e60b-4368-9533-920f156c817b",
"vm_ha": true,
"vmcpu": "4",
"vmhost": "host416",
"vmmem": "16"
}'
'''
EXAMPLES = '''
# basic get info from VM
- rhevm:
name: "demo"
user: "{{ rhev.admin.name }}"
password: "{{ rhev.admin.pass }}"
server: "rhevm01"
state: "info"
# basic create example from image
- rhevm:
name: "demo"
user: "{{ rhev.admin.name }}"
password: "{{ rhev.admin.pass }}"
server: "rhevm01"
state: "present"
image: "centos7_x64"
cluster: "centos"
# power management
- rhevm:
name: "uptime_server"
user: "{{ rhev.admin.name }}"
password: "{{ rhev.admin.pass }}"
server: "rhevm01"
cluster: "RH"
state: "down"
image: "centos7_x64"
# multi disk, multi nic create example
- rhevm:
name: "server007"
user: "{{ rhev.admin.name }}"
password: "{{ rhev.admin.pass }}"
server: "rhevm01"
cluster: "RH"
state: "present"
type: "server"
vmcpu: 4
vmmem: 2
ifaces:
- name: "eth0"
vlan: "vlan2202"
- name: "eth1"
vlan: "vlan36"
- name: "eth2"
vlan: "vlan38"
- name: "eth3"
vlan: "vlan2202"
disks:
- name: "root"
size: 10
domain: "ssd-san"
- name: "swap"
size: 10
domain: "15kiscsi-san"
- name: "opt"
size: 10
domain: "15kiscsi-san"
- name: "var"
size: 10
domain: "10kiscsi-san"
- name: "home"
size: 10
domain: "sata-san"
boot_order:
- "network"
- "hd"
# add a CD to the disk cd_drive
- rhevm:
name: 'server007'
user: "{{ rhev.admin.name }}"
password: "{{ rhev.admin.pass }}"
state: 'cd'
cd_drive: 'rhev-tools-setup.iso'
# new host deployment + host network configuration
- rhevm:
name: "ovirt_node007"
password: "{{ rhevm.admin.pass }}"
type: "host"
state: present
cluster: "rhevm01"
ifaces:
- name: em1
- name: em2
- name: p3p1
ip: '172.31.224.200'
netmask: '255.255.254.0'
- name: p3p2
ip: '172.31.225.200'
netmask: '255.255.254.0'
- name: bond0
bond:
- em1
- em2
network: 'rhevm'
ip: '172.31.222.200'
netmask: '255.255.255.0'
management: True
- name: bond0.36
network: 'vlan36'
ip: '10.2.36.200'
netmask: '255.255.254.0'
gateway: '10.2.36.254'
- name: bond0.2202
network: 'vlan2202'
- name: bond0.38
network: 'vlan38'
'''
import time
try:
from ovirtsdk.api import API
from ovirtsdk.xml import params
HAS_SDK = True
except ImportError:
HAS_SDK = False
from ansible.module_utils.basic import AnsibleModule
RHEV_FAILED = 1
RHEV_SUCCESS = 0
RHEV_UNAVAILABLE = 2
RHEV_TYPE_OPTS = ['server', 'desktop', 'host']
STATE_OPTS = ['ping', 'present', 'absent', 'up', 'down', 'restart', 'cd', 'info']
global msg, changed, failed
msg = []
changed = False
failed = False
class RHEVConn(object):
'Connection to RHEV-M'
def __init__(self, module):
self.module = module
user = module.params.get('user')
password = module.params.get('password')
server = module.params.get('server')
port = module.params.get('port')
insecure_api = module.params.get('insecure_api')
url = "https://%s:%s" % (server, port)
try:
api = API(url=url, username=user, password=password, insecure=str(insecure_api))
api.test()
self.conn = api
except:
raise Exception("Failed to connect to RHEV-M.")
def __del__(self):
self.conn.disconnect()
def createVMimage(self, name, cluster, template):
try:
vmparams = params.VM(
name=name,
cluster=self.conn.clusters.get(name=cluster),
template=self.conn.templates.get(name=template),
disks=params.Disks(clone=True)
)
self.conn.vms.add(vmparams)
setMsg("VM is created")
setChanged()
return True
except Exception as e:
setMsg("Failed to create VM")
setMsg(str(e))
setFailed()
return False
def createVM(self, name, cluster, os, actiontype):
try:
vmparams = params.VM(
name=name,
cluster=self.conn.clusters.get(name=cluster),
os=params.OperatingSystem(type_=os),
template=self.conn.templates.get(name="Blank"),
type_=actiontype
)
self.conn.vms.add(vmparams)
setMsg("VM is created")
setChanged()
return True
except Exception as e:
setMsg("Failed to create VM")
setMsg(str(e))
setFailed()
return False
def createDisk(self, vmname, diskname, disksize, diskdomain, diskinterface, diskformat, diskallocationtype, diskboot):
VM = self.get_VM(vmname)
newdisk = params.Disk(
name=diskname,
size=1024 * 1024 * 1024 * int(disksize),
wipe_after_delete=True,
sparse=diskallocationtype,
interface=diskinterface,
format=diskformat,
bootable=diskboot,
storage_domains=params.StorageDomains(
storage_domain=[self.get_domain(diskdomain)]
)
)
try:
VM.disks.add(newdisk)
VM.update()
setMsg("Successfully added disk " + diskname)
setChanged()
except Exception as e:
setFailed()
setMsg("Error attaching " + diskname + "disk, please recheck and remove any leftover configuration.")
setMsg(str(e))
return False
try:
currentdisk = VM.disks.get(name=diskname)
attempt = 1
while currentdisk.status.state != 'ok':
currentdisk = VM.disks.get(name=diskname)
if attempt == 100:
setMsg("Error, disk %s, state %s" % (diskname, str(currentdisk.status.state)))
raise Exception()
else:
attempt += 1
time.sleep(2)
setMsg("The disk " + diskname + " is ready.")
except Exception as e:
setFailed()
setMsg("Error getting the state of " + diskname + ".")
setMsg(str(e))
return False
return True
def createNIC(self, vmname, nicname, vlan, interface):
VM = self.get_VM(vmname)
CLUSTER = self.get_cluster_byid(VM.cluster.id)
DC = self.get_DC_byid(CLUSTER.data_center.id)
newnic = params.NIC(
name=nicname,
network=DC.networks.get(name=vlan),
interface=interface
)
try:
VM.nics.add(newnic)
VM.update()
setMsg("Successfully added iface " + nicname)
setChanged()
except Exception as e:
setFailed()
setMsg("Error attaching " + nicname + " iface, please recheck and remove any leftover configuration.")
setMsg(str(e))
return False
try:
currentnic = VM.nics.get(name=nicname)
attempt = 1
while currentnic.active is not True:
currentnic = VM.nics.get(name=nicname)
if attempt == 100:
setMsg("Error, iface %s, state %s" % (nicname, str(currentnic.active)))
raise Exception()
else:
attempt += 1
time.sleep(2)
setMsg("The iface " + nicname + " is ready.")
except Exception as e:
setFailed()
setMsg("Error getting the state of " + nicname + ".")
setMsg(str(e))
return False
return True
def get_DC(self, dc_name):
return self.conn.datacenters.get(name=dc_name)
def get_DC_byid(self, dc_id):
return self.conn.datacenters.get(id=dc_id)
def get_VM(self, vm_name):
return self.conn.vms.get(name=vm_name)
def get_cluster_byid(self, cluster_id):
return self.conn.clusters.get(id=cluster_id)
def get_cluster(self, cluster_name):
return self.conn.clusters.get(name=cluster_name)
def get_domain_byid(self, dom_id):
return self.conn.storagedomains.get(id=dom_id)
def get_domain(self, domain_name):
return self.conn.storagedomains.get(name=domain_name)
def get_disk(self, disk):
return self.conn.disks.get(disk)
def get_network(self, dc_name, network_name):
return self.get_DC(dc_name).networks.get(network_name)
def get_network_byid(self, network_id):
return self.conn.networks.get(id=network_id)
def get_NIC(self, vm_name, nic_name):
return self.get_VM(vm_name).nics.get(nic_name)
def get_Host(self, host_name):
return self.conn.hosts.get(name=host_name)
def get_Host_byid(self, host_id):
return self.conn.hosts.get(id=host_id)
def set_Memory(self, name, memory):
VM = self.get_VM(name)
VM.memory = int(int(memory) * 1024 * 1024 * 1024)
try:
VM.update()
setMsg("The Memory has been updated.")
setChanged()
return True
except Exception as e:
setMsg("Failed to update memory.")
setMsg(str(e))
setFailed()
return False
def set_Memory_Policy(self, name, memory_policy):
VM = self.get_VM(name)
VM.memory_policy.guaranteed = int(int(memory_policy) * 1024 * 1024 * 1024)
try:
VM.update()
setMsg("The memory policy has been updated.")
setChanged()
return True
except Exception as e:
setMsg("Failed to update memory policy.")
setMsg(str(e))
setFailed()
return False
def set_CPU(self, name, cpu):
VM = self.get_VM(name)
VM.cpu.topology.cores = int(cpu)
try:
VM.update()
setMsg("The number of CPUs has been updated.")
setChanged()
return True
except Exception as e:
setMsg("Failed to update the number of CPUs.")
setMsg(str(e))
setFailed()
return False
def set_CPU_share(self, name, cpu_share):
VM = self.get_VM(name)
VM.cpu_shares = int(cpu_share)
try:
VM.update()
setMsg("The CPU share has been updated.")
setChanged()
return True
except Exception as e:
setMsg("Failed to update the CPU share.")
setMsg(str(e))
setFailed()
return False
def set_Disk(self, diskname, disksize, diskinterface, diskboot):
DISK = self.get_disk(diskname)
setMsg("Checking disk " + diskname)
if DISK.get_bootable() != diskboot:
try:
DISK.set_bootable(diskboot)
setMsg("Updated the boot option on the disk.")
setChanged()
except Exception as e:
setMsg("Failed to set the boot option on the disk.")
setMsg(str(e))
setFailed()
return False
else:
setMsg("The boot option of the disk is correct")
if int(DISK.size) < (1024 * 1024 * 1024 * int(disksize)):
try:
DISK.size = (1024 * 1024 * 1024 * int(disksize))
setMsg("Updated the size of the disk.")
setChanged()
except Exception as e:
setMsg("Failed to update the size of the disk.")
setMsg(str(e))
setFailed()
return False
elif int(DISK.size) < (1024 * 1024 * 1024 * int(disksize)):
setMsg("Shrinking disks is not supported")
setMsg(str(e))
setFailed()
return False
else:
setMsg("The size of the disk is correct")
if str(DISK.interface) != str(diskinterface):
try:
DISK.interface = diskinterface
setMsg("Updated the interface of the disk.")
setChanged()
except Exception as e:
setMsg("Failed to update the interface of the disk.")
setMsg(str(e))
setFailed()
return False
else:
setMsg("The interface of the disk is correct")
return True
def set_NIC(self, vmname, nicname, newname, vlan, interface):
NIC = self.get_NIC(vmname, nicname)
VM = self.get_VM(vmname)
CLUSTER = self.get_cluster_byid(VM.cluster.id)
DC = self.get_DC_byid(CLUSTER.data_center.id)
NETWORK = self.get_network(str(DC.name), vlan)
checkFail()
if NIC.name != newname:
NIC.name = newname
setMsg('Updating iface name to ' + newname)
setChanged()
if str(NIC.network.id) != str(NETWORK.id):
NIC.set_network(NETWORK)
setMsg('Updating iface network to ' + vlan)
setChanged()
if NIC.interface != interface:
NIC.interface = interface
setMsg('Updating iface interface to ' + interface)
setChanged()
try:
NIC.update()
setMsg('iface has successfully been updated.')
except Exception as e:
setMsg("Failed to update the iface.")
setMsg(str(e))
setFailed()
return False
return True
def set_DeleteProtection(self, vmname, del_prot):
VM = self.get_VM(vmname)
VM.delete_protected = del_prot
try:
VM.update()
setChanged()
except Exception as e:
setMsg("Failed to update delete protection.")
setMsg(str(e))
setFailed()
return False
return True
def set_BootOrder(self, vmname, boot_order):
VM = self.get_VM(vmname)
bootorder = []
for device in boot_order:
bootorder.append(params.Boot(dev=device))
VM.os.boot = bootorder
try:
VM.update()
setChanged()
except Exception as e:
setMsg("Failed to update the boot order.")
setMsg(str(e))
setFailed()
return False
return True
def set_Host(self, host_name, cluster, ifaces):
HOST = self.get_Host(host_name)
CLUSTER = self.get_cluster(cluster)
if HOST is None:
setMsg("Host does not exist.")
ifacelist = dict()
networklist = []
manageip = ''
try:
for iface in ifaces:
try:
setMsg('creating host interface ' + iface['name'])
if 'management' in iface:
manageip = iface['ip']
if 'boot_protocol' not in iface:
if 'ip' in iface:
iface['boot_protocol'] = 'static'
else:
iface['boot_protocol'] = 'none'
if 'ip' not in iface:
iface['ip'] = ''
if 'netmask' not in iface:
iface['netmask'] = ''
if 'gateway' not in iface:
iface['gateway'] = ''
if 'network' in iface:
if 'bond' in iface:
bond = []
for slave in iface['bond']:
bond.append(ifacelist[slave])
try:
tmpiface = params.Bonding(
slaves=params.Slaves(host_nic=bond),
options=params.Options(
option=[
params.Option(name='miimon', value='100'),
params.Option(name='mode', value='4')
]
)
)
except Exception as e:
setMsg('Failed to create the bond for ' + iface['name'])
setFailed()
setMsg(str(e))
return False
try:
tmpnetwork = params.HostNIC(
network=params.Network(name=iface['network']),
name=iface['name'],
boot_protocol=iface['boot_protocol'],
ip=params.IP(
address=iface['ip'],
netmask=iface['netmask'],
gateway=iface['gateway']
),
override_configuration=True,
bonding=tmpiface)
networklist.append(tmpnetwork)
setMsg('Applying network ' + iface['name'])
except Exception as e:
setMsg('Failed to set' + iface['name'] + ' as network interface')
setFailed()
setMsg(str(e))
return False
else:
tmpnetwork = params.HostNIC(
network=params.Network(name=iface['network']),
name=iface['name'],
boot_protocol=iface['boot_protocol'],
ip=params.IP(
address=iface['ip'],
netmask=iface['netmask'],
gateway=iface['gateway']
))
networklist.append(tmpnetwork)
setMsg('Applying network ' + iface['name'])
else:
tmpiface = params.HostNIC(
name=iface['name'],
network=params.Network(),
boot_protocol=iface['boot_protocol'],
ip=params.IP(
address=iface['ip'],
netmask=iface['netmask'],
gateway=iface['gateway']
))
ifacelist[iface['name']] = tmpiface
except Exception as e:
setMsg('Failed to set ' + iface['name'])
setFailed()
setMsg(str(e))
return False
except Exception as e:
setMsg('Failed to set networks')
setMsg(str(e))
setFailed()
return False
if manageip == '':
setMsg('No management network is defined')
setFailed()
return False
try:
HOST = params.Host(name=host_name, address=manageip, cluster=CLUSTER, ssh=params.SSH(authentication_method='publickey'))
if self.conn.hosts.add(HOST):
setChanged()
HOST = self.get_Host(host_name)
state = HOST.status.state
while (state != 'non_operational' and state != 'up'):
HOST = self.get_Host(host_name)
state = HOST.status.state
time.sleep(1)
if state == 'non_responsive':
setMsg('Failed to add host to RHEVM')
setFailed()
return False
setMsg('status host: up')
time.sleep(5)
HOST = self.get_Host(host_name)
state = HOST.status.state
setMsg('State before setting to maintenance: ' + str(state))
HOST.deactivate()
while state != 'maintenance':
HOST = self.get_Host(host_name)
state = HOST.status.state
time.sleep(1)
setMsg('status host: maintenance')
try:
HOST.nics.setupnetworks(params.Action(
force=True,
check_connectivity=False,
host_nics=params.HostNics(host_nic=networklist)
))
setMsg('nics are set')
except Exception as e:
setMsg('Failed to apply networkconfig')
setFailed()
setMsg(str(e))
return False
try:
HOST.commitnetconfig()
setMsg('Network config is saved')
except Exception as e:
setMsg('Failed to save networkconfig')
setFailed()
setMsg(str(e))
return False
except Exception as e:
if 'The Host name is already in use' in str(e):
setMsg("Host already exists")
else:
setMsg("Failed to add host")
setFailed()
setMsg(str(e))
return False
HOST.activate()
while state != 'up':
HOST = self.get_Host(host_name)
state = HOST.status.state
time.sleep(1)
if state == 'non_responsive':
setMsg('Failed to apply networkconfig.')
setFailed()
return False
setMsg('status host: up')
else:
setMsg("Host exists.")
return True
def del_NIC(self, vmname, nicname):
return self.get_NIC(vmname, nicname).delete()
def remove_VM(self, vmname):
VM = self.get_VM(vmname)
try:
VM.delete()
except Exception as e:
setMsg("Failed to remove VM.")
setMsg(str(e))
setFailed()
return False
return True
def start_VM(self, vmname, timeout):
VM = self.get_VM(vmname)
try:
VM.start()
except Exception as e:
setMsg("Failed to start VM.")
setMsg(str(e))
setFailed()
return False
return self.wait_VM(vmname, "up", timeout)
def wait_VM(self, vmname, state, timeout):
VM = self.get_VM(vmname)
while VM.status.state != state:
VM = self.get_VM(vmname)
time.sleep(10)
if timeout is not False:
timeout -= 10
if timeout <= 0:
setMsg("Timeout expired")
setFailed()
return False
return True
def stop_VM(self, vmname, timeout):
VM = self.get_VM(vmname)
try:
VM.stop()
except Exception as e:
setMsg("Failed to stop VM.")
setMsg(str(e))
setFailed()
return False
return self.wait_VM(vmname, "down", timeout)
def set_CD(self, vmname, cd_drive):
VM = self.get_VM(vmname)
try:
if str(VM.status.state) == 'down':
cdrom = params.CdRom(file=cd_drive)
VM.cdroms.add(cdrom)
setMsg("Attached the image.")
setChanged()
else:
cdrom = VM.cdroms.get(id="00000000-0000-0000-0000-000000000000")
cdrom.set_file(cd_drive)
cdrom.update(current=True)
setMsg("Attached the image.")
setChanged()
except Exception as e:
setMsg("Failed to attach image.")
setMsg(str(e))
setFailed()
return False
return True
def set_VM_Host(self, vmname, vmhost):
VM = self.get_VM(vmname)
HOST = self.get_Host(vmhost)
try:
VM.placement_policy.host = HOST
VM.update()
setMsg("Set startup host to " + vmhost)
setChanged()
except Exception as e:
setMsg("Failed to set startup host.")
setMsg(str(e))
setFailed()
return False
return True
def migrate_VM(self, vmname, vmhost):
VM = self.get_VM(vmname)
HOST = self.get_Host_byid(VM.host.id)
if str(HOST.name) != vmhost:
try:
VM.migrate(
action=params.Action(
host=params.Host(
name=vmhost,
)
),
)
setChanged()
setMsg("VM migrated to " + vmhost)
except Exception as e:
setMsg("Failed to set startup host.")
setMsg(str(e))
setFailed()
return False
return True
def remove_CD(self, vmname):
VM = self.get_VM(vmname)
try:
VM.cdroms.get(id="00000000-0000-0000-0000-000000000000").delete()
setMsg("Removed the image.")
setChanged()
except Exception as e:
setMsg("Failed to remove the image.")
setMsg(str(e))
setFailed()
return False
return True
class RHEV(object):
def __init__(self, module):
self.module = module
def __get_conn(self):
self.conn = RHEVConn(self.module)
return self.conn
def test(self):
self.__get_conn()
return "OK"
def getVM(self, name):
self.__get_conn()
VM = self.conn.get_VM(name)
if VM:
vminfo = dict()
vminfo['uuid'] = VM.id
vminfo['name'] = VM.name
vminfo['status'] = VM.status.state
vminfo['cpu_cores'] = VM.cpu.topology.cores
vminfo['cpu_sockets'] = VM.cpu.topology.sockets
vminfo['cpu_shares'] = VM.cpu_shares
vminfo['memory'] = (int(VM.memory) // 1024 // 1024 // 1024)
vminfo['mem_pol'] = (int(VM.memory_policy.guaranteed) // 1024 // 1024 // 1024)
vminfo['os'] = VM.get_os().type_
vminfo['del_prot'] = VM.delete_protected
try:
vminfo['host'] = str(self.conn.get_Host_byid(str(VM.host.id)).name)
except Exception:
vminfo['host'] = None
vminfo['boot_order'] = []
for boot_dev in VM.os.get_boot():
vminfo['boot_order'].append(str(boot_dev.dev))
vminfo['disks'] = []
for DISK in VM.disks.list():
disk = dict()
disk['name'] = DISK.name
disk['size'] = (int(DISK.size) // 1024 // 1024 // 1024)
disk['domain'] = str((self.conn.get_domain_byid(DISK.get_storage_domains().get_storage_domain()[0].id)).name)
disk['interface'] = DISK.interface
vminfo['disks'].append(disk)
vminfo['ifaces'] = []
for NIC in VM.nics.list():
iface = dict()
iface['name'] = str(NIC.name)
iface['vlan'] = str(self.conn.get_network_byid(NIC.get_network().id).name)
iface['interface'] = NIC.interface
iface['mac'] = NIC.mac.address
vminfo['ifaces'].append(iface)
vminfo[str(NIC.name)] = NIC.mac.address
CLUSTER = self.conn.get_cluster_byid(VM.cluster.id)
if CLUSTER:
vminfo['cluster'] = CLUSTER.name
else:
vminfo = False
return vminfo
def createVMimage(self, name, cluster, template, disks):
self.__get_conn()
return self.conn.createVMimage(name, cluster, template, disks)
def createVM(self, name, cluster, os, actiontype):
self.__get_conn()
return self.conn.createVM(name, cluster, os, actiontype)
def setMemory(self, name, memory):
self.__get_conn()
return self.conn.set_Memory(name, memory)
def setMemoryPolicy(self, name, memory_policy):
self.__get_conn()
return self.conn.set_Memory_Policy(name, memory_policy)
def setCPU(self, name, cpu):
self.__get_conn()
return self.conn.set_CPU(name, cpu)
def setCPUShare(self, name, cpu_share):
self.__get_conn()
return self.conn.set_CPU_share(name, cpu_share)
def setDisks(self, name, disks):
self.__get_conn()
counter = 0
bootselect = False
for disk in disks:
if 'bootable' in disk:
if disk['bootable'] is True:
bootselect = True
for disk in disks:
diskname = name + "_Disk" + str(counter) + "_" + disk.get('name', '').replace('/', '_')
disksize = disk.get('size', 1)
diskdomain = disk.get('domain', None)
if diskdomain is None:
setMsg("`domain` is a required disk key.")
setFailed()
return False
diskinterface = disk.get('interface', 'virtio')
diskformat = disk.get('format', 'raw')
diskallocationtype = disk.get('thin', False)
diskboot = disk.get('bootable', False)
if bootselect is False and counter == 0:
diskboot = True
DISK = self.conn.get_disk(diskname)
if DISK is None:
self.conn.createDisk(name, diskname, disksize, diskdomain, diskinterface, diskformat, diskallocationtype, diskboot)
else:
self.conn.set_Disk(diskname, disksize, diskinterface, diskboot)
checkFail()
counter += 1
return True
def setNetworks(self, vmname, ifaces):
self.__get_conn()
VM = self.conn.get_VM(vmname)
counter = 0
length = len(ifaces)
for NIC in VM.nics.list():
if counter < length:
iface = ifaces[counter]
name = iface.get('name', None)
if name is None:
setMsg("`name` is a required iface key.")
setFailed()
elif str(name) != str(NIC.name):
setMsg("ifaces are in the wrong order, rebuilding everything.")
for NIC in VM.nics.list():
self.conn.del_NIC(vmname, NIC.name)
self.setNetworks(vmname, ifaces)
checkFail()
return True
vlan = iface.get('vlan', None)
if vlan is None:
setMsg("`vlan` is a required iface key.")
setFailed()
checkFail()
interface = iface.get('interface', 'virtio')
self.conn.set_NIC(vmname, str(NIC.name), name, vlan, interface)
else:
self.conn.del_NIC(vmname, NIC.name)
counter += 1
checkFail()
while counter < length:
iface = ifaces[counter]
name = iface.get('name', None)
if name is None:
setMsg("`name` is a required iface key.")
setFailed()
vlan = iface.get('vlan', None)
if vlan is None:
setMsg("`vlan` is a required iface key.")
setFailed()
if failed is True:
return False
interface = iface.get('interface', 'virtio')
self.conn.createNIC(vmname, name, vlan, interface)
counter += 1
checkFail()
return True
def setDeleteProtection(self, vmname, del_prot):
self.__get_conn()
VM = self.conn.get_VM(vmname)
if bool(VM.delete_protected) != bool(del_prot):
self.conn.set_DeleteProtection(vmname, del_prot)
checkFail()
setMsg("`delete protection` has been updated.")
else:
setMsg("`delete protection` already has the right value.")
return True
def setBootOrder(self, vmname, boot_order):
self.__get_conn()
VM = self.conn.get_VM(vmname)
bootorder = []
for boot_dev in VM.os.get_boot():
bootorder.append(str(boot_dev.dev))
if boot_order != bootorder:
self.conn.set_BootOrder(vmname, boot_order)
setMsg('The boot order has been set')
else:
setMsg('The boot order has already been set')
return True
def removeVM(self, vmname):
self.__get_conn()
self.setPower(vmname, "down", 300)
return self.conn.remove_VM(vmname)
def setPower(self, vmname, state, timeout):
self.__get_conn()
VM = self.conn.get_VM(vmname)
if VM is None:
setMsg("VM does not exist.")
setFailed()
return False
if state == VM.status.state:
setMsg("VM state was already " + state)
else:
if state == "up":
setMsg("VM is going to start")
self.conn.start_VM(vmname, timeout)
setChanged()
elif state == "down":
setMsg("VM is going to stop")
self.conn.stop_VM(vmname, timeout)
setChanged()
elif state == "restarted":
self.setPower(vmname, "down", timeout)
checkFail()
self.setPower(vmname, "up", timeout)
checkFail()
setMsg("the vm state is set to " + state)
return True
def setCD(self, vmname, cd_drive):
self.__get_conn()
if cd_drive:
return self.conn.set_CD(vmname, cd_drive)
else:
return self.conn.remove_CD(vmname)
def setVMHost(self, vmname, vmhost):
self.__get_conn()
return self.conn.set_VM_Host(vmname, vmhost)
# pylint: disable=unreachable
VM = self.conn.get_VM(vmname)
HOST = self.conn.get_Host(vmhost)
if VM.placement_policy.host is None:
self.conn.set_VM_Host(vmname, vmhost)
elif str(VM.placement_policy.host.id) != str(HOST.id):
self.conn.set_VM_Host(vmname, vmhost)
else:
setMsg("VM's startup host was already set to " + vmhost)
checkFail()
if str(VM.status.state) == "up":
self.conn.migrate_VM(vmname, vmhost)
checkFail()
return True
def setHost(self, hostname, cluster, ifaces):
self.__get_conn()
return self.conn.set_Host(hostname, cluster, ifaces)
def checkFail():
if failed:
module.fail_json(msg=msg)
else:
return True
def setFailed():
global failed
failed = True
def setChanged():
global changed
changed = True
def setMsg(message):
global failed
msg.append(message)
def core(module):
r = RHEV(module)
state = module.params.get('state', 'present')
if state == 'ping':
r.test()
return RHEV_SUCCESS, {"ping": "pong"}
elif state == 'info':
name = module.params.get('name')
if not name:
setMsg("`name` is a required argument.")
return RHEV_FAILED, msg
vminfo = r.getVM(name)
return RHEV_SUCCESS, {'changed': changed, 'msg': msg, 'vm': vminfo}
elif state == 'present':
created = False
name = module.params.get('name')
if not name:
setMsg("`name` is a required argument.")
return RHEV_FAILED, msg
actiontype = module.params.get('type')
if actiontype == 'server' or actiontype == 'desktop':
vminfo = r.getVM(name)
if vminfo:
setMsg('VM exists')
else:
# Create VM
cluster = module.params.get('cluster')
if cluster is None:
setMsg("cluster is a required argument.")
setFailed()
template = module.params.get('image')
if template:
disks = module.params.get('disks')
if disks is None:
setMsg("disks is a required argument.")
setFailed()
checkFail()
if r.createVMimage(name, cluster, template, disks) is False:
return RHEV_FAILED, vminfo
else:
os = module.params.get('osver')
if os is None:
setMsg("osver is a required argument.")
setFailed()
checkFail()
if r.createVM(name, cluster, os, actiontype) is False:
return RHEV_FAILED, vminfo
created = True
# Set MEMORY and MEMORY POLICY
vminfo = r.getVM(name)
memory = module.params.get('vmmem')
if memory is not None:
memory_policy = module.params.get('mempol')
if int(memory_policy) == 0:
memory_policy = memory
mem_pol_nok = True
if int(vminfo['mem_pol']) == int(memory_policy):
setMsg("Memory is correct")
mem_pol_nok = False
mem_nok = True
if int(vminfo['memory']) == int(memory):
setMsg("Memory is correct")
mem_nok = False
if memory_policy > memory:
setMsg('memory_policy cannot have a higher value than memory.')
return RHEV_FAILED, msg
if mem_nok and mem_pol_nok:
if int(memory_policy) > int(vminfo['memory']):
r.setMemory(vminfo['name'], memory)
r.setMemoryPolicy(vminfo['name'], memory_policy)
else:
r.setMemoryPolicy(vminfo['name'], memory_policy)
r.setMemory(vminfo['name'], memory)
elif mem_nok:
r.setMemory(vminfo['name'], memory)
elif mem_pol_nok:
r.setMemoryPolicy(vminfo['name'], memory_policy)
checkFail()
# Set CPU
cpu = module.params.get('vmcpu')
if int(vminfo['cpu_cores']) == int(cpu):
setMsg("Number of CPUs is correct")
else:
if r.setCPU(vminfo['name'], cpu) is False:
return RHEV_FAILED, msg
# Set CPU SHARE
cpu_share = module.params.get('cpu_share')
if cpu_share is not None:
if int(vminfo['cpu_shares']) == int(cpu_share):
setMsg("CPU share is correct.")
else:
if r.setCPUShare(vminfo['name'], cpu_share) is False:
return RHEV_FAILED, msg
# Set DISKS
disks = module.params.get('disks')
if disks is not None:
if r.setDisks(vminfo['name'], disks) is False:
return RHEV_FAILED, msg
# Set NETWORKS
ifaces = module.params.get('ifaces', None)
if ifaces is not None:
if r.setNetworks(vminfo['name'], ifaces) is False:
return RHEV_FAILED, msg
# Set Delete Protection
del_prot = module.params.get('del_prot')
if r.setDeleteProtection(vminfo['name'], del_prot) is False:
return RHEV_FAILED, msg
# Set Boot Order
boot_order = module.params.get('boot_order')
if r.setBootOrder(vminfo['name'], boot_order) is False:
return RHEV_FAILED, msg
# Set VM Host
vmhost = module.params.get('vmhost')
if vmhost is not False and vmhost is not "False":
if r.setVMHost(vminfo['name'], vmhost) is False:
return RHEV_FAILED, msg
vminfo = r.getVM(name)
vminfo['created'] = created
return RHEV_SUCCESS, {'changed': changed, 'msg': msg, 'vm': vminfo}
if actiontype == 'host':
cluster = module.params.get('cluster')
if cluster is None:
setMsg("cluster is a required argument.")
setFailed()
ifaces = module.params.get('ifaces')
if ifaces is None:
setMsg("ifaces is a required argument.")
setFailed()
if r.setHost(name, cluster, ifaces) is False:
return RHEV_FAILED, msg
return RHEV_SUCCESS, {'changed': changed, 'msg': msg}
elif state == 'absent':
name = module.params.get('name')
if not name:
setMsg("`name` is a required argument.")
return RHEV_FAILED, msg
actiontype = module.params.get('type')
if actiontype == 'server' or actiontype == 'desktop':
vminfo = r.getVM(name)
if vminfo:
setMsg('VM exists')
# Set Delete Protection
del_prot = module.params.get('del_prot')
if r.setDeleteProtection(vminfo['name'], del_prot) is False:
return RHEV_FAILED, msg
# Remove VM
if r.removeVM(vminfo['name']) is False:
return RHEV_FAILED, msg
setMsg('VM has been removed.')
vminfo['state'] = 'DELETED'
else:
setMsg('VM was already removed.')
return RHEV_SUCCESS, {'changed': changed, 'msg': msg, 'vm': vminfo}
elif state == 'up' or state == 'down' or state == 'restarted':
name = module.params.get('name')
if not name:
setMsg("`name` is a required argument.")
return RHEV_FAILED, msg
timeout = module.params.get('timeout')
if r.setPower(name, state, timeout) is False:
return RHEV_FAILED, msg
vminfo = r.getVM(name)
return RHEV_SUCCESS, {'changed': changed, 'msg': msg, 'vm': vminfo}
elif state == 'cd':
name = module.params.get('name')
cd_drive = module.params.get('cd_drive')
if r.setCD(name, cd_drive) is False:
return RHEV_FAILED, msg
return RHEV_SUCCESS, {'changed': changed, 'msg': msg}
def main():
global module
module = AnsibleModule(
argument_spec=dict(
state=dict(default='present', choices=['ping', 'present', 'absent', 'up', 'down', 'restarted', 'cd', 'info']),
user=dict(default="admin@internal"),
password=dict(required=True, no_log=True),
server=dict(default="127.0.0.1"),
port=dict(default="443"),
insecure_api=dict(default=False, type='bool'),
name=dict(),
image=dict(default=False),
datacenter=dict(default="Default"),
type=dict(default="server", choices=['server', 'desktop', 'host']),
cluster=dict(default=''),
vmhost=dict(default=False),
vmcpu=dict(default="2"),
vmmem=dict(default="1"),
disks=dict(),
osver=dict(default="rhel_6x64"),
ifaces=dict(aliases=['nics', 'interfaces']),
timeout=dict(default=False),
mempol=dict(default="1"),
vm_ha=dict(default=True),
cpu_share=dict(default="0"),
boot_order=dict(default=["network", "hd"]),
del_prot=dict(default=True, type="bool"),
cd_drive=dict(default=False)
),
)
if not HAS_SDK:
module.fail_json(
msg='The `ovirtsdk` module is not importable. Check the requirements.'
)
rc = RHEV_SUCCESS
try:
rc, result = core(module)
except Exception as e:
module.fail_json(msg=str(e))
if rc != 0: # something went wrong emit the msg
module.fail_json(rc=rc, msg=result)
else:
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
diydrones/ardupilot | Tools/scripts/magfit_flashlog.py | 15 | 4730 | #!/usr/bin/env python
''' fit best estimate of magnetometer offsets from ArduCopter flashlog
using the algorithm from Bill Premerlani
'''
import sys
# command line option handling
from optparse import OptionParser
parser = OptionParser("magfit_flashlog.py [options]")
parser.add_option("--verbose", action='store_true', default=False, help="verbose offset output")
parser.add_option("--gain", type='float', default=0.01, help="algorithm gain")
parser.add_option("--noise", type='float', default=0, help="noise to add")
parser.add_option("--max-change", type='float', default=10, help="max step change")
parser.add_option("--min-diff", type='float', default=50, help="min mag vector delta")
parser.add_option("--history", type='int', default=20, help="how many points to keep")
parser.add_option("--repeat", type='int', default=1, help="number of repeats through the data")
(opts, args) = parser.parse_args()
from pymavlink.rotmat import Vector3
if len(args) < 1:
print("Usage: magfit_flashlog.py [options] <LOGFILE...>")
sys.exit(1)
def noise():
'''a noise vector'''
from random import gauss
v = Vector3(gauss(0, 1), gauss(0, 1), gauss(0, 1))
v.normalize()
return v * opts.noise
def find_offsets(data, ofs):
'''find mag offsets by applying Bills "offsets revisited" algorithm
on the data
This is an implementation of the algorithm from:
http://gentlenav.googlecode.com/files/MagnetometerOffsetNullingRevisited.pdf
'''
# a limit on the maximum change in each step
max_change = opts.max_change
# the gain factor for the algorithm
gain = opts.gain
data2 = []
for d in data:
d = d.copy() + noise()
d.x = float(int(d.x + 0.5))
d.y = float(int(d.y + 0.5))
d.z = float(int(d.z + 0.5))
data2.append(d)
data = data2
history_idx = 0
mag_history = data[0:opts.history]
for i in range(opts.history, len(data)):
B1 = mag_history[history_idx] + ofs
B2 = data[i] + ofs
diff = B2 - B1
diff_length = diff.length()
if diff_length <= opts.min_diff:
# the mag vector hasn't changed enough - we don't get any
# information from this
history_idx = (history_idx+1) % opts.history
continue
mag_history[history_idx] = data[i]
history_idx = (history_idx+1) % opts.history
# equation 6 of Bills paper
delta = diff * (gain * (B2.length() - B1.length()) / diff_length)
# limit the change from any one reading. This is to prevent
# single crazy readings from throwing off the offsets for a long
# time
delta_length = delta.length()
if max_change != 0 and delta_length > max_change:
delta *= max_change / delta_length
# set the new offsets
ofs = ofs - delta
if opts.verbose:
print(ofs)
return ofs
def plot_corrected_field(filename, data, offsets):
f = open(filename, mode='w')
for d in data:
corrected = d + offsets
f.write("%.1f\n" % corrected.length())
f.close()
def magfit(logfile):
'''find best magnetometer offset fit to a log file'''
print("Processing log %s" % filename)
# open the log file
flog = open(filename, mode='r')
data = []
data_no_motors = []
mag = None
offsets = None
# now gather all the data
for line in flog:
if not line.startswith('COMPASS,'):
continue
line = line.rstrip()
line = line.replace(' ', '')
a = line.split(',')
ofs = Vector3(float(a[4]), float(a[5]), float(a[6]))
if offsets is None:
initial_offsets = ofs
offsets = ofs
motor_ofs = Vector3(float(a[7]), float(a[8]), float(a[9]))
mag = Vector3(float(a[1]), float(a[2]), float(a[3]))
mag = mag - offsets
data.append(mag)
data_no_motors.append(mag - motor_ofs)
print("Extracted %u data points" % len(data))
print("Current offsets: %s" % initial_offsets)
# run the fitting algorithm
ofs = initial_offsets
for r in range(opts.repeat):
ofs = find_offsets(data, ofs)
plot_corrected_field('plot.dat', data, ofs)
plot_corrected_field('initial.dat', data, initial_offsets)
plot_corrected_field('zero.dat', data, Vector3(0,0,0))
plot_corrected_field('hand.dat', data, Vector3(-25,-8,-2))
plot_corrected_field('zero-no-motors.dat', data_no_motors, Vector3(0,0,0))
print('Loop %u offsets %s' % (r, ofs))
sys.stdout.flush()
print("New offsets: %s" % ofs)
total = 0.0
for filename in args:
magfit(filename)
| gpl-3.0 |
Nate-Devv/Tuxemon | tuxemon/core/components/event/actions/combat.py | 3 | 9008 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Tuxemon
# Copyright (C) 2014, William Edwards <shadowapex@gmail.com>
#
# This file is part of Tuxemon.
#
# Tuxemon 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.
#
# Tuxemon 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 Tuxemon. If not, see <http://www.gnu.org/licenses/>.
#
# Contributor(s):
#
# William Edwards <shadowapex@gmail.com>
#
import logging
import random
from yapsy.IPlugin import IPlugin
from core.components import ai
from core.components import db
from core.components import monster
from core.components import player
# Create a logger for optional handling of debug messages.
logger = logging.getLogger(__name__)
# Import the android mixer if on the android platform
try:
import pygame.mixer as mixer
except ImportError:
import android.mixer as mixer
class Combat(IPlugin):
def start_battle(self, game, action):
"""Start a battle and switch to the combat module. The parameters must contain an NPC id
in the NPC database.
:param game: The main game object that contains all the game's variables.
:param action: The action (tuple) retrieved from the database that contains the action's
parameters
:type game: core.tools.Control
:type action: Tuple
:rtype: None
:returns: None
Valid Parameters: npc_id
**Examples:**
>>> action
... (u'start_battle', u'1', 1, 9)
"""
# Don't start a battle if we don't even have monsters in our party yet.
if len(game.player1.monsters) < 1:
logger.warning("Cannot start battle, player has no monsters!")
return False
# Start combat
npc_id = int(action[1])
# Create an NPC object that will be used as our opponent
npc = player.Npc()
# Look up the NPC's details from our NPC database
npcs = db.JSONDatabase()
npcs.load("npc")
npc_details = npcs.database['npc'][npc_id]
# Set the NPC object with the details fetched from the database.
npc.name = npc_details['name']
# Set the NPC object's AI model.
npc.ai = ai.AI()
# Look up the NPC's monster party
npc_party = npc_details['monsters']
# Look up the monster's details
monsters = db.JSONDatabase()
monsters.load("monster")
# Look up each monster in the NPC's party
for npc_monster_details in npc_party:
results = monsters.database['monster'][npc_monster_details['monster_id']]
# Create a monster object for each monster the NPC has in their party.
current_monster = monster.Monster()
current_monster.name = npc_monster_details['name']
current_monster.monster_id = npc_monster_details['monster_id']
current_monster.level = npc_monster_details['level']
current_monster.hp = npc_monster_details['hp']
current_monster.current_hp = npc_monster_details['hp']
current_monster.attack = npc_monster_details['attack']
current_monster.defense = npc_monster_details['defense']
current_monster.speed = npc_monster_details['speed']
current_monster.special_attack = npc_monster_details['special_attack']
current_monster.special_defense = npc_monster_details['special_defense']
current_monster.experience_give_modifier = npc_monster_details['exp_give_mod']
current_monster.experience_required_modifier = npc_monster_details['exp_req_mod']
current_monster.type1 = results['types'][0]
if len(results['types']) > 1:
current_monster.type2 = results['types'][1]
current_monster.load_sprite_from_db()
pound = monster.Technique('Pound')
current_monster.learn(pound)
# Add our monster to the NPC's party
npc.monsters.append(current_monster)
# Add our players and start combat
game.state_dict["COMBAT"].players.append(game.player1)
game.state_dict["COMBAT"].players.append(npc)
game.state_dict["COMBAT"].combat_type = "trainer"
#game.state_dict["WORLD"].combat_started = True
game.state_dict["WORLD"].start_battle_transition = True
# Start some music!
logger.info("Playing battle music!")
filename = "147066_pokemon.ogg"
mixer.music.load("resources/music/" + filename)
mixer.music.play(-1)
def random_encounter(self, game, action):
"""Randomly starts a battle with a monster defined in the "encounter" table in the
"monster.db" database. The chance that this will start a battle depends on the
"encounter_rate" specified in the database. The "encounter_rate" number is the chance
walking in to this tile will trigger a battle out of 100.
:param game: The main game object that contains all the game's variables.
:param action: The action (tuple) retrieved from the database that contains the action's
parameters
:type game: core.tools.Control
:type action: Tuple
:rtype: None
:returns: None
Valid Parameters: encounter_id
"""
player1 = game.player1
# Don't start a battle if we don't even have monsters in our party yet.
if len(player1.monsters) < 1:
logger.warning("Cannot start battle, player has no monsters!")
return False
else:
if player1.monsters[0].current_hp <= 0:
logger.warning("Cannot start battle, player's monsters are all DEAD")
return False
# Get the parameters to determine what encounter group we'll look up in the database.
encounter_id = int(action[1])
# Look up the encounter details
monsters = db.JSONDatabase()
monsters.load("encounter")
monsters.load("monster")
# Keep an encounter variable that will let us know if we're going to start a battle.
encounter = None
# Get all the monsters associated with this encounter.
encounters = monsters.database['encounter'][encounter_id]['monsters']
for item in encounters:
# Perform a roll to see if this monster is going to start a battle.
roll = random.randrange(1,100)
rate = range(1, int(item['encounter_rate']) + 1)
if roll in rate:
# Set our encounter details
encounter = item
# If a random encounter was successfully rolled, look up the monster and start the
# battle.
if encounter:
logger.info("Start battle!")
# Create a monster object
current_monster = monster.Monster()
current_monster.load_from_db(encounter['monster_id'])
# Set the monster's level based on the specified level range
if len(encounter['level_range']) > 1:
level = random.randrange(encounter['level_range'][0], encounter['level_range'][1])
else:
level = encounter['level_range'][0]
# Set the monster's level
current_monster.level = level
# Create an NPC object which will be this monster's "trainer"
npc = player.Npc()
npc.monsters.append(current_monster)
# Set the NPC object's AI model.
npc.ai = ai.AI()
# Add our players and start combat
game.state_dict["COMBAT"].players.append(player1)
game.state_dict["COMBAT"].players.append(npc)
game.state_dict["COMBAT"].combat_type = "monster"
game.state_dict["WORLD"].start_battle_transition = True
# Start some music!
filename = "147066_pokemon.ogg"
mixer.music.load("resources/music/" + filename)
mixer.music.play(-1)
game.current_music["status"] = "playing"
game.current_music["song"] = filename
# Stop the player's movement
game.state_dict["WORLD"].menu_blocking = True
player1.moving = False
player1.direction = {'down': False, 'left': False, 'right': False, 'up': False}
| gpl-3.0 |
peterfpeterson/mantid | scripts/test/SANS/state/move_test.py | 3 | 7671 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source,
# Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
# SPDX - License - Identifier: GPL - 3.0 +
import unittest
from unittest import mock
from sans.common.enums import (CanonicalCoordinates, SANSFacility, DetectorType, SANSInstrument)
from sans.state.StateObjects.StateData import get_data_builder
from sans.state.StateObjects.StateMoveDetectors import (StateMoveLOQ, StateMoveSANS2D, StateMoveLARMOR, StateMoveZOOM, StateMove,
StateMoveDetectors, get_move_builder)
from sans.test_helper.file_information_mock import SANSFileInformationMock
# ----------------------------------------------------------------------------------------------------------------------
# State
# ----------------------------------------------------------------------------------------------------------------------
class StateMoveWorkspaceTest(unittest.TestCase):
def test_that_general_isis_default_values_are_set_up(self):
state = StateMove()
state.detectors = {DetectorType.LAB.value: StateMoveDetectors(),
DetectorType.HAB.value: StateMoveDetectors()}
self.assertEqual(state.sample_offset, 0.0)
self.assertEqual(state.sample_offset_direction, CanonicalCoordinates.Z)
self.assertEqual(state.detectors[DetectorType.HAB.value].x_translation_correction, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].y_translation_correction, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].z_translation_correction, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].rotation_correction, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].side_correction, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].radius_correction, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].x_tilt_correction, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].y_tilt_correction, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].z_tilt_correction, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].sample_centre_pos1, 0.0)
self.assertEqual(state.detectors[DetectorType.HAB.value].sample_centre_pos2, 0.0)
class StateMoveWorkspaceLOQTest(unittest.TestCase):
def test_that_is_sans_state_move_object(self):
state = StateMoveLOQ()
self.assertTrue(isinstance(state, StateMove))
def test_that_LOQ_has_centre_position_set_up(self):
state = StateMoveLOQ()
self.assertEqual(state.center_position, 317.5 / 1000.)
class StateMoveWorkspaceSANS2DTest(unittest.TestCase):
def test_that_is_sans_state_data_object(self):
state = StateMoveSANS2D()
self.assertTrue(isinstance(state, StateMove))
def test_that_sans2d_has_default_values_set_up(self):
# Arrange
state = StateMoveSANS2D()
self.assertEqual(state.hab_detector_radius, 306.0/1000.)
self.assertEqual(state.hab_detector_default_sd_m, 4.0)
self.assertEqual(state.hab_detector_default_x_m, 1.1)
self.assertEqual(state.lab_detector_default_sd_m, 4.0)
self.assertEqual(state.hab_detector_x, 0.0)
self.assertEqual(state.hab_detector_z, 0.0)
self.assertEqual(state.hab_detector_rotation, 0.0)
self.assertEqual(state.lab_detector_x, 0.0)
self.assertEqual(state.lab_detector_z, 0.0)
self.assertEqual(state.monitor_4_offset, 0.0)
class StateMoveWorkspaceLARMORTest(unittest.TestCase):
def test_that_is_sans_state_data_object(self):
state = StateMoveLARMOR()
self.assertTrue(isinstance(state, StateMove))
def test_that_can_set_and_get_values(self):
state = StateMoveLARMOR()
self.assertEqual(state.bench_rotation, 0.0)
class StateMoveWorkspaceZOOMTest(unittest.TestCase):
def test_that_is_sans_state_data_object(self):
state = StateMoveZOOM()
self.assertTrue(isinstance(state, StateMove))
def test_that_can_set_and_get_values(self):
state = StateMoveZOOM()
self.assertEqual(len(state.detectors), 1)
# ----------------------------------------------------------------------------------------------------------------------
# Builder
# ----------------------------------------------------------------------------------------------------------------------
class StateMoveBuilderTest(unittest.TestCase):
def test_that_state_for_loq_can_be_built(self):
facility = SANSFacility.ISIS
file_information = SANSFileInformationMock(instrument=SANSInstrument.LOQ, run_number=74044)
data_builder = get_data_builder(facility, file_information)
data_builder.set_sample_scatter("LOQ74044")
data_builder.set_sample_scatter_period(3)
data_info = data_builder.build()
# Act
builder = get_move_builder(data_info)
self.assertTrue(builder)
value = 324.2
builder.set_center_position(value)
builder.set_HAB_x_translation_correction(value)
builder.set_LAB_sample_centre_pos1(value)
# Assert
state = builder.build()
self.assertEqual(state.center_position, value)
self.assertEqual(state.detectors[DetectorType.HAB.value].x_translation_correction, value)
self.assertEqual(state.detectors[DetectorType.LAB.value].sample_centre_pos1, value)
def test_that_state_for_sans2d_can_be_built(self):
# Arrange
facility = SANSFacility.ISIS
file_information = SANSFileInformationMock(instrument=SANSInstrument.SANS2D, run_number=22048)
data_builder = get_data_builder(facility, file_information)
data_builder.set_sample_scatter("SANS2D00022048")
data_info = data_builder.build()
# Act
builder = get_move_builder(data_info)
self.assertTrue(builder)
value = 324.2
builder.set_HAB_x_translation_correction(value)
# Assert
state = builder.build()
self.assertEqual(state.detectors[DetectorType.HAB.value].x_translation_correction, value)
def test_state_with_no_file_info_can_be_built(self):
data_info = mock.NonCallableMock()
data_info.instrument = SANSInstrument.LARMOR
data_info.idf_file_path = None
data_info.ipf_file_path = None
# This will happen if the user has not selected a run number
data_info.sample_scatter_run_number = None
builder = get_move_builder(data_info)
self.assertEqual(1., builder.conversion_value)
def test_that_state_for_larmor_can_be_built(self):
# Arrange
facility = SANSFacility.ISIS
file_information = SANSFileInformationMock(instrument=SANSInstrument.LARMOR, run_number=2260)
data_builder = get_data_builder(facility, file_information)
data_builder.set_sample_scatter("LARMOR00002260")
data_info = data_builder.build()
# Act
builder = get_move_builder(data_info)
self.assertTrue(builder)
value = 324.2
builder.set_LAB_x_translation_correction(value)
# Assert
state = builder.build()
self.assertEqual(state.detectors[DetectorType.LAB.value].x_translation_correction, value)
def test_that_state_for_zoom_can_be_built(self):
# TODO when data becomes available
pass
if __name__ == '__main__':
unittest.main()
| gpl-3.0 |
AMOboxTV/AMOBox.LegoBuild | script.module.youtube.dl/lib/youtube_dl/extractor/addanime.py | 117 | 3269 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_HTTPError,
compat_str,
compat_urllib_parse,
compat_urllib_parse_urlparse,
)
from ..utils import (
ExtractorError,
qualities,
)
class AddAnimeIE(InfoExtractor):
_VALID_URL = r'http://(?:\w+\.)?add-anime\.net/(?:watch_video\.php\?(?:.*?)v=|video/)(?P<id>[\w_]+)'
_TESTS = [{
'url': 'http://www.add-anime.net/watch_video.php?v=24MR3YO5SAS9',
'md5': '72954ea10bc979ab5e2eb288b21425a0',
'info_dict': {
'id': '24MR3YO5SAS9',
'ext': 'mp4',
'description': 'One Piece 606',
'title': 'One Piece 606',
}
}, {
'url': 'http://add-anime.net/video/MDUGWYKNGBD8/One-Piece-687',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
try:
webpage = self._download_webpage(url, video_id)
except ExtractorError as ee:
if not isinstance(ee.cause, compat_HTTPError) or \
ee.cause.code != 503:
raise
redir_webpage = ee.cause.read().decode('utf-8')
action = self._search_regex(
r'<form id="challenge-form" action="([^"]+)"',
redir_webpage, 'Redirect form')
vc = self._search_regex(
r'<input type="hidden" name="jschl_vc" value="([^"]+)"/>',
redir_webpage, 'redirect vc value')
av = re.search(
r'a\.value = ([0-9]+)[+]([0-9]+)[*]([0-9]+);',
redir_webpage)
if av is None:
raise ExtractorError('Cannot find redirect math task')
av_res = int(av.group(1)) + int(av.group(2)) * int(av.group(3))
parsed_url = compat_urllib_parse_urlparse(url)
av_val = av_res + len(parsed_url.netloc)
confirm_url = (
parsed_url.scheme + '://' + parsed_url.netloc +
action + '?' +
compat_urllib_parse.urlencode({
'jschl_vc': vc, 'jschl_answer': compat_str(av_val)}))
self._download_webpage(
confirm_url, video_id,
note='Confirming after redirect')
webpage = self._download_webpage(url, video_id)
FORMATS = ('normal', 'hq')
quality = qualities(FORMATS)
formats = []
for format_id in FORMATS:
rex = r"var %s_video_file = '(.*?)';" % re.escape(format_id)
video_url = self._search_regex(rex, webpage, 'video file URLx',
fatal=False)
if not video_url:
continue
formats.append({
'format_id': format_id,
'url': video_url,
'quality': quality(format_id),
})
self._sort_formats(formats)
video_title = self._og_search_title(webpage)
video_description = self._og_search_description(webpage)
return {
'_type': 'video',
'id': video_id,
'formats': formats,
'title': video_title,
'description': video_description
}
| gpl-2.0 |
OSSystems/lava-server | lava_scheduler_app/utils.py | 1 | 15102 | # Copyright (C) 2013 Linaro Limited
#
# Author: Neil Williams <neil.williams@linaro.org>
# Senthil Kumaran <senthil.kumaran@linaro.org>
#
# This file is part of LAVA Scheduler.
#
# LAVA Scheduler is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License version 3 as
# published by the Free Software Foundation
#
# LAVA Scheduler 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 Affero General Public License
# along with LAVA Scheduler. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import copy
import uuid
import socket
import urlparse
import simplejson
import models
import subprocess
import datetime
from collections import OrderedDict
from django.contrib.sites.models import Site
from lava_server.settings.getsettings import Settings
from lava_server.settings.config_file import ConfigFile
def rewrite_hostname(result_url):
"""If URL has hostname value as localhost/127.0.0.*, change it to the
actual server FQDN.
Returns the RESULT_URL (string) re-written with hostname.
See https://cards.linaro.org/browse/LAVA-611
"""
domain = socket.getfqdn()
try:
site = Site.objects.get_current()
except (Site.DoesNotExist, ImproperlyConfigured):
pass
else:
domain = site.domain
if domain == 'example.com' or domain == 'www.example.com':
domain = get_ip_address()
host = urlparse.urlparse(result_url).netloc
if host == "localhost":
result_url = result_url.replace("localhost", domain)
elif host.startswith("127.0.0"):
ip_pat = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
result_url = re.sub(ip_pat, domain, result_url)
return result_url
def split_multi_job(json_jobdata, target_group):
node_json = {}
all_nodes = {}
node_actions = {}
node_lmp = {}
# Check if we are operating on multinode job data. Else return the job
# data as it is.
if "device_group" in json_jobdata and target_group:
pass
else:
return json_jobdata
# get all the roles and create node action list for each role.
for group in json_jobdata["device_group"]:
node_actions[group["role"]] = []
node_lmp[group["role"]] = []
# Take each action and assign it to proper roles. If roles are not
# specified for a specific action, then assign it to all the roles.
all_actions = json_jobdata["actions"]
for role in node_actions.keys():
for action in all_actions:
new_action = copy.deepcopy(action)
if 'parameters' in new_action \
and 'role' in new_action["parameters"]:
if new_action["parameters"]["role"] == role:
new_action["parameters"].pop('role', None)
node_actions[role].append(new_action)
else:
node_actions[role].append(new_action)
if "lmp_module" in json_jobdata:
# For LMP init in multinode case
all_lmp_modules = json_jobdata["lmp_module"]
for role in node_lmp.keys():
for lmp in all_lmp_modules:
new_lmp = copy.deepcopy(lmp)
if 'parameters' in new_lmp \
and 'role' in new_lmp["parameters"]:
if new_lmp["parameters"]["role"] == role:
new_lmp["parameters"].pop('role', None)
node_lmp[role].append(new_lmp)
else:
node_lmp[role].append(new_lmp)
group_count = 0
for clients in json_jobdata["device_group"]:
group_count += int(clients["count"])
if group_count <= 1:
raise models.JSONDataError("Only one device requested in a MultiNode job submission.")
for clients in json_jobdata["device_group"]:
role = str(clients["role"])
count = int(clients["count"])
node_json[role] = []
for c in range(0, count):
node_json[role].append({})
node_json[role][c]["timeout"] = json_jobdata["timeout"]
if json_jobdata.get("job_name", False):
node_json[role][c]["job_name"] = json_jobdata["job_name"]
if clients.get("tags", False):
node_json[role][c]["tags"] = clients["tags"]
node_json[role][c]["group_size"] = group_count
node_json[role][c]["target_group"] = target_group
node_json[role][c]["actions"] = node_actions[role]
if "lmp_module" in json_jobdata:
node_json[role][c]["lmp_module"] = node_lmp[role]
node_json[role][c]["role"] = role
# multinode node stage 2
if json_jobdata.get("logging_level", False):
node_json[role][c]["logging_level"] = \
json_jobdata["logging_level"]
if json_jobdata.get("priority", False):
node_json[role][c]["priority"] = json_jobdata["priority"]
node_json[role][c]["device_type"] = clients["device_type"]
return node_json
def split_vm_job(json_jobdata, vm_group):
node_json = {}
all_nodes = {}
node_actions = {}
vms_list = []
# Check if we are operating on vm_group job data. Else return the job
# data as it is.
if "vm_group" in json_jobdata and vm_group:
pass
else:
raise Exception('Invalid vm_group data')
# Get the VM host details.
device_type = json_jobdata['vm_group']['host']['device_type']
role = json_jobdata['vm_group']['host']['role']
is_vmhost = True
vms_list.append((device_type, role, 1, is_vmhost)) # where 1 is the count
# Get all other constituting VMs.
for vm in json_jobdata['vm_group']['vms']:
device_type = vm['device_type']
count = int(vm.get('count', 1))
role = vm.get('role', None)
is_vmhost = False
vms_list.append((device_type, role, count, is_vmhost))
# get all the roles and create node action list for each role.
for vm in vms_list:
node_actions[vm[1]] = []
# Take each action and assign it to proper roles. If roles are not
# specified for a specific action, then assign it to all the roles.
all_actions = json_jobdata["actions"]
for role in node_actions.keys():
for action in all_actions:
new_action = copy.deepcopy(action)
if 'parameters' in new_action \
and 'role' in new_action["parameters"]:
if new_action["parameters"]["role"] == role:
new_action["parameters"].pop('role', None)
node_actions[role].append(new_action)
else:
node_actions[role].append(new_action)
group_count = 0
for vm in vms_list:
group_count += int(vm[2])
group_counter = group_count
for vm in vms_list:
role = vm[1]
count = int(vm[2])
node_json[role] = []
is_vmhost = vm[3]
for c in range(0, count):
node_json[role].append({})
node_json[role][c]["timeout"] = json_jobdata["timeout"]
node_json[role][c]["is_vmhost"] = is_vmhost
if json_jobdata.get("job_name", False):
node_json[role][c]["job_name"] = json_jobdata["job_name"]
node_json[role][c]["group_size"] = group_count
node_json[role][c]["target_group"] = vm_group
node_json[role][c]["actions"] = node_actions[role]
node_json[role][c]["role"] = role
# vm_group node stage 2
if json_jobdata.get("logging_level", False):
node_json[role][c]["logging_level"] = \
json_jobdata["logging_level"]
if json_jobdata.get("priority", False):
node_json[role][c]["priority"] = json_jobdata["priority"]
if is_vmhost:
node_json[role][c]["device_type"] = vm[0]
else:
node_json[role][c]["device_type"] = "dynamic-vm"
node_json[role][c]["config"] = {
"device_type": "dynamic-vm",
"dynamic_vm_backend_device_type": vm[0],
}
node_json[role][c]["target"] = 'vm%d' % group_counter
group_counter -= 1
return node_json
def is_master():
"""Checks if the current machine is the master.
"""
worker_config_path = '/etc/lava-server/worker.conf'
if "VIRTUAL_ENV" in os.environ:
worker_config_path = os.path.join(os.environ["VIRTUAL_ENV"],
worker_config_path[1:])
return not os.path.exists(worker_config_path)
def get_uptime():
"""Return the system uptime string.
"""
with open('/proc/uptime', 'r') as f:
uptime_seconds = float(f.readline().split()[0])
uptime = str(datetime.timedelta(seconds=uptime_seconds))
return uptime
def get_lshw_out():
"""Return the output of lshw command in html format.
"""
lshw_cmd = "lshw -html"
proc = subprocess.Popen(lshw_cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lshw_out, lshw_err = proc.communicate()
return simplejson.dumps(lshw_out)
def get_fqdn():
"""Returns the fully qualified domain name.
"""
return socket.getfqdn()
def get_ip_address():
"""Returns the IP address.
"""
return socket.gethostbyname_ex(socket.getfqdn())[2][0]
def format_sw_info_to_html(data_dict):
"""Formats the given software info DATA_DICT to viewable html.
"""
ordered_data_dict = OrderedDict(sorted(data_dict.items()))
html_content = '<table>\n'
html_content += '<tr>\n<th>Software</th>\n<th>Information</th>\n</tr>\n'
for k, v in ordered_data_dict.iteritems():
html_content += '<tr>\n<td>%s</td>\n<td>%s</td>\n</tr>\n' % (k, v)
return html_content
def installed_packages(prefix=None, package_name=None):
"""Queries dpkg and filters packages that are related to PACKAGE_NAME.
PREFIX is the installation prefix for the given instance ie.,
'/srv/lava/instances/<instance_name>/' which is used for finding out the
installed package via the python environment.
Returns a dictionary of packages where the key is the package and the value
is the package version.
"""
packages = {}
if package_name:
package_cmd = "dpkg -l | grep %s" % package_name
proc = subprocess.Popen(package_cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
package_out, package_err = proc.communicate()
pack_re = re.compile("ii\s+(?P<package>\S+)\s+(?P<version>\S+)\s+.*",
re.MULTILINE)
for package in pack_re.findall(package_out):
packages[package[0]] = package[1]
# Find packages via the python environment for this instance.
if prefix:
python_path = os.path.join(prefix, 'bin/python')
cmd = "grep exports %s" % python_path
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate()
# The output of the command looks like the following, which is a
# string, we process this string to populate the package dictionary.
#
# '/srv/lava/.cache/git-cache/exports/lava-android-test/2013.12',
# '/srv/lava/.cache/git-cache/exports/linaro-dashboard-bundle/2013.12',
if out:
out = out.replace("'", '')
for path in out.split(','):
path = path.strip()
if path:
path = path.replace("'", '')
key = os.path.basename(os.path.dirname(path))
value = os.path.basename(path)
packages[key] = value
return packages
def local_diffstat(prefix):
"""If there are local build outs available. Get the diffstat of the same.
PREFIX is the directory to search for local build outs.
Returns a dictionary of diffstat where the key is the package and the value
is the diffstat output.
"""
diffstat = {}
local_buildout_path = os.path.join(prefix, 'code/current/local')
for d in os.listdir(local_buildout_path):
diffstat_cmd = "cd %s; git diff | diffstat;" % \
os.path.join(local_buildout_path, d)
proc = subprocess.Popen(diffstat_cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
diffstat_out, diffstat_err = proc.communicate()
if diffstat_out:
diffstat_out = '<br />'.join(diffstat_out.split('\n'))
diffstat[d + '-local-buildout'] = diffstat_out
else:
diffstat[d + '-local-buildout'] = diffstat_err
return diffstat
def get_software_info():
"""Returns git status and version information for LAVA related software.
"""
sw_info = {}
# Populate the git status of server code from exports directory.
settings = Settings("lava-server")
instance_config_path = settings._get_pathname("instance")
instance_config = ConfigFile.load(instance_config_path)
prefix = os.path.join(instance_config.LAVA_PREFIX,
instance_config.LAVA_INSTANCE)
# Populate installed packages.
sw_info.update(installed_packages(package_name='lava'))
sw_info.update(installed_packages(package_name='linaro'))
sw_info.update(installed_packages(prefix=prefix))
# Summary of local build outs, if any.
if instance_config.LAVA_DEV_MODE == 'yes':
sw_info.update(local_diffstat(prefix))
return simplejson.dumps(format_sw_info_to_html(sw_info))
def get_heartbeat_timeout():
"""Returns the HEARTBEAT_TIMEOUT value specified in worker.conf
If there is no value found, we return a default timeout value 300.
"""
settings = Settings("lava-server")
worker_config_path = settings._get_pathname("worker")
try:
worker_config = ConfigFile.load(worker_config_path)
if worker_config and worker_config.HEARTBEAT_TIMEOUT != '':
return int(worker_config.HEARTBEAT_TIMEOUT)
else:
return 300
except (IOError, AttributeError):
return 300
# Private variable to record scheduler tick, which shouldn't be accessed from
# other modules, except via the following APIs.
__last_scheduler_tick = datetime.datetime.utcnow()
def record_scheduler_tick():
"""Records the scheduler tick timestamp in the global variable
__last_scheduler_tick
"""
global __last_scheduler_tick
__last_scheduler_tick = datetime.datetime.utcnow()
def last_scheduler_tick():
"""Returns datetime.dateime object of last scheduler tick timestamp.
"""
return __last_scheduler_tick
| agpl-3.0 |
BanBxda/Sense_5.5-JB-M7 | tools/perf/util/setup.py | 4998 | 1330 | #!/usr/bin/python2
from distutils.core import setup, Extension
from os import getenv
from distutils.command.build_ext import build_ext as _build_ext
from distutils.command.install_lib import install_lib as _install_lib
class build_ext(_build_ext):
def finalize_options(self):
_build_ext.finalize_options(self)
self.build_lib = build_lib
self.build_temp = build_tmp
class install_lib(_install_lib):
def finalize_options(self):
_install_lib.finalize_options(self)
self.build_dir = build_lib
cflags = ['-fno-strict-aliasing', '-Wno-write-strings']
cflags += getenv('CFLAGS', '').split()
build_lib = getenv('PYTHON_EXTBUILD_LIB')
build_tmp = getenv('PYTHON_EXTBUILD_TMP')
ext_sources = [f.strip() for f in file('util/python-ext-sources')
if len(f.strip()) > 0 and f[0] != '#']
perf = Extension('perf',
sources = ext_sources,
include_dirs = ['util/include'],
extra_compile_args = cflags,
)
setup(name='perf',
version='0.1',
description='Interface with the Linux profiling infrastructure',
author='Arnaldo Carvalho de Melo',
author_email='acme@redhat.com',
license='GPLv2',
url='http://perf.wiki.kernel.org',
ext_modules=[perf],
cmdclass={'build_ext': build_ext, 'install_lib': install_lib})
| gpl-2.0 |
Weihonghao/ECM | Vpy34/lib/python3.5/site-packages/numpy/lib/tests/test_type_check.py | 9 | 11493 | from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.compat import long
from numpy.testing import (
TestCase, assert_, assert_equal, assert_array_equal, run_module_suite
)
from numpy.lib.type_check import (
common_type, mintypecode, isreal, iscomplex, isposinf, isneginf,
nan_to_num, isrealobj, iscomplexobj, asfarray, real_if_close
)
def assert_all(x):
assert_(np.all(x), x)
class TestCommonType(TestCase):
def test_basic(self):
ai32 = np.array([[1, 2], [3, 4]], dtype=np.int32)
af16 = np.array([[1, 2], [3, 4]], dtype=np.float16)
af32 = np.array([[1, 2], [3, 4]], dtype=np.float32)
af64 = np.array([[1, 2], [3, 4]], dtype=np.float64)
acs = np.array([[1+5j, 2+6j], [3+7j, 4+8j]], dtype=np.csingle)
acd = np.array([[1+5j, 2+6j], [3+7j, 4+8j]], dtype=np.cdouble)
assert_(common_type(ai32) == np.float64)
assert_(common_type(af16) == np.float16)
assert_(common_type(af32) == np.float32)
assert_(common_type(af64) == np.float64)
assert_(common_type(acs) == np.csingle)
assert_(common_type(acd) == np.cdouble)
class TestMintypecode(TestCase):
def test_default_1(self):
for itype in '1bcsuwil':
assert_equal(mintypecode(itype), 'd')
assert_equal(mintypecode('f'), 'f')
assert_equal(mintypecode('d'), 'd')
assert_equal(mintypecode('F'), 'F')
assert_equal(mintypecode('D'), 'D')
def test_default_2(self):
for itype in '1bcsuwil':
assert_equal(mintypecode(itype+'f'), 'f')
assert_equal(mintypecode(itype+'d'), 'd')
assert_equal(mintypecode(itype+'F'), 'F')
assert_equal(mintypecode(itype+'D'), 'D')
assert_equal(mintypecode('ff'), 'f')
assert_equal(mintypecode('fd'), 'd')
assert_equal(mintypecode('fF'), 'F')
assert_equal(mintypecode('fD'), 'D')
assert_equal(mintypecode('df'), 'd')
assert_equal(mintypecode('dd'), 'd')
#assert_equal(mintypecode('dF',savespace=1),'F')
assert_equal(mintypecode('dF'), 'D')
assert_equal(mintypecode('dD'), 'D')
assert_equal(mintypecode('Ff'), 'F')
#assert_equal(mintypecode('Fd',savespace=1),'F')
assert_equal(mintypecode('Fd'), 'D')
assert_equal(mintypecode('FF'), 'F')
assert_equal(mintypecode('FD'), 'D')
assert_equal(mintypecode('Df'), 'D')
assert_equal(mintypecode('Dd'), 'D')
assert_equal(mintypecode('DF'), 'D')
assert_equal(mintypecode('DD'), 'D')
def test_default_3(self):
assert_equal(mintypecode('fdF'), 'D')
#assert_equal(mintypecode('fdF',savespace=1),'F')
assert_equal(mintypecode('fdD'), 'D')
assert_equal(mintypecode('fFD'), 'D')
assert_equal(mintypecode('dFD'), 'D')
assert_equal(mintypecode('ifd'), 'd')
assert_equal(mintypecode('ifF'), 'F')
assert_equal(mintypecode('ifD'), 'D')
assert_equal(mintypecode('idF'), 'D')
#assert_equal(mintypecode('idF',savespace=1),'F')
assert_equal(mintypecode('idD'), 'D')
class TestIsscalar(TestCase):
def test_basic(self):
assert_(np.isscalar(3))
assert_(not np.isscalar([3]))
assert_(not np.isscalar((3,)))
assert_(np.isscalar(3j))
assert_(np.isscalar(long(10)))
assert_(np.isscalar(4.0))
class TestReal(TestCase):
def test_real(self):
y = np.random.rand(10,)
assert_array_equal(y, np.real(y))
def test_cmplx(self):
y = np.random.rand(10,)+1j*np.random.rand(10,)
assert_array_equal(y.real, np.real(y))
class TestImag(TestCase):
def test_real(self):
y = np.random.rand(10,)
assert_array_equal(0, np.imag(y))
def test_cmplx(self):
y = np.random.rand(10,)+1j*np.random.rand(10,)
assert_array_equal(y.imag, np.imag(y))
class TestIscomplex(TestCase):
def test_fail(self):
z = np.array([-1, 0, 1])
res = iscomplex(z)
assert_(not np.sometrue(res, axis=0))
def test_pass(self):
z = np.array([-1j, 1, 0])
res = iscomplex(z)
assert_array_equal(res, [1, 0, 0])
class TestIsreal(TestCase):
def test_pass(self):
z = np.array([-1, 0, 1j])
res = isreal(z)
assert_array_equal(res, [1, 1, 0])
def test_fail(self):
z = np.array([-1j, 1, 0])
res = isreal(z)
assert_array_equal(res, [0, 1, 1])
class TestIscomplexobj(TestCase):
def test_basic(self):
z = np.array([-1, 0, 1])
assert_(not iscomplexobj(z))
z = np.array([-1j, 0, -1])
assert_(iscomplexobj(z))
def test_scalar(self):
assert_(not iscomplexobj(1.0))
assert_(iscomplexobj(1+0j))
def test_list(self):
assert_(iscomplexobj([3, 1+0j, True]))
assert_(not iscomplexobj([3, 1, True]))
def test_duck(self):
class DummyComplexArray:
@property
def dtype(self):
return np.dtype(complex)
dummy = DummyComplexArray()
assert_(iscomplexobj(dummy))
def test_pandas_duck(self):
# This tests a custom np.dtype duck-typed class, such as used by pandas
# (pandas.core.dtypes)
class PdComplex(np.complex128):
pass
class PdDtype(object):
name = 'category'
names = None
type = PdComplex
kind = 'c'
str = '<c16'
base = np.dtype('complex128')
class DummyPd:
@property
def dtype(self):
return PdDtype
dummy = DummyPd()
assert_(iscomplexobj(dummy))
def test_custom_dtype_duck(self):
class MyArray(list):
@property
def dtype(self):
return complex
a = MyArray([1+0j, 2+0j, 3+0j])
assert_(iscomplexobj(a))
class TestIsrealobj(TestCase):
def test_basic(self):
z = np.array([-1, 0, 1])
assert_(isrealobj(z))
z = np.array([-1j, 0, -1])
assert_(not isrealobj(z))
class TestIsnan(TestCase):
def test_goodvalues(self):
z = np.array((-1., 0., 1.))
res = np.isnan(z) == 0
assert_all(np.all(res, axis=0))
def test_posinf(self):
with np.errstate(divide='ignore'):
assert_all(np.isnan(np.array((1.,))/0.) == 0)
def test_neginf(self):
with np.errstate(divide='ignore'):
assert_all(np.isnan(np.array((-1.,))/0.) == 0)
def test_ind(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isnan(np.array((0.,))/0.) == 1)
def test_integer(self):
assert_all(np.isnan(1) == 0)
def test_complex(self):
assert_all(np.isnan(1+1j) == 0)
def test_complex1(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isnan(np.array(0+0j)/0.) == 1)
class TestIsfinite(TestCase):
# Fixme, wrong place, isfinite now ufunc
def test_goodvalues(self):
z = np.array((-1., 0., 1.))
res = np.isfinite(z) == 1
assert_all(np.all(res, axis=0))
def test_posinf(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isfinite(np.array((1.,))/0.) == 0)
def test_neginf(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isfinite(np.array((-1.,))/0.) == 0)
def test_ind(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isfinite(np.array((0.,))/0.) == 0)
def test_integer(self):
assert_all(np.isfinite(1) == 1)
def test_complex(self):
assert_all(np.isfinite(1+1j) == 1)
def test_complex1(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isfinite(np.array(1+1j)/0.) == 0)
class TestIsinf(TestCase):
# Fixme, wrong place, isinf now ufunc
def test_goodvalues(self):
z = np.array((-1., 0., 1.))
res = np.isinf(z) == 0
assert_all(np.all(res, axis=0))
def test_posinf(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isinf(np.array((1.,))/0.) == 1)
def test_posinf_scalar(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isinf(np.array(1.,)/0.) == 1)
def test_neginf(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isinf(np.array((-1.,))/0.) == 1)
def test_neginf_scalar(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isinf(np.array(-1.)/0.) == 1)
def test_ind(self):
with np.errstate(divide='ignore', invalid='ignore'):
assert_all(np.isinf(np.array((0.,))/0.) == 0)
class TestIsposinf(TestCase):
def test_generic(self):
with np.errstate(divide='ignore', invalid='ignore'):
vals = isposinf(np.array((-1., 0, 1))/0.)
assert_(vals[0] == 0)
assert_(vals[1] == 0)
assert_(vals[2] == 1)
class TestIsneginf(TestCase):
def test_generic(self):
with np.errstate(divide='ignore', invalid='ignore'):
vals = isneginf(np.array((-1., 0, 1))/0.)
assert_(vals[0] == 1)
assert_(vals[1] == 0)
assert_(vals[2] == 0)
class TestNanToNum(TestCase):
def test_generic(self):
with np.errstate(divide='ignore', invalid='ignore'):
vals = nan_to_num(np.array((-1., 0, 1))/0.)
assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0]))
assert_(vals[1] == 0)
assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2]))
def test_integer(self):
vals = nan_to_num(1)
assert_all(vals == 1)
vals = nan_to_num([1])
assert_array_equal(vals, np.array([1], np.int))
def test_complex_good(self):
vals = nan_to_num(1+1j)
assert_all(vals == 1+1j)
def test_complex_bad(self):
with np.errstate(divide='ignore', invalid='ignore'):
v = 1 + 1j
v += np.array(0+1.j)/0.
vals = nan_to_num(v)
# !! This is actually (unexpectedly) zero
assert_all(np.isfinite(vals))
def test_complex_bad2(self):
with np.errstate(divide='ignore', invalid='ignore'):
v = 1 + 1j
v += np.array(-1+1.j)/0.
vals = nan_to_num(v)
assert_all(np.isfinite(vals))
# Fixme
#assert_all(vals.imag > 1e10) and assert_all(np.isfinite(vals))
# !! This is actually (unexpectedly) positive
# !! inf. Comment out for now, and see if it
# !! changes
#assert_all(vals.real < -1e10) and assert_all(np.isfinite(vals))
class TestRealIfClose(TestCase):
def test_basic(self):
a = np.random.rand(10)
b = real_if_close(a+1e-15j)
assert_all(isrealobj(b))
assert_array_equal(a, b)
b = real_if_close(a+1e-7j)
assert_all(iscomplexobj(b))
b = real_if_close(a+1e-7j, tol=1e-6)
assert_all(isrealobj(b))
class TestArrayConversion(TestCase):
def test_asfarray(self):
a = asfarray(np.array([1, 2, 3]))
assert_equal(a.__class__, np.ndarray)
assert_(np.issubdtype(a.dtype, np.float))
if __name__ == "__main__":
run_module_suite()
| agpl-3.0 |
sorenk/ansible | lib/ansible/plugins/action/unarchive.py | 19 | 5228 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2013, Dylan Martin <dmartin@seattlecentral.edu>
#
# 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 __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.errors import AnsibleError, AnsibleAction, AnsibleActionFail, AnsibleActionSkip
from ansible.module_utils._text import to_text
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
TRANSFERS_FILES = True
def run(self, tmp=None, task_vars=None):
''' handler for unarchive operations '''
if task_vars is None:
task_vars = dict()
result = super(ActionModule, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect
source = self._task.args.get('src', None)
dest = self._task.args.get('dest', None)
remote_src = boolean(self._task.args.get('remote_src', False), strict=False)
creates = self._task.args.get('creates', None)
decrypt = self._task.args.get('decrypt', True)
try:
# "copy" is deprecated in favor of "remote_src".
if 'copy' in self._task.args:
# They are mutually exclusive.
if 'remote_src' in self._task.args:
raise AnsibleActionFail("parameters are mutually exclusive: ('copy', 'remote_src')")
# We will take the information from copy and store it in
# the remote_src var to use later in this file.
self._task.args['remote_src'] = remote_src = not boolean(self._task.args.pop('copy'), strict=False)
if source is None or dest is None:
raise AnsibleActionFail("src (or content) and dest are required")
if creates:
# do not run the command if the line contains creates=filename
# and the filename already exists. This allows idempotence
# of command executions.
creates = self._remote_expand_user(creates)
if self._remote_file_exists(creates):
raise AnsibleActionSkip("skipped, since %s exists" % creates)
dest = self._remote_expand_user(dest) # CCTODO: Fix path for Windows hosts.
source = os.path.expanduser(source)
if not remote_src:
try:
source = self._loader.get_real_file(self._find_needle('files', source), decrypt=decrypt)
except AnsibleError as e:
raise AnsibleActionFail(to_text(e))
try:
remote_stat = self._execute_remote_stat(dest, all_vars=task_vars, follow=True)
except AnsibleError as e:
raise AnsibleActionFail(to_text(e))
if not remote_stat['exists'] or not remote_stat['isdir']:
raise AnsibleActionFail("dest '%s' must be an existing dir" % dest)
if not remote_src:
# transfer the file to a remote tmp location
tmp_src = self._connection._shell.join_path(self._connection._shell.tmpdir, 'source')
self._transfer_file(source, tmp_src)
# handle diff mode client side
# handle check mode client side
if not remote_src:
# fix file permissions when the copy is done as a different user
self._fixup_perms2((self._connection._shell.tmpdir, tmp_src))
# Build temporary module_args.
new_module_args = self._task.args.copy()
new_module_args.update(
dict(
src=tmp_src,
original_basename=os.path.basename(source),
),
)
else:
new_module_args = self._task.args.copy()
new_module_args.update(
dict(
original_basename=os.path.basename(source),
),
)
# remove action plugin only key
for key in ('decrypt',):
if key in new_module_args:
del new_module_args[key]
# execute the unarchive module now, with the updated args
result.update(self._execute_module(module_args=new_module_args, task_vars=task_vars))
except AnsibleAction as e:
result.update(e.result)
finally:
self._remove_tmp_path(self._connection._shell.tmpdir)
return result
| gpl-3.0 |
FireBladeNooT/Medusa_1_6 | medusa/notifiers/pushbullet.py | 1 | 5362 | # -*- coding: utf-8 -*
# Author: Pedro Correia (http://github.com/pedrocorreia/)
# Based on pushalot.py by Nic Wolfe <nic@wolfeden.ca>
#
# This file is part of Medusa.
#
# Medusa 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.
#
# Medusa 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 Medusa. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import re
from requests.compat import urljoin
from .. import app, common, helpers, logger
class Notifier(object):
def __init__(self):
self.session = helpers.make_session()
self.url = 'https://api.pushbullet.com/v2/'
def test_notify(self, pushbullet_api):
logger.log('Sending a test Pushbullet notification.', logger.DEBUG)
return self._sendPushbullet(
pushbullet_api,
event='Test',
message='Testing Pushbullet settings from Medusa',
force=True
)
def get_devices(self, pushbullet_api):
logger.log('Testing Pushbullet authentication and retrieving the device list.', logger.DEBUG)
headers = {'Access-Token': pushbullet_api,
'Content-Type': 'application/json'}
try:
r = self.session.get(urljoin(self.url, 'devices'), headers=headers)
return r.text
except ValueError:
return {}
def notify_snatch(self, ep_name, is_proper):
if app.PUSHBULLET_NOTIFY_ONSNATCH:
self._sendPushbullet(
pushbullet_api=None,
event=common.notifyStrings[(common.NOTIFY_SNATCH, common.NOTIFY_SNATCH_PROPER)[is_proper]] + ' : ' + ep_name,
message=ep_name
)
def notify_download(self, ep_name):
if app.PUSHBULLET_NOTIFY_ONDOWNLOAD:
self._sendPushbullet(
pushbullet_api=None,
event=common.notifyStrings[common.NOTIFY_DOWNLOAD] + ' : ' + ep_name,
message=ep_name
)
def notify_subtitle_download(self, ep_name, lang):
if app.PUSHBULLET_NOTIFY_ONSUBTITLEDOWNLOAD:
self._sendPushbullet(
pushbullet_api=None,
event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD] + ' : ' + ep_name + ' : ' + lang,
message=ep_name + ': ' + lang
)
def notify_git_update(self, new_version='??'):
link = re.match(r'.*href="(.*?)" .*', app.NEWEST_VERSION_STRING)
if link:
link = link.group(1)
self._sendPushbullet(
pushbullet_api=None,
event=common.notifyStrings[common.NOTIFY_GIT_UPDATE],
message=common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] + new_version,
link=link
)
def notify_login(self, ipaddress=''):
self._sendPushbullet(
pushbullet_api=None,
event=common.notifyStrings[common.NOTIFY_LOGIN],
message=common.notifyStrings[common.NOTIFY_LOGIN_TEXT].format(ipaddress)
)
def _sendPushbullet( # pylint: disable=too-many-arguments
self, pushbullet_api=None, pushbullet_device=None, event=None, message=None, link=None, force=False):
push_result = {'success': False, 'error': ''}
if not (app.USE_PUSHBULLET or force):
return False
pushbullet_api = pushbullet_api or app.PUSHBULLET_API
pushbullet_device = pushbullet_device or app.PUSHBULLET_DEVICE
logger.log('Pushbullet event: %r' % event, logger.DEBUG)
logger.log('Pushbullet message: %r' % message, logger.DEBUG)
logger.log('Pushbullet api: %r' % pushbullet_api, logger.DEBUG)
logger.log('Pushbullet devices: %r' % pushbullet_device, logger.DEBUG)
post_data = {
'title': event,
'body': message,
'device_iden': pushbullet_device,
'type': 'link' if link else 'note'
}
if link:
post_data['url'] = link
headers = {'Access-Token': pushbullet_api,
'Content-Type': 'application/json'}
r = self.session.post(urljoin(self.url, 'pushes'), json=post_data, headers=headers)
try:
response = r.json()
except ValueError:
logger.log('Pushbullet notification failed. Could not parse pushbullet response.', logger.WARNING)
push_result['error'] = 'Pushbullet notification failed. Could not parse pushbullet response.'
return push_result
failed = response.pop('error', {})
if failed:
logger.log('Pushbullet notification failed: {0}'.format(failed.get('message')), logger.WARNING)
push_result['error'] = 'Pushbullet notification failed: {0}'.format(failed.get('message'))
else:
logger.log('Pushbullet notification sent.', logger.DEBUG)
push_result['success'] = True
return push_result
| gpl-3.0 |
ezrover/pjsip-2.3 | tests/cdash/builder.py | 107 | 17919 | #
# builder.py - PJSIP test scenarios builder
#
# Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import ccdash
import os
import platform
import re
import subprocess
import sys
import time
class Operation:
"""\
The Operation class describes the individual ccdash operation to be
performed.
"""
# Types:
UPDATE = "update" # Update operation
CONFIGURE = "configure" # Configure operation
BUILD = "build" # Build operation
TEST = "test" # Unit test operation
def __init__(self, type, cmdline, name="", wdir=""):
self.type = type
self.cmdline = cmdline
self.name = name
self.wdir = wdir
if self.type==self.TEST and not self.name:
raise "name required for tests"
def encode(self, base_dir):
s = [self.type]
if self.type == self.TEST:
s.append(self.name)
if self.type != self.UPDATE:
s.append(self.cmdline)
s.append("-w")
if self.wdir:
s.append(base_dir + "/" + self.wdir)
else:
s.append(base_dir)
return s
#
# Update operation
#
update_ops = [Operation(Operation.UPDATE, "")]
#
# The standard library tests (e.g. pjlib-test, pjsip-test, etc.)
#
std_test_ops= [
Operation(Operation.TEST, "./pjlib-test$SUFFIX", name="pjlib test",
wdir="pjlib/bin"),
Operation(Operation.TEST, "./pjlib-util-test$SUFFIX",
name="pjlib-util test", wdir="pjlib-util/bin"),
Operation(Operation.TEST, "./pjnath-test$SUFFIX", name="pjnath test",
wdir="pjnath/bin"),
Operation(Operation.TEST, "./pjmedia-test$SUFFIX", name="pjmedia test",
wdir="pjmedia/bin"),
Operation(Operation.TEST, "./pjsip-test$SUFFIX", name="pjsip test",
wdir="pjsip/bin")
]
#
# These are pjsua Python based unit test operations
#
def build_pjsua_test_ops(pjsua_exe=""):
ops = []
if pjsua_exe:
exe = " -e ../../pjsip-apps/bin/" + pjsua_exe
else:
exe = ""
cwd = os.getcwd()
os.chdir("../pjsua")
os.system("python runall.py --list > list")
f = open("list", "r")
for e in f:
e = e.rstrip("\r\n ")
(mod,param) = e.split(None,2)
name = mod[4:mod.find(".py")] + "_" + \
param[param.find("/")+1:param.find(".py")]
ops.append(Operation(Operation.TEST, "python run.py" + exe + " " + \
e, name=name, wdir="tests/pjsua"))
f.close()
os.remove("list")
os.chdir(cwd)
return ops
#
# Get gcc version
#
def gcc_version(gcc):
proc = subprocess.Popen(gcc + " -v", stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, shell=True)
ver = ""
while True:
s = proc.stdout.readline()
if not s:
break
if s.find("gcc version") >= 0:
ver = s.split(None, 3)[2]
break
proc.wait()
return "gcc-" + ver
#
# Get Visual Studio version
#
def vs_get_version():
proc = subprocess.Popen("cl", stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while True:
s = proc.stdout.readline()
if s=="":
break
pos = s.find("Version")
if pos > 0:
proc.wait()
s = s[pos+8:]
ver = s.split(None, 1)[0]
major = ver[0:2]
if major=="12":
return "vs6"
elif major=="13":
return "vs2003"
elif major=="14":
return "vs2005"
elif major=="15":
return "vs2008"
else:
return "vs-" + major
proc.wait()
return "vs-unknown"
#
# Test config
#
class BaseConfig:
def __init__(self, base_dir, url, site, group, options=None):
self.base_dir = base_dir
self.url = url
self.site = site
self.group = group
self.options = options
#
# Base class for test configurator
#
class TestBuilder:
def __init__(self, config, build_config_name="",
user_mak="", config_site="", exclude=[], not_exclude=[]):
self.config = config # BaseConfig instance
self.build_config_name = build_config_name # Optional build suffix
self.user_mak = user_mak # To be put in user.mak
self.config_site = config_site # To be put in config_s..
self.saved_user_mak = "" # To restore user.mak
self.saved_config_site = "" # To restore config_s..
self.exclude = exclude # List of exclude pattern
self.not_exclude = not_exclude # List of include pattern
self.ccdash_args = [] # ccdash cmd line
def stamp(self):
return time.strftime("%Y%m%d-%H%M", time.localtime())
def pre_action(self):
# Override user.mak
name = self.config.base_dir + "/user.mak"
if os.access(name, os.F_OK):
f = open(name, "r")
self.saved_user_mak = f.read()
f.close()
if True:
f = open(name, "w")
f.write(self.user_mak)
f.close()
# Override config_site.h
name = self.config.base_dir + "/pjlib/include/pj/config_site.h"
if os.access(name, os.F_OK):
f = open(name, "r")
self.saved_config_site= f.read()
f.close()
if True:
f = open(name, "wt")
f.write(self.config_site)
f.close()
def post_action(self):
# Restore user.mak
name = self.config.base_dir + "/user.mak"
f = open(name, "wt")
f.write(self.saved_user_mak)
f.close()
# Restore config_site.h
name = self.config.base_dir + "/pjlib/include/pj/config_site.h"
f = open(name, "wt")
f.write(self.saved_config_site)
f.close()
def build_tests(self):
# This should be overridden by subclasses
pass
def execute(self):
if len(self.ccdash_args)==0:
self.build_tests()
self.pre_action()
mandatory_op = ["update", "configure", "build"]
counter = 0
for a in self.ccdash_args:
# Check if this test is in exclusion list
fullcmd = " ".join(a)
excluded = False
included = False
for pat in self.exclude:
if pat and re.search(pat, fullcmd) != None:
excluded = True
break
if excluded:
for pat in self.not_exclude:
if pat and re.search(pat, fullcmd) != None:
included = True
break
if excluded and not included:
if len(fullcmd)>60:
fullcmd = fullcmd[0:60] + ".."
print "Skipping '%s'" % (fullcmd)
continue
b = ["ccdash.py"]
b.extend(a)
a = b
#print a
try:
rc = ccdash.main(a)
except Exception, e:
errmsg = str(e)
print "**** Error: ccdash got exception %s ****" % errmsg
rc = -1
except:
print "**** Error: ccdash got unknown exception ****"
rc = -1
if rc!=0 and a[1] in mandatory_op:
print "Stopping because of error.."
break
counter = counter + 1
self.post_action()
#
# GNU test configurator
#
class GNUTestBuilder(TestBuilder):
"""\
This class creates list of tests suitable for GNU targets.
"""
def __init__(self, config, build_config_name="", user_mak="", \
config_site="", cross_compile="", exclude=[], not_exclude=[]):
"""\
Parameters:
config - BaseConfig instance
build_config_name - Optional name to be added as suffix to the build
name. Sample: "min-size", "O4", "TLS", etc.
user_mak - Contents to be put on user.mak
config_site - Contents to be put on config_site.h
cross_compile - Optional cross-compile prefix. Must include the
trailing dash, e.g. "arm-unknown-linux-"
exclude - List of regular expression patterns for tests
that will be excluded from the run
not_exclude - List of regular expression patterns for tests
that will be run regardless of whether they
match the excluded pattern.
"""
TestBuilder.__init__(self, config, build_config_name=build_config_name,
user_mak=user_mak, config_site=config_site,
exclude=exclude, not_exclude=not_exclude)
self.cross_compile = cross_compile
if self.cross_compile and self.cross_compile[-1] != '-':
self.cross_compile.append("-")
def build_tests(self):
if self.cross_compile:
suffix = "-" + self.cross_compile[0:-1]
build_name = self.cross_compile + \
gcc_version(self.cross_compile + "gcc")
else:
proc = subprocess.Popen("sh "+self.config.base_dir+"/config.guess",
shell=True, stdout=subprocess.PIPE)
plat = proc.stdout.readline().rstrip(" \r\n")
build_name = plat + "-"+gcc_version(self.cross_compile + "gcc")
suffix = "-" + plat
if self.build_config_name:
build_name = build_name + "-" + self.build_config_name
cmds = []
cmds.extend(update_ops)
cmds.append(Operation(Operation.CONFIGURE, "sh ./configure"))
if sys.platform=="win32":
# Don't build python module on Mingw
cmds.append(Operation(Operation.BUILD,
"sh -c 'make distclean && make dep && make'"))
else:
cmds.append(Operation(Operation.BUILD,
"sh -c 'make distclean && make dep && make" + \
" && cd pjsip-apps/src/python && " + \
"python setup.py clean build'"))
cmds.extend(std_test_ops)
cmds.extend(build_pjsua_test_ops())
self.ccdash_args = []
for c in cmds:
c.cmdline = c.cmdline.replace("$SUFFIX", suffix)
args = c.encode(self.config.base_dir)
args.extend(["-U", self.config.url,
"-S", self.config.site,
"-T", self.stamp(),
"-B", build_name,
"-G", self.config.group])
args.extend(self.config.options)
self.ccdash_args.append(args)
#
# MSVC test configurator
#
class MSVCTestBuilder(TestBuilder):
"""\
This class creates list of tests suitable for Visual Studio builds.
You need to set the MSVC environment variables (typically by calling
vcvars32.bat) prior to running this class.
"""
def __init__(self, config, target="Release|Win32", build_config_name="",
config_site="", exclude=[], not_exclude=[]):
"""\
Parameters:
config - BaseConfig instance
target - Visual Studio build configuration to build.
Sample: "Debug|Win32", "Release|Win32".
build_config_name - Optional name to be added as suffix to the build
name. Sample: "Debug", "Release", "IPv6", etc.
config_site - Contents to be put on config_site.h
exclude - List of regular expression patterns for tests
that will be excluded from the run
not_exclude - List of regular expression patterns for tests
that will be run regardless of whether they
match the excluded pattern.
"""
TestBuilder.__init__(self, config, build_config_name=build_config_name,
config_site=config_site, exclude=exclude,
not_exclude=not_exclude)
self.target = target.lower()
def build_tests(self):
(vsbuild,sys) = self.target.split("|",2)
build_name = sys + "-" + vs_get_version() + "-" + vsbuild
if self.build_config_name:
build_name = build_name + "-" + self.build_config_name
vccmd = "vcbuild.exe /nologo /nohtmllog /nocolor /rebuild " + \
"pjproject-vs8.sln " + " \"" + self.target + "\""
suffix = "-i386-win32-vc8-" + vsbuild
pjsua = "pjsua_vc8"
if vsbuild=="debug":
pjsua = pjsua + "d"
cmds = []
cmds.extend(update_ops)
cmds.append(Operation(Operation.CONFIGURE, "CMD /C echo Nothing to do"))
cmds.append(Operation(Operation.BUILD, vccmd))
cmds.extend(std_test_ops)
cmds.extend(build_pjsua_test_ops(pjsua))
self.ccdash_args = []
for c in cmds:
c.cmdline = c.cmdline.replace("$SUFFIX", suffix)
args = c.encode(self.config.base_dir)
args.extend(["-U", self.config.url,
"-S", self.config.site,
"-T", self.stamp(),
"-B", build_name,
"-G", self.config.group])
args.extend(self.config.options)
self.ccdash_args.append(args)
#
# Symbian test configurator
#
class SymbianTestBuilder(TestBuilder):
"""\
This class creates list of tests suitable for Symbian builds. You need to
set the command line build settings prior to running this class (typically
that involves setting the EPOCROOT variable and current device).
"""
def __init__(self, config, target="gcce urel", build_config_name="",
config_site="", exclude=[], not_exclude=[]):
"""\
Parameters:
config - BaseConfig instance
target - Symbian target to build. Default is "gcce urel".
build_config_name - Optional name to be added as suffix to the build
name. Sample: "APS", "VAS", etc.
config_site - Contents to be put on config_site.h
exclude - List of regular expression patterns for tests
that will be excluded from the run
not_exclude - List of regular expression patterns for tests
that will be run regardless of whether they
match the excluded pattern.
"""
TestBuilder.__init__(self, config, build_config_name=build_config_name,
config_site=config_site, exclude=exclude,
not_exclude=not_exclude)
self.target = target.lower()
def build_tests(self):
# Check that EPOCROOT is set
if not "EPOCROOT" in os.environ:
print "Error: EPOCROOT environment variable is not set"
sys.exit(1)
epocroot = os.environ["EPOCROOT"]
# EPOCROOT must have trailing backslash
if epocroot[-1] != "\\":
epocroot = epocroot + "\\"
os.environ["EPOCROOT"] = epocroot
sdk1 = epocroot.split("\\")[-2]
# Check that correct device is set
proc = subprocess.Popen("devices", stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, shell=True)
sdk2 = ""
while True:
line = proc.stdout.readline()
if line.find("- default") > 0:
sdk2 = line.split(":",1)[0]
break
proc.wait()
if sdk1 != sdk2:
print "Error: default SDK in device doesn't match EPOCROOT"
print "Default device SDK =", sdk2
print "EPOCROOT SDK =", sdk1
sys.exit(1)
build_name = sdk2.replace("_", "-") + "-" + \
self.target.replace(" ", "-")
if self.build_config_name:
build_name = build_name + "-" + self.build_config_name
cmdline = "cmd /C \"cd build.symbian && bldmake bldfiles && abld build %s\"" % (self.target)
cmds = []
cmds.extend(update_ops)
cmds.append(Operation(Operation.CONFIGURE, "CMD /C echo Nothing to do"))
cmds.extend([Operation(Operation.BUILD, cmdline)])
self.ccdash_args = []
suffix = ""
for c in cmds:
c.cmdline = c.cmdline.replace("$SUFFIX", suffix)
args = c.encode(self.config.base_dir)
args.extend(["-U", self.config.url,
"-S", self.config.site,
"-T", self.stamp(),
"-B", build_name,
"-G", self.config.group])
args.extend(self.config.options)
self.ccdash_args.append(args)
| gpl-2.0 |
python-bugzilla/python-bugzilla | tests/test_api_authfiles.py | 1 | 7309 | #
# Copyright Red Hat, Inc. 2012
#
# This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
#
"""
Test miscellaneous API bits
"""
import os
import shutil
import tempfile
import pytest
import requests
import bugzilla
import tests
import tests.mockbackend
import tests.utils
def testCookies(monkeypatch):
monkeypatch.setitem(os.environ, "HOME",
os.path.dirname(__file__) + "/data/homedir")
dirname = os.path.dirname(__file__)
cookiesbad = dirname + "/data/cookies-bad.txt"
cookieslwp = dirname + "/data/cookies-lwp.txt"
cookiesmoz = dirname + "/data/cookies-moz.txt"
# We used to convert LWP cookies, but it shouldn't matter anymore,
# so verify they fail at least
with pytest.raises(bugzilla.BugzillaError):
tests.mockbackend.make_bz(version="3.0.0",
bz_kwargs={"cookiefile": cookieslwp, "use_creds": True})
with pytest.raises(bugzilla.BugzillaError):
tests.mockbackend.make_bz(version="3.0.0",
bz_kwargs={"cookiefile": cookiesbad, "use_creds": True})
# Mozilla should 'just work'
bz = tests.mockbackend.make_bz(version="3.0.0",
bz_kwargs={"cookiefile": cookiesmoz, "use_creds": True})
# cookie/token property magic
bz = tests.mockbackend.make_bz(bz_kwargs={"use_creds": True})
token = dirname + "/data/homedir/.cache/python-bugzilla/bugzillatoken"
cookie = dirname + "/data/homedir/.cache/python-bugzilla/bugzillacookies"
assert token == bz.tokenfile
assert cookie == bz.cookiefile
del(bz.tokenfile)
del(bz.cookiefile)
assert bz.tokenfile is None
assert bz.cookiefile is None
def test_readconfig():
# Testing for bugzillarc handling
bzapi = tests.mockbackend.make_bz(version="4.4.0", rhbz=True)
bzapi.url = "example.com"
temp = tempfile.NamedTemporaryFile(mode="w")
def _check(user, password, api_key, cert):
assert bzapi.user == user
assert bzapi.password == password
assert bzapi.api_key == api_key
assert bzapi.cert == cert
def _write(c):
temp.seek(0)
temp.write(c)
temp.flush()
return temp.name
# Check readconfig normal usage
content = """
[example.com]
foo=1
user=test1
password=test2
api_key=123abc
cert=/a/b/c
someunknownkey=someval
"""
bzapi.readconfig(_write(content))
_check("test1", "test2", "123abc", "/a/b/c")
# Check loading a different URL, that values aren't overwritten
content = """
[foo.example.com]
user=test3
password=test4
api_key=567abc
cert=/newpath
"""
bzapi.readconfig(_write(content))
_check("test1", "test2", "123abc", "/a/b/c")
# Change URL, but check readconfig with overwrite=False
bzapi.url = "foo.example.com"
bzapi.readconfig(temp.name, overwrite=False)
_check("test1", "test2", "123abc", "/a/b/c")
# With default overwrite=True, values will be updated
# Alter the config to have a / in the hostname, which hits different code
content = content.replace("example.com", "example.com/xmlrpc.cgi")
bzapi.url = "https://foo.example.com/xmlrpc.cgi"
bzapi.readconfig(_write(content))
_check("test3", "test4", "567abc", "/newpath")
# Confirm nothing overwritten for a totally different URL
bzapi.user = None
bzapi.password = None
bzapi.api_key = None
bzapi.cert = None
bzapi.url = "bugzilla.redhat.com"
bzapi.readconfig(temp.name)
_check(None, None, None, None)
# Test confipath overwrite
assert [temp.name] == bzapi.configpath
del(bzapi.configpath)
assert [] == bzapi.configpath
bzapi.readconfig()
_check(None, None, None, None)
def _get_cookiejar():
cookiefile = os.path.dirname(__file__) + "/data/cookies-moz.txt"
inputbz = tests.mockbackend.make_bz(
bz_kwargs={"use_creds": True, "cookiefile": cookiefile})
cookiecache = inputbz._cookiecache # pylint: disable=protected-access
return cookiecache.get_cookiejar()
def test_authfiles_saving(monkeypatch):
tmpdir = tempfile.mkdtemp()
try:
monkeypatch.setitem(os.environ, "HOME", tmpdir)
bzapi = tests.mockbackend.make_bz(
bz_kwargs={"use_creds": True, "cert": "foo-fake-cert"})
bzapi.connect("https://example.com/fakebz")
bzapi.cert = "foo-fake-path"
backend = bzapi._backend # pylint: disable=protected-access
bsession = backend._bugzillasession # pylint: disable=protected-access
response = requests.Response()
response.cookies = _get_cookiejar()
# token testing, with repetitions to hit various code paths
bsession.set_token_value(None)
bsession.set_token_value("MY-FAKE-TOKEN")
bsession.set_token_value("MY-FAKE-TOKEN")
bsession.set_token_value(None)
bsession.set_token_value("MY-FAKE-TOKEN")
# cookie testing
bsession.set_response_cookies(response)
dirname = os.path.dirname(__file__) + "/data/authfiles/"
output_token = dirname + "output-token.txt"
output_cookies = dirname + "output-cookies.txt"
tests.utils.diff_compare(open(bzapi.tokenfile).read(), output_token)
# On RHEL7 the cookie comment header is different. Strip off leading
# comments
def strip_comments(f):
return "".join([
line for line in open(f).readlines() if
not line.startswith("#")])
tests.utils.diff_compare(strip_comments(bzapi.cookiefile),
None, expect_out=strip_comments(output_cookies))
# Make sure file can re-read them and not error
bzapi = tests.mockbackend.make_bz(
bz_kwargs={"use_creds": True,
"cookiefile": output_cookies,
"tokenfile": output_token})
assert bzapi.tokenfile == output_token
assert bzapi.cookiefile == output_cookies
# Test rcfile writing for api_key
rcfile = bzapi._rcfile # pylint: disable=protected-access
bzapi.url = "https://example.com/fake"
rcfile.save_api_key(bzapi.url, "TEST-API-KEY")
rcfilepath = tmpdir + "/.config/python-bugzilla/bugzillarc"
assert rcfile.get_configpaths()[-1] == rcfilepath
tests.utils.diff_compare(open(rcfilepath).read(),
dirname + "output-bugzillarc.txt")
# Use that generated rcfile to test default URL lookup
fakeurl = "http://foo.bar.baz/wibble"
open(rcfilepath, "w").write("\n[DEFAULT]\nurl = %s" % fakeurl)
assert bzapi.get_rcfile_default_url() == fakeurl
finally:
shutil.rmtree(tmpdir)
def test_authfiles_nowrite():
# Set values when n when cookiefile is None, should be fine
bzapi = tests.mockbackend.make_bz(bz_kwargs={"use_creds": False})
bzapi.connect("https://example.com/foo")
backend = bzapi._backend # pylint: disable=protected-access
bsession = backend._bugzillasession # pylint: disable=protected-access
rcfile = bzapi._rcfile # pylint: disable=protected-access
response = requests.Response()
response.cookies = _get_cookiejar()
bsession.set_token_value("NEW-TOKEN-VALUE")
bsession.set_response_cookies(response)
assert rcfile.save_api_key(bzapi.url, "fookey") is None
| gpl-2.0 |
dvliman/jaikuengine | common/test/base.py | 30 | 8167 | # Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import urlparse
import sys
from beautifulsoup import BeautifulSoup
import mox
from django import http
from django import test
from django.conf import settings
from django.test import client
from common import clean
from common import memcache
from common import megamox
from common import profile
from common import util
from common.protocol import pshb
from common.protocol import sms
from common.protocol import xmpp
from common.test import util as test_util
try:
import xml.etree.ElementTree as etree
import xml.parsers.expat
except ImportError:
etree = None
class FixturesTestCase(test.TestCase):
fixtures = ['actors', 'streams', 'contacts', 'streamentries',
'inboxentries', 'subscriptions', 'oauthconsumers',
'invites', 'emails', 'ims', 'activations',
'oauthaccesstokens', 'mobiles']
passwords = {'obligated@example.com': 'bar',
'popular@example.com': 'baz',
'celebrity@example.com': 'baz',
'boyfriend@example.com': 'baz',
'girlfriend@example.com': 'baz',
'annoying@example.com': 'foo',
'unpopular@example.com': 'foo',
'hermit@example.com': 'baz',
'broken@example.com': 'baz',
'CapitalPunishment@example.com': 'baz',
'root@example.com': 'fakepassword',
'hotness@example.com': 'fakepassword'};
__metaclass__ = megamox.MoxMetaTestBase
def setUp(self):
settings.DEBUG = False
xmpp.XmppConnection = test_util.TestXmppConnection
xmpp.outbox = []
sms.SmsConnection = test_util.TestSmsConnection
sms.outbox = []
pshb.PshbConnection = test_util.TestPshbConnection
pshb.outbox = []
memcache.client = test_util.FakeMemcache()
if profile.PROFILE_ALL_TESTS:
profile.start()
self.client = client.Client(SERVER_NAME=settings.DOMAIN)
self.mox = megamox.ExtendedMox()
def tearDown(self):
if profile.PROFILE_ALL_TESTS:
profile.stop()
if hasattr(self, 'override'):
self.override.reset()
del self.override
def assertSetEqual(self, expected_set, test_set):
if expected_set != test_set:
more = test_set - expected_set
less = expected_set - test_set
raise AssertionError('Expected: %s\nGot: %s\n + %s\n - %s' % (
expected_set, test_set, more, less))
def clear_cache(self):
memcache.client._data = {}
def exhaust_queue(self, nick):
test_util.exhaust_queue(nick)
def exhaust_queue_any(self):
test_util.exhaust_queue_any()
class ViewTestCase(FixturesTestCase):
def login(self, nick, password=None):
if not password:
password = self.passwords[clean.nick(nick)]
r = self.client.post('/login', {'log': nick, 'pwd': password})
return
def logout(self):
self.client.cookies.pop(settings.USER_COOKIE)
self.client.cookies.pop(settings.PASSWORD_COOKIE)
def login_and_get(self, nick, path, *args, **kw):
if nick:
self.login(nick, kw.get('password', None))
return self.client.get(path, *args, **kw)
def assert_error_contains(self, response, content, code=200):
self.assertContains(response, content, 1, code);
# TODO(teemu): propose this to appengine_django project, when best submit path (Google-internal or
# public) is decided.
def assertRedirectsPrefix(self, response, expected_url_prefix,
status_code=302, target_status_code=200,
host=None):
"""Asserts that a response redirected to an URL with specified prefix,
and that the redirect URL can be loaded. Return redirected response, so
that further asserts can be performed on it.
Note that assertRedirects won't work for external links since it uses
TestClient to do a request.
"""
self.assertEqual(response.status_code, status_code,
("Response didn't redirect as expected: Response code was"
" %d (expected %d) content %s" % (
response.status_code, status_code, response.content)))
url = response['Location']
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
e_scheme, e_netloc, e_path, e_query, e_fragment = (
urlparse.urlsplit(expected_url_prefix))
if not (e_scheme or e_netloc):
expected_url_prefix = urlparse.urlunsplit(
('http', host or settings.DOMAIN, e_path, e_query, e_fragment))
self.assertEqual(url.find(expected_url_prefix), 0,
"Response redirected to '%s',"
" expected prefix url '%s'" % (url, expected_url_prefix))
# Get the redirection page, using the same client that was used
# to obtain the original response.
params = {'path': path,
'data': http.QueryDict(query),
'SERVER_NAME': netloc,
}
if scheme == 'https':
params['wsgi.url_scheme'] = 'https'
params['SERVER_PORT'] = '443'
redirect_response = response.client.get(**params)
self.assertEqual(redirect_response.status_code,
target_status_code,
"Couldn't retrieve redirection page '%s': response code"
" was %d (expected %d)" % (url,
redirect_response.status_code,
target_status_code)
)
return redirect_response
def assertWellformed(self, r):
"""Tries to parse the xhmtl content in r, fails the test if not wellformed,
returns the ElementTree object if it is.
Not run if elementtree is not available (e.g., plain 2.4).
"""
if not etree:
return None
try:
parsed = etree.fromstring(r.content)
return parsed
except xml.parsers.expat.ExpatError, e:
# TODO(mikie): this should save the output to a file for inspection.
line = ''
lineno = -1
if getattr(e, 'lineno', None):
lines = r.content.splitlines()
line = lines[e.lineno - 1]
line = "'" + line + "'"
lineno = e.lineno
codestr = ''
if getattr(e, 'code', None):
codestr = xml.parsers.expat.ErrorString(e.code)
self.assertTrue(False,
'failed to parse response, error %s on line %d %s (%s)' %
(codestr, lineno, line, str(e)))
except:
self.assertTrue(False, 'failed to parse response, error %s' %
str(sys.exc_info()[0]))
def assertGetLink(self, response, link_class, link_no,
of_count=-1, msg=''):
"""Tries to find an anchor element with the given class from the response.
Checks that there are of_count total links of that class
(unless of_count==-1). Gets the page from that link.
"""
self.assertWellformed(response)
parsed = BeautifulSoup.BeautifulSoup(response.content)
found = parsed.findAll('a', attrs = { 'class': link_class})
anchors = [a for a in found]
if of_count > -1:
self.assertEqual(len(anchors), of_count, msg)
a = anchors[link_no]
href = a['href']
# 2.4 sgmllib/HTMLParser doesn't decode HTML entities, this
# fixes the query parameter separator.
# TODO(mikie): how do we properly detect the sgmllib version?
if int(sys.version.split(' ')[0].split('.')[1]) < 5:
href = href.replace('&', '&')
args = util.href_to_queryparam_dict(href)
args['confirm'] = 1
url = response.request['PATH_INFO']
return self.client.get(url, args)
| apache-2.0 |
BAMitUp/Fantasy-Football-Shuffler | ENV/lib/python2.7/site-packages/pip/commands/show.py | 142 | 5815 | from __future__ import absolute_import
from email.parser import FeedParser
import logging
import os
from pip.basecommand import Command
from pip.status_codes import SUCCESS, ERROR
from pip._vendor import pkg_resources
logger = logging.getLogger(__name__)
class ShowCommand(Command):
"""Show information about one or more installed packages."""
name = 'show'
usage = """
%prog [options] <package> ..."""
summary = 'Show information about installed packages.'
def __init__(self, *args, **kw):
super(ShowCommand, self).__init__(*args, **kw)
self.cmd_opts.add_option(
'-f', '--files',
dest='files',
action='store_true',
default=False,
help='Show the full list of installed files for each package.')
self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options, args):
if not args:
logger.warning('ERROR: Please provide a package name or names.')
return ERROR
query = args
results = search_packages_info(query)
if not print_results(results, options.files):
return ERROR
return SUCCESS
def search_packages_info(query):
"""
Gather details from installed distributions. Print distribution name,
version, location, and installed files. Installed files requires a
pip generated 'installed-files.txt' in the distributions '.egg-info'
directory.
"""
installed = dict(
[(p.project_name.lower(), p) for p in pkg_resources.working_set])
query_names = [name.lower() for name in query]
for dist in [installed[pkg] for pkg in query_names if pkg in installed]:
package = {
'name': dist.project_name,
'version': dist.version,
'location': dist.location,
'requires': [dep.project_name for dep in dist.requires()],
}
file_list = None
metadata = None
if isinstance(dist, pkg_resources.DistInfoDistribution):
# RECORDs should be part of .dist-info metadatas
if dist.has_metadata('RECORD'):
lines = dist.get_metadata_lines('RECORD')
paths = [l.split(',')[0] for l in lines]
paths = [os.path.join(dist.location, p) for p in paths]
file_list = [os.path.relpath(p, dist.location) for p in paths]
if dist.has_metadata('METADATA'):
metadata = dist.get_metadata('METADATA')
else:
# Otherwise use pip's log for .egg-info's
if dist.has_metadata('installed-files.txt'):
paths = dist.get_metadata_lines('installed-files.txt')
paths = [os.path.join(dist.egg_info, p) for p in paths]
file_list = [os.path.relpath(p, dist.location) for p in paths]
if dist.has_metadata('PKG-INFO'):
metadata = dist.get_metadata('PKG-INFO')
if dist.has_metadata('entry_points.txt'):
entry_points = dist.get_metadata_lines('entry_points.txt')
package['entry_points'] = entry_points
installer = None
if dist.has_metadata('INSTALLER'):
for line in dist.get_metadata_lines('INSTALLER'):
if line.strip():
installer = line.strip()
break
package['installer'] = installer
# @todo: Should pkg_resources.Distribution have a
# `get_pkg_info` method?
feed_parser = FeedParser()
feed_parser.feed(metadata)
pkg_info_dict = feed_parser.close()
for key in ('metadata-version', 'summary',
'home-page', 'author', 'author-email', 'license'):
package[key] = pkg_info_dict.get(key)
# It looks like FeedParser can not deal with repeated headers
classifiers = []
for line in metadata.splitlines():
if not line:
break
# Classifier: License :: OSI Approved :: MIT License
if line.startswith('Classifier: '):
classifiers.append(line[len('Classifier: '):])
package['classifiers'] = classifiers
if file_list:
package['files'] = sorted(file_list)
yield package
def print_results(distributions, list_all_files):
"""
Print the informations from installed distributions found.
"""
results_printed = False
for dist in distributions:
results_printed = True
logger.info("---")
logger.info("Metadata-Version: %s", dist.get('metadata-version'))
logger.info("Name: %s", dist['name'])
logger.info("Version: %s", dist['version'])
logger.info("Summary: %s", dist.get('summary'))
logger.info("Home-page: %s", dist.get('home-page'))
logger.info("Author: %s", dist.get('author'))
logger.info("Author-email: %s", dist.get('author-email'))
if dist['installer'] is not None:
logger.info("Installer: %s", dist['installer'])
logger.info("License: %s", dist.get('license'))
logger.info("Location: %s", dist['location'])
logger.info("Requires: %s", ', '.join(dist['requires']))
logger.info("Classifiers:")
for classifier in dist['classifiers']:
logger.info(" %s", classifier)
if list_all_files:
logger.info("Files:")
if 'files' in dist:
for line in dist['files']:
logger.info(" %s", line.strip())
else:
logger.info("Cannot locate installed-files.txt")
if 'entry_points' in dist:
logger.info("Entry-points:")
for line in dist['entry_points']:
logger.info(" %s", line.strip())
return results_printed
| gpl-3.0 |
tillahoffmann/tensorflow | tensorflow/contrib/learn/python/learn/preprocessing/categorical.py | 153 | 4269 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Implements preprocessing transformers for categorical variables."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
# pylint: disable=g-bad-import-order
from . import categorical_vocabulary
from ..learn_io.data_feeder import setup_processor_data_feeder
# pylint: enable=g-bad-import-order
class CategoricalProcessor(object):
"""Maps documents to sequences of word ids.
As a common convention, Nan values are handled as unknown tokens.
Both float('nan') and np.nan are accepted.
"""
def __init__(self, min_frequency=0, share=False, vocabularies=None):
"""Initializes a CategoricalProcessor instance.
Args:
min_frequency: Minimum frequency of categories in the vocabulary.
share: Share vocabulary between variables.
vocabularies: list of CategoricalVocabulary objects for each variable in
the input dataset.
Attributes:
vocabularies_: list of CategoricalVocabulary objects.
"""
self.min_frequency = min_frequency
self.share = share
self.vocabularies_ = vocabularies
def freeze(self, freeze=True):
"""Freeze or unfreeze all vocabularies.
Args:
freeze: Boolean, indicate if vocabularies should be frozen.
"""
for vocab in self.vocabularies_:
vocab.freeze(freeze)
def fit(self, x, unused_y=None):
"""Learn a vocabulary dictionary of all categories in `x`.
Args:
x: numpy matrix or iterable of lists/numpy arrays.
unused_y: to match fit format signature of estimators.
Returns:
self
"""
x = setup_processor_data_feeder(x)
for row in x:
# Create vocabularies if not given.
if self.vocabularies_ is None:
# If not share, one per column, else one shared across.
if not self.share:
self.vocabularies_ = [
categorical_vocabulary.CategoricalVocabulary() for _ in row
]
else:
vocab = categorical_vocabulary.CategoricalVocabulary()
self.vocabularies_ = [vocab for _ in row]
for idx, value in enumerate(row):
# Nans are handled as unknowns.
if (isinstance(value, float) and math.isnan(value)) or value == np.nan:
continue
self.vocabularies_[idx].add(value)
if self.min_frequency > 0:
for vocab in self.vocabularies_:
vocab.trim(self.min_frequency)
self.freeze()
return self
def fit_transform(self, x, unused_y=None):
"""Learn the vocabulary dictionary and return indexies of categories.
Args:
x: numpy matrix or iterable of lists/numpy arrays.
unused_y: to match fit_transform signature of estimators.
Returns:
x: iterable, [n_samples]. Category-id matrix.
"""
self.fit(x)
return self.transform(x)
def transform(self, x):
"""Transform documents to category-id matrix.
Converts categories to ids give fitted vocabulary from `fit` or
one provided in the constructor.
Args:
x: numpy matrix or iterable of lists/numpy arrays.
Yields:
x: iterable, [n_samples]. Category-id matrix.
"""
self.freeze()
x = setup_processor_data_feeder(x)
for row in x:
output_row = []
for idx, value in enumerate(row):
# Return <UNK> when it's Nan.
if (isinstance(value, float) and math.isnan(value)) or value == np.nan:
output_row.append(0)
continue
output_row.append(self.vocabularies_[idx].get(value))
yield np.array(output_row, dtype=np.int64)
| apache-2.0 |
andreif/django | tests/raw_query/tests.py | 119 | 12624 | from __future__ import unicode_literals
from datetime import date
from django.db.models.query_utils import InvalidQuery
from django.test import TestCase, skipUnlessDBFeature
from .models import Author, Book, BookFkAsPk, Coffee, FriendlyAuthor, Reviewer
class RawQueryTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(first_name='Joe', last_name='Smith', dob=date(1950, 9, 20))
cls.a2 = Author.objects.create(first_name='Jill', last_name='Doe', dob=date(1920, 4, 2))
cls.a3 = Author.objects.create(first_name='Bob', last_name='Smith', dob=date(1986, 1, 25))
cls.a4 = Author.objects.create(first_name='Bill', last_name='Jones', dob=date(1932, 5, 10))
cls.b1 = Book.objects.create(
title='The awesome book', author=cls.a1, paperback=False,
opening_line='It was a bright cold day in April and the clocks were striking thirteen.',
)
cls.b2 = Book.objects.create(
title='The horrible book', author=cls.a1, paperback=True,
opening_line=(
'On an evening in the latter part of May a middle-aged man '
'was walking homeward from Shaston to the village of Marlott, '
'in the adjoining Vale of Blakemore, or Blackmoor.'
),
)
cls.b3 = Book.objects.create(
title='Another awesome book', author=cls.a1, paperback=False,
opening_line='A squat grey building of only thirty-four stories.',
)
cls.b4 = Book.objects.create(
title='Some other book', author=cls.a3, paperback=True,
opening_line='It was the day my grandmother exploded.',
)
cls.c1 = Coffee.objects.create(brand='dunkin doughnuts')
cls.c2 = Coffee.objects.create(brand='starbucks')
cls.r1 = Reviewer.objects.create()
cls.r2 = Reviewer.objects.create()
cls.r1.reviewed.add(cls.b2, cls.b3, cls.b4)
def assertSuccessfulRawQuery(self, model, query, expected_results,
expected_annotations=(), params=[], translations=None):
"""
Execute the passed query against the passed model and check the output
"""
results = list(model.objects.raw(query, params=params, translations=translations))
self.assertProcessed(model, results, expected_results, expected_annotations)
self.assertAnnotations(results, expected_annotations)
def assertProcessed(self, model, results, orig, expected_annotations=()):
"""
Compare the results of a raw query against expected results
"""
self.assertEqual(len(results), len(orig))
for index, item in enumerate(results):
orig_item = orig[index]
for annotation in expected_annotations:
setattr(orig_item, *annotation)
for field in model._meta.fields:
# Check that all values on the model are equal
self.assertEqual(
getattr(item, field.attname),
getattr(orig_item, field.attname)
)
# This includes checking that they are the same type
self.assertEqual(
type(getattr(item, field.attname)),
type(getattr(orig_item, field.attname))
)
def assertNoAnnotations(self, results):
"""
Check that the results of a raw query contain no annotations
"""
self.assertAnnotations(results, ())
def assertAnnotations(self, results, expected_annotations):
"""
Check that the passed raw query results contain the expected
annotations
"""
if expected_annotations:
for index, result in enumerate(results):
annotation, value = expected_annotations[index]
self.assertTrue(hasattr(result, annotation))
self.assertEqual(getattr(result, annotation), value)
def test_simple_raw_query(self):
"""
Basic test of raw query with a simple database query
"""
query = "SELECT * FROM raw_query_author"
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors)
def test_raw_query_lazy(self):
"""
Raw queries are lazy: they aren't actually executed until they're
iterated over.
"""
q = Author.objects.raw('SELECT * FROM raw_query_author')
self.assertIsNone(q.query.cursor)
list(q)
self.assertIsNotNone(q.query.cursor)
def test_FK_raw_query(self):
"""
Test of a simple raw query against a model containing a foreign key
"""
query = "SELECT * FROM raw_query_book"
books = Book.objects.all()
self.assertSuccessfulRawQuery(Book, query, books)
def test_db_column_handler(self):
"""
Test of a simple raw query against a model containing a field with
db_column defined.
"""
query = "SELECT * FROM raw_query_coffee"
coffees = Coffee.objects.all()
self.assertSuccessfulRawQuery(Coffee, query, coffees)
def test_order_handler(self):
"""
Test of raw raw query's tolerance for columns being returned in any
order
"""
selects = (
('dob, last_name, first_name, id'),
('last_name, dob, first_name, id'),
('first_name, last_name, dob, id'),
)
for select in selects:
query = "SELECT %s FROM raw_query_author" % select
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors)
def test_translations(self):
"""
Test of raw query's optional ability to translate unexpected result
column names to specific model fields
"""
query = "SELECT first_name AS first, last_name AS last, dob, id FROM raw_query_author"
translations = {'first': 'first_name', 'last': 'last_name'}
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors, translations=translations)
def test_params(self):
"""
Test passing optional query parameters
"""
query = "SELECT * FROM raw_query_author WHERE first_name = %s"
author = Author.objects.all()[2]
params = [author.first_name]
qset = Author.objects.raw(query, params=params)
results = list(qset)
self.assertProcessed(Author, results, [author])
self.assertNoAnnotations(results)
self.assertEqual(len(results), 1)
self.assertIsInstance(repr(qset), str)
@skipUnlessDBFeature('supports_paramstyle_pyformat')
def test_pyformat_params(self):
"""
Test passing optional query parameters
"""
query = "SELECT * FROM raw_query_author WHERE first_name = %(first)s"
author = Author.objects.all()[2]
params = {'first': author.first_name}
qset = Author.objects.raw(query, params=params)
results = list(qset)
self.assertProcessed(Author, results, [author])
self.assertNoAnnotations(results)
self.assertEqual(len(results), 1)
self.assertIsInstance(repr(qset), str)
def test_query_representation(self):
"""
Test representation of raw query with parameters
"""
query = "SELECT * FROM raw_query_author WHERE last_name = %(last)s"
qset = Author.objects.raw(query, {'last': 'foo'})
self.assertEqual(repr(qset), "<RawQuerySet: SELECT * FROM raw_query_author WHERE last_name = foo>")
self.assertEqual(repr(qset.query), "<RawQuery: SELECT * FROM raw_query_author WHERE last_name = foo>")
query = "SELECT * FROM raw_query_author WHERE last_name = %s"
qset = Author.objects.raw(query, {'foo'})
self.assertEqual(repr(qset), "<RawQuerySet: SELECT * FROM raw_query_author WHERE last_name = foo>")
self.assertEqual(repr(qset.query), "<RawQuery: SELECT * FROM raw_query_author WHERE last_name = foo>")
def test_many_to_many(self):
"""
Test of a simple raw query against a model containing a m2m field
"""
query = "SELECT * FROM raw_query_reviewer"
reviewers = Reviewer.objects.all()
self.assertSuccessfulRawQuery(Reviewer, query, reviewers)
def test_extra_conversions(self):
"""
Test to insure that extra translations are ignored.
"""
query = "SELECT * FROM raw_query_author"
translations = {'something': 'else'}
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors, translations=translations)
def test_missing_fields(self):
query = "SELECT id, first_name, dob FROM raw_query_author"
for author in Author.objects.raw(query):
self.assertNotEqual(author.first_name, None)
# last_name isn't given, but it will be retrieved on demand
self.assertNotEqual(author.last_name, None)
def test_missing_fields_without_PK(self):
query = "SELECT first_name, dob FROM raw_query_author"
try:
list(Author.objects.raw(query))
self.fail('Query without primary key should fail')
except InvalidQuery:
pass
def test_annotations(self):
query = (
"SELECT a.*, count(b.id) as book_count "
"FROM raw_query_author a "
"LEFT JOIN raw_query_book b ON a.id = b.author_id "
"GROUP BY a.id, a.first_name, a.last_name, a.dob ORDER BY a.id"
)
expected_annotations = (
('book_count', 3),
('book_count', 0),
('book_count', 1),
('book_count', 0),
)
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors, expected_annotations)
def test_white_space_query(self):
query = " SELECT * FROM raw_query_author"
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors)
def test_multiple_iterations(self):
query = "SELECT * FROM raw_query_author"
normal_authors = Author.objects.all()
raw_authors = Author.objects.raw(query)
# First Iteration
first_iterations = 0
for index, raw_author in enumerate(raw_authors):
self.assertEqual(normal_authors[index], raw_author)
first_iterations += 1
# Second Iteration
second_iterations = 0
for index, raw_author in enumerate(raw_authors):
self.assertEqual(normal_authors[index], raw_author)
second_iterations += 1
self.assertEqual(first_iterations, second_iterations)
def test_get_item(self):
# Indexing on RawQuerySets
query = "SELECT * FROM raw_query_author ORDER BY id ASC"
third_author = Author.objects.raw(query)[2]
self.assertEqual(third_author.first_name, 'Bob')
first_two = Author.objects.raw(query)[0:2]
self.assertEqual(len(first_two), 2)
self.assertRaises(TypeError, lambda: Author.objects.raw(query)['test'])
def test_inheritance(self):
# date is the end of the Cuban Missile Crisis, I have no idea when
# Wesley was born
f = FriendlyAuthor.objects.create(first_name="Wesley", last_name="Chun",
dob=date(1962, 10, 28))
query = "SELECT * FROM raw_query_friendlyauthor"
self.assertEqual(
[o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk]
)
def test_query_count(self):
self.assertNumQueries(1, list, Author.objects.raw("SELECT * FROM raw_query_author"))
def test_subquery_in_raw_sql(self):
try:
list(Book.objects.raw('SELECT id FROM (SELECT * FROM raw_query_book WHERE paperback IS NOT NULL) sq'))
except InvalidQuery:
self.fail("Using a subquery in a RawQuerySet raised InvalidQuery")
def test_db_column_name_is_used_in_raw_query(self):
"""
Regression test that ensures the `column` attribute on the field is
used to generate the list of fields included in the query, as opposed
to the `attname`. This is important when the primary key is a
ForeignKey field because `attname` and `column` are not necessarily the
same.
"""
b = BookFkAsPk.objects.create(book=self.b1)
self.assertEqual(list(BookFkAsPk.objects.raw('SELECT not_the_default FROM raw_query_bookfkaspk')), [b])
| bsd-3-clause |
bixbydev/Bixby | google/gdata-2.0.18/tests/gdata_tests/apps/organization/service_test.py | 39 | 15471 | #!/usr/bin/python
#
# Copyright (C) 2008 Google
#
# 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.
"""Test for Organization service."""
__author__ = 'Alexandre Vivien (alex@simplecode.fr)'
import urllib
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata.apps
import gdata.apps.service
import gdata.apps.organization.service
import getpass
import time
domain = ''
admin_email = ''
admin_password = ''
username = ''
class OrganizationTest(unittest.TestCase):
"""Test for the OrganizationService."""
def setUp(self):
self.postfix = time.strftime("%Y%m%d%H%M%S")
self.apps_client = gdata.apps.service.AppsService(
email=admin_email, domain=domain, password=admin_password,
source='OrganizationClient "Unit" Tests')
self.apps_client.ProgrammaticLogin()
self.organization_client = gdata.apps.organization.service.OrganizationService(
email=admin_email, domain=domain, password=admin_password,
source='GroupsClient "Unit" Tests')
self.organization_client.ProgrammaticLogin()
self.created_users = []
self.created_org_units = []
self.cutomer_id = None
self.createUsers();
def createUsers(self):
user_name = 'yujimatsuo-' + self.postfix
family_name = 'Matsuo'
given_name = 'Yuji'
password = '123$$abc'
suspended = 'false'
try:
self.user_yuji = self.apps_client.CreateUser(user_name=user_name,
family_name=family_name,
given_name=given_name,
password=password,
suspended=suspended)
print 'User ' + user_name + ' created'
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.created_users.append(self.user_yuji)
user_name = 'taromatsuo-' + self.postfix
family_name = 'Matsuo'
given_name = 'Taro'
password = '123$$abc'
suspended = 'false'
try:
self.user_taro = self.apps_client.CreateUser(user_name=user_name,
family_name=family_name,
given_name=given_name,
password=password,
suspended=suspended)
print 'User ' + user_name + ' created'
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.created_users.append(self.user_taro)
user_name = 'alexandrevivien-' + self.postfix
family_name = 'Vivien'
given_name = 'Alexandre'
password = '123$$abc'
suspended = 'false'
try:
self.user_alex = self.apps_client.CreateUser(user_name=user_name,
family_name=family_name,
given_name=given_name,
password=password,
suspended=suspended)
print 'User ' + user_name + ' created'
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.created_users.append(self.user_alex)
def tearDown(self):
print '\n'
for user in self.created_users:
try:
self.apps_client.DeleteUser(user.login.user_name)
print 'User ' + user.login.user_name + ' deleted'
except Exception, e:
print e
# We reverse to delete sub OrgUnit first
self.created_org_units.reverse()
for org_unit_path in self.created_org_units:
try:
self.organization_client.DeleteOrgUnit(self.customer_id, org_unit_path)
print 'OrgUnit ' + org_unit_path + ' deleted'
except Exception, e:
print e
def testOrganizationService(self):
# tests RetrieveCustomerId method
try:
customer = self.organization_client.RetrieveCustomerId()
self.customer_id = customer['customerId']
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
print 'tests RetrieveCustomerId successful'
# tests CreateOrgUnit method
orgUnit01_name = 'OrgUnit01-' + self.postfix
orgUnit02_name = 'OrgUnit02-' + self.postfix
sub0rgUnit01_name = 'SubOrgUnit01-' + self.postfix
orgUnit03_name = 'OrgUnit03-' + self.postfix
try:
orgUnit01 = self.organization_client.CreateOrgUnit(self.customer_id,
name=orgUnit01_name,
parent_org_unit_path='/',
description='OrgUnit Test 01',
block_inheritance=False)
orgUnit02 = self.organization_client.CreateOrgUnit(self.customer_id,
name=orgUnit02_name,
parent_org_unit_path='/',
description='OrgUnit Test 02',
block_inheritance=False)
sub0rgUnit01 = self.organization_client.CreateOrgUnit(self.customer_id,
name=sub0rgUnit01_name,
parent_org_unit_path=orgUnit02['orgUnitPath'],
description='SubOrgUnit Test 01',
block_inheritance=False)
orgUnit03 = self.organization_client.CreateOrgUnit(self.customer_id,
name=orgUnit03_name,
parent_org_unit_path='/',
description='OrgUnit Test 03',
block_inheritance=False)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(orgUnit01['orgUnitPath'], urllib.quote_plus(orgUnit01_name))
self.assertEquals(orgUnit02['orgUnitPath'], urllib.quote_plus(orgUnit02_name))
self.assertEquals(sub0rgUnit01['orgUnitPath'], urllib.quote_plus(orgUnit02_name) + '/' + urllib.quote_plus(sub0rgUnit01_name))
self.assertEquals(orgUnit03['orgUnitPath'], urllib.quote_plus(orgUnit03_name))
self.created_org_units.append(orgUnit01['orgUnitPath'])
self.created_org_units.append(orgUnit02['orgUnitPath'])
self.created_org_units.append(sub0rgUnit01['orgUnitPath'])
self.created_org_units.append(orgUnit03['orgUnitPath'])
print 'tests CreateOrgUnit successful'
# tests UpdateOrgUnit method
try:
updated_orgunit = self.organization_client.UpdateOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[3],
description='OrgUnit Test 03 Updated description')
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(updated_orgunit['orgUnitPath'], self.created_org_units[3])
print 'tests UpdateOrgUnit successful'
# tests RetrieveOrgUnit method
try:
retrieved_orgunit = self.organization_client.RetrieveOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[1])
retrieved_suborgunit = self.organization_client.RetrieveOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[2])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(retrieved_orgunit['orgUnitPath'], self.created_org_units[1])
self.assertEquals(retrieved_suborgunit['orgUnitPath'], self.created_org_units[2])
print 'tests RetrieveOrgUnit successful'
# tests RetrieveAllOrgUnits method
try:
retrieved_orgunits = self.organization_client.RetrieveAllOrgUnits(self.customer_id)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertTrue(len(retrieved_orgunits) >= len(self.created_org_units))
print 'tests RetrieveAllOrgUnits successful'
# tests MoveUserToOrgUnit method
try:
updated_orgunit01 = self.organization_client.MoveUserToOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[0],
users_to_move=[self.user_yuji.login.user_name + '@' + domain])
updated_orgunit02 = self.organization_client.MoveUserToOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[1],
users_to_move=[self.user_taro.login.user_name + '@' + domain,
self.user_alex.login.user_name + '@' + domain])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(updated_orgunit01['usersMoved'], self.user_yuji.login.user_name + '@' + domain)
self.assertEquals(updated_orgunit02['usersMoved'], self.user_taro.login.user_name + '@' + domain + ',' + \
self.user_alex.login.user_name + '@' + domain)
print 'tests MoveUserToOrgUnit successful'
# tests RetrieveSubOrgUnits method
try:
retrieved_suborgunits = self.organization_client.RetrieveSubOrgUnits(self.customer_id,
org_unit_path=self.created_org_units[1])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(len(retrieved_suborgunits), 1)
self.assertEquals(retrieved_suborgunits[0]['orgUnitPath'], self.created_org_units[2])
print 'tests RetrieveSubOrgUnits successful'
# tests RetrieveOrgUser method
try:
retrieved_orguser = self.organization_client.RetrieveOrgUser(self.customer_id,
user_email=self.user_yuji.login.user_name + '@' + domain)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(retrieved_orguser['orgUserEmail'], self.user_yuji.login.user_name + '@' + domain)
self.assertEquals(retrieved_orguser['orgUnitPath'], self.created_org_units[0])
print 'tests RetrieveOrgUser successful'
# tests UpdateOrgUser method
try:
updated_orguser = self.organization_client.UpdateOrgUser(self.customer_id,
org_unit_path=self.created_org_units[0],
user_email=self.user_alex.login.user_name + '@' + domain)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(updated_orguser['orgUserEmail'], self.user_alex.login.user_name + '@' + domain)
self.assertEquals(updated_orguser['orgUnitPath'], self.created_org_units[0])
print 'tests UpdateOrgUser successful'
# tests RetrieveAllOrgUsers method
try:
retrieved_orgusers = self.organization_client.RetrieveAllOrgUsers(self.customer_id)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertTrue(len(retrieved_orgusers) >= len(self.created_users))
print 'tests RetrieveAllOrgUsers successful'
""" This test needs to create more than 100 test users
# tests RetrievePageOfOrgUsers method
try:
retrieved_orgusers01_feed = self.organization_client.RetrievePageOfOrgUsers(self.customer_id)
next = retrieved_orgusers01_feed.GetNextLink()
self.assertNotEquals(next, None)
startKey = next.href.split("startKey=")[1]
retrieved_orgusers02_feed = self.organization_client.RetrievePageOfOrgUsers(self.customer_id, startKey=startKey)
retrieved_orgusers01_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers01_feed.entry[0])
retrieved_orgusers02_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers02_feed.entry[0])
self.assertNotEquals(retrieved_orgusers01_entry['orgUserEmail'], retrieved_orgusers02_entry['orgUserEmail'])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
print 'tests RetrievePageOfOrgUsers successful'
"""
# tests RetrieveOrgUnitUsers method
try:
retrieved_orgusers = self.organization_client.RetrieveOrgUnitUsers(self.customer_id,
org_unit_path=self.created_org_units[0])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(len(retrieved_orgusers), 2)
print 'tests RetrieveOrgUnitUsers successful'
""" This test needs to create more than 100 test users
# tests RetrieveOrgUnitPageOfUsers method
try:
retrieved_orgusers01_feed = self.organization_client.RetrieveOrgUnitPageOfUsers(self.customer_id,
org_unit_path='/')
next = retrieved_orgusers01_feed.GetNextLink()
self.assertNotEquals(next, None)
startKey = next.href.split("startKey=")[1]
retrieved_orgusers02_feed = self.organization_client.RetrieveOrgUnitPageOfUsers(self.customer_id,
org_unit_path='/',
startKey=startKey)
retrieved_orgusers01_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers01_feed.entry[0])
retrieved_orgusers02_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers02_feed.entry[0])
self.assertNotEquals(retrieved_orgusers01_entry['orgUserEmail'], retrieved_orgusers02_entry['orgUserEmail'])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
print 'tests RetrieveOrgUnitPageOfUsers successful'
"""
if __name__ == '__main__':
print("""Google Apps Groups Service Tests
NOTE: Please run these tests only with a test user account.
""")
domain = raw_input('Google Apps domain: ')
admin_email = '%s@%s' % (raw_input('Administrator username: '), domain)
admin_password = getpass.getpass('Administrator password: ')
unittest.main()
| gpl-3.0 |
Yellowen/Owrang | setup/doctype/item_group/item_group.py | 2 | 2002 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import webnotes
from webnotes.utils.nestedset import DocTypeNestedSet
class DocType(DocTypeNestedSet):
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
self.nsm_parent_field = 'parent_item_group'
def on_update(self):
super(DocType, self).on_update()
self.validate_name_with_item()
from selling.utils.product import invalidate_cache_for
if self.doc.show_in_website:
from webnotes.webutils import update_page_name
# webpage updates
page_name = self.doc.name
update_page_name(self.doc, page_name)
invalidate_cache_for(self.doc.name)
elif self.doc.page_name:
# if unchecked show in website
from webnotes.webutils import delete_page_cache
delete_page_cache(self.doc.page_name)
invalidate_cache_for(self.doc.name)
webnotes.conn.set(self.doc, "page_name", None)
self.validate_one_root()
def validate_name_with_item(self):
if webnotes.conn.exists("Item", self.doc.name):
webnotes.msgprint("An item exists with same name (%s), please change the \
item group name or rename the item" % self.doc.name, raise_exception=1)
def get_context(self):
from selling.utils.product import get_product_list_for_group, \
get_parent_item_groups, get_group_item_count
self.doc.sub_groups = webnotes.conn.sql("""select name, page_name
from `tabItem Group` where parent_item_group=%s
and ifnull(show_in_website,0)=1""", self.doc.name, as_dict=1)
for d in self.doc.sub_groups:
d.count = get_group_item_count(d.name)
self.doc.items = get_product_list_for_group(product_group = self.doc.name, limit=100)
self.parent_groups = get_parent_item_groups(self.doc.name)
self.doc.title = self.doc.name
if self.doc.slideshow:
from website.doctype.website_slideshow.website_slideshow import get_slideshow
get_slideshow(self)
| agpl-3.0 |
rubyinhell/brython | www/src/Lib/test/test_copyreg.py | 173 | 4217 | import copyreg
import unittest
from test import support
from test.pickletester import ExtensionSaver
class C:
pass
class WithoutSlots(object):
pass
class WithWeakref(object):
__slots__ = ('__weakref__',)
class WithPrivate(object):
__slots__ = ('__spam',)
class WithSingleString(object):
__slots__ = 'spam'
class WithInherited(WithSingleString):
__slots__ = ('eggs',)
class CopyRegTestCase(unittest.TestCase):
def test_class(self):
self.assertRaises(TypeError, copyreg.pickle,
C, None, None)
def test_noncallable_reduce(self):
self.assertRaises(TypeError, copyreg.pickle,
type(1), "not a callable")
def test_noncallable_constructor(self):
self.assertRaises(TypeError, copyreg.pickle,
type(1), int, "not a callable")
def test_bool(self):
import copy
self.assertEqual(True, copy.copy(True))
def test_extension_registry(self):
mod, func, code = 'junk1 ', ' junk2', 0xabcd
e = ExtensionSaver(code)
try:
# Shouldn't be in registry now.
self.assertRaises(ValueError, copyreg.remove_extension,
mod, func, code)
copyreg.add_extension(mod, func, code)
# Should be in the registry.
self.assertTrue(copyreg._extension_registry[mod, func] == code)
self.assertTrue(copyreg._inverted_registry[code] == (mod, func))
# Shouldn't be in the cache.
self.assertNotIn(code, copyreg._extension_cache)
# Redundant registration should be OK.
copyreg.add_extension(mod, func, code) # shouldn't blow up
# Conflicting code.
self.assertRaises(ValueError, copyreg.add_extension,
mod, func, code + 1)
self.assertRaises(ValueError, copyreg.remove_extension,
mod, func, code + 1)
# Conflicting module name.
self.assertRaises(ValueError, copyreg.add_extension,
mod[1:], func, code )
self.assertRaises(ValueError, copyreg.remove_extension,
mod[1:], func, code )
# Conflicting function name.
self.assertRaises(ValueError, copyreg.add_extension,
mod, func[1:], code)
self.assertRaises(ValueError, copyreg.remove_extension,
mod, func[1:], code)
# Can't remove one that isn't registered at all.
if code + 1 not in copyreg._inverted_registry:
self.assertRaises(ValueError, copyreg.remove_extension,
mod[1:], func[1:], code + 1)
finally:
e.restore()
# Shouldn't be there anymore.
self.assertNotIn((mod, func), copyreg._extension_registry)
# The code *may* be in copyreg._extension_registry, though, if
# we happened to pick on a registered code. So don't check for
# that.
# Check valid codes at the limits.
for code in 1, 0x7fffffff:
e = ExtensionSaver(code)
try:
copyreg.add_extension(mod, func, code)
copyreg.remove_extension(mod, func, code)
finally:
e.restore()
# Ensure invalid codes blow up.
for code in -1, 0, 0x80000000:
self.assertRaises(ValueError, copyreg.add_extension,
mod, func, code)
def test_slotnames(self):
self.assertEqual(copyreg._slotnames(WithoutSlots), [])
self.assertEqual(copyreg._slotnames(WithWeakref), [])
expected = ['_WithPrivate__spam']
self.assertEqual(copyreg._slotnames(WithPrivate), expected)
self.assertEqual(copyreg._slotnames(WithSingleString), ['spam'])
expected = ['eggs', 'spam']
expected.sort()
result = copyreg._slotnames(WithInherited)
result.sort()
self.assertEqual(result, expected)
def test_main():
support.run_unittest(CopyRegTestCase)
if __name__ == "__main__":
test_main()
| bsd-3-clause |
technologiescollege/s2a_fr | s2a/Python/Lib/idlelib/AutoExpand.py | 227 | 2483 | import string
import re
###$ event <<expand-word>>
###$ win <Alt-slash>
###$ unix <Alt-slash>
class AutoExpand:
menudefs = [
('edit', [
('E_xpand Word', '<<expand-word>>'),
]),
]
wordchars = string.ascii_letters + string.digits + "_"
def __init__(self, editwin):
self.text = editwin.text
self.state = None
def expand_word_event(self, event):
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
if not self.state:
words = self.getwords()
index = 0
else:
words, index, insert, line = self.state
if insert != curinsert or line != curline:
words = self.getwords()
index = 0
if not words:
self.text.bell()
return "break"
word = self.getprevword()
self.text.delete("insert - %d chars" % len(word), "insert")
newword = words[index]
index = (index + 1) % len(words)
if index == 0:
self.text.bell() # Warn we cycled around
self.text.insert("insert", newword)
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
self.state = words, index, curinsert, curline
return "break"
def getwords(self):
word = self.getprevword()
if not word:
return []
before = self.text.get("1.0", "insert wordstart")
wbefore = re.findall(r"\b" + word + r"\w+\b", before)
del before
after = self.text.get("insert wordend", "end")
wafter = re.findall(r"\b" + word + r"\w+\b", after)
del after
if not wbefore and not wafter:
return []
words = []
dict = {}
# search backwards through words before
wbefore.reverse()
for w in wbefore:
if dict.get(w):
continue
words.append(w)
dict[w] = w
# search onwards through words after
for w in wafter:
if dict.get(w):
continue
words.append(w)
dict[w] = w
words.append(word)
return words
def getprevword(self):
line = self.text.get("insert linestart", "insert")
i = len(line)
while i > 0 and line[i-1] in self.wordchars:
i = i-1
return line[i:]
| gpl-3.0 |
danalec/dotfiles | sublime/.config/sublime-text-3/Packages/SublimeCodeIntel/libs/codeintel2/lang_php.py | 6 | 152263 | #!/usr/bin/env python
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is Komodo code.
#
# The Initial Developer of the Original Code is ActiveState Software Inc.
# Portions created by ActiveState Software Inc are Copyright (C) 2000-2007
# ActiveState Software Inc. All Rights Reserved.
#
# Contributor(s):
# ActiveState Software Inc
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
#
# Contributors:
# Shane Caraveo (ShaneC@ActiveState.com)
# Trent Mick (TrentM@ActiveState.com)
# Todd Whiteman (ToddW@ActiveState.com)
"""codeintel support for PHP"""
import os
from os.path import isdir, join, basename, splitext, exists, dirname
import sys
import re
import logging
import time
import warnings
from io import StringIO
import weakref
from glob import glob
from SilverCity.ScintillaConstants import (SCE_UDL_SSL_DEFAULT,
SCE_UDL_SSL_OPERATOR,
SCE_UDL_SSL_IDENTIFIER,
SCE_UDL_SSL_WORD,
SCE_UDL_SSL_VARIABLE,
SCE_UDL_SSL_STRING,
SCE_UDL_SSL_NUMBER,
SCE_UDL_SSL_COMMENT,
SCE_UDL_SSL_COMMENTBLOCK)
from codeintel2.parseutil import *
from codeintel2.phpdoc import phpdoc_tags
from codeintel2.citadel import ImportHandler, CitadelLangIntel
from codeintel2.udl import UDLBuffer, UDLLexer, UDLCILEDriver, is_udl_csl_style, XMLParsingBufferMixin
from codeintel2.common import *
from codeintel2 import util
from codeintel2.indexer import PreloadBufLibsRequest, PreloadLibRequest
from codeintel2.gencix_utils import *
from codeintel2.tree_php import PHPTreeEvaluator
from codeintel2.langintel import (ParenStyleCalltipIntelMixin,
ProgLangTriggerIntelMixin)
from codeintel2.accessor import AccessorCache, KoDocumentAccessor
if _xpcom_:
from xpcom.server import UnwrapObject
#---- global data
lang = "PHP"
log = logging.getLogger("codeintel.php")
# log.setLevel(logging.DEBUG)
util.makePerformantLogger(log)
#---- language support
class PHPLexer(UDLLexer):
lang = lang
def _walk_php_symbols(elem, _prefix=None):
if _prefix:
lpath = _prefix + (elem.get("name"), )
else:
lpath = (elem.get("name"), )
yield lpath
if not (elem.tag == "scope" and elem.get("ilk") == "function"):
for child in elem:
for child_lpath in _walk_php_symbols(child, lpath):
yield child_lpath
class PHPLangIntel(CitadelLangIntel, ParenStyleCalltipIntelMixin,
ProgLangTriggerIntelMixin):
lang = lang
# Used by ProgLangTriggerIntelMixin.preceding_trg_from_pos()
trg_chars = tuple('$>:(,@"\' \\')
calltip_trg_chars = tuple('(') # excluded ' ' for perf (bug 55497)
# named styles used by the class
whitespace_style = SCE_UDL_SSL_DEFAULT
operator_style = SCE_UDL_SSL_OPERATOR
identifier_style = SCE_UDL_SSL_IDENTIFIER
keyword_style = SCE_UDL_SSL_WORD
variable_style = SCE_UDL_SSL_VARIABLE
string_style = SCE_UDL_SSL_STRING
comment_styles = (SCE_UDL_SSL_COMMENT, SCE_UDL_SSL_COMMENTBLOCK)
comment_styles_or_whitespace = comment_styles + (whitespace_style, )
def _functionCalltipTrigger(self, ac, pos, DEBUG=False):
# Implicit calltip triggering from an arg separater ",", we trigger a
# calltip if we find a function open paren "(" and function identifier
# http://bugs.activestate.com/show_bug.cgi?id=70470
if DEBUG:
print("Arg separater found, looking for start of function")
# Move back to the open paren of the function
paren_count = 0
p = pos
min_p = max(0, p - 200) # look back max 200 chars
while p > min_p:
p, c, style = ac.getPrecedingPosCharStyle(
ignore_styles=self.comment_styles)
if style == self.operator_style:
if c == ")":
paren_count += 1
elif c == "(":
if paren_count == 0:
# We found the open brace of the func
trg_from_pos = p+1
p, ch, style = ac.getPrevPosCharStyle()
if DEBUG:
print("Function start found, pos: %d" % (p, ))
if style in self.comment_styles_or_whitespace:
# Find previous non-ignored style then
p, c, style = ac.getPrecedingPosCharStyle(
style, self.comment_styles_or_whitespace)
if style in (self.identifier_style, self.keyword_style):
return Trigger(lang, TRG_FORM_CALLTIP,
"call-signature",
trg_from_pos, implicit=True)
else:
paren_count -= 1
elif c in ";{}":
# Gone too far and noting was found
if DEBUG:
print("No function found, hit stop char: %s at p: %d" % (c, p))
return None
# Did not find the function open paren
if DEBUG:
print("No function found, ran out of chars to look at, p: %d" % (p,))
return None
#@util.hotshotit
def trg_from_pos(self, buf, pos, implicit=True, DEBUG=False, ac=None):
# DEBUG = True
if pos < 4:
return None
# DEBUG = True
# Last four chars and styles
if ac is None:
ac = AccessorCache(buf.accessor, pos, fetchsize=4)
last_pos, last_char, last_style = ac.getPrevPosCharStyle()
prev_pos, prev_char, prev_style = ac.getPrevPosCharStyle()
# Bump up how much text is retrieved when cache runs out
ac.setCacheFetchSize(20)
if DEBUG:
print("\nphp trg_from_pos")
print(" last_pos: %s" % last_pos)
print(" last_char: %s" % last_char)
print(" last_style: %r" % last_style)
ac.dump()
try:
# Note: If a "$" exists by itself, it's styled as whitespace.
# Generally we want it to be indicating a variable instead.
if last_style == self.whitespace_style and last_char != "$":
if DEBUG:
print("Whitespace style")
WHITESPACE = tuple(" \t\n\r\v\f")
if not implicit:
# If we're not already at the keyword style, find it
if prev_style != self.keyword_style:
prev_pos, prev_char, prev_style = ac.getPrecedingPosCharStyle(
last_style, self.comment_styles)
if DEBUG:
print("Explicit: prev_pos: %d, style: %d, ch: %r" % (prev_pos, prev_style, prev_char))
else:
prev_pos = pos - 2
if last_char in WHITESPACE and \
(prev_style == self.keyword_style or
(prev_style == self.operator_style and prev_char == ",")):
p = prev_pos
style = prev_style
ch = prev_char
# print "p: %d" % p
while p > 0 and style == self.operator_style and ch == ",":
p, ch, style = ac.getPrecedingPosCharStyle(
style, self.comment_styles_or_whitespace)
# print "p 1: %d" % p
if p > 0 and style == self.identifier_style:
# Skip the identifier too
p, ch, style = ac.getPrecedingPosCharStyle(
style, self.comment_styles_or_whitespace)
# print "p 2: %d" % p
if DEBUG:
ac.dump()
p, text = ac.getTextBackWithStyle(
style, self.comment_styles, max_text_len=len("implements"))
if DEBUG:
print("ac.getTextBackWithStyle:: pos: %d, text: %r" % (p, text))
if text in ("new", "extends"):
return Trigger(lang, TRG_FORM_CPLN, "classes", pos, implicit)
elif text in ("implements", ):
return Trigger(lang, TRG_FORM_CPLN, "interfaces", pos, implicit)
elif text in ("use", ):
return Trigger(lang, TRG_FORM_CPLN, "use", pos, implicit)
elif prev_style == self.operator_style and \
prev_char == "," and implicit:
return self._functionCalltipTrigger(ac, prev_pos, DEBUG)
elif text == "namespace":
return Trigger(lang, TRG_FORM_CPLN, "use-global-namespaces", pos, implicit)
elif last_style == self.operator_style:
if DEBUG:
print(" lang_style is operator style")
print("Prev char: %r" % (prev_char))
ac.dump()
if last_char == ":":
if not prev_char == ":":
return None
ac.setCacheFetchSize(10)
p, c, style = ac.getPrecedingPosCharStyle(
prev_style, self.comment_styles)
if DEBUG:
print("Preceding: %d, %r, %d" % (p, c, style))
if style is None:
return None
elif style == self.keyword_style:
# Check if it's a "self::" or "parent::" expression
p, text = ac.getTextBackWithStyle(self.keyword_style,
# Ensure we don't go
# too far
max_text_len=6)
if DEBUG:
print("Keyword text: %d, %r" % (p, text))
ac.dump()
if text not in ("parent", "self", "static"):
return None
return Trigger(lang, TRG_FORM_CPLN, "static-members",
pos, implicit)
elif last_char == ">":
if prev_char == "-":
p, c, style = ac.getPrevPosCharStyle(
ignore_styles=self.comment_styles_or_whitespace)
if style in (self.variable_style, self.identifier_style) or \
(style == self.operator_style and c == ')'):
return Trigger(
lang, TRG_FORM_CPLN, "object-members",
pos, implicit)
elif DEBUG:
print("Preceding style is not a variable, pos: %d, style: %d" % (p, style))
elif last_char in "(,":
# where to trigger from, updated by "," calltip handler
if DEBUG:
print("Checking for function calltip")
# Implicit calltip triggering from an arg separater ","
# http://bugs.activestate.com/show_bug.cgi?id=70470
if implicit and last_char == ',':
return self._functionCalltipTrigger(ac, prev_pos, DEBUG)
if prev_style in self.comment_styles_or_whitespace:
# Find previous non-ignored style then
p, c, prev_style = ac.getPrecedingPosCharStyle(
prev_style, self.comment_styles_or_whitespace)
if prev_style in (self.identifier_style, self.keyword_style):
if buf.caller == "on_modified":
##call function trigger in within function brackets
if last_char == "(" and buf.orig_pos-pos >= 3:
## at least 3 char have been typed to trigger
if buf.accessor.char_at_pos(buf.orig_pos-1) in "(,\"":
#don't annoy with completions to early
return None
trig_pos, ch, style = ac.getPrevPosCharStyle()
return Trigger(
lang, TRG_FORM_CPLN, "functions",
buf.orig_pos-3, implicit)
else:
return Trigger(
lang, TRG_FORM_CALLTIP, "call-signature",
pos, implicit)
elif last_char == "\\":
style = last_style
while style in (self.operator_style, self.identifier_style):
p, c, style = ac.getPrecedingPosCharStyle(
style, max_look_back=30)
if style == self.whitespace_style:
p, c, style = ac.getPrecedingPosCharStyle(
self.whitespace_style, max_look_back=30)
if style is None:
if DEBUG:
print("Triggering namespace completion")
return Trigger(
lang, TRG_FORM_CPLN, "namespace-members",
pos, implicit)
prev_text = ac.getTextBackWithStyle(style, max_text_len=15)
if DEBUG:
print("prev_text: %r" % (prev_text, ))
if prev_text[1] == "use":
if DEBUG:
print("Triggering use-namespace completion")
return Trigger(lang, TRG_FORM_CPLN, "use-namespace",
pos, implicit)
elif prev_text[1] == "namespace": #namespace completions on "namespace" keyword!
if DEBUG:
print("Triggering namespace completion")
return Trigger(
lang, TRG_FORM_CPLN, "namespace-members-nmspc-only",
pos, implicit)
else:
if DEBUG:
print("Triggering namespace completion")
return Trigger(
lang, TRG_FORM_CPLN, "namespace-members",
pos, implicit)
elif last_style == self.variable_style or (not implicit and last_char == "$"):
if DEBUG:
print("Variable style")
if prev_char == ":":
if not prev_char == ":":
return None
ac.setCacheFetchSize(10)
p, c, style = ac.getPrecedingPosCharStyle(
prev_style, self.comment_styles)
if DEBUG:
print("Preceding: %d, %r, %d" % (p, c, style))
if style is None:
return None
elif style == self.keyword_style:
# Check if it's a "self::" or "parent::" expression
p, text = ac.getTextBackWithStyle(self.keyword_style,
# Ensure we don't go
# too far
max_text_len=6)
if DEBUG:
print("Keyword text: %d, %r" % (p, text))
ac.dump()
print(text)
#if text not in ("parent", "self", "static"):
# return None
return Trigger(lang, TRG_FORM_CPLN, "static-members",
pos, implicit)
# Completion for variables (builtins and user defined variables),
# must occur after a "$" character.
if not implicit and last_char == '$':
# Explicit call, move ahead one for real trigger position
pos += 1
if not implicit or prev_char == "$":
# Ensure we are not triggering over static class variables.
# Do this by checking that the preceding text is not "::"
# http://bugs.activestate.com/show_bug.cgi?id=78099
p, c, style = ac.getPrecedingPosCharStyle(last_style,
max_look_back=30)
if c == ":" and style == self.operator_style and \
ac.getTextBackWithStyle(style, max_text_len=3)[1] == "::":
return None
return Trigger(lang, TRG_FORM_CPLN, "variables",
pos-1, implicit)
elif last_style in (self.identifier_style, self.keyword_style):
if DEBUG:
if last_style == self.identifier_style:
print("Identifier style")
else:
print("Identifier keyword style")
# Completion for keywords,function and class names
# Works after first 3 characters have been typed
# if DEBUG:
# print "identifier_style: pos - 4 %s" % (accessor.style_at_pos(pos - 4))
# third_char, third_style = last_four_char_and_styles[2]
# fourth_char, fourth_style = last_four_char_and_styles[3]
if prev_style == last_style:
trig_pos, ch, style = ac.getPrevPosCharStyle()
if buf.accessor.char_at_pos(pos-2) == '_' and buf.accessor.char_at_pos(pos-3) == '_' and buf.accessor.style_at_pos(pos-4) == self.whitespace_style:
# XXX - Check the php version, magic methods only
# appeared in php 5.
#
p, ch, style = ac.getPrevPosCharStyle(ignore_styles=self.comment_styles)
last_keyword = ac.getTextBackWithStyle(self.keyword_style, max_text_len=9)[1].strip()
if last_keyword == "function":
if DEBUG:
print("triggered:: complete magic-methods")
return Trigger(
lang, TRG_FORM_CPLN, "magic-methods",
prev_pos, implicit)
elif style == last_style:
p, ch, style = ac.getPrevPosCharStyle(
ignore_styles=self.comment_styles)
# style is None if no change of style (not ignored) was
# found in the last x number of chars
# if not implicit and style == last_style:
# if DEBUG:
# print "Checking back further for explicit call"
# p, c, style = ac.getPrecedingPosCharStyle(style, max_look_back=100)
# if p is not None:
# trg_pos = p + 3
if style in (None, self.whitespace_style,
self.operator_style):
# Ensure we are not in another trigger zone, we do
# this by checking that the preceeding text is not
# one of "->", "::", "new", "function", "class",
# ...
if style == self.whitespace_style:
p, c, style = ac.getPrecedingPosCharStyle(
self.whitespace_style, max_look_back=30)
if style is None:
return Trigger(
lang, TRG_FORM_CPLN, "functions",
trig_pos, implicit)
prev_text = ac.getTextBackWithStyle(
style, max_text_len=15)
if DEBUG:
print("prev_text: %r" % (prev_text, ))
if (prev_text[1] not in ("new", "function", "use",
"class", "interface", "implements",
"public", "private", "protected",
"final", "abstract", "instanceof",)
# For the operator styles, we must use
# endswith, as it could follow a "()",
# bug 90846.
and prev_text[1][-2:] not in ("->", "::",)
# Don't trigger when accessing a
# namespace - bug 88736.
and not prev_text[1].endswith("\\")):
return Trigger(
lang, TRG_FORM_CPLN, "functions",
trig_pos, implicit)
# If we want implicit triggering on more than 3 chars
# elif style == self.identifier_style:
# p, c, style = ac.getPrecedingPosCharStyle(self.identifier_style)
# return Trigger(lang, TRG_FORM_CPLN, "functions",
# p+1, implicit)
elif DEBUG:
print("identifier preceeded by an invalid style: " \
"%r, p: %r" % (style, p, ))
# PHPDoc completions
elif last_char == "@" and last_style in self.comment_styles:
# If the preceeding non-whitespace character is a "*" or newline
# then we complete for phpdoc tag names
p = last_pos - 1
min_p = max(0, p - 50) # Don't look more than 50 chars
if DEBUG:
print("Checking match for phpdoc completions")
accessor = buf.accessor
while p >= min_p and \
accessor.style_at_pos(p) in self.comment_styles:
ch = accessor.char_at_pos(p)
p -= 1
# if DEBUG:
# print "Looking at ch: %r" % (ch)
if ch in "*\r\n":
break
elif ch not in " \t\v":
# Not whitespace, not a valid tag then
return None
else:
# Nothing found in the specified range
if DEBUG:
print("trg_from_pos: not a phpdoc")
return None
if DEBUG:
print("Matched trigger for phpdoc completion")
return Trigger("PHP", TRG_FORM_CPLN,
"phpdoc-tags", pos, implicit)
# PHPDoc calltip
elif last_char in " \t" and last_style in self.comment_styles:
# whitespace in a comment, see if it matches for phpdoc calltip
p = last_pos - 1
min_p = max(0, p - 50) # Don't look more than 50 chars
if DEBUG:
print("Checking match for phpdoc calltip")
ch = None
ident_found_pos = None
accessor = buf.accessor
while p >= min_p and \
accessor.style_at_pos(p) in self.comment_styles:
ch = accessor.char_at_pos(p)
p -= 1
if ident_found_pos is None:
# print "phpdoc: Looking for identifier, ch: %r" % (ch)
if ch in " \t":
pass
elif _isident(ch):
ident_found_pos = p+1
else:
if DEBUG:
print("No phpdoc, whitespace not preceeded " \
"by an identifer")
return None
elif ch == "@":
# This is what we've been looking for!
phpdoc_field = accessor.text_range(p+2,
ident_found_pos+1)
if DEBUG:
print("Matched trigger for phpdoc calltip: '%s'" % (
phpdoc_field, ))
return Trigger("PHP", TRG_FORM_CALLTIP,
"phpdoc-tags", ident_found_pos, implicit,
phpdoc_field=phpdoc_field)
elif not _isident(ch):
if DEBUG:
print("No phpdoc, identifier not preceeded by '@'")
# Not whitespace, not a valid tag then
return None
# Nothing found in the specified range
if DEBUG:
print("No phpdoc, ran out of characters to look at.")
# Array completions
elif last_style == self.string_style and last_char in '\'"':
if prev_char != '[':
if prev_style in self.comment_styles_or_whitespace:
# Look back further.
prev_pos, prev_char, prev_style = ac.getPrevPosCharStyle(
ignore_styles=self.comment_styles_or_whitespace)
if prev_char == '[':
# We're good to go.
if DEBUG:
print("Matched trigger for array completions")
return Trigger("PHP", TRG_FORM_CPLN,
"array-members", pos, implicit,
bracket_pos=prev_pos,
trg_char=last_char)
# Variable completions inside of comments
elif prev_char == "$" and last_style in self.comment_styles:
if DEBUG:
print("Comment variable style")
# Completion for variables (builtins and user defined variables),
# must occur after a "$" character.
return Trigger(lang, TRG_FORM_CPLN, "comment-variables",
pos-1, implicit)
elif DEBUG:
print("trg_from_pos: no handle for style: %d" % last_style)
except IndexError:
# Not enough chars found, therefore no trigger
pass
return None
#@util.hotshotit
def preceding_trg_from_pos(self, buf, pos, curr_pos,
preceding_trg_terminators=None, DEBUG=False):
# DEBUG = True
# Try the default preceding_trg_from_pos handler
trg = ProgLangTriggerIntelMixin.preceding_trg_from_pos(
self, buf, pos, curr_pos, preceding_trg_terminators,
DEBUG=DEBUG)
if trg is not None:
return trg
# Else, let's try to work out some other options
accessor = buf.accessor
prev_style = accessor.style_at_pos(curr_pos - 1)
if prev_style in (self.identifier_style, self.keyword_style):
# We don't know what to trigger here... could be one of:
# functions:
# apache<$><|>_getenv()...
# if(get_e<$><|>nv()...
# classes:
# new Exce<$><|>ption()...
# extends Exce<$><|>ption()...
# interfaces:
# implements apache<$><|>_getenv()...
ac = AccessorCache(accessor, curr_pos)
pos_before_identifer, ch, prev_style = \
ac.getPrecedingPosCharStyle(prev_style)
if DEBUG:
print("\nphp preceding_trg_from_pos, first chance for identifer style")
print(" curr_pos: %d" % (curr_pos))
print(" pos_before_identifer: %d" % (pos_before_identifer))
print(" ch: %r" % ch)
print(" prev_style: %d" % prev_style)
ac.dump()
if pos_before_identifer < pos:
last_keyword = ac.getTextBackWithStyle(self.keyword_style, max_text_len=9)[1].strip()
if last_keyword == "namespace":
implicit = False
return Trigger(
lang, TRG_FORM_CPLN, "use-global-namespaces",
pos, implicit)
resetPos = min(pos_before_identifer + 4, accessor.length() - 1)
ac.resetToPosition(resetPos)
if DEBUG:
print("preceding_trg_from_pos:: reset to position: %d, ac now:" % (resetPos))
ac.dump()
# Trigger on the third identifier character
return self.trg_from_pos(buf, resetPos,
implicit=False, DEBUG=DEBUG, ac=ac)
elif DEBUG:
print("Out of scope of the identifier")
elif prev_style in self.comment_styles:
# Check if there is a PHPDoc to provide a calltip for, example:
# /** @param $foo foobar - This is field for <|>
if DEBUG:
print("\nphp preceding_trg_from_pos::phpdoc: check for calltip")
comment = accessor.text_range(max(0, curr_pos-200), curr_pos)
at_idx = comment.rfind("@")
if at_idx >= 0:
if DEBUG:
print("\nphp preceding_trg_from_pos::phpdoc: contains '@'")
space_idx = comment[at_idx:].find(" ")
if space_idx >= 0:
# Trigger after the space character.
trg_pos = (curr_pos - len(
comment)) + at_idx + space_idx + 1
if DEBUG:
print("\nphp preceding_trg_from_pos::phpdoc: calltip at %d" % (trg_pos, ))
return self.trg_from_pos(buf, trg_pos,
implicit=False, DEBUG=DEBUG)
_phpdoc_cplns = [("variable", t) for t in sorted(phpdoc_tags)]
#@util.hotshotit
def async_eval_at_trg(self, buf, trg, ctlr):
buf.last_citdl_expr = None
if _xpcom_:
trg = UnwrapObject(trg)
ctlr = UnwrapObject(ctlr)
pos = trg.pos
ctlr.start(buf, trg)
# print "trg.type: %r" % (trg.type)
# PHPDoc completions
if trg.id == ("PHP", TRG_FORM_CPLN, "phpdoc-tags"):
# TODO: Would like a "javadoc tag" completion image name.
ctlr.set_cplns(self._phpdoc_cplns)
ctlr.done("success")
return
# PHPDoc calltip
elif trg.id == ("PHP", TRG_FORM_CALLTIP, "phpdoc-tags"):
phpdoc_field = trg.extra.get("phpdoc_field")
if phpdoc_field:
# print "phpdoc_field: %r" % (phpdoc_field, )
calltip = phpdoc_tags.get(phpdoc_field)
if calltip:
ctlr.set_calltips([calltip])
ctlr.done("success")
return
elif trg.type in ("classes", "interfaces"):
# Triggers from zero characters, thus calling citdl_expr_from_trg
# is no help
line = buf.accessor.line_from_pos(pos)
evalr = PHPTreeEvaluator(ctlr, buf, trg, "", line)
buf.mgr.request_eval(evalr)
else:
if trg.type == "static-members":
if buf.accessor.char_at_pos(trg.pos-1) == "$":
#adjust trigger position so that static properties
#with leading "$" will scatter the citdl_expr
trg.pos -= 1
try:
citdl_expr = self.citdl_expr_from_trg(buf, trg)
except CodeIntelError as ex:
ctlr.error(str(ex))
ctlr.done("error")
return
buf.last_citdl_expr = citdl_expr
line = buf.accessor.line_from_pos(pos)
evalr = PHPTreeEvaluator(ctlr, buf, trg, citdl_expr, line)
buf.mgr.request_eval(evalr)
def _citdl_expr_from_pos(self, trg, buf, pos, implicit=True,
include_forwards=False, DEBUG=False):
# DEBUG = True
# PERF: Would dicts be faster for all of these?
WHITESPACE = tuple(" \t\n\r\v\f")
EOL = tuple("\r\n")
BLOCKCLOSES = tuple(")}]")
STOPOPS = tuple("({[,&$+=^|%/<;:->!.@?")
EXTRA_STOPOPS_PRECEDING_IDENT = BLOCKCLOSES # Might be others.
# TODO: This style picking is a problem for the LangIntel move.
if trg.type == "comment-variables":
# Dev note: skip_styles in the other cases below will be a dict.
skip_styles = set()
elif implicit:
skip_styles = buf.implicit_completion_skip_styles
else:
skip_styles = buf.completion_skip_styles
citdl_expr = []
accessor = buf.accessor
# Use a cache of characters, easy to keep track this way
i = pos
ac = AccessorCache(accessor, i)
if include_forwards:
try:
# Move ahead to include forward chars as well
lastch_was_whitespace = False
while 1:
i, ch, style = ac.getNextPosCharStyle()
if DEBUG:
print("include_forwards:: i now: %d, ch: %r" % (i, ch))
if ch in WHITESPACE:
lastch_was_whitespace = True
continue
lastch_was_whitespace = False
if ch in STOPOPS:
if DEBUG:
print("include_forwards:: ch in STOPOPS, i:%d ch:%r" % (i, ch))
break
elif ch in BLOCKCLOSES:
if DEBUG:
print("include_forwards:: ch in BLOCKCLOSES, i:%d ch:%r" % (i, ch))
break
elif lastch_was_whitespace:
# Two whitespace separated words
if DEBUG:
print("include_forwards:: ch separated by whitespace, i:%d ch:%r" % (i, ch))
break
# Move back to last valid char
i -= 1
if DEBUG:
if i > pos:
print("include_forwards:: Including chars from pos %d up to %d" % (pos, i))
else:
print("include_forwards:: No valid chars forward from pos %d, i now: %d" % (pos, i))
except IndexError:
# Nothing forwards, user what we have then
i = min(i, accessor.length() - 1)
if DEBUG:
print("include_forwards:: No more buffer, i now: %d" % (i))
ac.resetToPosition(i)
ch = None
try:
while i >= 0:
if ch == None and include_forwards:
i, ch, style = ac.getCurrentPosCharStyle()
else:
i, ch, style = ac.getPrevPosCharStyle()
if DEBUG:
print("i now: %d, ch: %r" % (i, ch))
if ch in WHITESPACE:
if trg.type in ("use-namespace", "namespace-members", "namespace-members-nmspc-only"):
# Namespaces cannot be split over whitespace.
break
while ch in WHITESPACE:
# drop all whitespace
next_char = ch
i, ch, style = ac.getPrevPosCharStyle()
if ch in WHITESPACE \
or (ch == '\\' and next_char in EOL):
if DEBUG:
print("drop whitespace: %r" % ch)
# If there are two whitespace-separated words then this is
# (likely or always?) a language keyword or declaration
# construct at which we want to stop. E.g.
# if foo<|> and ...
# def foo<|>(...
# if \foo<|>(... # uses a namespace
if citdl_expr \
and (_isident(citdl_expr[-1]) or citdl_expr[-1] == '\\') \
and (_isident(ch) or _isdigit(ch)):
if DEBUG:
print("stop at (likely?) start of keyword or "\
"declaration: %r" % ch)
break
# Not whitespace anymore, move into the main checks below
if DEBUG:
print("Out of whitespace: i now: %d, ch: %s" % (i, ch))
if style in skip_styles: # drop styles to ignore
while i >= 0 and style in skip_styles:
i, ch, style = ac.getPrevPosCharStyle()
if DEBUG:
print("drop char of style to ignore: %r" % ch)
elif ch in ":>" and i > 0:
# Next char has to be ":" or "-" respectively
prev_pos, prev_ch, prev_style = ac.getPrevPosCharStyle()
if (ch == ">" and prev_ch == "-") or \
(ch == ":" and prev_ch == ":"):
citdl_expr.append(".")
if DEBUG:
print("Turning member accessor '%s%s' into '.'" % (prev_ch, ch))
i -= 2
else:
if DEBUG:
print("citdl_expr: %r" % (citdl_expr))
print("stop at special stop-operator %d: %r" % (i, ch))
break
elif (ch in STOPOPS or ch in EXTRA_STOPOPS_PRECEDING_IDENT) and \
(ch != ")" or (citdl_expr and citdl_expr[-1] != ".")):
if ch == '$':
# This may not be the end of the road, given static
# variables are accessed through "Class::$static".
prev_pos, prev_ch, prev_style = ac.peekPrevPosCharStyle(
)
if prev_ch == ":":
# Continue building up the citdl then.
continue
if DEBUG:
print("citdl_expr: %r" % (citdl_expr))
print("stop at stop-operator %d: %r" % (i, ch))
break
elif ch in BLOCKCLOSES:
if DEBUG:
print("found block at %d: %r" % (i, ch))
citdl_expr.append(ch)
BLOCKS = { # map block close char to block open char
')': '(',
']': '[',
'}': '{',
}
stack = []
# stack of blocks: (<block close char>, <style>)
stack.append((ch, style, BLOCKS[ch], i))
while i >= 0:
i, ch, style = ac.getPrevPosCharStyle()
if DEBUG:
print("finding matching brace: ch %r (%s), stack %r"\
% (ch, ', '.join(buf.style_names_from_style_num(style)), stack))
if ch in BLOCKS and style not in skip_styles:
stack.append((ch, style, BLOCKS[ch]))
elif ch == stack[-1][2] and style not in skip_styles:
# XXX Replace the second test with the following
# when LexPython+SilverCity styling bugs are fixed
# (spurious 'stderr' problem):
# and style == stack[-1][1]:
stack.pop()
if not stack:
if DEBUG:
print("jump to matching brace at %d: %r" % (i, ch))
citdl_expr.append(ch)
break
else:
# Didn't find the matching brace.
if DEBUG:
print("couldn't find matching brace")
raise EvalError("could not find matching brace for "
"'%s' at position %d"
% (stack[-1][0], stack[-1][3]))
else:
if DEBUG:
style_names = buf.style_names_from_style_num(style)
print("add char: %r (%s)" % (ch, ', '.join(style_names)))
citdl_expr.append(ch)
i -= 1
except IndexError:
# Nothing left to consume, return what we have
pass
# Remove any unecessary starting dots
while citdl_expr and citdl_expr[-1] == ".":
citdl_expr.pop()
citdl_expr.reverse()
citdl_expr = ''.join(citdl_expr)
if DEBUG:
print("return: %r" % citdl_expr)
print(util.banner("done"))
return citdl_expr
def citdl_expr_from_trg(self, buf, trg, DEBUG=False):
"""Return a PHP CITDL expression preceding the given trigger.
The expression drops newlines, whitespace, and function call
arguments -- basically any stuff that is not used by the codeintel
database system for determining the resultant object type of the
expression. For example (in which <|> represents the given position):
GIVEN RETURN
----- ------
foo-<|>> foo
Foo:<|>: Foo
foo(bar-<|>> bar
foo(bar,blam)-<|>> foo()
foo(bar, foo()
blam)-<|>>
foo(arg1, arg2)->bar-<|>> foo().bar
Foo(arg1, arg2)::bar-<|>> Foo().bar
Foo\bar:<|>: Foo\bar
Foo\bar::bam-<|>> Foo\bar.bam
Foo\bar(arg1, arg2)::bam-<|>> Foo\bar().bam
"""
# DEBUG = True
DEBUG = False
if DEBUG:
print(util.banner("%s citdl_expr_from_trg @ %r" % (buf.lang, trg)))
if trg.form == TRG_FORM_CPLN:
# "->" or "::"
if trg.type == "classes":
i = trg.pos + 1
elif trg.type == "functions":
i = trg.pos + 3 # 3-char trigger, skip over it
elif trg.type in ("variables", "comment-variables"):
i = trg.pos + 1 # triggered on the $, skip over it
elif trg.type == "array-members":
i = trg.extra.get("bracket_pos") # triggered on foo['
elif trg.type == "use":
i = trg.pos + 1
elif trg.type in ["namespace-members","use-namespace","namespace-members-nmspc-only"]:
i = trg.pos - 1
elif trg.type == "use-global-namespaces":
i = trg.pos + 1
else:
i = trg.pos - 2 # skip past the trigger char
citdl_expr = self._citdl_expr_from_pos(trg, buf, i, trg.implicit,
DEBUG=DEBUG)
if trg.type == "functions" and len(citdl_expr) < 3:
#ensure function trigger has at least 3 chars typed
raise CodeIntelError
return citdl_expr
elif trg.form == TRG_FORM_DEFN:
return self.citdl_expr_under_pos(trg, buf, trg.pos, DEBUG)
else: # trg.form == TRG_FORM_CALLTIP:
# (<|>
return self._citdl_expr_from_pos(trg, buf, trg.pos-1, trg.implicit,
DEBUG=DEBUG)
def citdl_expr_under_pos(self, trg, buf, pos, DEBUG=False):
"""Return a PHP CITDL expression around the given pos.
Similar to citdl_expr_from_trg(), but looks forward to grab additional
characters.
GIVEN RETURN
----- ------
foo-<|>> foo
F<|>oo:: Foo
foo->ba<|>r foo.bar
f<|>oo->bar foo
foo(bar-<|>> bar
foo(bar,blam)-<|>> foo()
foo(bar, foo()
blam)-<|>>
foo(arg1, arg2)->bar-<|>> foo().bar
Foo(arg1, arg2)::ba<|>r-> Foo().bar
Fo<|>o(arg1, arg2)::bar-> Foo
"""
# DEBUG = True
expr = self._citdl_expr_from_pos(trg, buf, pos-1, implicit=True,
include_forwards=True, DEBUG=DEBUG)
if expr:
# Chop off any trailing "." characters
return expr.rstrip(".")
return expr
def libs_from_buf(self, buf):
env = buf.env
# A buffer's libs depend on its env and the buf itself so
# we cache it on the env and key off the buffer.
if "php-buf-libs" not in env.cache:
env.cache["php-buf-libs"] = weakref.WeakKeyDictionary()
cache = env.cache["php-buf-libs"] # <buf-weak-ref> -> <libs>
if buf not in cache:
# - curdirlib
# Using the dirname of this buffer isn't always right, but
# hopefully is a good first approximation.
cwd = dirname(buf.path)
if cwd == "<Unsaved>":
libs = []
else:
libs = [self.mgr.db.get_lang_lib(
"PHP", "curdirlib", [cwd], "PHP")]
libs += self._buf_indep_libs_from_env(env)
cache[buf] = libs
return cache[buf]
def lpaths_from_blob(self, blob):
"""Return <lpaths> for this blob
where,
<lpaths> is a set of externally referencable lookup-paths, e.g.
[("MyOwnClass",), ("MyOwnClass", "function1"), ...]
"""
return set(lpath for child in blob
for lpath in _walk_php_symbols(child))
def _php_from_env(self, env):
import which
path = [d.strip()
for d in env.get_envvar("PATH", "").split(os.pathsep)
if d.strip()]
for exe_name in ("php", "php4", "php-cgi", "php-cli"):
try:
return which.which(exe_name, path=path)
except which.WhichError:
pass
return None
def _php_info_from_php(self, php, env):
"""Call the given PHP and return:
(<version>, <include_path>)
Returns (None, []) if could not determine.
"""
import process
import tempfile
# Use a marker to separate the start of output from possible
# leading lines of PHP loading errors/logging.
marker = "--- Start of Good Stuff ---"
info_cmd = (r'<?php '
+ r'echo("%s\n");' % marker
+ r'echo(phpversion()."\n");'
+ r'echo(ini_get("include_path")."\n");'
+ r' ?>')
argv = [php]
envvars = env.get_all_envvars()
php_ini_path = env.get_pref("phpConfigFile")
if php_ini_path:
envvars["PHPRC"] = php_ini_path
fd, filepath = tempfile.mkstemp(suffix=".php")
try:
os.write(fd, info_cmd.encode('utf-8'))
os.close(fd)
argv.append(filepath)
p = process.ProcessOpen(argv, env=env.get_all_envvars())
stdout, stderr = p.communicate()
finally:
os.remove(filepath)
stdout_lines = stdout.splitlines(0)
retval = p.returncode
if retval:
log.warn("failed to determine PHP info:\n"
" path: %s\n"
" retval: %s\n"
" stdout:\n%s\n"
" stderr:\n%s\n",
php, retval, util.indent('\n'.join(stdout_lines)),
util.indent(stderr))
return None, []
stdout_lines = stdout_lines[stdout_lines.index(marker)+1:]
php_ver = stdout_lines[0]
include_path = [p.strip() for p in stdout_lines[1].split(os.pathsep)
if p.strip()]
return php_ver, include_path
def _expand_extra_dirs(self, env, extra_dirs):
max_depth = env.get_pref("codeintel_max_recursive_dir_depth", 10)
php_assocs = env.assoc_patterns_from_lang("PHP")
return util.gen_dirs_under_dirs(extra_dirs, max_depth=max_depth,
interesting_file_patterns=php_assocs)
#def _extra_dirs_from_env(self, env):
# extra_dirs = set()
# include_project = env.get_pref("codeintel_scan_files_in_project", True)
# if include_project:
# proj_base_dir = env.get_proj_base_dir()
# if proj_base_dir is not None:
# extra_dirs.add(proj_base_dir) # Bug 68850.
# for pref in env.get_all_prefs("scanExtraPaths"):
# if not pref:
# continue
# extra_dirs.update(d.strip() for d in pref.split(os.pathsep)
# if exists(d.strip()))
# if extra_dirs:
# log.debug("PHP extra lib dirs: %r", extra_dirs)
# max_depth = env.get_pref("codeintel_max_recursive_dir_depth", 10)
# php_assocs = env.assoc_patterns_from_lang("PHP")
# extra_dirs = tuple(
# util.gen_dirs_under_dirs(extra_dirs,
# max_depth=max_depth,
# interesting_file_patterns=php_assocs)
# )
# exclude_patterns = env.get_pref("codeintel_scan_exclude_dir")
# if not exclude_patterns is None:
# for p in exclude_patterns:
# extra_dirs = [d for d in extra_dirs if not re.search(p, d)]
# else:
# extra_dirs = () # ensure retval is a tuple
# return extra_dirs
def _buf_indep_libs_from_env(self, env):
"""Create the buffer-independent list of libs."""
cache_key = "php-libs"
if cache_key not in env.cache:
env.add_pref_observer("php", self._invalidate_cache)
env.add_pref_observer("codeintel_scan_extra_dir",
self._invalidate_cache_and_rescan_extra_dirs)
env.add_pref_observer("phpConfigFile",
self._invalidate_cache)
env.add_pref_observer("codeintel_selected_catalogs",
self._invalidate_cache)
env.add_pref_observer("codeintel_max_recursive_dir_depth",
self._invalidate_cache)
env.add_pref_observer("codeintel_scan_files_in_project",
self._invalidate_cache)
# (Bug 68850) Both of these 'live_*' prefs on the *project*
# prefset can result in a change of project base dir. It is
# possible that we can false positives here if there is ever
# a global pref of this name.
env.add_pref_observer("import_live",
self._invalidate_cache_and_rescan_extra_dirs)
env.add_pref_observer("import_dirname",
self._invalidate_cache_and_rescan_extra_dirs)
db = self.mgr.db
# Gather information about the current php.
php = None
if env.has_pref("php"):
php = env.get_pref("php").strip() or None
if not php or not exists(php):
php = self._php_from_env(env)
if not php:
log.warn("no PHP was found from which to determine the "
"import path")
php_ver, include_path = None, []
else:
php_ver, include_path \
= self._php_info_from_php(php, env)
libs = []
# - extradirslib
extra_dirs = self._extra_dirs_from_env(env)
if extra_dirs:
libs.append(db.get_lang_lib("PHP", "extradirslib",
extra_dirs, "PHP"))
# - inilib (i.e. dirs in the include_path in PHP.ini)
include_dirs = [d for d in include_path
if d != '.' # handled separately
if exists(d)]
if include_dirs:
max_depth = env.get_pref(
"codeintel_max_recursive_dir_depth", 10)
php_assocs = env.assoc_patterns_from_lang("PHP")
include_dirs = tuple(
util.gen_dirs_under_dirs(include_dirs,
max_depth=max_depth,
interesting_file_patterns=php_assocs)
)
exclude_patterns = env.get_pref("codeintel_scan_exclude_dir")
if not exclude_patterns is None:
for p in exclude_patterns:
include_dirs = [d for d in include_dirs if not re.search(p, d)]
if include_dirs:
libs.append(db.get_lang_lib("PHP", "inilib",
include_dirs, "PHP"))
# Warn the user if there is a huge number of import dirs that
# might slow down completion.
all_dirs = list(extra_dirs) + list(include_dirs)
num_import_dirs = len(all_dirs)
if num_import_dirs > 100:
msg = "This buffer is configured with %d %s import dirs: " \
"this may result in poor completion performance" % \
(num_import_dirs, self.lang)
self.mgr.report_message(msg, "\n".join(all_dirs))
# - cataloglib, stdlib
catalog_selections = env.get_pref("codeintel_selected_catalogs")
libs += [
db.get_catalog_lib("PHP", catalog_selections),
db.get_stdlib("PHP", php_ver)
]
env.cache[cache_key] = libs
return env.cache[cache_key]
def _invalidate_cache(self, env, pref_name):
for key in ("php-buf-libs", "php-libs"):
if key in env.cache:
log.debug("invalidate '%s' cache on %r", key, env)
del env.cache[key]
def _invalidate_cache_and_rescan_extra_dirs(self, env, pref_name):
self._invalidate_cache(env, pref_name)
extra_dirs = self._extra_dirs_from_env(env)
if extra_dirs:
extradirslib = self.mgr.db.get_lang_lib(
"PHP", "extradirslib", extra_dirs, "PHP")
request = PreloadLibRequest(extradirslib)
self.mgr.idxr.stage_request(request, 1.0)
#---- code browser integration
cb_import_group_title = "Includes and Requires"
def cb_import_data_from_elem(self, elem):
alias = elem.get("alias")
symbol = elem.get("symbol")
module = elem.get("module")
if alias is not None:
if symbol is not None:
name = "%s (%s\%s)" % (alias, module, symbol)
detail = "from %(module)s import %(symbol)s as %(alias)s" % locals(
)
else:
name = "%s (%s)" % (alias, module)
detail = "import %(module)s as %(alias)s" % locals()
elif symbol is not None:
if module == "\\":
name = '\\%s' % (symbol)
else:
name = '%s\\%s' % (module, symbol)
detail = "from %(module)s import %(symbol)s" % locals()
else:
name = module
detail = 'include "%s"' % module
return {"name": name, "detail": detail}
def cb_variable_data_from_elem(self, elem):
"""Use the 'constant' image in the Code Browser for a variable constant.
"""
data = CitadelLangIntel.cb_variable_data_from_elem(self, elem)
if elem.get("ilk") == "constant":
data["img"] = "constant"
return data
class PHPBuffer(UDLBuffer, XMLParsingBufferMixin):
lang = lang
m_lang = "HTML"
css_lang = "CSS"
csl_lang = "JavaScript"
ssl_lang = "PHP"
cb_show_if_empty = True
# Fillup chars for PHP: basically, any non-identifier char.
# - dropped '#' to prevent annoying behavior with $form['#foo']
# - dropped '@' I could find no common use of "@" following func/variable
# - dropped '$' It gets in the way of common usage: "$this->$"
# - dropped '\\' I could find no common use of "\" following func/variable
# - dropped '?' It gets in the way of common usage: "<?php "
# - dropped '/', it gets in the way of "</" closing an XML/HTML tag
# - dropped '!' It gets in the way of "<!" in XML/HTML tag (bug 78632)
# - dropped '=' It gets in the way of "<a href=" in XML/HTML cpln (bug 78632)
# - dropped ':' It gets in the way of "<a d:blah=" in XML/HTML cpln
# - dropped '>' It gets in the way of "<p>asdf</" in XML/HTML tag cpln (bug 80348)
cpln_fillup_chars = "~`%^&*()-+{}[]|;'\",.< "
# TODO: c.f. cpln_stop_chars stuff in lang_html.py
# - dropping '[' because need for "<!<|>" -> "<![CDATA[" cpln
# - dropping '#' because we need it for $form['#foo']
# - dropping '$' because: MyClass::$class_var
# - dropping '-' because causes problem with CSS (bug 78312)
# - dropping '!' because causes problem with CSS "!important" (bug 78312)
cpln_stop_chars = "~`@%^&*()=+{}]|\\;:'\",.<>?/ "
def __init__(self, *args, **kwargs):
super(PHPBuffer, self).__init__(*args, **kwargs)
if isinstance(self.accessor, KoDocumentAccessor):
# Encourage the database to pre-scan dirs relevant to completion
# for this buffer -- because of recursive-dir-include-everything
# semantics for PHP this first-time scan can take a while.
request = PreloadBufLibsRequest(self)
self.mgr.idxr.stage_request(request, 1.0)
@property
def libs(self):
return self.langintel.libs_from_buf(self)
@property
def stdlib(self):
return self.libs[-1]
class PHPImportHandler(ImportHandler):
sep = '/'
def setCorePath(self, compiler=None, extra=None):
# XXX To do this independent of Komodo this would need to do all
# the garbage that koIPHPInfoEx is doing to determine this. It
# might also require adding a "rcfile" argument to this method
# so the proper php.ini file is used in the "_shellOutForPath".
# This is not crucial now because koCodeIntel._Manager() handles
# this for us.
if not self.corePath:
raise CodeIntelError("Do not know how to determine the core "
"PHP include path. 'corePath' must be set "
"manually.")
def _findScannableFiles(self, xxx_todo_changeme, dirname, names):
(files, searchedDirs) = xxx_todo_changeme
if sys.platform.startswith("win"):
cpath = dirname.lower()
else:
cpath = dirname
if cpath in searchedDirs:
while names:
del names[0]
return
else:
searchedDirs[cpath] = 1
for i in range(len(names)-1, -1, -1): # backward so can del from list
path = os.path.join(dirname, names[i])
if os.path.isdir(path):
pass
elif os.path.splitext(names[i])[1] in (".php", ".inc",
".module", ".tpl"):
# XXX The list of extensions should be settable on
# the ImportHandler and Komodo should set whatever is
# set in prefs. ".module" and ".tpl" are for
# drupal-nerds until CodeIntel gets this right.
# XXX This check for files should probably include
# scripts, which might likely not have the
# extension: need to grow filetype-from-content smarts.
files.append(path)
def find_importables_in_dir(self, dir):
"""See citadel.py::ImportHandler.find_importables_in_dir() for
details.
Importables for PHP look like this:
{"foo.php": ("foo.php", None, False),
"bar.inc": ("bar.inc", None, False),
"somedir": (None, None, True)}
TODO: log the fs-stat'ing a la codeintel.db logging.
"""
from os.path import join, isdir
from fnmatch import fnmatch
if dir == "<Unsaved>":
# TODO: stop these getting in here.
return {}
try:
names = os.listdir(dir)
except OSError as ex:
return {}
dirs, nondirs = set(), set()
for name in names:
try:
if isdir(join(dir, name)):
dirs.add(name)
else:
nondirs.add(name)
except UnicodeDecodeError:
# Hit a filename that cannot be encoded in the default encoding.
# Just skip it. (Bug 82268)
pass
importables = {}
patterns = self.mgr.env.assoc_patterns_from_lang("PHP")
for name in nondirs:
for pattern in patterns:
if fnmatch(name, pattern):
break
else:
continue
if name in dirs:
importables[name] = (name, None, True)
dirs.remove(name)
else:
importables[name] = (name, None, False)
for name in dirs:
importables[name] = (None, None, True)
return importables
class PHPCILEDriver(UDLCILEDriver):
lang = lang
ssl_lang = "PHP"
csl_lang = "JavaScript"
def scan_multilang(self, buf, csl_cile_driver=None):
# try:
"""Scan the given multilang (UDL-based) buffer and return a CIX
element tree.
"buf" is the multi-lang Buffer instance (e.g.
lang_rhtml.RHTMLBuffer for RHTML).
"csl_cile_driver" (optional) is the CSL (client-side language)
CILE driver. While scanning, CSL tokens should be gathered and,
if any, passed to the CSL scanner like this:
csl_cile_driver.scan_csl_tokens(
file_elem, blob_name, csl_tokens)
The CSL scanner will append a CIX <scope ilk="blob"> element
to the <file> element.
"""
log.info("scan_multilang: path: %r lang: %s", buf.path, buf.lang)
# Create the CIX tree.
mtime = "XXX"
fullpath = buf.path
cixtree = createCixRoot()
cixfile = createCixFile(cixtree, fullpath, lang=buf.lang)
if sys.platform.startswith("win"):
fullpath = fullpath.replace('\\', '/')
basepath = os.path.basename(fullpath)
cixblob = createCixModule(cixfile, basepath, "PHP", src=fullpath)
phpciler = PHPParser(fullpath, buf.accessor.text, mtime)
csl_tokens = phpciler.scan_multilang_content(buf.accessor.text)
phpciler.convertToElementTreeModule(cixblob)
# Hand off the csl tokens if any
if csl_cile_driver and csl_tokens:
csl_cile_driver.scan_csl_tokens(cixfile, basepath, csl_tokens)
return cixtree
# except Exception, e:
# print "\nPHP cile exception"
# import traceback
# traceback.print_exc()
# print
# raise
#---- internal routines and classes
# States used by PHP scanner when parsing information
S_DEFAULT = 0
S_IN_ARGS = 1
S_IN_ASSIGNMENT = 2
S_IGNORE_SCOPE = 3
S_OBJECT_ARGUMENT = 4
S_GET_HEREDOC_MARKER = 5
S_IN_HEREDOC = 6
S_TRAIT_RESOLUTION = 7
# Special tags for multilang handling (i.e. through UDL)
S_OPEN_TAG = 10
S_CHECK_CLOSE_TAG = 11
S_IN_SCRIPT = 12
# Types used by JavaScriptScanner when parsing information
TYPE_NONE = 0
TYPE_FUNCTION = 1
TYPE_VARIABLE = 2
TYPE_GETTER = 3
TYPE_SETTER = 4
TYPE_MEMBER = 5
TYPE_OBJECT = 6
TYPE_CLASS = 7
TYPE_PARENT = 8
def sortByLine(seq):
seq.sort(key=lambda x: getattr(x, 'linestart', x))
return seq
class PHPArg:
def __init__(self, name, citdl=None, signature=None, default=None):
"""Set details for a function argument"""
self.name = name
self.citdl = citdl
if signature:
self.signature = signature
else:
if citdl:
self.signature = "%s $%s" % (citdl, name)
else:
self.signature = "$%s" % (name, )
self.default = default
def __repr__(self):
return self.signature
def updateCitdl(self, citdl):
self.citdl = citdl
if self.signature.startswith("$") or self.signature.startswith("&") or \
" " not in self.signature:
self.signature = "%s %s" % (citdl, self.signature)
else:
self.signature = "%s %s" % (citdl, self.signature.split(" ", 1)[1])
def toElementTree(self, cixelement, linestart=None):
cixarg = addCixArgument(cixelement, self.name, argtype=self.citdl)
if self.default:
cixarg.attrib["default"] = self.default
if linestart is not None:
cixarg.attrib["line"] = str(linestart)
class PHPVariable:
# PHPDoc variable type sniffer.
_re_var = re.compile(
r'^\s*@var\s+(\$(?P<variable>\w+)\s+)?(?P<type>[\w\\]+)(?:\s+(?P<doc>.*?))?', re.M | re.U)
_ignored_php_types = ("object", "mixed")
def __init__(self, name, line, vartype='', attributes='', doc=None,
fromPHPDoc=False, namespace=None):
self.name = name
self.types = [(line, vartype, fromPHPDoc)]
self.linestart = line
if attributes:
if not isinstance(attributes, list):
attributes = attributes.strip().split()
self.attributes = ' '.join(attributes)
else:
self.attributes = None
self.doc = doc
self.created_namespace = None
if namespace:
self.created_namespace = namespace.name
def addType(self, line, type, fromPHPDoc=False):
self.types.append((line, type, fromPHPDoc))
def __repr__(self):
return "var %s line %s type %s attributes %s\n"\
% (self.name, self.linestart, self.types, self.attributes)
def toElementTree(self, cixblob):
# Work out the best vartype
vartype = None
doc = None
if self.doc:
# We are only storing the doc string for cases where we have an
# "@var" phpdoc tag, we should actually store the docs anyway, but
# we don't yet have a clean way to ensure the doc is really meant
# for this specific variable (i.e. the comment was ten lines before
# the variable definition).
if "@var" in self.doc:
doc = uncommentDocString(self.doc)
# get the variable citdl type set by "@var"
all_matches = re.findall(self._re_var, doc)
if len(all_matches) >= 1:
# print "all_matches[0]: %r" % (all_matches[0], )
vartype = all_matches[0][2]
if vartype and vartype.lower() in self._ignored_php_types:
# Ignore these PHP types, they don't help codeintel.
# http://bugs.activestate.com/show_bug.cgi?id=77602
vartype = None
if not vartype and self.types:
d = {}
max_count = 0
for line, vtype, fromPHPDoc in self.types:
if vtype:
if fromPHPDoc:
if vtype.lower() in self._ignored_php_types:
# Ignore these PHP types, they don't help
# codeintel.
continue
# The doc gets priority.
vartype = vtype
break
count = d.get(vtype, 0) + 1
d[vtype] = count
if count > max_count:
# Best found so far
vartype = vtype
max_count = count
cixelement = createCixVariable(cixblob, self.name, vartype=vartype,
attributes=self.attributes)
if doc:
setCixDoc(cixelement, doc)
cixelement.attrib["line"] = str(self.linestart)
if self.created_namespace:
# Need to remember that the object was created in a namespace, so
# that the starting lookup scope can start in the given namespace.
cixelement.attrib["namespace"] = self.created_namespace
return cixelement
class PHPConstant(PHPVariable):
def __init__(self, name, line, vartype=''):
PHPVariable.__init__(self, name, line, vartype)
def __repr__(self):
return "constant %s line %s type %s\n"\
% (self.name, self.linestart, self.types)
def toElementTree(self, cixblob):
cixelement = PHPVariable.toElementTree(self, cixblob)
cixelement.attrib["ilk"] = "constant"
return cixelement
class PHPFunction:
def __init__(self, funcname, phpArgs, lineno, depth=0,
attributes=None, doc=None, classname='', classparent='',
returnType=None, returnByRef=False):
self.name = funcname
self.args = phpArgs
self.linestart = lineno
self.lineend = None
self.depth = depth
self.classname = classname
self.classparent = classparent
self.returnType = returnType
self.returnByRef = returnByRef
self.variables = {} # all variables used in class
# build the signature before we add any attributes that are not part
# of the signature
if returnByRef:
self.signature = '&%s' % (self.name)
else:
self.signature = '%s' % (self.name)
if attributes:
attrs = ' '.join(attributes)
self.shortSig = '%s %s' % (attrs, self.name)
else:
self.shortSig = self.name
# both php 4 and 5 constructor methods
if funcname == '__construct' or (classname and funcname.lower() == classname.lower()):
attributes.append('__ctor__')
# if we add destructor attributes...
# elif funcname == '__destruct':
# attributes += ['__dtor__']
self.attributes = attributes and ' '.join(attributes) or ''
self.doc = None
if doc:
if isinstance(doc, list):
doc = "".join(doc)
docinfo = parseDocString(doc)
self.doc = docinfo[0]
# See if there are any PHPDoc arguments defined in the docstring.
if docinfo[1]:
for argInfo in docinfo[1]:
for phpArg in self.args:
if phpArg.name == argInfo[1]:
phpArg.updateCitdl(argInfo[0])
break
else:
self.args.append(PHPArg(argInfo[1], citdl=argInfo[0]))
if docinfo[2]:
self.returnType = docinfo[2][0]
if self.returnType:
self.signature = '%s %s' % (self.returnType, self.signature, )
self.signature += "("
if self.args:
self.signature += ", ".join([x.signature for x in self.args])
self.signature += ")"
def addReturnType(self, returnType):
if self.returnType is None:
self.returnType = returnType
def __str__(self):
return self.signature
# The following is busted and outputting multiple lines from __str__
# and __repr__ is bad form: make debugging prints hard.
# if self.doc:
# if self.args:
# return "%s(%s)\n%s" % (self.shortSig, self.args.argline, self.doc)
# else:
# return "%s()\n%s" % (self.shortSig, self.doc)
# return "%s(%s)" % (self.shortSig, self.argline)
def __repr__(self):
return self.signature
def hasArgumentWithName(self, name):
if self.args:
for phpArg in self.args:
if phpArg.name == name:
return True
return False
def toElementTree(self, cixblob):
cixelement = createCixFunction(cixblob, self.name,
attributes=self.attributes)
cixelement.attrib["line"] = str(self.linestart)
if self.lineend is not None:
cixelement.attrib['lineend'] = str(self.lineend)
setCixSignature(cixelement, self.signature)
if self.doc:
setCixDoc(cixelement, self.doc)
if self.args:
for phpArg in self.args:
phpArg.toElementTree(cixelement, self.linestart)
if self.returnType:
addCixReturns(cixelement, self.returnType)
# Add a "this" and "self" member for class functions
# if self.classname:
# createCixVariable(cixelement, "this", vartype=self.classname)
# createCixVariable(cixelement, "self", vartype=self.classname)
# Add a "parent" member for class functions that have a parent
# if self.classparent:
# createCixVariable(cixelement, "parent", vartype=self.classparent)
# XXX for variables inside functions
for v in list(self.variables.values()):
v.toElementTree(cixelement)
class PHPInterface:
def __init__(self, name, extends, lineno, depth, doc=None):
self.name = name
self.extends = extends
self.linestart = lineno
self.lineend = None
self.depth = depth
self.constants = {} # declared class constants
self.members = {} # declared class variables
self.variables = {} # all variables used in class
self.functions = {}
self.doc = None
if doc:
self.doc = uncommentDocString(doc)
def __repr__(self):
# dump our contents to human readable form
r = "INTERFACE %s" % self.name
if self.extends:
r += " EXTENDS %s" % self.extends
r += '\n'
if self.constants:
r += "Constants:\n"
for m in self.constants:
r += " var %s line %s\n" % (m, self.constants[m])
if self.members:
r += "Members:\n"
for m in self.members:
r += " var %s line %s\n" % (m, self.members[m])
if self.functions:
r += "functions:\n"
for f in list(self.functions.values()):
r += " %r" % f
if self.variables:
r += "variables:\n"
for v in list(self.variables.values()):
r += " %r" % v
return r + '\n'
def toElementTree(self, cixblob):
cixelement = createCixInterface(cixblob, self.name)
cixelement.attrib["line"] = str(self.linestart)
if self.lineend is not None:
cixelement.attrib["lineend"] = str(self.lineend)
signature = "%s" % (self.name)
if self.extends:
signature += " extends %s" % (self.extends)
for name in self.extends.split(","):
addInterfaceRef(cixelement, name.strip())
# SubElement(cixelement, "classref", name=self.extends)
cixelement.attrib["signature"] = signature
if self.doc:
setCixDoc(self.doc)
allValues = list(self.functions.values()) + list(self.constants.values()) + \
list(self.members.values()) + list(self.variables.values())
for v in sortByLine(allValues):
v.toElementTree(cixelement)
class PHPClass:
cixtype = "CLASS"
# PHPDoc magic property sniffer.
_re_magic_property = re.compile(
r'^\s*@property(-(?P<type>read|write))?\s+((?P<citdl>[\w\\]+)\s+)?(?P<name>\$\w+)(?:\s+(?P<doc>.*?))?', re.M | re.U)
_re_magic_method = re.compile(
r'^\s*@method\s+((?P<citdl>[\w\\]+)\s+)?(?P<name>\w+)(\(\))?(?P<doc>.*?)$', re.M | re.U)
def __init__(self, name, extends, lineno, depth, attributes=None,
interfaces=None, doc=None):
self.name = name
self.extends = extends
self.linestart = lineno
self.lineend = None
self.depth = depth
self.constants = {} # declared class constants
self.members = {} # declared class variables
self.variables = {} # all variables used in class
self.functions = {}
self.traits = {}
self.traitOverrides = {}
if interfaces:
self.interfaces = interfaces.split(',')
else:
self.interfaces = []
if attributes:
self.attributes = ' '.join(attributes)
else:
self.attributes = None
self.doc = None
if doc:
if isinstance(doc, list):
doc = "".join(doc)
self.doc = uncommentDocString(doc)
if self.doc.find("@property") >= 0:
all_matches = re.findall(self._re_magic_property, self.doc)
for match in all_matches:
varname = match[4][1:] # skip "$" in the name.
v = PHPVariable(varname, lineno, match[3], doc=match[5])
self.members[varname] = v
if self.doc.find("@method") >= 0:
all_matches = re.findall(self._re_magic_method, self.doc)
for match in all_matches:
citdl = match[1] or None
fnname = match[2]
fndoc = match[4]
phpArgs = []
fn = PHPFunction(
fnname, phpArgs, lineno, depth=self.depth+1,
doc=fndoc, returnType=citdl)
self.functions[fnname] = fn
def __repr__(self):
# dump our contents to human readable form
r = "%s %s" % (self.cixtype, self.name)
if self.extends:
r += " EXTENDS %s" % self.extends
r += '\n'
if self.constants:
r += "Constants:\n"
for m in self.constants:
r += " var %s line %s\n" % (m, self.constants[m])
if self.members:
r += "Members:\n"
for m in self.members:
r += " var %s line %s\n" % (m, self.members[m])
if self.functions:
r += "functions:\n"
for f in list(self.functions.values()):
r += " %r" % f
if self.variables:
r += "variables:\n"
for v in list(self.variables.values()):
r += " %r" % v
if self.traits:
r += "traits:\n"
for k, v in list(self.traits.items()):
r += " %r" % k
if self.traitOverrides:
r += "trait overrides:\n"
for k, v in list(self.traitOverrides.items()):
r += " %r, %r" % (k, v)
return r + '\n'
def addTraitReference(self, name):
self.traits[name] = []
def addTraitOverride(self, namelist, alias, visibility=None, insteadOf=False):
self.traitOverrides[".".join(namelist)] = (
alias, visibility, insteadOf)
def _toElementTree(self, cixblob, cixelement):
cixelement.attrib["line"] = str(self.linestart)
if self.lineend is not None:
cixelement.attrib["lineend"] = str(self.lineend)
if self.attributes:
cixelement.attrib["attributes"] = self.attributes
if self.doc:
setCixDoc(cixelement, self.doc)
if self.extends:
addClassRef(cixelement, self.extends)
if self.traits:
cixelement.attrib["traitrefs"] = " ".join(self.traits)
for citdl, data in list(self.traitOverrides.items()):
alias, vis, insteadOf = data
if alias and not insteadOf:
name = alias
else:
name = citdl.split(".")[-1]
override_elem = SubElement(
cixelement, "alias", name=name, citdl=citdl)
if insteadOf:
override_elem.attrib["insteadof"] = alias
if vis:
override_elem.attrib["attributes"] = vis
for i in self.interfaces:
addInterfaceRef(cixelement, i.strip())
allValues = list(self.functions.values()) + list(self.constants.values()) + \
list(self.members.values()) + list(self.variables.values())
for v in sortByLine(allValues):
v.toElementTree(cixelement)
def toElementTree(self, cixblob):
cixelement = createCixClass(cixblob, self.name)
self._toElementTree(cixblob, cixelement)
class PHPTrait(PHPClass):
cixtype = "TRAIT"
def toElementTree(self, cixblob):
cixelement = SubElement(cixblob, "scope", ilk="trait", name=self.name)
self._toElementTree(cixblob, cixelement)
class PHPImport:
def __init__(self, name, lineno, alias=None, symbol=None):
self.name = name
self.lineno = lineno
self.alias = alias
self.symbol = symbol
def __repr__(self):
# dump our contents to human readable form
if self.alias:
return "IMPORT %s as %s\n" % (self.name, self.alias)
else:
return "IMPORT %s\n" % self.name
def toElementTree(self, cixmodule):
elem = SubElement(
cixmodule, "import", module=self.name, line=str(self.lineno))
if self.alias:
elem.attrib["alias"] = self.alias
if self.symbol:
elem.attrib["symbol"] = self.symbol
return elem
def qualifyNamespacePath(namespace_path):
# Ensure the namespace does not begin or end with a backslash.
return namespace_path.strip("\\")
class PHPNamespace:
def __init__(self, name, lineno, depth, doc=None):
assert not name.startswith("\\")
assert not name.endswith("\\")
self.name = name
self.linestart = lineno
self.lineend = None
self.depth = depth
self.doc = None
if doc:
self.doc = uncommentDocString(doc)
self.functions = {} # functions declared in file
self.classes = {} # classes declared in file
self.constants = {} # all constants used in file
self.interfaces = {} # interfaces declared in file
self.includes = [] # imported files/namespaces
def __repr__(self):
# dump our contents to human readable form
r = "NAMESPACE %s\n" % self.name
for v in self.includes:
r += " %r" % v
r += "constants:\n"
for v in list(self.constants.values()):
r += " %r" % v
r += "interfaces:\n"
for v in list(self.interfaces.values()):
r += " %r" % v
r += "functions:\n"
for f in list(self.functions.values()):
r += " %r" % f
r += "classes:\n"
for c in list(self.classes.values()):
r += repr(c)
return r + '\n'
def toElementTree(self, cixblob):
cixelement = createCixNamespace(cixblob, self.name)
cixelement.attrib["line"] = str(self.linestart)
if self.lineend is not None:
cixelement.attrib["lineend"] = str(self.lineend)
if self.doc:
setCixDoc(cixelement, self.doc)
for v in self.includes:
v.toElementTree(cixelement)
allValues = list(self.functions.values()) + list(self.constants.values()) + \
list(self.interfaces.values()) + list(self.classes.values())
for v in sortByLine(allValues):
v.toElementTree(cixelement)
class PHPFile:
"""CIX specifies that a <file> tag have zero or more
<scope ilk="blob"> children. In PHP this is a one-to-one
relationship, so this class represents both (and emits the XML tags
for both).
"""
def __init__(self, filename, content=None, mtime=None):
self.filename = filename
self.content = content
self.mtime = mtime
self.error = None
self.content = content
if mtime is None:
self.mtime = int(time.time())
self.functions = {} # functions declared in file
self.classes = {} # classes declared in file
self.variables = {} # all variables used in file
self.constants = {} # all constants used in file
self.includes = [] # imported files/namespaces
self.interfaces = {} # interfaces declared in file
self.namespaces = {} # namespaces declared in file
def __repr__(self):
# dump our contents to human readable form
r = "FILE %s\n" % self.filename
for v in self.includes:
r += " %r" % v
r += "constants:\n"
for v in list(self.constants.values()):
r += " %r" % v
r += "interfaces:\n"
for v in list(self.interfaces.values()):
r += " %r" % v
r += "functions:\n"
for f in list(self.functions.values()):
r += " %r" % f
r += "variables:\n"
for v in list(self.variables.values()):
r += " %r" % v
r += "classes:\n"
for c in list(self.classes.values()):
r += repr(c)
r += "namespaces:\n"
for v in list(self.namespaces.values()):
r += " %r" % v
return r + '\n'
def convertToElementTreeModule(self, cixmodule):
for v in self.includes:
v.toElementTree(cixmodule)
allValues = list(self.constants.values()) + list(self.functions.values()) + \
list(self.interfaces.values()) + list(self.variables.values()) + \
list(self.classes.values()) + list(self.namespaces.values())
for v in sortByLine(allValues):
v.toElementTree(cixmodule)
def convertToElementTreeFile(self, cix):
if sys.platform.startswith("win"):
path = self.filename.replace('\\', '/')
else:
path = self.filename
cixfile = createCixFile(cix, path, lang="PHP", mtime=str(self.mtime))
if self.error:
cixfile.attrib["error"] = self.error
cixmodule = createCixModule(cixfile, os.path.basename(self.filename),
"PHP")
self.convertToElementTreeModule(cixmodule)
class PHPcile:
def __init__(self):
# filesparsed contains all files parsed
self.filesparsed = {}
def clear(self, filename):
# clear include links from the cache
if filename not in self.filesparsed:
return
del self.filesparsed[filename]
def __repr__(self):
r = ''
for f in self.filesparsed:
r += repr(self.filesparsed[f])
return r + '\n'
# def toElementTree(self, cix):
# for f in self.filesparsed.values():
# f.toElementTree(cix)
def convertToElementTreeModule(self, cixmodule):
for f in list(self.filesparsed.values()):
f.convertToElementTreeModule(cixmodule)
def convertToElementTreeFile(self, cix):
for f in list(self.filesparsed.values()):
f.convertToElementTreeFile(cix)
class PHPParser:
PHP_COMMENT_STYLES = (SCE_UDL_SSL_COMMENT, SCE_UDL_SSL_COMMENTBLOCK)
# lastText, lastStyle are use to remember the previous tokens.
lastText = None
lastStyle = None
def __init__(self, filename, content=None, mtime=None):
self.filename = filename
self.cile = PHPcile()
self.fileinfo = PHPFile(self.filename, content, mtime)
# Working variables, used in conjunction with state
self.classStack = []
self.currentClass = None
self.currentNamespace = None
self.currentFunction = None
self.csl_tokens = []
self.lineno = 0
self.depth = 0
self.styles = []
self.linenos = []
self.text = []
self.comment = None
self.comments = []
self.heredocMarker = None
# state : used to store the current JS lexing state
# return_to_state : used to store JS state to return to
# multilang_state : used to store the current UDL lexing state
self.state = S_DEFAULT
self.return_to_state = S_DEFAULT
self.multilang_state = S_DEFAULT
self.PHP_WORD = SCE_UDL_SSL_WORD
self.PHP_IDENTIFIER = SCE_UDL_SSL_IDENTIFIER
self.PHP_VARIABLE = SCE_UDL_SSL_VARIABLE
self.PHP_OPERATOR = SCE_UDL_SSL_OPERATOR
self.PHP_STRINGS = (SCE_UDL_SSL_STRING,)
self.PHP_NUMBER = SCE_UDL_SSL_NUMBER
# XXX bug 44775
# having the next line after scanData below causes a crash on osx
# in python's UCS2 to UTF8. leaving this here for later
# investigation, see bug 45362 for details.
self.cile.filesparsed[self.filename] = self.fileinfo
# parses included files
def include_file(self, filename):
# XXX Very simple prevention of include looping. Really should
# recurse the indices to make sure we are not creating a loop
if self.filename == filename:
return ""
# add the included file to our list of included files
self.fileinfo.includes.append(PHPImport(filename, self.lineno))
def incBlock(self):
self.depth = self.depth+1
# log.debug("depth at %d", self.depth)
def decBlock(self):
self.depth = self.depth-1
# log.debug("depth at %d", self.depth)
if self.currentClass and self.currentClass.depth == self.depth:
# log.debug("done with class %s at depth %d",
# self.currentClass.name, self.depth)
self.currentClass.lineend = self.lineno
log.debug("done with %s %s at depth %r",
isinstance(
self.currentClass, PHPInterface) and "interface" or "class",
self.currentClass.name, self.depth)
self.currentClass = self.classStack.pop()
if self.currentNamespace and self.currentNamespace.depth == self.depth:
log.debug("done with namespace %s at depth %r",
self.currentNamespace.name, self.depth)
self.currentNamespace.lineend = self.lineno
self.currentNamespace = None
elif self.currentFunction and self.currentFunction.depth == self.depth:
self.currentFunction.lineend = self.lineno
# XXX stacked functions used to work in php, need verify still is
self.currentFunction = None
def addFunction(self, name, phpArgs=None, attributes=None, doc=None,
returnByRef=False):
log.debug("FUNC: %s(%r) on line %d", name, phpArgs, self.lineno)
classname = ''
extendsName = ''
if self.currentClass:
classname = self.currentClass.name
extendsName = self.currentClass.extends
self.currentFunction = PHPFunction(name,
phpArgs,
self.lineno,
self.depth,
attributes=attributes,
doc=doc,
classname=classname,
classparent=extendsName,
returnByRef=returnByRef)
if self.currentClass:
self.currentClass.functions[
self.currentFunction.name] = self.currentFunction
elif self.currentNamespace:
self.currentNamespace.functions[
self.currentFunction.name] = self.currentFunction
else:
self.fileinfo.functions[
self.currentFunction.name] = self.currentFunction
if isinstance(self.currentClass, PHPInterface) or self.currentFunction.attributes.find('abstract') >= 0:
self.currentFunction.lineend = self.lineno
self.currentFunction = None
def addReturnType(self, typeName):
if self.currentFunction:
log.debug("RETURN TYPE: %r on line %d", typeName, self.lineno)
self.currentFunction.addReturnType(typeName)
else:
log.debug("addReturnType: No current function for return value!?")
def addClass(self, name, extends=None, attributes=None, interfaces=None, doc=None, isTrait=False):
toScope = self.currentNamespace or self.fileinfo
if name not in toScope.classes:
# push the current class onto the class stack
self.classStack.append(self.currentClass)
# make this class the current class
cixClass = isTrait and PHPTrait or PHPClass
self.currentClass = cixClass(name,
extends,
self.lineno,
self.depth,
attributes,
interfaces,
doc=doc)
toScope.classes[self.currentClass.name] = self.currentClass
log.debug(
"%s: %s extends %s interfaces %s attributes %s on line %d in %s at depth %d\nDOCS: %s",
self.currentClass.cixtype,
self.currentClass.name, self.currentClass.extends,
self.currentClass.interfaces, self.currentClass.attributes,
self.currentClass.linestart, self.filename, self.depth,
self.currentClass.doc)
else:
# shouldn't ever get here
pass
def addClassMember(self, name, vartype, attributes=None, doc=None, forceToClass=False):
if self.currentFunction and not forceToClass:
if name not in self.currentFunction.variables:
phpVariable = self.currentClass.members.get(name)
if phpVariable is None:
log.debug("Class FUNC variable: %r", name)
self.currentFunction.variables[name] = PHPVariable(name,
self.lineno,
vartype,
doc=doc)
elif vartype:
log.debug(
"Adding type information for VAR: %r, vartype: %r",
name, vartype)
phpVariable.addType(self.lineno, vartype)
elif self.currentClass:
phpVariable = self.currentClass.members.get(name)
if phpVariable is None:
log.debug("CLASSMBR: %r", name)
self.currentClass.members[name] = PHPVariable(
name, self.lineno,
vartype,
attributes,
doc=doc)
elif vartype:
log.debug(
"Adding type information for CLASSMBR: %r, vartype: %r",
name, vartype)
phpVariable.addType(self.lineno, vartype)
def addClassConstant(self, name, vartype, doc=None):
"""Add a constant variable into the current class."""
if self.currentClass:
phpConstant = self.currentClass.constants.get(name)
if phpConstant is None:
log.debug("CLASS CONST: %r", name)
self.currentClass.constants[name] = PHPConstant(
name, self.lineno,
vartype)
elif vartype:
log.debug("Adding type information for CLASS CONST: %r, "
"vartype: %r", name, vartype)
phpConstant.addType(self.lineno, vartype)
def addInterface(self, name, extends=None, doc=None):
toScope = self.currentNamespace or self.fileinfo
if name not in toScope.interfaces:
# push the current interface onto the class stack
self.classStack.append(self.currentClass)
# make this interface the current interface
self.currentClass = PHPInterface(
name, extends, self.lineno, self.depth)
toScope.interfaces[name] = self.currentClass
log.debug("INTERFACE: %s extends %s on line %d, depth %d",
name, extends, self.lineno, self.depth)
else:
# shouldn't ever get here
pass
def setNamespace(self, namelist, usesBracketedStyle, doc=None):
"""Create and set as the current namespace."""
if self.currentNamespace:
# End the current namespace before starting the next.
self.currentNamespace.lineend = self.lineno - 1
if not namelist:
# This means to use the global namespace, i.e.:
# namespace { // global code }
# http://ca3.php.net/manual/en/language.namespaces.definitionmultiple.php
self.currentNamespace = None
else:
depth = self.depth
if not usesBracketedStyle:
# If the namespacing does not uses brackets, then there is no
# good way to find out when the namespace end, we can only
# guarentee that the namespace ends if another namespace starts.
# Using None as the depth will ensure these semantics hold.
depth = None
namespace_path = qualifyNamespacePath("\\".join(namelist))
namespace = self.fileinfo.namespaces.get(namespace_path)
if namespace is None:
namespace = PHPNamespace(namespace_path, self.lineno, depth,
doc=doc)
self.fileinfo.namespaces[namespace_path] = namespace
self.currentNamespace = namespace
log.debug("NAMESPACE: %r on line %d in %s at depth %r",
namespace_path, self.lineno, self.filename, depth)
def addNamespaceImport(self, namespace, alias):
"""Import the namespace."""
namelist = namespace.split("\\")
namespace_path = "\\".join(namelist[:-1])
if namespace.startswith("\\") and not namespace_path.startswith("\\"):
namespace_path = "\\%s" % (namespace_path, )
symbol = namelist[-1]
toScope = self.currentNamespace or self.fileinfo
toScope.includes.append(PHPImport(namespace_path, self.lineno,
alias=alias, symbol=symbol))
log.debug("IMPORT NAMESPACE: %s\%s as %r on line %d",
namespace_path, symbol, alias, self.lineno)
def addVariable(self, name, vartype='', attributes=None, doc=None,
fromPHPDoc=False):
log.debug("VAR: %r type: %r on line %d", name, vartype, self.lineno)
phpVariable = None
already_existed = True
if self.currentFunction:
phpVariable = self.currentFunction.variables.get(name)
# Also ensure the variable is not a function argument.
if phpVariable is None and \
not self.currentFunction.hasArgumentWithName(name):
phpVariable = PHPVariable(name, self.lineno, vartype,
attributes, doc=doc,
fromPHPDoc=fromPHPDoc)
self.currentFunction.variables[name] = phpVariable
already_existed = False
elif self.currentClass:
pass
# XXX this variable is local to a class method, what to do with it?
# if m.group('name') not in self.currentClass.variables:
# self.currentClass.variables[m.group('name')] =\
# PHPVariable(m.group('name'), self.lineno)
else:
# Variables cannot get defined in a namespace, so if it's not a
# function or a class, then it goes into the global scope.
phpVariable = self.fileinfo.variables.get(name)
if phpVariable is None:
phpVariable = PHPVariable(name, self.lineno, vartype,
attributes, doc=doc,
fromPHPDoc=fromPHPDoc,
namespace=self.currentNamespace)
self.fileinfo.variables[name] = phpVariable
already_existed = False
if phpVariable and already_existed:
if doc:
if phpVariable.doc:
phpVariable.doc += doc
else:
phpVariable.doc = doc
if vartype:
log.debug("Adding type information for VAR: %r, vartype: %r",
name, vartype)
phpVariable.addType(
self.lineno, vartype, fromPHPDoc=fromPHPDoc)
return phpVariable
def addConstant(self, name, vartype='', doc=None):
"""Add a constant at the global or namelisted scope level."""
log.debug(
"CONSTANT: %r type: %r on line %d", name, vartype, self.lineno)
toScope = self.currentNamespace or self.fileinfo
phpConstant = toScope.constants.get(name)
# Add it if it's not already defined
if phpConstant is None:
if vartype and isinstance(vartype, (list, tuple)):
vartype = ".".join(vartype)
toScope.constants[name] = PHPConstant(name, self.lineno, vartype)
def addDefine(self, name, vartype='', doc=None):
"""Add a define at the global or namelisted scope level."""
log.debug("DEFINE: %r type: %r on line %d", name, vartype, self.lineno)
# Defines always go into the global scope unless explicitly defined
# with a namespace:
# http://ca3.php.net/manual/en/language.namespaces.definition.php
toScope = self.fileinfo
namelist = name.split("\\")
if len(namelist) > 1:
namespace_path = "\\".join(namelist[:-1])
namespace_path = qualifyNamespacePath(namespace_path)
log.debug("defined in namespace: %r", namespace_path)
namespace = toScope.namespaces.get(namespace_path)
# Note: This does not change to the namespace, it just creates
# it when it does not already exist!
if namespace is None:
namespace = PHPNamespace(namespace_path, self.lineno,
self.depth)
self.fileinfo.namespaces[namespace_path] = namespace
toScope = namespace
const_name = namelist[-1]
phpConstant = toScope.constants.get(const_name)
# Add it if it's not already defined
if phpConstant is None:
if vartype and isinstance(vartype, (list, tuple)):
vartype = ".".join(vartype)
toScope.constants[const_name] = PHPConstant(
const_name, self.lineno, vartype)
def _parseOneArgument(self, styles, text):
"""Create a PHPArg object from the given text"""
# Arguments can be of the form:
# foo($a, $b, $c)
# foo(&$a, &$b, &$c)
# foo($a, &$b, $c)
# foo($a = "123")
# makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
# Arguments can be statically typed declarations too, bug 79003:
# foo(MyClass $a)
# foo(string $a = "123")
# foo(MyClass &$a)
# References the inner class:
# static function bar($x=self::X)
pos = 0
name = None
citdl = None
default = None
sig_parts = []
log.debug("_parseOneArgument: text: %r", text)
while pos < len(styles):
sig_parts.append(text[pos])
if name is None:
if styles[pos] == self.PHP_VARIABLE:
name = self._removeDollarSymbolFromVariableName(text[pos])
elif styles[pos] in (self.PHP_IDENTIFIER, self.PHP_WORD):
# Statically typed argument.
citdl = text[pos]
sig_parts.append(" ")
elif text[pos] == '&':
sig_parts.append(" ")
elif not citdl:
if text[pos] == "=":
sig_parts[-1] = " = "
# It's an optional argument
default = "".join(text[pos+1:])
valueType, pos = self._getVariableType(styles, text, pos+1)
if valueType:
citdl = valueType[0]
break
else:
pos += 1
break
pos += 1
sig_parts += text[pos:]
if name is not None:
return PHPArg(name, citdl=citdl, signature="".join(sig_parts),
default=default)
def _getArgumentsFromPos(self, styles, text, pos):
"""Return a list of PHPArg objects"""
p = pos
log.debug("_getArgumentsFromPos: text: %r", text[p:])
phpArgs = []
if p < len(styles) and styles[p] == self.PHP_OPERATOR and text[p] == "(":
p += 1
paren_count = 0
start_pos = p
while p < len(styles):
if styles[p] == self.PHP_OPERATOR:
if text[p] == "(":
paren_count += 1
elif text[p] == ")":
if paren_count <= 0:
# End of the arguments.
break
paren_count -= 1
elif text[p] == "," and paren_count == 0:
# End of the current argument.
phpArg = self._parseOneArgument(styles[start_pos:p],
text[start_pos:p])
if phpArg:
phpArgs.append(phpArg)
start_pos = p + 1
p += 1
if start_pos < p:
phpArg = self._parseOneArgument(styles[start_pos:p],
text[start_pos:p])
if phpArg:
phpArgs.append(phpArg)
return phpArgs, p
def _getOneIdentifierFromPos(self, styles, text, pos, identifierStyle=None):
if identifierStyle is None:
identifierStyle = self.PHP_IDENTIFIER
log.debug("_getIdentifiersFromPos: text: %r", text[pos:])
start_pos = pos
ids = []
last_style = self.PHP_OPERATOR
isNamespace = False
while pos < len(styles):
style = styles[pos]
# print "Style: %d, Text[%d]: %r" % (style, pos, text[pos])
if style == identifierStyle:
if last_style != self.PHP_OPERATOR:
break
if isNamespace:
ids[-1] += text[pos]
else:
ids.append(text[pos])
elif style == self.PHP_OPERATOR:
t = text[pos]
isNamespace = False
if t == "\\":
isNamespace = True
if ids:
ids[-1] += "\\"
else:
ids.append("\\")
elif ((t != "&" or last_style != self.PHP_OPERATOR) and
(t != ":" or last_style != identifierStyle)):
break
else:
break
pos += 1
last_style = style
return ids, pos
def _getIdentifiersFromPos(self, styles, text, pos, identifierStyle=None):
typeNames, p = self._getOneIdentifierFromPos(
styles, text, pos, identifierStyle)
if typeNames:
typeNames[0] = self._removeDollarSymbolFromVariableName(
typeNames[0])
log.debug(
"typeNames: %r, p: %d, text left: %r", typeNames, p, text[p:])
# Grab additional fields
# Example: $x = $obj<p>->getFields()->field2
while p+2 < len(styles) and styles[p] == self.PHP_OPERATOR and \
text[p] in (":->\\"):
isNamespace = False
if text[p] == "\\":
isNamespace = True
p += 1
log.debug("while:: p: %d, text left: %r", p, text[p:])
if styles[p] == self.PHP_IDENTIFIER or \
(styles[p] == self.PHP_VARIABLE and text[p-1] == ":"):
additionalNames, p = self._getOneIdentifierFromPos(
styles, text, p, styles[p])
log.debug("p: %d, additionalNames: %r", p, additionalNames)
if additionalNames:
if isNamespace:
if typeNames:
typeNames[-1] += "\\%s" % (additionalNames[0])
else:
typeNames.append("\\%s" % (additionalNames[0]))
else:
typeNames.append(additionalNames[0])
if p < len(styles) and \
styles[p] == self.PHP_OPERATOR and text[p][0] == "(":
typeNames[-1] += "()"
p = self._skipPastParenArguments(styles, text, p+1)
log.debug(
"_skipPastParenArguments:: p: %d, text left: %r", p, text[p:])
return typeNames, p
def _skipPastParenArguments(self, styles, text, p):
paren_count = 1
while p < len(styles):
if styles[p] == self.PHP_OPERATOR:
if text[p] == "(":
paren_count += 1
elif text[p] == ")":
if paren_count == 1:
return p+1
paren_count -= 1
p += 1
return p
_citdl_type_from_cast = {
"int": "int",
"integer": "int",
"bool": "boolean",
"boolean": "boolean",
"float": "int",
"double": "int",
"real": "int",
"string": "string",
"binary": "string",
"array": "array()", # array(), see bug 32896.
"object": "object",
}
def _getVariableType(self, styles, text, p, assignmentChar="="):
"""Set assignmentChar to None to skip over looking for this char first"""
log.debug("_getVariableType: text: %r", text[p:])
typeNames = []
if p+1 < len(styles) and (assignmentChar is None or
(styles[p] == self.PHP_OPERATOR and
text[p] == assignmentChar)):
# Assignment to the variable
if assignmentChar is not None:
p += 1
if p+1 >= len(styles):
return typeNames, p
if styles[p] == self.PHP_OPERATOR and text[p] == '&':
log.debug("_getVariableType: skipping over reference char '&'")
p += 1
if p+1 >= len(styles):
return typeNames, p
elif p+3 <= len(styles) and styles[p] == self.PHP_OPERATOR and \
text[p+2] == ')' and text[p+1] in self._citdl_type_from_cast:
# Looks like a casting:
# http://ca.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting
# $bar = (boolean) $foo;
typeNames = [self._citdl_type_from_cast.get(text[p+1])]
log.debug("_getVariableType: casted to type: %r", typeNames)
p += 3
return typeNames, p
if styles[p] == self.PHP_WORD:
# Keyword
keyword = text[p].lower()
p += 1
if keyword == "new":
typeNames, p = self._getIdentifiersFromPos(styles, text, p)
# if not typeNames:
# typeNames = ["object"]
elif keyword in ("true", "false"):
typeNames = ["boolean"]
elif keyword == "array":
typeNames = ["array()"]
elif keyword == "clone":
# clone is a special method - bug 85534.
typeNames, p = self._getIdentifiersFromPos(styles, text, p,
identifierStyle=self.PHP_VARIABLE)
elif styles[p] in self.PHP_STRINGS:
p += 1
typeNames = ["string"]
elif styles[p] == self.PHP_NUMBER:
p += 1
typeNames = ["int"]
elif styles[p] == self.PHP_IDENTIFIER:
# PHP Uses mixed upper/lower case for boolean values.
if text[p].lower() in ("true", "false"):
p += 1
typeNames = ["boolean"]
else:
typeNames, p = self._getIdentifiersFromPos(styles, text, p)
# Don't record null, as it doesn't help us with anything
if typeNames == ["NULL"]:
typeNames = []
elif typeNames and p < len(styles) and \
styles[p] == self.PHP_OPERATOR and text[p][0] == "(":
typeNames[-1] += "()"
elif styles[p] == self.PHP_VARIABLE:
typeNames, p = self._getIdentifiersFromPos(
styles, text, p, self.PHP_VARIABLE)
elif styles[p] == self.PHP_OPERATOR and text[p] == "\\":
typeNames, p = self._getIdentifiersFromPos(
styles, text, p, self.PHP_IDENTIFIER)
return typeNames, p
def _getKeywordArguments(self, styles, text, p, keywordName):
arguments = None
while p < len(styles):
if styles[p] == self.PHP_WORD and text[p] == keywordName:
# Grab the definition
p += 1
arguments = []
last_style = self.PHP_OPERATOR
namespaced = False
while p < len(styles):
if styles[p] == self.PHP_IDENTIFIER and \
last_style == self.PHP_OPERATOR:
if namespaced:
arguments[-1] += text[p]
namespaced = False
else:
arguments.append(text[p])
elif styles[p] == self.PHP_OPERATOR and text[p] == "\\":
if not arguments or last_style != self.PHP_IDENTIFIER:
arguments.append(text[p])
else:
arguments[-1] += text[p]
namespaced = True
elif styles[p] != self.PHP_OPERATOR or text[p] != ",":
break
last_style = styles[p]
p += 1
arguments = ", ".join(arguments)
break
p += 1
return arguments
def _getExtendsArgument(self, styles, text, p):
return self._getKeywordArguments(styles, text, p, "extends")
def _getImplementsArgument(self, styles, text, p):
return self._getKeywordArguments(styles, text, p, "implements")
def _unquoteString(self, s):
"""Return the string without quotes around it"""
if len(s) >= 2 and s[0] in "\"'":
return s[1:-1]
return s
def _removeDollarSymbolFromVariableName(self, name):
if name[0] == "$":
return name[1:]
return name
def _getIncludePath(self, styles, text, p):
"""Work out the include string and return it (without the quotes)"""
# Some examples (include has identical syntax):
# require 'prepend.php';
# require $somefile;
# require ('somefile.txt');
# From bug: http://bugs.activestate.com/show_bug.cgi?id=64208
# We just find the first string and use that
# require_once(CEON_CORE_DIR . 'core/datatypes/class.CustomDT.php');
# Skip over first brace if it exists
if p < len(styles) and \
styles[p] == self.PHP_OPERATOR and text[p] == "(":
p += 1
while p < len(styles):
if styles[p] in self.PHP_STRINGS:
requirename = self._unquoteString(text[p])
if requirename:
# Return with the first string found, we could do better...
return requirename
p += 1
return None
def _unescape_string(self, s):
"""Unescape a PHP string."""
return s.replace("\\\\", "\\")
def _getConstantNameAndType(self, styles, text, p):
"""Work out the constant name and type is, returns these as tuple"""
# Some examples (include has identical syntax):
# define('prepend', 1);
# define ('somefile', "file.txt");
# define('\namespace\CONSTANT', True);
# define(__NAMESPACE__ . '\CONSTANT', True);
constant_name = ""
constant_type = None
if styles[p] == self.PHP_OPERATOR and text[p] == "(":
p += 1
while p < len(styles):
if styles[p] in self.PHP_STRINGS:
constant_name += self._unquoteString(text[p])
elif styles[p] == self.PHP_WORD and \
text[p] == "__NAMESPACE__" and self.currentNamespace:
# __NAMESPACE__ is a special constant - we can expand this as we
# know what the current namespace is.
constant_name += self.currentNamespace.name
elif text[p] == ",":
constant_type, p = self._getVariableType(styles, text, p+1,
assignmentChar=None)
break
p += 1
# We must ensure the name (which came from a PHP string is unescaped),
# bug 90795.
return self._unescape_string(constant_name), constant_type
def _addAllVariables(self, styles, text, p):
while p < len(styles):
if styles[p] == self.PHP_VARIABLE:
namelist, p = self._getIdentifiersFromPos(
styles, text, p, self.PHP_VARIABLE)
if len(namelist) == 1:
name = self._removeDollarSymbolFromVariableName(
namelist[0])
# Don't add special internal variable names
if name in ("this", "self"):
# Lets see what we are doing with this
if p+3 < len(styles) and "".join(text[p:p+2]) in ("->", "::"):
# Get the variable the code is accessing
namelist, p = self._getIdentifiersFromPos(
styles, text, p+2)
typeNames, p = self._getVariableType(
styles, text, p)
if len(namelist) == 1 and typeNames:
log.debug(
"Assignment through %r for variable: %r", name, namelist)
self.addClassMember(namelist[0],
".".join(typeNames),
doc=self.comment,
forceToClass=True)
elif name is not "parent":
# If next text/style is not an "=" operator, then add
# __not_defined__, which means the variable was not yet
# defined at the position it was ciled.
attributes = None
if p < len(styles) and text[p] != "=":
attributes = "__not_yet_defined__"
self.addVariable(name, attributes=attributes)
p += 1
def _handleVariableComment(self, namelist, comment):
"""Determine any necessary information from the provided comment.
Returns true when the comment was used to apply variable info, false
otherwise.
"""
log.debug("_handleVariableComment:: namelist: %r, comment: %r",
namelist, comment)
if "@var" in comment:
doc = uncommentDocString(comment)
# get the variable citdl type set by "@var"
all_matches = re.findall(PHPVariable._re_var, doc)
if len(all_matches) >= 1:
# print all_matches[0]
varname = all_matches[0][1]
vartype = all_matches[0][2]
php_variable = None
if varname:
# Optional, defines the variable this is applied to.
php_variable = self.addVariable(varname, vartype,
doc=comment,
fromPHPDoc=True)
return True
elif namelist:
php_variable = self.addVariable(namelist[0], vartype,
doc=comment,
fromPHPDoc=True)
return True
return False
def _variableHandler(self, styles, text, p, attributes, doc=None,
style="variable"):
log.debug("_variableHandler:: style: %r, text: %r, attributes: %r",
style, text[p:], attributes)
classVar = False
if attributes:
classVar = True
if "var" in attributes:
attributes.remove("var") # Don't want this in cile output
if style == "const":
if self.currentClass is not None:
classVar = True
elif self.currentNamespace is not None:
classVar = False
else:
log.debug("Ignoring const %r, as not defined in a "
"class or namespace context.", text)
return
looped = False
while p < len(styles):
if looped:
if text[p] != ",": # Variables need to be comma delimited.
p += 1
continue
p += 1
else:
looped = True
if style == "const":
namelist, p = self._getIdentifiersFromPos(styles, text, p,
self.PHP_IDENTIFIER)
elif text[p:p+3] == ["self", ":", ":"]:
# Handle things like: "self::$instance = FOO", bug 92813.
classVar = True
namelist, p = self._getIdentifiersFromPos(styles, text, p+3,
self.PHP_VARIABLE)
else:
namelist, p = self._getIdentifiersFromPos(styles, text, p,
self.PHP_VARIABLE)
if not namelist:
break
log.debug("namelist:%r, p:%d", namelist, p)
# Remove the dollar sign
name = self._removeDollarSymbolFromVariableName(namelist[0])
# Parse special internal variable names
if name == "parent":
continue
thisVar = False
if name in ("this", "self", ):
classVar = True
thisVar = True # need to distinguish between class var types.
if len(namelist) <= 1:
continue
# We don't need the this/self piece of the namelist.
namelist = namelist[1:]
name = namelist[0]
if len(namelist) != 1:
# Example: "item->foo;" translates to namelist: [item, foo]
if self.comment:
# We may be able to get some PHPDoc out of the comment.
if self._handleVariableComment(namelist, self.comment):
self.comment = None
log.info("multiple part variable namelist (ignoring): "
"%r, line: %d in file: %r", namelist,
self.lineno, self.filename)
continue
if name.endswith("()"):
# Example: "foo(x);" translates to namelist: [foo()]
if self.comment:
# We may be able to get some PHPDoc out of the comment.
if self._handleVariableComment(namelist, self.comment):
self.comment = None
log.info("variable is making a method call (ignoring): "
"%r, line: %d in file: %r", namelist,
self.lineno, self.filename)
continue
assignChar = text[p]
typeNames = []
mustCreateVariable = False
# Work out the citdl, we also ensure this is not just a comparison,
# i.e. not "$x == 2".
if p+1 < len(styles) and styles[p] == self.PHP_OPERATOR and \
assignChar in "=" and \
(p+2 >= len(styles) or text[p+1] != "="):
# Assignment to the variable
mustCreateVariable = True
typeNames, p = self._getVariableType(
styles, text, p, assignChar)
log.debug("typeNames: %r", typeNames)
# Skip over paren arguments from class, function calls.
if typeNames and p < len(styles) and \
styles[p] == self.PHP_OPERATOR and text[p] == "(":
p = self._skipPastParenArguments(styles, text, p+1)
# Create the variable cix information.
if mustCreateVariable or (not thisVar and p < len(styles) and
styles[p] == self.PHP_OPERATOR and
text[p] in ",;"):
log.debug("Line %d, variable definition: %r",
self.lineno, namelist)
if style == "const":
if classVar:
self.addClassConstant(name, ".".join(typeNames),
doc=self.comment)
else:
self.addConstant(name, ".".join(typeNames),
doc=self.comment)
elif classVar and self.currentClass is not None:
self.addClassMember(name, ".".join(typeNames),
attributes=attributes, doc=self.comment,
forceToClass=classVar)
else:
self.addVariable(name, ".".join(typeNames),
attributes=attributes, doc=self.comment)
def _useKeywordHandler(self, styles, text, p):
log.debug("_useKeywordHandler:: text: %r", text[p:])
looped = False
while p < len(styles):
if looped:
if text[p] != ",": # Use statements need to be comma delimited.
p += 1
continue
p += 1
else:
looped = True
namelist, p = self._getIdentifiersFromPos(styles, text, p)
log.debug("use:%r, p:%d", namelist, p)
if namelist:
alias = None
if p+1 < len(styles):
if styles[p] == self.PHP_WORD and \
text[p] == "as":
# Uses an alias
alias, p = self._getIdentifiersFromPos(
styles, text, p+1)
if alias:
alias = alias[0]
if self.currentClass:
# Must be a trait.
self.currentClass.addTraitReference(namelist[0])
else:
# Must be a namespace reference.
self.addNamespaceImport(namelist[0], alias)
def _handleTraitResolution(self, styles, text, p, doc=None):
log.debug("_handleTraitResolution:: text: %r", text[p:])
# Examples:
# B::smallTalk insteadof A;
# B::bigTalk as talk;
# sayHello as protected;
# sayHello as private myPrivateHello;
# Can only be defined on a trait or a class.
if not self.currentClass:
log.warn(
"_handleTraitResolution:: not in a class|trait definition")
return
# Look for the identifier first.
#
namelist, p = self._getIdentifiersFromPos(styles, text, p,
self.PHP_IDENTIFIER)
log.debug("namelist:%r, p:%d", namelist, p)
if not namelist or p+2 >= len(text):
log.warn("Not enough arguments in trait use statement: %r", text)
return
# Get the keyword "as", "insteadof"
keyword = text[p]
log.debug("keyword:%r", keyword)
p += 1
# Get the settings.
alias = None
visibility = None
# Get special attribute keywords.
if keyword == "as" and \
text[p] in ("public", "protected", "private"):
visibility = text[p]
p += 1
log.debug("_handleTraitResolution: visibility %r", visibility)
if p < len(text):
# Get the alias name.
names, p = self._getIdentifiersFromPos(styles, text, p)
if names:
alias = names[0]
if len(names) > 1:
log.warn("Ignoring multiple alias identifiers in text: %r",
text)
if alias or visibility:
# Set override.
self.currentClass.addTraitOverride(namelist, alias,
visibility=visibility,
insteadOf=(keyword == "insteadof"))
else:
self.warn("Unknown trait resolution: %r", text)
def _addCodePiece(self, newstate=S_DEFAULT, varnames=None):
styles = self.styles
if len(styles) == 0:
return
text = self.text
lines = self.linenos
log.debug("*** Line: %d ********************************", self.lineno)
# log.debug("Styles: %r", self.styles)
log.debug("Text: %r", self.text)
# log.debug("Comment: %r", self.comment)
# log.debug("")
pos = 0
attributes = []
firstStyle = styles[pos]
try:
# We may be able to get some PHPDoc out of the comment already,
# such as targeted "@var " comments.
# http://bugs.activestate.com/show_bug.cgi?id=76676
if self.comment and self._handleVariableComment(None, self.comment):
self.comment = None
# Eat special attribute keywords
while firstStyle == self.PHP_WORD and \
text[pos] in ("var", "public", "protected", "private",
"final", "static", "abstract"):
attributes.append(text[pos])
pos += 1
firstStyle = styles[pos]
if firstStyle == self.PHP_WORD:
keyword = text[pos].lower()
pos += 1
if pos >= len(lines):
# Nothing else here, go home
return
self.lineno = lines[pos]
if keyword in ("require", "include", "require_once", "include_once"):
# Some examples (include has identical syntax):
# require 'prepend.php';
# require $somefile;
# require ('somefile.txt');
# XXX - Below syntax is not handled...
# if ((include 'vars.php') == 'OK') {
namelist = None
if pos < len(styles):
requirename = self._getIncludePath(styles, text, pos)
if requirename:
self.include_file(requirename)
else:
log.debug(
"Could not work out requirename. Text: %r",
text[pos:])
elif keyword == "define":
# Defining a constant
# define("FOO", "something");
# define('TEST_CONSTANT', FALSE);
name, citdl = self._getConstantNameAndType(
styles, text, pos)
if name:
self.addDefine(name, citdl)
elif keyword == "const":
# Defining a class constant
# const myconstant = x;
self._variableHandler(styles, text, pos, attributes,
doc=self.comment, style="const")
elif keyword == "function":
namelist, p = self._getIdentifiersFromPos(
styles, text, pos)
log.debug("namelist:%r, p:%d", namelist, p)
if namelist:
returnByRef = (text[pos] == "&")
phpArgs, p = self._getArgumentsFromPos(styles, text, p)
log.debug("Line %d, function: %r(%r)",
self.lineno, namelist, phpArgs)
if len(namelist) != 1:
log.info("warn: invalid function name (ignoring): "
"%r, line: %d in file: %r", namelist,
self.lineno, self.filename)
return
self.addFunction(namelist[0], phpArgs, attributes,
doc=self.comment,
returnByRef=returnByRef)
elif keyword == "class" or keyword == "trait":
# Examples:
# class SimpleClass {
# class SimpleClass2 extends SimpleClass {
# class MyClass extends AbstractClass implements TestInterface, TestMethodsInterface {
#
namelist, p = self._getIdentifiersFromPos(
styles, text, pos)
if namelist and "{" in text:
if len(namelist) != 1:
log.info("warn: invalid class name (ignoring): %r, "
"line: %d in file: %r", namelist,
self.lineno, self.filename)
return
extends = self._getExtendsArgument(styles, text, p)
implements = self._getImplementsArgument(
styles, text, p)
# print "extends: %r" % (extends)
# print "implements: %r" % (implements)
self.addClass(namelist[0], extends=extends,
attributes=attributes,
interfaces=implements, doc=self.comment,
isTrait=(keyword == "trait"))
elif keyword == "interface":
# Examples:
# interface Foo {
# interface SQL_Result extends SeekableIterator, Countable {
#
namelist, p = self._getIdentifiersFromPos(
styles, text, pos)
if namelist and "{" in text:
if len(namelist) != 1:
log.info("warn: invalid interface name (ignoring): "
"%r, line: %d in file: %r", namelist,
self.lineno, self.filename)
return
extends = self._getExtendsArgument(styles, text, p)
self.addInterface(namelist[
0], extends, doc=self.comment)
elif keyword in ("return", "yield"):
# Returning value for a function call
# return 123;
# return $x;
typeNames, p = self._getVariableType(
styles, text, pos, assignmentChar=None)
log.debug("typeNames:%r", typeNames)
if typeNames:
self.addReturnType(".".join(typeNames))
elif keyword == "catch" and pos+3 >= len(text):
# catch ( Exception $e)
pos += 1 # skip the paren
typeNames, p = self._getVariableType(
styles, text, pos, assignmentChar=None)
namelist, p = self._getIdentifiersFromPos(
styles, text, p, self.PHP_VARIABLE)
if namelist and typeNames:
self.addVariable(namelist[0], ".".join(typeNames))
elif keyword == "namespace":
namelist, p = self._getIdentifiersFromPos(
styles, text, pos)
log.debug("namelist:%r, p:%d", namelist, p)
if namelist:
usesBraces = "{" in text
self.setNamespace(namelist, usesBraces,
doc=self.comment)
elif keyword == "use":
self._useKeywordHandler(styles, text, pos)
if text and text[-1] == "{":
self.return_to_state = newstate
newstate = S_TRAIT_RESOLUTION
else:
log.debug("Ignoring keyword: %s", keyword)
self._addAllVariables(styles, text, pos)
elif firstStyle == self.PHP_IDENTIFIER:
if text[0] == "self":
self._variableHandler(styles, text, pos, attributes,
doc=self.comment)
elif self.state == S_TRAIT_RESOLUTION:
self._handleTraitResolution(
styles, text, pos, doc=self.comment)
log.debug("Trait resolution: text: %r, pos: %d", text, pos)
# Stay in this state.
newstate = S_TRAIT_RESOLUTION
else:
log.debug("Ignoring when starting with identifier")
elif firstStyle == self.PHP_VARIABLE:
# Defining scope for action
self._variableHandler(styles, text, pos, attributes,
doc=self.comment)
else:
log.debug("Unhandled first style:%d", firstStyle)
finally:
self._resetState(newstate)
def _resetState(self, newstate=S_DEFAULT):
self.state = newstate
self.styles = []
self.linenos = []
self.text = []
self.comment = None
self.comments = []
def token_next(self, style, text, start_column, start_line, **other_args):
"""Loops over the styles in the document and stores important info.
When enough info is gathered, will perform a call to analyze the code
and generate subsequent language structures. These language structures
will later be used to generate XML output for the document."""
# log.debug("text: %r", text)
# print "text: %r, style: %r" % (text, style)
if self.state == S_GET_HEREDOC_MARKER:
if not text.strip():
log.debug("Ignoring whitespace after <<<: %r", text)
return
self.heredocMarker = self._unquoteString(text)
log.debug("getting heredoc marker: %r, now in heredoc state", text)
self._resetState(S_IN_HEREDOC)
elif self.state == S_IN_HEREDOC:
# Heredocs *must* be on the start of a newline
if text == self.heredocMarker and self.lastText and \
self.lastText[-1] in "\r\n":
log.debug("end of heredoc: %r", self.heredocMarker)
self._resetState(self.return_to_state)
else:
log.debug("ignoring heredoc material")
elif (style in (self.PHP_WORD, self.PHP_IDENTIFIER,
self.PHP_OPERATOR, self.PHP_NUMBER, self.PHP_VARIABLE) or
style in (self.PHP_STRINGS)):
# We keep track of these styles and the text associated with it.
# When we gather enough info, these will be sent to the
# _addCodePiece() function which will analyze the info.
self.lineno = start_line + 1
if style != self.PHP_OPERATOR:
# Have to trim whitespace, as the identifier style is
# also the default whitespace style... ugly!
if style == self.PHP_IDENTIFIER:
text = text.strip()
if text:
self.text.append(text)
self.styles.append(style)
self.linenos.append(self.lineno)
# print "Text:", text
else:
# Do heredoc parsing, since UDL cannot as yet
if text == "<<<":
self.return_to_state = self.state
self.state = S_GET_HEREDOC_MARKER
# Remove out any "<?php" and "?>" tags, see syntax description:
# http://www.php.net/manual/en/language.basic-syntax.php
elif text.startswith("<?"):
if text[:5].lower() == "<?php":
text = text[5:]
elif text.startswith("<?="):
text = text[len("<?="):]
else:
text = text[len("<?"):]
elif text.startswith("<%"):
if text.startswith("<%="):
text = text[len("<%="):]
else:
text = text[len("<%"):]
if text.endswith("?>"):
text = text[:-len("?>")]
elif text.endswith("<%"):
text = text[:-len("%>")]
col = start_column + 1
# for op in text:
# self.styles.append(style)
# self.text.append(op)
# log.debug("token_next: line %d, %r" % (self.lineno, text))
for op in text:
self.styles.append(style)
self.text.append(op)
self.linenos.append(self.lineno)
if op == "(":
# We can start defining arguments now
# log.debug("Entering S_IN_ARGS state")
self.return_to_state = self.state
self.state = S_IN_ARGS
elif op == ")":
# log.debug("Entering state %d", self.return_to_state)
self.state = self.return_to_state
elif op == "=":
if text == op:
# log.debug("Entering S_IN_ASSIGNMENT state")
self.state = S_IN_ASSIGNMENT
elif op == "{":
# Increasing depth/scope, could be an argument object
self._addCodePiece()
self.incBlock()
elif op == "}":
# Decreasing depth/scope
if len(self.text) == 1:
self._resetState()
else:
self._addCodePiece()
self.decBlock()
elif op == ":":
# May be an alternative syntax
if len(self.text) > 0 and \
self.styles[0] == self.PHP_WORD and \
self.text[0].lower() in ("if", "elseif", "else", "while", "for", "foreach", "switch"):
# print "Alt syntax? text: %r" % (self.text, )
self._addCodePiece()
elif "case" in self.text or "default" in self.text:
# Part of a switch statement - bug 86927.
self._addCodePiece()
elif op == ";":
# Statement is done
if len(self.text) > 0 and \
self.styles[0] == self.PHP_WORD and \
self.text[-1].lower() in ("endif", "endwhile", "endfor", "endforeach", "endswitch"):
# Alternative syntax, remove this from the text.
self.text = self.text[:-1]
self._addCodePiece()
col += 1
elif style in self.PHP_COMMENT_STYLES:
# Use rstrip to remove any trailing spaces or newline characters.
comment = text.rstrip()
# Check if it's a continuation from the last comment. If we have
# already collected text then this is a comment in the middle of a
# statement, so do not set self.comment, but rather just add it to
# the list of known comment sections (self.comments).
if not self.text:
if style == SCE_UDL_SSL_COMMENT and self.comment and \
start_line <= (self.comments[-1][2] + 1) and \
style == self.comments[-1][1]:
self.comment += comment
else:
self.comment = comment
self.comments.append([comment, style, start_line, start_column])
elif style == SCE_UDL_SSL_DEFAULT and \
self.lastStyle in self.PHP_COMMENT_STYLES and text[0] in "\r\n":
# This is necessary as line comments are supplied to us without
# the newlines, so check to see if this is a newline and if the
# last line was a comment, append it the newline to it.
if self.comment:
self.comment += "\n"
self.comments[-1][0] += "\n"
elif is_udl_csl_style(style):
self.csl_tokens.append({"style": style,
"text": text,
"start_column": start_column,
"start_line": start_line})
self.lastText = text
self.lastStyle = style
def scan_multilang_content(self, content):
"""Scan the given PHP content, only processes SSL styles"""
PHPLexer().tokenize_by_style(content, self.token_next)
return self.csl_tokens
def convertToElementTreeFile(self, cixelement):
"""Store PHP information into the cixelement as a file(s) sub element"""
self.cile.convertToElementTreeFile(cixelement)
def convertToElementTreeModule(self, cixblob):
"""Store PHP information into already created cixblob"""
self.cile.convertToElementTreeModule(cixblob)
#---- internal utility functions
def _isident(char):
return "a" <= char <= "z" or "A" <= char <= "Z" or char == "_"
def _isdigit(char):
return "0" <= char <= "9"
#---- public module interface
#---- registration
def register(mgr):
"""Register language support with the Manager."""
mgr.set_lang_info(lang,
silvercity_lexer=PHPLexer(),
buf_class=PHPBuffer,
langintel_class=PHPLangIntel,
import_handler_class=PHPImportHandler,
cile_driver_class=PHPCILEDriver,
is_cpln_lang=True,
import_everything=True)
| mit |
open-motivation/motivation-ide | ninja_ide/gui/main_panel/class_diagram.py | 2 | 8685 | # -*- coding: utf-8 -*-
#
# This file is part of NINJA-IDE (http://ninja-ide.org).
#
# NINJA-IDE 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
# any later version.
#
# NINJA-IDE 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 NINJA-IDE; If not, see <http://www.gnu.org/licenses/>.
from PyQt4.QtCore import Qt
from PyQt4.QtCore import QRectF
from PyQt4.QtGui import QGraphicsItem
from PyQt4.QtGui import QRadialGradient
from PyQt4.QtGui import QGraphicsTextItem
from PyQt4.QtGui import QStyle
from PyQt4.QtGui import QColor
from PyQt4.QtGui import QPen
from PyQt4.QtGui import QWidget
from PyQt4.QtGui import QGraphicsView
from PyQt4.QtGui import QGraphicsScene
from PyQt4.QtGui import QVBoxLayout
from ninja_ide.gui.main_panel import itab_item
from ninja_ide.tools import introspection
from ninja_ide.core import file_manager
class ClassDiagram(QWidget, itab_item.ITabItem):
def __init__(self, actions, parent=None):
QWidget.__init__(self, parent)
itab_item.ITabItem.__init__(self)
self.actions = actions
self.graphicView = QGraphicsView(self)
self.scene = QGraphicsScene()
self.graphicView.setScene(self.scene)
self.graphicView.setViewportUpdateMode(
QGraphicsView.BoundingRectViewportUpdate)
vLayout = QVBoxLayout(self)
self.setLayout(vLayout)
vLayout.addWidget(self.graphicView)
self.scene.setItemIndexMethod(QGraphicsScene.NoIndex)
self.scene.setSceneRect(-200, -200, 400, 400)
self.graphicView.setMinimumSize(400, 400)
actualProject = self.actions.ide.explorer.get_actual_project()
arrClasses = self.actions._locator.get_classes_from_project(
actualProject)
#FIXME:dirty need to fix
self.mX = -400
self.mY = -320
self.hightestY = self.mY
filesList = []
for elem in arrClasses:
#loking for paths
filesList.append(elem[2])
for path in set(filesList):
self.create_class(path)
def create_class(self, path):
content = file_manager.read_file_content(path)
items = introspection.obtain_symbols(content)
mYPadding = 10
mXPadding = 10
for classname, classdetail in list(items["classes"].items()):
cl = ClassModel(self.graphicView, self.scene)
cl.set_class_name(classname)
self.fill_clases(cl, classdetail[1])
self.scene.addItem(cl)
cl.setPos(self.mX, self.mY)
self.mX += cl._get_width() + mXPadding
if self.hightestY < self.mY + cl.get_height():
self.hightestY = self.mY + cl.get_height()
if self.mX > 2000:
self.mX = -400
self.mY += self.hightestY + mYPadding
def fill_clases(self, classComponent, classContent):
funct = classContent['functions']
classComponent.set_functions_list(funct)
attr = classContent['attributes']
classComponent.set_attributes_list(attr)
def scale_view(self, scaleFactor):
factor = self.graphicView.transform().scale(
scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width()
if factor > 0.05 and factor < 15:
self.graphicView.scale(scaleFactor, scaleFactor)
def keyPressEvent(self, event):
taskList = {
Qt.Key_Plus: lambda: self.scaleView(1.2),
Qt.Key_Minus: lambda: self.scaleView(1 / 1.2)}
if(event.key() in taskList):
taskList[event.key()]()
else:
QWidget.keyPressEvent(self, event)
class ClassModel(QGraphicsItem):
def __init__(self, parent=None, graphicView=None, graphicScene=None):
QGraphicsItem.__init__(self)
self.set_default_data()
self.className = QGraphicsTextItem(self)
self.functionsItem = FunctionsContainerModel(self)
self.className.setPlainText(self.defaultClassName)
self.setFlag(self.ItemIsMovable)
self.setFlag(self.ItemSendsGeometryChanges)
self.functionsItem.setPos(0, self.__get_title_height())
self.attributesItem = FunctionsContainerModel(self)
self.attributesItem.setPos(0, self.functionsItem.get_height())
def set_default_data(self):
self.maxWidth = 100
self.defaultClassNameHeight = 30
self.defaultClassName = "No name"
def set_functions_list(self, functionsList):
self.functionsItem.set_functions_list(functionsList, "*", "()")
self.update_positions()
def set_attributes_list(self, attributesList):
self.attributesItem.set_functions_list(attributesList)
self.update_positions()
def set_class_name(self, className):
self.className.setPlainText(className)
def _get_width(self):
self.__calc_max_width()
return self.maxWidth
def __get_title_height(self):
titleHeight = self.defaultClassNameHeight
if titleHeight == self.className.document().size().height():
titleHeight = self.className.document().size().height()
return titleHeight
def get_height(self):
summary = self.defaultClassNameHeight
summary += self.functionsItem.get_height()
summary += self.attributesItem.get_height()
return summary
def __calc_max_width(self):
if self.maxWidth < self.className.document().size().width():
self.maxWidth = self.className.document().size().width()
if hasattr(self, "functionsItem"):
if self.maxWidth < self.functionsItem.get_width():
self.maxWidth = self.functionsItem.get_width()
if hasattr(self, "attributesItem"):
if self.maxWidth < self.attributesItem.get_width():
self.maxWidth = self.attributesItem.get_width()
def set_bg_color(self, qColor):
self.backgroundColor = qColor
def set_method_list(self, itemList):
self.methodList = itemList
def update_positions(self):
self.functionsItem.setPos(0, self.__get_title_height())
self.attributesItem.setPos(
0, self.functionsItem.y() + self.functionsItem.get_height())
def paint(self, painter, option, widget):
gradient = QRadialGradient(-3, -3, 10)
if option.state & QStyle.State_Sunken:
gradient.setCenter(3, 3)
gradient.setFocalPoint(3, 3)
gradient.setColorAt(0, QColor(Qt.yellow).light(120))
else:
gradient.setColorAt(0, QColor(Qt.yellow).light(120))
painter.setBrush(gradient)
painter.setPen(QPen(Qt.black, 0))
painter.drawRoundedRect(self.boundingRect(), 3, 3)
def boundingRect(self):
return QRectF(0, 0, self._get_width(), self.get_height())
def add_edge(self, edge):
self.myEdge = edge
edge.adjust()
class FunctionsContainerModel(QGraphicsItem):
def __init__(self, parent=None):
QGraphicsItem.__init__(self, parent)
self.parent = parent
self.maxWidth = self.parent._get_width()
self.maxHeight = 0
def paint(self, painter, option, widget):
painter.drawLine(
self.boundingRect().topLeft(), self.boundingRect().topRight())
def set_functions_list(self, functionsList, prefix="", sufix=""):
self.funtionsList = functionsList
self.funtionsListItems = []
self.maxHeight = 0
tempHeight = 0
for element in functionsList:
tempElement = QGraphicsTextItem(self)
tempElement.setPlainText(prefix + element + sufix)
tempElement.setPos(0, tempHeight)
tempHeight += tempElement.document().size().height()
if self.maxWidth < tempElement.document().size().width():
self.maxWidth = tempElement.document().size().width()
self.funtionsListItems.append(tempElement)
self.maxHeight = tempHeight
def get_height(self):
return self.maxHeight
def get_width(self):
if self.parent.maxWidth < self.maxWidth:
return self.maxWidth
else:
return self.parent.maxWidth
def boundingRect(self):
return QRectF(0, 0, self.get_width(), self.get_height())
| gpl-3.0 |
efortuna/AndroidSDKClone | ndk/prebuilt/linux-x86_64/lib/python2.7/test/test_unicode.py | 36 | 75653 | """ Test script for the Unicode implementation.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#"
import sys
import struct
import codecs
import unittest
from test import test_support, string_tests
# decorator to skip tests on narrow builds
requires_wide_build = unittest.skipIf(sys.maxunicode == 65535,
'requires wide build')
# Error handling (bad decoder return)
def search_function(encoding):
def decode1(input, errors="strict"):
return 42 # not a tuple
def encode1(input, errors="strict"):
return 42 # not a tuple
def encode2(input, errors="strict"):
return (42, 42) # no unicode
def decode2(input, errors="strict"):
return (42, 42) # no unicode
if encoding=="test.unicode1":
return (encode1, decode1, None, None)
elif encoding=="test.unicode2":
return (encode2, decode2, None, None)
else:
return None
codecs.register(search_function)
class UnicodeTest(
string_tests.CommonTest,
string_tests.MixinStrUnicodeUserStringTest,
string_tests.MixinStrUnicodeTest,
):
type2test = unicode
def assertEqual(self, first, second, msg=None):
# strict assertEqual method: reject implicit bytes/unicode equality
super(UnicodeTest, self).assertEqual(first, second, msg)
if isinstance(first, unicode) or isinstance(second, unicode):
self.assertIsInstance(first, unicode)
self.assertIsInstance(second, unicode)
elif isinstance(first, str) or isinstance(second, str):
self.assertIsInstance(first, str)
self.assertIsInstance(second, str)
def checkequalnofix(self, result, object, methodname, *args):
method = getattr(object, methodname)
realresult = method(*args)
self.assertEqual(realresult, result)
self.assertTrue(type(realresult) is type(result))
# if the original is returned make sure that
# this doesn't happen with subclasses
if realresult is object:
class usub(unicode):
def __repr__(self):
return 'usub(%r)' % unicode.__repr__(self)
object = usub(object)
method = getattr(object, methodname)
realresult = method(*args)
self.assertEqual(realresult, result)
self.assertTrue(object is not realresult)
def test_literals(self):
self.assertEqual(u'\xff', u'\u00ff')
self.assertEqual(u'\uffff', u'\U0000ffff')
self.assertRaises(SyntaxError, eval, 'u\'\\Ufffffffe\'')
self.assertRaises(SyntaxError, eval, 'u\'\\Uffffffff\'')
self.assertRaises(SyntaxError, eval, 'u\'\\U%08x\'' % 0x110000)
def test_repr(self):
if not sys.platform.startswith('java'):
# Test basic sanity of repr()
self.assertEqual(repr(u'abc'), "u'abc'")
self.assertEqual(repr(u'ab\\c'), "u'ab\\\\c'")
self.assertEqual(repr(u'ab\\'), "u'ab\\\\'")
self.assertEqual(repr(u'\\c'), "u'\\\\c'")
self.assertEqual(repr(u'\\'), "u'\\\\'")
self.assertEqual(repr(u'\n'), "u'\\n'")
self.assertEqual(repr(u'\r'), "u'\\r'")
self.assertEqual(repr(u'\t'), "u'\\t'")
self.assertEqual(repr(u'\b'), "u'\\x08'")
self.assertEqual(repr(u"'\""), """u'\\'"'""")
self.assertEqual(repr(u"'\""), """u'\\'"'""")
self.assertEqual(repr(u"'"), '''u"'"''')
self.assertEqual(repr(u'"'), """u'"'""")
latin1repr = (
"u'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
"\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
"\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
"JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
"\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
"\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
"\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
"\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
"\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
"\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
"\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
"\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
"\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
"\\xfe\\xff'")
testrepr = repr(u''.join(map(unichr, xrange(256))))
self.assertEqual(testrepr, latin1repr)
# Test repr works on wide unicode escapes without overflow.
self.assertEqual(repr(u"\U00010000" * 39 + u"\uffff" * 4096),
repr(u"\U00010000" * 39 + u"\uffff" * 4096))
def test_count(self):
string_tests.CommonTest.test_count(self)
# check mixed argument types
self.checkequalnofix(3, 'aaa', 'count', u'a')
self.checkequalnofix(0, 'aaa', 'count', u'b')
self.checkequalnofix(3, u'aaa', 'count', 'a')
self.checkequalnofix(0, u'aaa', 'count', 'b')
self.checkequalnofix(0, u'aaa', 'count', 'b')
self.checkequalnofix(1, u'aaa', 'count', 'a', -1)
self.checkequalnofix(3, u'aaa', 'count', 'a', -10)
self.checkequalnofix(2, u'aaa', 'count', 'a', 0, -1)
self.checkequalnofix(0, u'aaa', 'count', 'a', 0, -10)
def test_find(self):
self.checkequalnofix(0, u'abcdefghiabc', 'find', u'abc')
self.checkequalnofix(9, u'abcdefghiabc', 'find', u'abc', 1)
self.checkequalnofix(-1, u'abcdefghiabc', 'find', u'def', 4)
self.assertRaises(TypeError, u'hello'.find)
self.assertRaises(TypeError, u'hello'.find, 42)
def test_rfind(self):
string_tests.CommonTest.test_rfind(self)
# check mixed argument types
self.checkequalnofix(9, 'abcdefghiabc', 'rfind', u'abc')
self.checkequalnofix(12, 'abcdefghiabc', 'rfind', u'')
self.checkequalnofix(12, u'abcdefghiabc', 'rfind', '')
def test_index(self):
string_tests.CommonTest.test_index(self)
# check mixed argument types
for (t1, t2) in ((str, unicode), (unicode, str)):
self.checkequalnofix(0, t1('abcdefghiabc'), 'index', t2(''))
self.checkequalnofix(3, t1('abcdefghiabc'), 'index', t2('def'))
self.checkequalnofix(0, t1('abcdefghiabc'), 'index', t2('abc'))
self.checkequalnofix(9, t1('abcdefghiabc'), 'index', t2('abc'), 1)
self.assertRaises(ValueError, t1('abcdefghiabc').index, t2('hib'))
self.assertRaises(ValueError, t1('abcdefghiab').index, t2('abc'), 1)
self.assertRaises(ValueError, t1('abcdefghi').index, t2('ghi'), 8)
self.assertRaises(ValueError, t1('abcdefghi').index, t2('ghi'), -1)
def test_rindex(self):
string_tests.CommonTest.test_rindex(self)
# check mixed argument types
for (t1, t2) in ((str, unicode), (unicode, str)):
self.checkequalnofix(12, t1('abcdefghiabc'), 'rindex', t2(''))
self.checkequalnofix(3, t1('abcdefghiabc'), 'rindex', t2('def'))
self.checkequalnofix(9, t1('abcdefghiabc'), 'rindex', t2('abc'))
self.checkequalnofix(0, t1('abcdefghiabc'), 'rindex', t2('abc'), 0, -1)
self.assertRaises(ValueError, t1('abcdefghiabc').rindex, t2('hib'))
self.assertRaises(ValueError, t1('defghiabc').rindex, t2('def'), 1)
self.assertRaises(ValueError, t1('defghiabc').rindex, t2('abc'), 0, -1)
self.assertRaises(ValueError, t1('abcdefghi').rindex, t2('ghi'), 0, 8)
self.assertRaises(ValueError, t1('abcdefghi').rindex, t2('ghi'), 0, -1)
def test_translate(self):
self.checkequalnofix(u'bbbc', u'abababc', 'translate', {ord('a'):None})
self.checkequalnofix(u'iiic', u'abababc', 'translate', {ord('a'):None, ord('b'):ord('i')})
self.checkequalnofix(u'iiix', u'abababc', 'translate', {ord('a'):None, ord('b'):ord('i'), ord('c'):u'x'})
self.checkequalnofix(u'<i><i><i>c', u'abababc', 'translate', {ord('a'):None, ord('b'):u'<i>'})
self.checkequalnofix(u'c', u'abababc', 'translate', {ord('a'):None, ord('b'):u''})
self.checkequalnofix(u'xyyx', u'xzx', 'translate', {ord('z'):u'yy'})
self.assertRaises(TypeError, u'hello'.translate)
self.assertRaises(TypeError, u'abababc'.translate, {ord('a'):''})
def test_split(self):
string_tests.CommonTest.test_split(self)
# Mixed arguments
self.checkequalnofix([u'a', u'b', u'c', u'd'], u'a//b//c//d', 'split', '//')
self.checkequalnofix([u'a', u'b', u'c', u'd'], 'a//b//c//d', 'split', u'//')
self.checkequalnofix([u'endcase ', u''], u'endcase test', 'split', 'test')
def test_join(self):
string_tests.MixinStrUnicodeUserStringTest.test_join(self)
# mixed arguments
self.checkequalnofix(u'a b c d', u' ', 'join', ['a', 'b', u'c', u'd'])
self.checkequalnofix(u'abcd', u'', 'join', (u'a', u'b', u'c', u'd'))
self.checkequalnofix(u'w x y z', u' ', 'join', string_tests.Sequence('wxyz'))
self.checkequalnofix(u'a b c d', ' ', 'join', [u'a', u'b', u'c', u'd'])
self.checkequalnofix(u'a b c d', ' ', 'join', ['a', 'b', u'c', u'd'])
self.checkequalnofix(u'abcd', '', 'join', (u'a', u'b', u'c', u'd'))
self.checkequalnofix(u'w x y z', ' ', 'join', string_tests.Sequence(u'wxyz'))
def test_strip(self):
string_tests.CommonTest.test_strip(self)
self.assertRaises(UnicodeError, u"hello".strip, "\xff")
def test_replace(self):
string_tests.CommonTest.test_replace(self)
# method call forwarded from str implementation because of unicode argument
self.checkequalnofix(u'one@two!three!', 'one!two!three!', 'replace', u'!', u'@', 1)
self.assertRaises(TypeError, 'replace'.replace, u"r", 42)
def test_comparison(self):
# Comparisons:
self.assertTrue(u'abc' == 'abc')
self.assertTrue('abc' == u'abc')
self.assertTrue(u'abc' == u'abc')
self.assertTrue(u'abcd' > 'abc')
self.assertTrue('abcd' > u'abc')
self.assertTrue(u'abcd' > u'abc')
self.assertTrue(u'abc' < 'abcd')
self.assertTrue('abc' < u'abcd')
self.assertTrue(u'abc' < u'abcd')
if 0:
# Move these tests to a Unicode collation module test...
# Testing UTF-16 code point order comparisons...
# No surrogates, no fixup required.
self.assertTrue(u'\u0061' < u'\u20ac')
# Non surrogate below surrogate value, no fixup required
self.assertTrue(u'\u0061' < u'\ud800\udc02')
# Non surrogate above surrogate value, fixup required
def test_lecmp(s, s2):
self.assertTrue(s < s2)
def test_fixup(s):
s2 = u'\ud800\udc01'
test_lecmp(s, s2)
s2 = u'\ud900\udc01'
test_lecmp(s, s2)
s2 = u'\uda00\udc01'
test_lecmp(s, s2)
s2 = u'\udb00\udc01'
test_lecmp(s, s2)
s2 = u'\ud800\udd01'
test_lecmp(s, s2)
s2 = u'\ud900\udd01'
test_lecmp(s, s2)
s2 = u'\uda00\udd01'
test_lecmp(s, s2)
s2 = u'\udb00\udd01'
test_lecmp(s, s2)
s2 = u'\ud800\ude01'
test_lecmp(s, s2)
s2 = u'\ud900\ude01'
test_lecmp(s, s2)
s2 = u'\uda00\ude01'
test_lecmp(s, s2)
s2 = u'\udb00\ude01'
test_lecmp(s, s2)
s2 = u'\ud800\udfff'
test_lecmp(s, s2)
s2 = u'\ud900\udfff'
test_lecmp(s, s2)
s2 = u'\uda00\udfff'
test_lecmp(s, s2)
s2 = u'\udb00\udfff'
test_lecmp(s, s2)
test_fixup(u'\ue000')
test_fixup(u'\uff61')
# Surrogates on both sides, no fixup required
self.assertTrue(u'\ud800\udc02' < u'\ud84d\udc56')
def test_capitalize(self):
string_tests.CommonTest.test_capitalize(self)
# check that titlecased chars are lowered correctly
# \u1ffc is the titlecased char
self.checkequal(u'\u1ffc\u1ff3\u1ff3\u1ff3',
u'\u1ff3\u1ff3\u1ffc\u1ffc', 'capitalize')
# check with cased non-letter chars
self.checkequal(u'\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
u'\u24c5\u24ce\u24c9\u24bd\u24c4\u24c3', 'capitalize')
self.checkequal(u'\u24c5\u24e8\u24e3\u24d7\u24de\u24dd',
u'\u24df\u24e8\u24e3\u24d7\u24de\u24dd', 'capitalize')
self.checkequal(u'\u2160\u2171\u2172',
u'\u2160\u2161\u2162', 'capitalize')
self.checkequal(u'\u2160\u2171\u2172',
u'\u2170\u2171\u2172', 'capitalize')
# check with Ll chars with no upper - nothing changes here
self.checkequal(u'\u019b\u1d00\u1d86\u0221\u1fb7',
u'\u019b\u1d00\u1d86\u0221\u1fb7', 'capitalize')
def test_islower(self):
string_tests.MixinStrUnicodeUserStringTest.test_islower(self)
self.checkequalnofix(False, u'\u1FFc', 'islower')
@requires_wide_build
def test_islower_non_bmp(self):
# non-BMP, uppercase
self.assertFalse(u'\U00010401'.islower())
self.assertFalse(u'\U00010427'.islower())
# non-BMP, lowercase
self.assertTrue(u'\U00010429'.islower())
self.assertTrue(u'\U0001044E'.islower())
# non-BMP, non-cased
self.assertFalse(u'\U0001F40D'.islower())
self.assertFalse(u'\U0001F46F'.islower())
def test_isupper(self):
string_tests.MixinStrUnicodeUserStringTest.test_isupper(self)
if not sys.platform.startswith('java'):
self.checkequalnofix(False, u'\u1FFc', 'isupper')
@requires_wide_build
def test_isupper_non_bmp(self):
# non-BMP, uppercase
self.assertTrue(u'\U00010401'.isupper())
self.assertTrue(u'\U00010427'.isupper())
# non-BMP, lowercase
self.assertFalse(u'\U00010429'.isupper())
self.assertFalse(u'\U0001044E'.isupper())
# non-BMP, non-cased
self.assertFalse(u'\U0001F40D'.isupper())
self.assertFalse(u'\U0001F46F'.isupper())
def test_istitle(self):
string_tests.MixinStrUnicodeUserStringTest.test_istitle(self)
self.checkequalnofix(True, u'\u1FFc', 'istitle')
self.checkequalnofix(True, u'Greek \u1FFcitlecases ...', 'istitle')
@requires_wide_build
def test_istitle_non_bmp(self):
# non-BMP, uppercase + lowercase
self.assertTrue(u'\U00010401\U00010429'.istitle())
self.assertTrue(u'\U00010427\U0001044E'.istitle())
# apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
for ch in [u'\U00010429', u'\U0001044E', u'\U0001F40D', u'\U0001F46F']:
self.assertFalse(ch.istitle(), '{!r} is not title'.format(ch))
def test_isspace(self):
string_tests.MixinStrUnicodeUserStringTest.test_isspace(self)
self.checkequalnofix(True, u'\u2000', 'isspace')
self.checkequalnofix(True, u'\u200a', 'isspace')
self.checkequalnofix(False, u'\u2014', 'isspace')
@requires_wide_build
def test_isspace_non_bmp(self):
# apparently there are no non-BMP spaces chars in Unicode 6
for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
u'\U0001F40D', u'\U0001F46F']:
self.assertFalse(ch.isspace(), '{!r} is not space.'.format(ch))
@requires_wide_build
def test_isalnum_non_bmp(self):
for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
u'\U0001D7F6', u'\U000104A0', u'\U000104A0', u'\U0001F107']:
self.assertTrue(ch.isalnum(), '{!r} is alnum.'.format(ch))
def test_isalpha(self):
string_tests.MixinStrUnicodeUserStringTest.test_isalpha(self)
self.checkequalnofix(True, u'\u1FFc', 'isalpha')
@requires_wide_build
def test_isalpha_non_bmp(self):
# non-BMP, cased
self.assertTrue(u'\U00010401'.isalpha())
self.assertTrue(u'\U00010427'.isalpha())
self.assertTrue(u'\U00010429'.isalpha())
self.assertTrue(u'\U0001044E'.isalpha())
# non-BMP, non-cased
self.assertFalse(u'\U0001F40D'.isalpha())
self.assertFalse(u'\U0001F46F'.isalpha())
def test_isdecimal(self):
self.checkequalnofix(False, u'', 'isdecimal')
self.checkequalnofix(False, u'a', 'isdecimal')
self.checkequalnofix(True, u'0', 'isdecimal')
self.checkequalnofix(False, u'\u2460', 'isdecimal') # CIRCLED DIGIT ONE
self.checkequalnofix(False, u'\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
self.checkequalnofix(True, u'\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
self.checkequalnofix(True, u'0123456789', 'isdecimal')
self.checkequalnofix(False, u'0123456789a', 'isdecimal')
self.checkraises(TypeError, 'abc', 'isdecimal', 42)
@requires_wide_build
def test_isdecimal_non_bmp(self):
for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
u'\U0001F40D', u'\U0001F46F', u'\U00011065', u'\U0001F107']:
self.assertFalse(ch.isdecimal(), '{!r} is not decimal.'.format(ch))
for ch in [u'\U0001D7F6', u'\U000104A0', u'\U000104A0']:
self.assertTrue(ch.isdecimal(), '{!r} is decimal.'.format(ch))
def test_isdigit(self):
string_tests.MixinStrUnicodeUserStringTest.test_isdigit(self)
self.checkequalnofix(True, u'\u2460', 'isdigit')
self.checkequalnofix(False, u'\xbc', 'isdigit')
self.checkequalnofix(True, u'\u0660', 'isdigit')
@requires_wide_build
def test_isdigit_non_bmp(self):
for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
u'\U0001F40D', u'\U0001F46F', u'\U00011065']:
self.assertFalse(ch.isdigit(), '{!r} is not a digit.'.format(ch))
for ch in [u'\U0001D7F6', u'\U000104A0', u'\U000104A0', u'\U0001F107']:
self.assertTrue(ch.isdigit(), '{!r} is a digit.'.format(ch))
def test_isnumeric(self):
self.checkequalnofix(False, u'', 'isnumeric')
self.checkequalnofix(False, u'a', 'isnumeric')
self.checkequalnofix(True, u'0', 'isnumeric')
self.checkequalnofix(True, u'\u2460', 'isnumeric')
self.checkequalnofix(True, u'\xbc', 'isnumeric')
self.checkequalnofix(True, u'\u0660', 'isnumeric')
self.checkequalnofix(True, u'0123456789', 'isnumeric')
self.checkequalnofix(False, u'0123456789a', 'isnumeric')
self.assertRaises(TypeError, u"abc".isnumeric, 42)
@requires_wide_build
def test_isnumeric_non_bmp(self):
for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
u'\U0001F40D', u'\U0001F46F']:
self.assertFalse(ch.isnumeric(), '{!r} is not numeric.'.format(ch))
for ch in [u'\U00010107', u'\U0001D7F6', u'\U00023b1b',
u'\U000104A0', u'\U0001F107']:
self.assertTrue(ch.isnumeric(), '{!r} is numeric.'.format(ch))
@requires_wide_build
def test_surrogates(self):
# this test actually passes on narrow too, but it's just by accident.
# Surrogates are seen as non-cased chars, so u'X\uD800X' is as
# uppercase as 'X X'
for s in (u'a\uD800b\uDFFF', u'a\uDFFFb\uD800',
u'a\uD800b\uDFFFa', u'a\uDFFFb\uD800a'):
self.assertTrue(s.islower())
self.assertFalse(s.isupper())
self.assertFalse(s.istitle())
for s in (u'A\uD800B\uDFFF', u'A\uDFFFB\uD800',
u'A\uD800B\uDFFFA', u'A\uDFFFB\uD800A'):
self.assertFalse(s.islower())
self.assertTrue(s.isupper())
self.assertTrue(s.istitle())
for meth_name in ('islower', 'isupper', 'istitle'):
meth = getattr(unicode, meth_name)
for s in (u'\uD800', u'\uDFFF', u'\uD800\uD800', u'\uDFFF\uDFFF'):
self.assertFalse(meth(s), '%r.%s() is False' % (s, meth_name))
for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
'isdecimal', 'isnumeric'):
meth = getattr(unicode, meth_name)
for s in (u'\uD800', u'\uDFFF', u'\uD800\uD800', u'\uDFFF\uDFFF',
u'a\uD800b\uDFFF', u'a\uDFFFb\uD800',
u'a\uD800b\uDFFFa', u'a\uDFFFb\uD800a'):
self.assertFalse(meth(s), '%r.%s() is False' % (s, meth_name))
@requires_wide_build
def test_lower(self):
string_tests.CommonTest.test_lower(self)
self.assertEqual(u'\U00010427'.lower(), u'\U0001044F')
self.assertEqual(u'\U00010427\U00010427'.lower(),
u'\U0001044F\U0001044F')
self.assertEqual(u'\U00010427\U0001044F'.lower(),
u'\U0001044F\U0001044F')
self.assertEqual(u'X\U00010427x\U0001044F'.lower(),
u'x\U0001044Fx\U0001044F')
@requires_wide_build
def test_upper(self):
string_tests.CommonTest.test_upper(self)
self.assertEqual(u'\U0001044F'.upper(), u'\U00010427')
self.assertEqual(u'\U0001044F\U0001044F'.upper(),
u'\U00010427\U00010427')
self.assertEqual(u'\U00010427\U0001044F'.upper(),
u'\U00010427\U00010427')
self.assertEqual(u'X\U00010427x\U0001044F'.upper(),
u'X\U00010427X\U00010427')
@requires_wide_build
def test_capitalize(self):
string_tests.CommonTest.test_capitalize(self)
self.assertEqual(u'\U0001044F'.capitalize(), u'\U00010427')
self.assertEqual(u'\U0001044F\U0001044F'.capitalize(),
u'\U00010427\U0001044F')
self.assertEqual(u'\U00010427\U0001044F'.capitalize(),
u'\U00010427\U0001044F')
self.assertEqual(u'\U0001044F\U00010427'.capitalize(),
u'\U00010427\U0001044F')
self.assertEqual(u'X\U00010427x\U0001044F'.capitalize(),
u'X\U0001044Fx\U0001044F')
@requires_wide_build
def test_title(self):
string_tests.MixinStrUnicodeUserStringTest.test_title(self)
self.assertEqual(u'\U0001044F'.title(), u'\U00010427')
self.assertEqual(u'\U0001044F\U0001044F'.title(),
u'\U00010427\U0001044F')
self.assertEqual(u'\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
u'\U00010427\U0001044F \U00010427\U0001044F')
self.assertEqual(u'\U00010427\U0001044F \U00010427\U0001044F'.title(),
u'\U00010427\U0001044F \U00010427\U0001044F')
self.assertEqual(u'\U0001044F\U00010427 \U0001044F\U00010427'.title(),
u'\U00010427\U0001044F \U00010427\U0001044F')
self.assertEqual(u'X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
u'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
@requires_wide_build
def test_swapcase(self):
string_tests.CommonTest.test_swapcase(self)
self.assertEqual(u'\U0001044F'.swapcase(), u'\U00010427')
self.assertEqual(u'\U00010427'.swapcase(), u'\U0001044F')
self.assertEqual(u'\U0001044F\U0001044F'.swapcase(),
u'\U00010427\U00010427')
self.assertEqual(u'\U00010427\U0001044F'.swapcase(),
u'\U0001044F\U00010427')
self.assertEqual(u'\U0001044F\U00010427'.swapcase(),
u'\U00010427\U0001044F')
self.assertEqual(u'X\U00010427x\U0001044F'.swapcase(),
u'x\U0001044FX\U00010427')
def test_contains(self):
# Testing Unicode contains method
self.assertIn('a', u'abdb')
self.assertIn('a', u'bdab')
self.assertIn('a', u'bdaba')
self.assertIn('a', u'bdba')
self.assertIn('a', u'bdba')
self.assertIn(u'a', u'bdba')
self.assertNotIn(u'a', u'bdb')
self.assertNotIn(u'a', 'bdb')
self.assertIn(u'a', 'bdba')
self.assertIn(u'a', ('a',1,None))
self.assertIn(u'a', (1,None,'a'))
self.assertIn(u'a', (1,None,u'a'))
self.assertIn('a', ('a',1,None))
self.assertIn('a', (1,None,'a'))
self.assertIn('a', (1,None,u'a'))
self.assertNotIn('a', ('x',1,u'y'))
self.assertNotIn('a', ('x',1,None))
self.assertNotIn(u'abcd', u'abcxxxx')
self.assertIn(u'ab', u'abcd')
self.assertIn('ab', u'abc')
self.assertIn(u'ab', 'abc')
self.assertIn(u'ab', (1,None,u'ab'))
self.assertIn(u'', u'abc')
self.assertIn('', u'abc')
# If the following fails either
# the contains operator does not propagate UnicodeErrors or
# someone has changed the default encoding
self.assertRaises(UnicodeDecodeError, 'g\xe2teau'.__contains__, u'\xe2')
self.assertRaises(UnicodeDecodeError, u'g\xe2teau'.__contains__, '\xe2')
self.assertIn(u'', '')
self.assertIn('', u'')
self.assertIn(u'', u'')
self.assertIn(u'', 'abc')
self.assertIn('', u'abc')
self.assertIn(u'', u'abc')
self.assertNotIn(u'\0', 'abc')
self.assertNotIn('\0', u'abc')
self.assertNotIn(u'\0', u'abc')
self.assertIn(u'\0', '\0abc')
self.assertIn('\0', u'\0abc')
self.assertIn(u'\0', u'\0abc')
self.assertIn(u'\0', 'abc\0')
self.assertIn('\0', u'abc\0')
self.assertIn(u'\0', u'abc\0')
self.assertIn(u'a', '\0abc')
self.assertIn('a', u'\0abc')
self.assertIn(u'a', u'\0abc')
self.assertIn(u'asdf', 'asdf')
self.assertIn('asdf', u'asdf')
self.assertIn(u'asdf', u'asdf')
self.assertNotIn(u'asdf', 'asd')
self.assertNotIn('asdf', u'asd')
self.assertNotIn(u'asdf', u'asd')
self.assertNotIn(u'asdf', '')
self.assertNotIn('asdf', u'')
self.assertNotIn(u'asdf', u'')
self.assertRaises(TypeError, u"abc".__contains__)
self.assertRaises(TypeError, u"abc".__contains__, object())
def test_formatting(self):
string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
# Testing Unicode formatting strings...
self.assertEqual(u"%s, %s" % (u"abc", "abc"), u'abc, abc')
self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, 2, 3), u'abc, abc, 1, 2.000000, 3.00')
self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, -2, 3), u'abc, abc, 1, -2.000000, 3.00')
self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.5), u'abc, abc, -1, -2.000000, 3.50')
self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.57), u'abc, abc, -1, -2.000000, 3.57')
self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 1003.57), u'abc, abc, -1, -2.000000, 1003.57')
if not sys.platform.startswith('java'):
self.assertEqual(u"%r, %r" % (u"abc", "abc"), u"u'abc', 'abc'")
self.assertEqual(u"%(x)s, %(y)s" % {'x':u"abc", 'y':"def"}, u'abc, def')
self.assertEqual(u"%(x)s, %(\xfc)s" % {'x':u"abc", u'\xfc':"def"}, u'abc, def')
self.assertEqual(u'%c' % 0x1234, u'\u1234')
self.assertRaises(OverflowError, u"%c".__mod__, (sys.maxunicode+1,))
self.assertRaises(ValueError, u"%.1\u1032f".__mod__, (1.0/3))
for num in range(0x00,0x80):
char = chr(num)
self.assertEqual(u"%c" % char, unicode(char))
self.assertEqual(u"%c" % num, unicode(char))
self.assertTrue(char == u"%c" % char)
self.assertTrue(char == u"%c" % num)
# Issue 7649
for num in range(0x80,0x100):
uchar = unichr(num)
self.assertEqual(uchar, u"%c" % num) # works only with ints
self.assertEqual(uchar, u"%c" % uchar) # and unicode chars
# the implicit decoding should fail for non-ascii chars
self.assertRaises(UnicodeDecodeError, u"%c".__mod__, chr(num))
self.assertRaises(UnicodeDecodeError, u"%s".__mod__, chr(num))
# formatting jobs delegated from the string implementation:
self.assertEqual('...%(foo)s...' % {'foo':u"abc"}, u'...abc...')
self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
self.assertEqual('...%(foo)s...' % {u'foo':"abc"}, '...abc...')
self.assertEqual('...%(foo)s...' % {u'foo':u"abc"}, u'...abc...')
self.assertEqual('...%(foo)s...' % {u'foo':u"abc",'def':123}, u'...abc...')
self.assertEqual('...%(foo)s...' % {u'foo':u"abc",u'def':123}, u'...abc...')
self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,u"abc"), u'...1...2...3...abc...')
self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,u"abc"), u'...%...%s...1...2...3...abc...')
self.assertEqual('...%s...' % u"abc", u'...abc...')
self.assertEqual('%*s' % (5,u'abc',), u' abc')
self.assertEqual('%*s' % (-5,u'abc',), u'abc ')
self.assertEqual('%*.*s' % (5,2,u'abc',), u' ab')
self.assertEqual('%*.*s' % (5,3,u'abc',), u' abc')
self.assertEqual('%i %*.*s' % (10, 5,3,u'abc',), u'10 abc')
self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, u'abc',), u'103 abc')
self.assertEqual('%c' % u'a', u'a')
class Wrapper:
def __str__(self):
return u'\u1234'
self.assertEqual('%s' % Wrapper(), u'\u1234')
@test_support.cpython_only
def test_formatting_huge_precision(self):
from _testcapi import INT_MAX
format_string = u"%.{}f".format(INT_MAX + 1)
with self.assertRaises(ValueError):
result = format_string % 2.34
def test_formatting_huge_width(self):
format_string = u"%{}f".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format_string % 2.34
def test_startswith_endswith_errors(self):
for meth in (u'foo'.startswith, u'foo'.endswith):
with self.assertRaises(UnicodeDecodeError):
meth('\xff')
with self.assertRaises(TypeError) as cm:
meth(['f'])
exc = str(cm.exception)
self.assertIn('unicode', exc)
self.assertIn('str', exc)
self.assertIn('tuple', exc)
@test_support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
def test_format_float(self):
# should not format with a comma, but always with C locale
self.assertEqual(u'1.0', u'%.1f' % 1.0)
def test_constructor(self):
# unicode(obj) tests (this maps to PyObject_Unicode() at C level)
self.assertEqual(
unicode(u'unicode remains unicode'),
u'unicode remains unicode'
)
class UnicodeSubclass(unicode):
pass
self.assertEqual(
unicode(UnicodeSubclass('unicode subclass becomes unicode')),
u'unicode subclass becomes unicode'
)
self.assertEqual(
unicode('strings are converted to unicode'),
u'strings are converted to unicode'
)
class UnicodeCompat:
def __init__(self, x):
self.x = x
def __unicode__(self):
return self.x
self.assertEqual(
unicode(UnicodeCompat('__unicode__ compatible objects are recognized')),
u'__unicode__ compatible objects are recognized')
class StringCompat:
def __init__(self, x):
self.x = x
def __str__(self):
return self.x
self.assertEqual(
unicode(StringCompat('__str__ compatible objects are recognized')),
u'__str__ compatible objects are recognized'
)
# unicode(obj) is compatible to str():
o = StringCompat('unicode(obj) is compatible to str()')
self.assertEqual(unicode(o), u'unicode(obj) is compatible to str()')
self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
# %-formatting and .__unicode__()
self.assertEqual(u'%s' %
UnicodeCompat(u"u'%s' % obj uses obj.__unicode__()"),
u"u'%s' % obj uses obj.__unicode__()")
self.assertEqual(u'%s' %
UnicodeCompat(u"u'%s' % obj falls back to obj.__str__()"),
u"u'%s' % obj falls back to obj.__str__()")
for obj in (123, 123.45, 123L):
self.assertEqual(unicode(obj), unicode(str(obj)))
# unicode(obj, encoding, error) tests (this maps to
# PyUnicode_FromEncodedObject() at C level)
if not sys.platform.startswith('java'):
self.assertRaises(
TypeError,
unicode,
u'decoding unicode is not supported',
'utf-8',
'strict'
)
self.assertEqual(
unicode('strings are decoded to unicode', 'utf-8', 'strict'),
u'strings are decoded to unicode'
)
if not sys.platform.startswith('java'):
with test_support.check_py3k_warnings():
buf = buffer('character buffers are decoded to unicode')
self.assertEqual(
unicode(
buf,
'utf-8',
'strict'
),
u'character buffers are decoded to unicode'
)
self.assertRaises(TypeError, unicode, 42, 42, 42)
def test_codecs_utf7(self):
utfTests = [
(u'A\u2262\u0391.', 'A+ImIDkQ.'), # RFC2152 example
(u'Hi Mom -\u263a-!', 'Hi Mom -+Jjo--!'), # RFC2152 example
(u'\u65E5\u672C\u8A9E', '+ZeVnLIqe-'), # RFC2152 example
(u'Item 3 is \u00a31.', 'Item 3 is +AKM-1.'), # RFC2152 example
(u'+', '+-'),
(u'+-', '+--'),
(u'+?', '+-?'),
(u'\?', '+AFw?'),
(u'+?', '+-?'),
(ur'\\?', '+AFwAXA?'),
(ur'\\\?', '+AFwAXABc?'),
(ur'++--', '+-+---'),
(u'\U000abcde', '+2m/c3g-'), # surrogate pairs
(u'/', '/'),
]
for (x, y) in utfTests:
self.assertEqual(x.encode('utf-7'), y)
# Unpaired surrogates are passed through
self.assertEqual(u'\uD801'.encode('utf-7'), '+2AE-')
self.assertEqual(u'\uD801x'.encode('utf-7'), '+2AE-x')
self.assertEqual(u'\uDC01'.encode('utf-7'), '+3AE-')
self.assertEqual(u'\uDC01x'.encode('utf-7'), '+3AE-x')
self.assertEqual('+2AE-'.decode('utf-7'), u'\uD801')
self.assertEqual('+2AE-x'.decode('utf-7'), u'\uD801x')
self.assertEqual('+3AE-'.decode('utf-7'), u'\uDC01')
self.assertEqual('+3AE-x'.decode('utf-7'), u'\uDC01x')
self.assertEqual(u'\uD801\U000abcde'.encode('utf-7'), '+2AHab9ze-')
self.assertEqual('+2AHab9ze-'.decode('utf-7'), u'\uD801\U000abcde')
# Direct encoded characters
set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
# Optional direct characters
set_o = '!"#$%&*;<=>@[]^_`{|}'
for c in set_d:
self.assertEqual(c.encode('utf7'), c.encode('ascii'))
self.assertEqual(c.encode('ascii').decode('utf7'), unicode(c))
self.assertTrue(c == c.encode('ascii').decode('utf7'))
for c in set_o:
self.assertEqual(c.encode('ascii').decode('utf7'), unicode(c))
self.assertTrue(c == c.encode('ascii').decode('utf7'))
def test_codecs_utf8(self):
self.assertEqual(u''.encode('utf-8'), '')
self.assertEqual(u'\u20ac'.encode('utf-8'), '\xe2\x82\xac')
self.assertEqual(u'\ud800\udc02'.encode('utf-8'), '\xf0\x90\x80\x82')
self.assertEqual(u'\ud84d\udc56'.encode('utf-8'), '\xf0\xa3\x91\x96')
self.assertEqual(u'\ud800'.encode('utf-8'), '\xed\xa0\x80')
self.assertEqual(u'\udc00'.encode('utf-8'), '\xed\xb0\x80')
self.assertEqual(
(u'\ud800\udc02'*1000).encode('utf-8'),
'\xf0\x90\x80\x82'*1000
)
self.assertEqual(
u'\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
u'\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
u'\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
u'\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
u'\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
u' Nunstuck git und'.encode('utf-8'),
'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
'\xe3\x80\x8cWenn ist das Nunstuck git und'
)
# UTF-8 specific decoding tests
self.assertEqual(unicode('\xf0\xa3\x91\x96', 'utf-8'), u'\U00023456')
self.assertEqual(unicode('\xf0\x90\x80\x82', 'utf-8'), u'\U00010002')
self.assertEqual(unicode('\xe2\x82\xac', 'utf-8'), u'\u20ac')
# Other possible utf-8 test cases:
# * strict decoding testing for all of the
# UTF8_ERROR cases in PyUnicode_DecodeUTF8
def test_utf8_decode_valid_sequences(self):
sequences = [
# single byte
('\x00', u'\x00'), ('a', u'a'), ('\x7f', u'\x7f'),
# 2 bytes
('\xc2\x80', u'\x80'), ('\xdf\xbf', u'\u07ff'),
# 3 bytes
('\xe0\xa0\x80', u'\u0800'), ('\xed\x9f\xbf', u'\ud7ff'),
('\xee\x80\x80', u'\uE000'), ('\xef\xbf\xbf', u'\uffff'),
# 4 bytes
('\xF0\x90\x80\x80', u'\U00010000'),
('\xf4\x8f\xbf\xbf', u'\U0010FFFF')
]
for seq, res in sequences:
self.assertEqual(seq.decode('utf-8'), res)
for ch in map(unichr, range(0, sys.maxunicode)):
self.assertEqual(ch, ch.encode('utf-8').decode('utf-8'))
def test_utf8_decode_invalid_sequences(self):
# continuation bytes in a sequence of 2, 3, or 4 bytes
continuation_bytes = map(chr, range(0x80, 0xC0))
# start bytes of a 2-byte sequence equivalent to codepoints < 0x7F
invalid_2B_seq_start_bytes = map(chr, range(0xC0, 0xC2))
# start bytes of a 4-byte sequence equivalent to codepoints > 0x10FFFF
invalid_4B_seq_start_bytes = map(chr, range(0xF5, 0xF8))
invalid_start_bytes = (
continuation_bytes + invalid_2B_seq_start_bytes +
invalid_4B_seq_start_bytes + map(chr, range(0xF7, 0x100))
)
for byte in invalid_start_bytes:
self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
for sb in invalid_2B_seq_start_bytes:
for cb in continuation_bytes:
self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
for sb in invalid_4B_seq_start_bytes:
for cb1 in continuation_bytes[:3]:
for cb3 in continuation_bytes[:3]:
self.assertRaises(UnicodeDecodeError,
(sb+cb1+'\x80'+cb3).decode, 'utf-8')
for cb in map(chr, range(0x80, 0xA0)):
self.assertRaises(UnicodeDecodeError,
('\xE0'+cb+'\x80').decode, 'utf-8')
self.assertRaises(UnicodeDecodeError,
('\xE0'+cb+'\xBF').decode, 'utf-8')
# XXX: surrogates shouldn't be valid UTF-8!
# see http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
# (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt
#for cb in map(chr, range(0xA0, 0xC0)):
#self.assertRaises(UnicodeDecodeError,
#('\xED'+cb+'\x80').decode, 'utf-8')
#self.assertRaises(UnicodeDecodeError,
#('\xED'+cb+'\xBF').decode, 'utf-8')
# but since they are valid on Python 2 add a test for that:
for cb, surrogate in zip(map(chr, range(0xA0, 0xC0)),
map(unichr, range(0xd800, 0xe000, 64))):
encoded = '\xED'+cb+'\x80'
self.assertEqual(encoded.decode('utf-8'), surrogate)
self.assertEqual(surrogate.encode('utf-8'), encoded)
for cb in map(chr, range(0x80, 0x90)):
self.assertRaises(UnicodeDecodeError,
('\xF0'+cb+'\x80\x80').decode, 'utf-8')
self.assertRaises(UnicodeDecodeError,
('\xF0'+cb+'\xBF\xBF').decode, 'utf-8')
for cb in map(chr, range(0x90, 0xC0)):
self.assertRaises(UnicodeDecodeError,
('\xF4'+cb+'\x80\x80').decode, 'utf-8')
self.assertRaises(UnicodeDecodeError,
('\xF4'+cb+'\xBF\xBF').decode, 'utf-8')
def test_issue8271(self):
# Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
# only the start byte and the continuation byte(s) are now considered
# invalid, instead of the number of bytes specified by the start byte.
# See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
# table 3-8, Row 2) for more information about the algorithm used.
FFFD = u'\ufffd'
sequences = [
# invalid start bytes
('\x80', FFFD), # continuation byte
('\x80\x80', FFFD*2), # 2 continuation bytes
('\xc0', FFFD),
('\xc0\xc0', FFFD*2),
('\xc1', FFFD),
('\xc1\xc0', FFFD*2),
('\xc0\xc1', FFFD*2),
# with start byte of a 2-byte sequence
('\xc2', FFFD), # only the start byte
('\xc2\xc2', FFFD*2), # 2 start bytes
('\xc2\xc2\xc2', FFFD*3), # 2 start bytes
('\xc2\x41', FFFD+'A'), # invalid continuation byte
# with start byte of a 3-byte sequence
('\xe1', FFFD), # only the start byte
('\xe1\xe1', FFFD*2), # 2 start bytes
('\xe1\xe1\xe1', FFFD*3), # 3 start bytes
('\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
('\xe1\x80', FFFD), # only 1 continuation byte
('\xe1\x41', FFFD+'A'), # invalid continuation byte
('\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
('\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
('\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
('\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
('\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
# with start byte of a 4-byte sequence
('\xf1', FFFD), # only the start byte
('\xf1\xf1', FFFD*2), # 2 start bytes
('\xf1\xf1\xf1', FFFD*3), # 3 start bytes
('\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
('\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
('\xf1\x80', FFFD), # only 1 continuation bytes
('\xf1\x80\x80', FFFD), # only 2 continuation bytes
('\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
('\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
('\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
('\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
('\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
('\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
('\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
('\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
('\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
('\xf1\xf1\x80\x41', FFFD*2+'A'),
('\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
# with invalid start byte of a 4-byte sequence (rfc2279)
('\xf5', FFFD), # only the start byte
('\xf5\xf5', FFFD*2), # 2 start bytes
('\xf5\x80', FFFD*2), # only 1 continuation byte
('\xf5\x80\x80', FFFD*3), # only 2 continuation byte
('\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
('\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid
('\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
('\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
# with invalid start byte of a 5-byte sequence (rfc2279)
('\xf8', FFFD), # only the start byte
('\xf8\xf8', FFFD*2), # 2 start bytes
('\xf8\x80', FFFD*2), # only one continuation byte
('\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
('\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
# with invalid start byte of a 6-byte sequence (rfc2279)
('\xfc', FFFD), # only the start byte
('\xfc\xfc', FFFD*2), # 2 start bytes
('\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
('\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
# invalid start byte
('\xfe', FFFD),
('\xfe\x80\x80', FFFD*3),
# other sequences
('\xf1\x80\x41\x42\x43', u'\ufffd\x41\x42\x43'),
('\xf1\x80\xff\x42\x43', u'\ufffd\ufffd\x42\x43'),
('\xf1\x80\xc2\x81\x43', u'\ufffd\x81\x43'),
('\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
u'\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
]
for n, (seq, res) in enumerate(sequences):
self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
self.assertEqual(seq.decode('utf-8', 'replace'), res)
self.assertEqual((seq+'b').decode('utf-8', 'replace'), res+'b')
self.assertEqual(seq.decode('utf-8', 'ignore'),
res.replace(u'\uFFFD', ''))
def test_codecs_idna(self):
# Test whether trailing dot is preserved
self.assertEqual(u"www.python.org.".encode("idna"), "www.python.org.")
def test_codecs_errors(self):
# Error handling (encoding)
self.assertRaises(UnicodeError, u'Andr\202 x'.encode, 'ascii')
self.assertRaises(UnicodeError, u'Andr\202 x'.encode, 'ascii','strict')
self.assertEqual(u'Andr\202 x'.encode('ascii','ignore'), "Andr x")
self.assertEqual(u'Andr\202 x'.encode('ascii','replace'), "Andr? x")
self.assertEqual(u'Andr\202 x'.encode('ascii', 'replace'),
u'Andr\202 x'.encode('ascii', errors='replace'))
self.assertEqual(u'Andr\202 x'.encode('ascii', 'ignore'),
u'Andr\202 x'.encode(encoding='ascii', errors='ignore'))
# Error handling (decoding)
self.assertRaises(UnicodeError, unicode, 'Andr\202 x', 'ascii')
self.assertRaises(UnicodeError, unicode, 'Andr\202 x', 'ascii','strict')
self.assertEqual(unicode('Andr\202 x','ascii','ignore'), u"Andr x")
self.assertEqual(unicode('Andr\202 x','ascii','replace'), u'Andr\uFFFD x')
self.assertEqual(u'abcde'.decode('ascii', 'ignore'),
u'abcde'.decode('ascii', errors='ignore'))
self.assertEqual(u'abcde'.decode('ascii', 'replace'),
u'abcde'.decode(encoding='ascii', errors='replace'))
# Error handling (unknown character names)
self.assertEqual("\\N{foo}xx".decode("unicode-escape", "ignore"), u"xx")
# Error handling (truncated escape sequence)
self.assertRaises(UnicodeError, "\\".decode, "unicode-escape")
self.assertRaises(TypeError, "hello".decode, "test.unicode1")
self.assertRaises(TypeError, unicode, "hello", "test.unicode2")
self.assertRaises(TypeError, u"hello".encode, "test.unicode1")
self.assertRaises(TypeError, u"hello".encode, "test.unicode2")
# executes PyUnicode_Encode()
import imp
self.assertRaises(
ImportError,
imp.find_module,
"non-existing module",
[u"non-existing dir"]
)
# Error handling (wrong arguments)
self.assertRaises(TypeError, u"hello".encode, 42, 42, 42)
# Error handling (PyUnicode_EncodeDecimal())
self.assertRaises(UnicodeError, int, u"\u0200")
def test_codecs(self):
# Encoding
self.assertEqual(u'hello'.encode('ascii'), 'hello')
self.assertEqual(u'hello'.encode('utf-7'), 'hello')
self.assertEqual(u'hello'.encode('utf-8'), 'hello')
self.assertEqual(u'hello'.encode('utf8'), 'hello')
self.assertEqual(u'hello'.encode('utf-16-le'), 'h\000e\000l\000l\000o\000')
self.assertEqual(u'hello'.encode('utf-16-be'), '\000h\000e\000l\000l\000o')
self.assertEqual(u'hello'.encode('latin-1'), 'hello')
# Roundtrip safety for BMP (just the first 1024 chars)
for c in xrange(1024):
u = unichr(c)
for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
'utf-16-be', 'raw_unicode_escape',
'unicode_escape', 'unicode_internal'):
self.assertEqual(unicode(u.encode(encoding),encoding), u)
# Roundtrip safety for BMP (just the first 256 chars)
for c in xrange(256):
u = unichr(c)
for encoding in ('latin-1',):
self.assertEqual(unicode(u.encode(encoding),encoding), u)
# Roundtrip safety for BMP (just the first 128 chars)
for c in xrange(128):
u = unichr(c)
for encoding in ('ascii',):
self.assertEqual(unicode(u.encode(encoding),encoding), u)
# Roundtrip safety for non-BMP (just a few chars)
u = u'\U00010001\U00020002\U00030003\U00040004\U00050005'
for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
#'raw_unicode_escape',
'unicode_escape', 'unicode_internal'):
self.assertEqual(unicode(u.encode(encoding),encoding), u)
# UTF-8 must be roundtrip safe for all UCS-2 code points
# This excludes surrogates: in the full range, there would be
# a surrogate pair (\udbff\udc00), which gets converted back
# to a non-BMP character (\U0010fc00)
u = u''.join(map(unichr, range(0,0xd800)+range(0xe000,0x10000)))
for encoding in ('utf-8',):
self.assertEqual(unicode(u.encode(encoding),encoding), u)
def test_codecs_charmap(self):
# 0-127
s = ''.join(map(chr, xrange(128)))
for encoding in (
'cp037', 'cp1026',
'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
'cp863', 'cp865', 'cp866',
'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
'iso8859_7', 'iso8859_9', 'koi8_r', 'latin_1',
'mac_cyrillic', 'mac_latin2',
'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
'cp1256', 'cp1257', 'cp1258',
'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
'cp1006', 'iso8859_8',
### These have undefined mappings:
#'cp424',
### These fail the round-trip:
#'cp875'
):
self.assertEqual(unicode(s, encoding).encode(encoding), s)
# 128-255
s = ''.join(map(chr, xrange(128, 256)))
for encoding in (
'cp037', 'cp1026',
'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
'cp863', 'cp865', 'cp866',
'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
'iso8859_2', 'iso8859_4', 'iso8859_5',
'iso8859_9', 'koi8_r', 'latin_1',
'mac_cyrillic', 'mac_latin2',
### These have undefined mappings:
#'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
#'cp1256', 'cp1257', 'cp1258',
#'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
#'iso8859_3', 'iso8859_6', 'iso8859_7',
#'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
### These fail the round-trip:
#'cp1006', 'cp875', 'iso8859_8',
):
self.assertEqual(unicode(s, encoding).encode(encoding), s)
def test_concatenation(self):
self.assertEqual((u"abc" u"def"), u"abcdef")
self.assertEqual(("abc" u"def"), u"abcdef")
self.assertEqual((u"abc" "def"), u"abcdef")
self.assertEqual((u"abc" u"def" "ghi"), u"abcdefghi")
self.assertEqual(("abc" "def" u"ghi"), u"abcdefghi")
def test_printing(self):
class BitBucket:
def write(self, text):
pass
out = BitBucket()
print >>out, u'abc'
print >>out, u'abc', u'def'
print >>out, u'abc', 'def'
print >>out, 'abc', u'def'
print >>out, u'abc\n'
print >>out, u'abc\n',
print >>out, u'abc\n',
print >>out, u'def\n'
print >>out, u'def\n'
def test_ucs4(self):
x = u'\U00100000'
y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
self.assertEqual(x, y)
y = r'\U00100000'
x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
self.assertEqual(x, y)
y = r'\U00010000'
x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
self.assertEqual(x, y)
try:
'\U11111111'.decode("raw-unicode-escape")
except UnicodeDecodeError as e:
self.assertEqual(e.start, 0)
self.assertEqual(e.end, 10)
else:
self.fail("Should have raised UnicodeDecodeError")
def test_conversion(self):
# Make sure __unicode__() works properly
class Foo0:
def __str__(self):
return "foo"
class Foo1:
def __unicode__(self):
return u"foo"
class Foo2(object):
def __unicode__(self):
return u"foo"
class Foo3(object):
def __unicode__(self):
return "foo"
class Foo4(str):
def __unicode__(self):
return "foo"
class Foo5(unicode):
def __unicode__(self):
return "foo"
class Foo6(str):
def __str__(self):
return "foos"
def __unicode__(self):
return u"foou"
class Foo7(unicode):
def __str__(self):
return "foos"
def __unicode__(self):
return u"foou"
class Foo8(unicode):
def __new__(cls, content=""):
return unicode.__new__(cls, 2*content)
def __unicode__(self):
return self
class Foo9(unicode):
def __str__(self):
return "string"
def __unicode__(self):
return "not unicode"
self.assertEqual(unicode(Foo0()), u"foo")
self.assertEqual(unicode(Foo1()), u"foo")
self.assertEqual(unicode(Foo2()), u"foo")
self.assertEqual(unicode(Foo3()), u"foo")
self.assertEqual(unicode(Foo4("bar")), u"foo")
self.assertEqual(unicode(Foo5("bar")), u"foo")
self.assertEqual(unicode(Foo6("bar")), u"foou")
self.assertEqual(unicode(Foo7("bar")), u"foou")
self.assertEqual(unicode(Foo8("foo")), u"foofoo")
self.assertEqual(str(Foo9("foo")), "string")
self.assertEqual(unicode(Foo9("foo")), u"not unicode")
def test_unicode_repr(self):
class s1:
def __repr__(self):
return '\\n'
class s2:
def __repr__(self):
return u'\\n'
self.assertEqual(repr(s1()), '\\n')
self.assertEqual(repr(s2()), '\\n')
def test_expandtabs_overflows_gracefully(self):
# This test only affects 32-bit platforms because expandtabs can only take
# an int as the max value, not a 64-bit C long. If expandtabs is changed
# to take a 64-bit long, this test should apply to all platforms.
if sys.maxint > (1 << 32) or struct.calcsize('P') != 4:
return
self.assertRaises(OverflowError, u't\tt\t'.expandtabs, sys.maxint)
def test__format__(self):
def test(value, format, expected):
# test both with and without the trailing 's'
self.assertEqual(value.__format__(format), expected)
self.assertEqual(value.__format__(format + u's'), expected)
test(u'', u'', u'')
test(u'abc', u'', u'abc')
test(u'abc', u'.3', u'abc')
test(u'ab', u'.3', u'ab')
test(u'abcdef', u'.3', u'abc')
test(u'abcdef', u'.0', u'')
test(u'abc', u'3.3', u'abc')
test(u'abc', u'2.3', u'abc')
test(u'abc', u'2.2', u'ab')
test(u'abc', u'3.2', u'ab ')
test(u'result', u'x<0', u'result')
test(u'result', u'x<5', u'result')
test(u'result', u'x<6', u'result')
test(u'result', u'x<7', u'resultx')
test(u'result', u'x<8', u'resultxx')
test(u'result', u' <7', u'result ')
test(u'result', u'<7', u'result ')
test(u'result', u'>7', u' result')
test(u'result', u'>8', u' result')
test(u'result', u'^8', u' result ')
test(u'result', u'^9', u' result ')
test(u'result', u'^10', u' result ')
test(u'a', u'10000', u'a' + u' ' * 9999)
test(u'', u'10000', u' ' * 10000)
test(u'', u'10000000', u' ' * 10000000)
# test mixing unicode and str
self.assertEqual(u'abc'.__format__('s'), u'abc')
self.assertEqual(u'abc'.__format__('->10s'), u'-------abc')
def test_format(self):
self.assertEqual(u''.format(), u'')
self.assertEqual(u'a'.format(), u'a')
self.assertEqual(u'ab'.format(), u'ab')
self.assertEqual(u'a{{'.format(), u'a{')
self.assertEqual(u'a}}'.format(), u'a}')
self.assertEqual(u'{{b'.format(), u'{b')
self.assertEqual(u'}}b'.format(), u'}b')
self.assertEqual(u'a{{b'.format(), u'a{b')
# examples from the PEP:
import datetime
self.assertEqual(u"My name is {0}".format(u'Fred'), u"My name is Fred")
self.assertEqual(u"My name is {0[name]}".format(dict(name=u'Fred')),
u"My name is Fred")
self.assertEqual(u"My name is {0} :-{{}}".format(u'Fred'),
u"My name is Fred :-{}")
# datetime.__format__ doesn't work with unicode
#d = datetime.date(2007, 8, 18)
#self.assertEqual("The year is {0.year}".format(d),
# "The year is 2007")
# classes we'll use for testing
class C:
def __init__(self, x=100):
self._x = x
def __format__(self, spec):
return spec
class D:
def __init__(self, x):
self.x = x
def __format__(self, spec):
return str(self.x)
# class with __str__, but no __format__
class E:
def __init__(self, x):
self.x = x
def __str__(self):
return u'E(' + self.x + u')'
# class with __repr__, but no __format__ or __str__
class F:
def __init__(self, x):
self.x = x
def __repr__(self):
return u'F(' + self.x + u')'
# class with __format__ that forwards to string, for some format_spec's
class G:
def __init__(self, x):
self.x = x
def __str__(self):
return u"string is " + self.x
def __format__(self, format_spec):
if format_spec == 'd':
return u'G(' + self.x + u')'
return object.__format__(self, format_spec)
# class that returns a bad type from __format__
class H:
def __format__(self, format_spec):
return 1.0
class I(datetime.date):
def __format__(self, format_spec):
return self.strftime(format_spec)
class J(int):
def __format__(self, format_spec):
return int.__format__(self * 2, format_spec)
self.assertEqual(u''.format(), u'')
self.assertEqual(u'abc'.format(), u'abc')
self.assertEqual(u'{0}'.format(u'abc'), u'abc')
self.assertEqual(u'{0:}'.format(u'abc'), u'abc')
self.assertEqual(u'X{0}'.format(u'abc'), u'Xabc')
self.assertEqual(u'{0}X'.format(u'abc'), u'abcX')
self.assertEqual(u'X{0}Y'.format(u'abc'), u'XabcY')
self.assertEqual(u'{1}'.format(1, u'abc'), u'abc')
self.assertEqual(u'X{1}'.format(1, u'abc'), u'Xabc')
self.assertEqual(u'{1}X'.format(1, u'abc'), u'abcX')
self.assertEqual(u'X{1}Y'.format(1, u'abc'), u'XabcY')
self.assertEqual(u'{0}'.format(-15), u'-15')
self.assertEqual(u'{0}{1}'.format(-15, u'abc'), u'-15abc')
self.assertEqual(u'{0}X{1}'.format(-15, u'abc'), u'-15Xabc')
self.assertEqual(u'{{'.format(), u'{')
self.assertEqual(u'}}'.format(), u'}')
self.assertEqual(u'{{}}'.format(), u'{}')
self.assertEqual(u'{{x}}'.format(), u'{x}')
self.assertEqual(u'{{{0}}}'.format(123), u'{123}')
self.assertEqual(u'{{{{0}}}}'.format(), u'{{0}}')
self.assertEqual(u'}}{{'.format(), u'}{')
self.assertEqual(u'}}x{{'.format(), u'}x{')
# weird field names
self.assertEqual(u"{0[foo-bar]}".format({u'foo-bar':u'baz'}), u'baz')
self.assertEqual(u"{0[foo bar]}".format({u'foo bar':u'baz'}), u'baz')
self.assertEqual(u"{0[ ]}".format({u' ':3}), u'3')
self.assertEqual(u'{foo._x}'.format(foo=C(20)), u'20')
self.assertEqual(u'{1}{0}'.format(D(10), D(20)), u'2010')
self.assertEqual(u'{0._x.x}'.format(C(D(u'abc'))), u'abc')
self.assertEqual(u'{0[0]}'.format([u'abc', u'def']), u'abc')
self.assertEqual(u'{0[1]}'.format([u'abc', u'def']), u'def')
self.assertEqual(u'{0[1][0]}'.format([u'abc', [u'def']]), u'def')
self.assertEqual(u'{0[1][0].x}'.format(['abc', [D(u'def')]]), u'def')
# strings
self.assertEqual(u'{0:.3s}'.format(u'abc'), u'abc')
self.assertEqual(u'{0:.3s}'.format(u'ab'), u'ab')
self.assertEqual(u'{0:.3s}'.format(u'abcdef'), u'abc')
self.assertEqual(u'{0:.0s}'.format(u'abcdef'), u'')
self.assertEqual(u'{0:3.3s}'.format(u'abc'), u'abc')
self.assertEqual(u'{0:2.3s}'.format(u'abc'), u'abc')
self.assertEqual(u'{0:2.2s}'.format(u'abc'), u'ab')
self.assertEqual(u'{0:3.2s}'.format(u'abc'), u'ab ')
self.assertEqual(u'{0:x<0s}'.format(u'result'), u'result')
self.assertEqual(u'{0:x<5s}'.format(u'result'), u'result')
self.assertEqual(u'{0:x<6s}'.format(u'result'), u'result')
self.assertEqual(u'{0:x<7s}'.format(u'result'), u'resultx')
self.assertEqual(u'{0:x<8s}'.format(u'result'), u'resultxx')
self.assertEqual(u'{0: <7s}'.format(u'result'), u'result ')
self.assertEqual(u'{0:<7s}'.format(u'result'), u'result ')
self.assertEqual(u'{0:>7s}'.format(u'result'), u' result')
self.assertEqual(u'{0:>8s}'.format(u'result'), u' result')
self.assertEqual(u'{0:^8s}'.format(u'result'), u' result ')
self.assertEqual(u'{0:^9s}'.format(u'result'), u' result ')
self.assertEqual(u'{0:^10s}'.format(u'result'), u' result ')
self.assertEqual(u'{0:10000}'.format(u'a'), u'a' + u' ' * 9999)
self.assertEqual(u'{0:10000}'.format(u''), u' ' * 10000)
self.assertEqual(u'{0:10000000}'.format(u''), u' ' * 10000000)
# format specifiers for user defined type
self.assertEqual(u'{0:abc}'.format(C()), u'abc')
# !r and !s coercions
self.assertEqual(u'{0!s}'.format(u'Hello'), u'Hello')
self.assertEqual(u'{0!s:}'.format(u'Hello'), u'Hello')
self.assertEqual(u'{0!s:15}'.format(u'Hello'), u'Hello ')
self.assertEqual(u'{0!s:15s}'.format(u'Hello'), u'Hello ')
self.assertEqual(u'{0!r}'.format(u'Hello'), u"u'Hello'")
self.assertEqual(u'{0!r:}'.format(u'Hello'), u"u'Hello'")
self.assertEqual(u'{0!r}'.format(F(u'Hello')), u'F(Hello)')
# test fallback to object.__format__
self.assertEqual(u'{0}'.format({}), u'{}')
self.assertEqual(u'{0}'.format([]), u'[]')
self.assertEqual(u'{0}'.format([1]), u'[1]')
self.assertEqual(u'{0}'.format(E(u'data')), u'E(data)')
self.assertEqual(u'{0:d}'.format(G(u'data')), u'G(data)')
self.assertEqual(u'{0!s}'.format(G(u'data')), u'string is data')
msg = 'object.__format__ with a non-empty format string is deprecated'
with test_support.check_warnings((msg, PendingDeprecationWarning)):
self.assertEqual(u'{0:^10}'.format(E(u'data')), u' E(data) ')
self.assertEqual(u'{0:^10s}'.format(E(u'data')), u' E(data) ')
self.assertEqual(u'{0:>15s}'.format(G(u'data')), u' string is data')
self.assertEqual(u"{0:date: %Y-%m-%d}".format(I(year=2007,
month=8,
day=27)),
u"date: 2007-08-27")
# test deriving from a builtin type and overriding __format__
self.assertEqual(u"{0}".format(J(10)), u"20")
# string format specifiers
self.assertEqual(u'{0:}'.format('a'), u'a')
# computed format specifiers
self.assertEqual(u"{0:.{1}}".format(u'hello world', 5), u'hello')
self.assertEqual(u"{0:.{1}s}".format(u'hello world', 5), u'hello')
self.assertEqual(u"{0:.{precision}s}".format('hello world', precision=5), u'hello')
self.assertEqual(u"{0:{width}.{precision}s}".format('hello world', width=10, precision=5), u'hello ')
self.assertEqual(u"{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), u'hello ')
# test various errors
self.assertRaises(ValueError, u'{'.format)
self.assertRaises(ValueError, u'}'.format)
self.assertRaises(ValueError, u'a{'.format)
self.assertRaises(ValueError, u'a}'.format)
self.assertRaises(ValueError, u'{a'.format)
self.assertRaises(ValueError, u'}a'.format)
self.assertRaises(IndexError, u'{0}'.format)
self.assertRaises(IndexError, u'{1}'.format, u'abc')
self.assertRaises(KeyError, u'{x}'.format)
self.assertRaises(ValueError, u"}{".format)
self.assertRaises(ValueError, u"{".format)
self.assertRaises(ValueError, u"}".format)
self.assertRaises(ValueError, u"abc{0:{}".format)
self.assertRaises(ValueError, u"{0".format)
self.assertRaises(IndexError, u"{0.}".format)
self.assertRaises(ValueError, u"{0.}".format, 0)
self.assertRaises(IndexError, u"{0[}".format)
self.assertRaises(ValueError, u"{0[}".format, [])
self.assertRaises(KeyError, u"{0]}".format)
self.assertRaises(ValueError, u"{0.[]}".format, 0)
self.assertRaises(ValueError, u"{0..foo}".format, 0)
self.assertRaises(ValueError, u"{0[0}".format, 0)
self.assertRaises(ValueError, u"{0[0:foo}".format, 0)
self.assertRaises(KeyError, u"{c]}".format)
self.assertRaises(ValueError, u"{{ {{{0}}".format, 0)
self.assertRaises(ValueError, u"{0}}".format, 0)
self.assertRaises(KeyError, u"{foo}".format, bar=3)
self.assertRaises(ValueError, u"{0!x}".format, 3)
self.assertRaises(ValueError, u"{0!}".format, 0)
self.assertRaises(ValueError, u"{0!rs}".format, 0)
self.assertRaises(ValueError, u"{!}".format)
self.assertRaises(IndexError, u"{:}".format)
self.assertRaises(IndexError, u"{:s}".format)
self.assertRaises(IndexError, u"{}".format)
big = u"23098475029384702983476098230754973209482573"
self.assertRaises(ValueError, (u"{" + big + u"}").format)
self.assertRaises(ValueError, (u"{[" + big + u"]}").format, [0])
# issue 6089
self.assertRaises(ValueError, u"{0[0]x}".format, [None])
self.assertRaises(ValueError, u"{0[0](10)}".format, [None])
# can't have a replacement on the field name portion
self.assertRaises(TypeError, u'{0[{1}]}'.format, u'abcdefg', 4)
# exceed maximum recursion depth
self.assertRaises(ValueError, u"{0:{1:{2}}}".format, u'abc', u's', u'')
self.assertRaises(ValueError, u"{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
0, 1, 2, 3, 4, 5, 6, 7)
# string format spec errors
self.assertRaises(ValueError, u"{0:-s}".format, u'')
self.assertRaises(ValueError, format, u"", u"-")
self.assertRaises(ValueError, u"{0:=s}".format, u'')
# test combining string and unicode
self.assertEqual(u"foo{0}".format('bar'), u'foobar')
# This will try to convert the argument from unicode to str, which
# will succeed
self.assertEqual("foo{0}".format(u'bar'), 'foobar')
# This will try to convert the argument from unicode to str, which
# will fail
self.assertRaises(UnicodeEncodeError, "foo{0}".format, u'\u1000bar')
def test_format_huge_precision(self):
format_string = u".{}f".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format(2.34, format_string)
def test_format_huge_width(self):
format_string = u"{}f".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format(2.34, format_string)
def test_format_huge_item_number(self):
format_string = u"{{{}:.6f}}".format(sys.maxsize + 1)
with self.assertRaises(ValueError):
result = format_string.format(2.34)
def test_format_auto_numbering(self):
class C:
def __init__(self, x=100):
self._x = x
def __format__(self, spec):
return spec
self.assertEqual(u'{}'.format(10), u'10')
self.assertEqual(u'{:5}'.format('s'), u's ')
self.assertEqual(u'{!r}'.format('s'), u"'s'")
self.assertEqual(u'{._x}'.format(C(10)), u'10')
self.assertEqual(u'{[1]}'.format([1, 2]), u'2')
self.assertEqual(u'{[a]}'.format({'a':4, 'b':2}), u'4')
self.assertEqual(u'a{}b{}c'.format(0, 1), u'a0b1c')
self.assertEqual(u'a{:{}}b'.format('x', '^10'), u'a x b')
self.assertEqual(u'a{:{}x}b'.format(20, '#'), u'a0x14b')
# can't mix and match numbering and auto-numbering
self.assertRaises(ValueError, u'{}{1}'.format, 1, 2)
self.assertRaises(ValueError, u'{1}{}'.format, 1, 2)
self.assertRaises(ValueError, u'{:{1}}'.format, 1, 2)
self.assertRaises(ValueError, u'{0:{}}'.format, 1, 2)
# can mix and match auto-numbering and named
self.assertEqual(u'{f}{}'.format(4, f='test'), u'test4')
self.assertEqual(u'{}{f}'.format(4, f='test'), u'4test')
self.assertEqual(u'{:{f}}{g}{}'.format(1, 3, g='g', f=2), u' 1g3')
self.assertEqual(u'{f:{}}{}{g}'.format(2, 4, f=1, g='g'), u' 14g')
def test_raiseMemError(self):
# Ensure that the freelist contains a consistent object, even
# when a string allocation fails with a MemoryError.
# This used to crash the interpreter,
# or leak references when the number was smaller.
charwidth = 4 if sys.maxunicode >= 0x10000 else 2
# Note: sys.maxsize is half of the actual max allocation because of
# the signedness of Py_ssize_t.
alloc = lambda: u"a" * (sys.maxsize // charwidth * 2)
self.assertRaises(MemoryError, alloc)
self.assertRaises(MemoryError, alloc)
def test_format_subclass(self):
class U(unicode):
def __unicode__(self):
return u'__unicode__ overridden'
u = U(u'xxx')
self.assertEqual("%s" % u, u'__unicode__ overridden')
self.assertEqual("{}".format(u), '__unicode__ overridden')
def test_encode_decimal(self):
from _testcapi import unicode_encodedecimal
self.assertEqual(unicode_encodedecimal(u'123'),
b'123')
self.assertEqual(unicode_encodedecimal(u'\u0663.\u0661\u0664'),
b'3.14')
self.assertEqual(unicode_encodedecimal(u"\N{EM SPACE}3.14\N{EN SPACE}"),
b' 3.14 ')
self.assertRaises(UnicodeEncodeError,
unicode_encodedecimal, u"123\u20ac", "strict")
self.assertEqual(unicode_encodedecimal(u"123\u20ac", "replace"),
b'123?')
self.assertEqual(unicode_encodedecimal(u"123\u20ac", "ignore"),
b'123')
self.assertEqual(unicode_encodedecimal(u"123\u20ac", "xmlcharrefreplace"),
b'123€')
self.assertEqual(unicode_encodedecimal(u"123\u20ac", "backslashreplace"),
b'123\\u20ac')
self.assertEqual(unicode_encodedecimal(u"123\u20ac\N{EM SPACE}", "replace"),
b'123? ')
self.assertEqual(unicode_encodedecimal(u"123\u20ac\u20ac", "replace"),
b'123??')
self.assertEqual(unicode_encodedecimal(u"123\u20ac\u0660", "replace"),
b'123?0')
def test_main():
test_support.run_unittest(__name__)
if __name__ == "__main__":
test_main()
| apache-2.0 |
hubsaysnuaa/odoo | addons/account/report/account_central_journal.py | 381 | 5417 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.osv import osv
from openerp.report import report_sxw
from common_report_header import common_report_header
#
# Use period and Journal for selection or resources
#
class journal_print(report_sxw.rml_parse, common_report_header):
def __init__(self, cr, uid, name, context=None):
if context is None:
context = {}
super(journal_print, self).__init__(cr, uid, name, context=context)
self.period_ids = []
self.journal_ids = []
self.localcontext.update({
'time': time,
'lines': self.lines,
'sum_debit': self._sum_debit,
'sum_credit': self._sum_credit,
'get_filter': self._get_filter,
'get_fiscalyear': self._get_fiscalyear,
'get_account': self._get_account,
'get_start_period': self.get_start_period,
'get_end_period': self.get_end_period,
'get_sortby': self._get_sortby,
'get_start_date':self._get_start_date,
'get_end_date':self._get_end_date,
'display_currency':self._display_currency,
'get_target_move': self._get_target_move,
})
def set_context(self, objects, data, ids, report_type=None):
obj_move = self.pool.get('account.move.line')
new_ids = ids
self.query_get_clause = ''
self.target_move = data['form'].get('target_move', 'all')
if (data['model'] == 'ir.ui.menu'):
new_ids = 'active_ids' in data['form'] and data['form']['active_ids'] or []
self.query_get_clause = 'AND '
self.query_get_clause += obj_move._query_get(self.cr, self.uid, obj='l', context=data['form'].get('used_context', {}))
objects = self.pool.get('account.journal.period').browse(self.cr, self.uid, new_ids)
if new_ids:
self.cr.execute('SELECT period_id, journal_id FROM account_journal_period WHERE id IN %s', (tuple(new_ids),))
res = self.cr.fetchall()
self.period_ids, self.journal_ids = zip(*res)
return super(journal_print, self).set_context(objects, data, ids, report_type=report_type)
def lines(self, period_id, journal_id):
move_state = ['draft','posted']
if self.target_move == 'posted':
move_state = ['posted']
self.cr.execute('SELECT a.currency_id, a.code, a.name, c.symbol AS currency_code, l.currency_id, l.amount_currency, SUM(debit) AS debit, SUM(credit) AS credit \
from account_move_line l \
LEFT JOIN account_move am ON (l.move_id=am.id) \
LEFT JOIN account_account a ON (l.account_id=a.id) \
LEFT JOIN res_currency c on (l.currency_id=c.id) WHERE am.state IN %s AND l.period_id=%s AND l.journal_id=%s '+self.query_get_clause+' GROUP BY a.id, a.code, a.name,l.amount_currency,c.symbol, a.currency_id,l.currency_id', (tuple(move_state), period_id, journal_id))
return self.cr.dictfetchall()
def _set_get_account_currency_code(self, account_id):
self.cr.execute("SELECT c.symbol as code "\
"FROM res_currency c,account_account as ac "\
"WHERE ac.id = %s AND ac.currency_id = c.id"%(account_id))
result = self.cr.fetchone()
if result:
self.account_currency = result[0]
else:
self.account_currency = False
def _get_account(self, data):
if data['model'] == 'account.journal.period':
return self.pool.get('account.journal.period').browse(self.cr, self.uid, data['id']).company_id.name
return super(journal_print,self)._get_account(data)
def _get_fiscalyear(self, data):
if data['model'] == 'account.journal.period':
return self.pool.get('account.journal.period').browse(self.cr, self.uid, data['id']).fiscalyear_id.name
return super(journal_print,self)._get_fiscalyear(data)
def _display_currency(self, data):
if data['model'] == 'account.journal.period':
return True
return data['form']['amount_currency']
class report_agedpartnerbalance(osv.AbstractModel):
_name = 'report.account.report_centraljournal'
_inherit = 'report.abstract_report'
_template = 'account.report_centraljournal'
_wrapped_report_class = journal_print
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
huobaowangxi/scikit-learn | doc/sphinxext/numpy_ext/numpydoc.py | 413 | 6182 | """
========
numpydoc
========
Sphinx extension that handles docstrings in the Numpy standard format. [1]
It will:
- Convert Parameters etc. sections to field lists.
- Convert See Also section to a See also entry.
- Renumber references.
- Extract the signature from the docstring, if it can't be determined
otherwise.
.. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard
"""
from __future__ import unicode_literals
import sys # Only needed to check Python version
import os
import re
import pydoc
from .docscrape_sphinx import get_doc_object
from .docscrape_sphinx import SphinxDocString
import inspect
def mangle_docstrings(app, what, name, obj, options, lines,
reference_offset=[0]):
cfg = dict(use_plots=app.config.numpydoc_use_plots,
show_class_members=app.config.numpydoc_show_class_members)
if what == 'module':
# Strip top title
title_re = re.compile(r'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*',
re.I | re.S)
lines[:] = title_re.sub('', "\n".join(lines)).split("\n")
else:
doc = get_doc_object(obj, what, "\n".join(lines), config=cfg)
if sys.version_info[0] < 3:
lines[:] = unicode(doc).splitlines()
else:
lines[:] = str(doc).splitlines()
if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \
obj.__name__:
if hasattr(obj, '__module__'):
v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__))
else:
v = dict(full_name=obj.__name__)
lines += [u'', u'.. htmlonly::', '']
lines += [u' %s' % x for x in
(app.config.numpydoc_edit_link % v).split("\n")]
# replace reference numbers so that there are no duplicates
references = []
for line in lines:
line = line.strip()
m = re.match(r'^.. \[([a-z0-9_.-])\]', line, re.I)
if m:
references.append(m.group(1))
# start renaming from the longest string, to avoid overwriting parts
references.sort(key=lambda x: -len(x))
if references:
for i, line in enumerate(lines):
for r in references:
if re.match(r'^\d+$', r):
new_r = "R%d" % (reference_offset[0] + int(r))
else:
new_r = u"%s%d" % (r, reference_offset[0])
lines[i] = lines[i].replace(u'[%s]_' % r,
u'[%s]_' % new_r)
lines[i] = lines[i].replace(u'.. [%s]' % r,
u'.. [%s]' % new_r)
reference_offset[0] += len(references)
def mangle_signature(app, what, name, obj,
options, sig, retann):
# Do not try to inspect classes that don't define `__init__`
if (inspect.isclass(obj) and
(not hasattr(obj, '__init__') or
'initializes x; see ' in pydoc.getdoc(obj.__init__))):
return '', ''
if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')):
return
if not hasattr(obj, '__doc__'):
return
doc = SphinxDocString(pydoc.getdoc(obj))
if doc['Signature']:
sig = re.sub("^[^(]*", "", doc['Signature'])
return sig, ''
def setup(app, get_doc_object_=get_doc_object):
global get_doc_object
get_doc_object = get_doc_object_
if sys.version_info[0] < 3:
app.connect(b'autodoc-process-docstring', mangle_docstrings)
app.connect(b'autodoc-process-signature', mangle_signature)
else:
app.connect('autodoc-process-docstring', mangle_docstrings)
app.connect('autodoc-process-signature', mangle_signature)
app.add_config_value('numpydoc_edit_link', None, False)
app.add_config_value('numpydoc_use_plots', None, False)
app.add_config_value('numpydoc_show_class_members', True, True)
# Extra mangling domains
app.add_domain(NumpyPythonDomain)
app.add_domain(NumpyCDomain)
#-----------------------------------------------------------------------------
# Docstring-mangling domains
#-----------------------------------------------------------------------------
try:
import sphinx # lazy to avoid test dependency
except ImportError:
CDomain = PythonDomain = object
else:
from sphinx.domains.c import CDomain
from sphinx.domains.python import PythonDomain
class ManglingDomainBase(object):
directive_mangling_map = {}
def __init__(self, *a, **kw):
super(ManglingDomainBase, self).__init__(*a, **kw)
self.wrap_mangling_directives()
def wrap_mangling_directives(self):
for name, objtype in self.directive_mangling_map.items():
self.directives[name] = wrap_mangling_directive(
self.directives[name], objtype)
class NumpyPythonDomain(ManglingDomainBase, PythonDomain):
name = 'np'
directive_mangling_map = {
'function': 'function',
'class': 'class',
'exception': 'class',
'method': 'function',
'classmethod': 'function',
'staticmethod': 'function',
'attribute': 'attribute',
}
class NumpyCDomain(ManglingDomainBase, CDomain):
name = 'np-c'
directive_mangling_map = {
'function': 'function',
'member': 'attribute',
'macro': 'function',
'type': 'class',
'var': 'object',
}
def wrap_mangling_directive(base_directive, objtype):
class directive(base_directive):
def run(self):
env = self.state.document.settings.env
name = None
if self.arguments:
m = re.match(r'^(.*\s+)?(.*?)(\(.*)?', self.arguments[0])
name = m.group(2).strip()
if not name:
name = self.arguments[0]
lines = list(self.content)
mangle_docstrings(env.app, objtype, name, None, None, lines)
# local import to avoid testing dependency
from docutils.statemachine import ViewList
self.content = ViewList(lines, self.content.parent)
return base_directive.run(self)
return directive
| bsd-3-clause |
asdfsx/chardet | chardet/euctwfreq.py | 53 | 31621 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
# EUCTW frequency table
# Converted from big5 work
# by Taiwan's Mandarin Promotion Council
# <http:#www.edu.tw:81/mandr/>
# 128 --> 0.42261
# 256 --> 0.57851
# 512 --> 0.74851
# 1024 --> 0.89384
# 2048 --> 0.97583
#
# Idea Distribution Ratio = 0.74851/(1-0.74851) =2.98
# Random Distribution Ration = 512/(5401-512)=0.105
#
# Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR
EUCTW_TYPICAL_DISTRIBUTION_RATIO = 0.75
# Char to FreqOrder table ,
EUCTW_TABLE_SIZE = 8102
EUCTW_CHAR_TO_FREQ_ORDER = (
1,1800,1506, 255,1431, 198, 9, 82, 6,7310, 177, 202,3615,1256,2808, 110, # 2742
3735, 33,3241, 261, 76, 44,2113, 16,2931,2184,1176, 659,3868, 26,3404,2643, # 2758
1198,3869,3313,4060, 410,2211, 302, 590, 361,1963, 8, 204, 58,4296,7311,1931, # 2774
63,7312,7313, 317,1614, 75, 222, 159,4061,2412,1480,7314,3500,3068, 224,2809, # 2790
3616, 3, 10,3870,1471, 29,2774,1135,2852,1939, 873, 130,3242,1123, 312,7315, # 2806
4297,2051, 507, 252, 682,7316, 142,1914, 124, 206,2932, 34,3501,3173, 64, 604, # 2822
7317,2494,1976,1977, 155,1990, 645, 641,1606,7318,3405, 337, 72, 406,7319, 80, # 2838
630, 238,3174,1509, 263, 939,1092,2644, 756,1440,1094,3406, 449, 69,2969, 591, # 2854
179,2095, 471, 115,2034,1843, 60, 50,2970, 134, 806,1868, 734,2035,3407, 180, # 2870
995,1607, 156, 537,2893, 688,7320, 319,1305, 779,2144, 514,2374, 298,4298, 359, # 2886
2495, 90,2707,1338, 663, 11, 906,1099,2545, 20,2436, 182, 532,1716,7321, 732, # 2902
1376,4062,1311,1420,3175, 25,2312,1056, 113, 399, 382,1949, 242,3408,2467, 529, # 2918
3243, 475,1447,3617,7322, 117, 21, 656, 810,1297,2295,2329,3502,7323, 126,4063, # 2934
706, 456, 150, 613,4299, 71,1118,2036,4064, 145,3069, 85, 835, 486,2114,1246, # 2950
1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,7324,2127,2354, 347,3736, 221, # 2966
3503,3110,7325,1955,1153,4065, 83, 296,1199,3070, 192, 624, 93,7326, 822,1897, # 2982
2810,3111, 795,2064, 991,1554,1542,1592, 27, 43,2853, 859, 139,1456, 860,4300, # 2998
437, 712,3871, 164,2392,3112, 695, 211,3017,2096, 195,3872,1608,3504,3505,3618, # 3014
3873, 234, 811,2971,2097,3874,2229,1441,3506,1615,2375, 668,2076,1638, 305, 228, # 3030
1664,4301, 467, 415,7327, 262,2098,1593, 239, 108, 300, 200,1033, 512,1247,2077, # 3046
7328,7329,2173,3176,3619,2673, 593, 845,1062,3244, 88,1723,2037,3875,1950, 212, # 3062
266, 152, 149, 468,1898,4066,4302, 77, 187,7330,3018, 37, 5,2972,7331,3876, # 3078
7332,7333, 39,2517,4303,2894,3177,2078, 55, 148, 74,4304, 545, 483,1474,1029, # 3094
1665, 217,1869,1531,3113,1104,2645,4067, 24, 172,3507, 900,3877,3508,3509,4305, # 3110
32,1408,2811,1312, 329, 487,2355,2247,2708, 784,2674, 4,3019,3314,1427,1788, # 3126
188, 109, 499,7334,3620,1717,1789, 888,1217,3020,4306,7335,3510,7336,3315,1520, # 3142
3621,3878, 196,1034, 775,7337,7338, 929,1815, 249, 439, 38,7339,1063,7340, 794, # 3158
3879,1435,2296, 46, 178,3245,2065,7341,2376,7342, 214,1709,4307, 804, 35, 707, # 3174
324,3622,1601,2546, 140, 459,4068,7343,7344,1365, 839, 272, 978,2257,2572,3409, # 3190
2128,1363,3623,1423, 697, 100,3071, 48, 70,1231, 495,3114,2193,7345,1294,7346, # 3206
2079, 462, 586,1042,3246, 853, 256, 988, 185,2377,3410,1698, 434,1084,7347,3411, # 3222
314,2615,2775,4308,2330,2331, 569,2280, 637,1816,2518, 757,1162,1878,1616,3412, # 3238
287,1577,2115, 768,4309,1671,2854,3511,2519,1321,3737, 909,2413,7348,4069, 933, # 3254
3738,7349,2052,2356,1222,4310, 765,2414,1322, 786,4311,7350,1919,1462,1677,2895, # 3270
1699,7351,4312,1424,2437,3115,3624,2590,3316,1774,1940,3413,3880,4070, 309,1369, # 3286
1130,2812, 364,2230,1653,1299,3881,3512,3882,3883,2646, 525,1085,3021, 902,2000, # 3302
1475, 964,4313, 421,1844,1415,1057,2281, 940,1364,3116, 376,4314,4315,1381, 7, # 3318
2520, 983,2378, 336,1710,2675,1845, 321,3414, 559,1131,3022,2742,1808,1132,1313, # 3334
265,1481,1857,7352, 352,1203,2813,3247, 167,1089, 420,2814, 776, 792,1724,3513, # 3350
4071,2438,3248,7353,4072,7354, 446, 229, 333,2743, 901,3739,1200,1557,4316,2647, # 3366
1920, 395,2744,2676,3740,4073,1835, 125, 916,3178,2616,4317,7355,7356,3741,7357, # 3382
7358,7359,4318,3117,3625,1133,2547,1757,3415,1510,2313,1409,3514,7360,2145, 438, # 3398
2591,2896,2379,3317,1068, 958,3023, 461, 311,2855,2677,4074,1915,3179,4075,1978, # 3414
383, 750,2745,2617,4076, 274, 539, 385,1278,1442,7361,1154,1964, 384, 561, 210, # 3430
98,1295,2548,3515,7362,1711,2415,1482,3416,3884,2897,1257, 129,7363,3742, 642, # 3446
523,2776,2777,2648,7364, 141,2231,1333, 68, 176, 441, 876, 907,4077, 603,2592, # 3462
710, 171,3417, 404, 549, 18,3118,2393,1410,3626,1666,7365,3516,4319,2898,4320, # 3478
7366,2973, 368,7367, 146, 366, 99, 871,3627,1543, 748, 807,1586,1185, 22,2258, # 3494
379,3743,3180,7368,3181, 505,1941,2618,1991,1382,2314,7369, 380,2357, 218, 702, # 3510
1817,1248,3418,3024,3517,3318,3249,7370,2974,3628, 930,3250,3744,7371, 59,7372, # 3526
585, 601,4078, 497,3419,1112,1314,4321,1801,7373,1223,1472,2174,7374, 749,1836, # 3542
690,1899,3745,1772,3885,1476, 429,1043,1790,2232,2116, 917,4079, 447,1086,1629, # 3558
7375, 556,7376,7377,2020,1654, 844,1090, 105, 550, 966,1758,2815,1008,1782, 686, # 3574
1095,7378,2282, 793,1602,7379,3518,2593,4322,4080,2933,2297,4323,3746, 980,2496, # 3590
544, 353, 527,4324, 908,2678,2899,7380, 381,2619,1942,1348,7381,1341,1252, 560, # 3606
3072,7382,3420,2856,7383,2053, 973, 886,2080, 143,4325,7384,7385, 157,3886, 496, # 3622
4081, 57, 840, 540,2038,4326,4327,3421,2117,1445, 970,2259,1748,1965,2081,4082, # 3638
3119,1234,1775,3251,2816,3629, 773,1206,2129,1066,2039,1326,3887,1738,1725,4083, # 3654
279,3120, 51,1544,2594, 423,1578,2130,2066, 173,4328,1879,7386,7387,1583, 264, # 3670
610,3630,4329,2439, 280, 154,7388,7389,7390,1739, 338,1282,3073, 693,2857,1411, # 3686
1074,3747,2440,7391,4330,7392,7393,1240, 952,2394,7394,2900,1538,2679, 685,1483, # 3702
4084,2468,1436, 953,4085,2054,4331, 671,2395, 79,4086,2441,3252, 608, 567,2680, # 3718
3422,4087,4088,1691, 393,1261,1791,2396,7395,4332,7396,7397,7398,7399,1383,1672, # 3734
3748,3182,1464, 522,1119, 661,1150, 216, 675,4333,3888,1432,3519, 609,4334,2681, # 3750
2397,7400,7401,7402,4089,3025, 0,7403,2469, 315, 231,2442, 301,3319,4335,2380, # 3766
7404, 233,4090,3631,1818,4336,4337,7405, 96,1776,1315,2082,7406, 257,7407,1809, # 3782
3632,2709,1139,1819,4091,2021,1124,2163,2778,1777,2649,7408,3074, 363,1655,3183, # 3798
7409,2975,7410,7411,7412,3889,1567,3890, 718, 103,3184, 849,1443, 341,3320,2934, # 3814
1484,7413,1712, 127, 67, 339,4092,2398, 679,1412, 821,7414,7415, 834, 738, 351, # 3830
2976,2146, 846, 235,1497,1880, 418,1992,3749,2710, 186,1100,2147,2746,3520,1545, # 3846
1355,2935,2858,1377, 583,3891,4093,2573,2977,7416,1298,3633,1078,2549,3634,2358, # 3862
78,3750,3751, 267,1289,2099,2001,1594,4094, 348, 369,1274,2194,2175,1837,4338, # 3878
1820,2817,3635,2747,2283,2002,4339,2936,2748, 144,3321, 882,4340,3892,2749,3423, # 3894
4341,2901,7417,4095,1726, 320,7418,3893,3026, 788,2978,7419,2818,1773,1327,2859, # 3910
3894,2819,7420,1306,4342,2003,1700,3752,3521,2359,2650, 787,2022, 506, 824,3636, # 3926
534, 323,4343,1044,3322,2023,1900, 946,3424,7421,1778,1500,1678,7422,1881,4344, # 3942
165, 243,4345,3637,2521, 123, 683,4096, 764,4346, 36,3895,1792, 589,2902, 816, # 3958
626,1667,3027,2233,1639,1555,1622,3753,3896,7423,3897,2860,1370,1228,1932, 891, # 3974
2083,2903, 304,4097,7424, 292,2979,2711,3522, 691,2100,4098,1115,4347, 118, 662, # 3990
7425, 611,1156, 854,2381,1316,2861, 2, 386, 515,2904,7426,7427,3253, 868,2234, # 4006
1486, 855,2651, 785,2212,3028,7428,1040,3185,3523,7429,3121, 448,7430,1525,7431, # 4022
2164,4348,7432,3754,7433,4099,2820,3524,3122, 503, 818,3898,3123,1568, 814, 676, # 4038
1444, 306,1749,7434,3755,1416,1030, 197,1428, 805,2821,1501,4349,7435,7436,7437, # 4054
1993,7438,4350,7439,7440,2195, 13,2779,3638,2980,3124,1229,1916,7441,3756,2131, # 4070
7442,4100,4351,2399,3525,7443,2213,1511,1727,1120,7444,7445, 646,3757,2443, 307, # 4086
7446,7447,1595,3186,7448,7449,7450,3639,1113,1356,3899,1465,2522,2523,7451, 519, # 4102
7452, 128,2132, 92,2284,1979,7453,3900,1512, 342,3125,2196,7454,2780,2214,1980, # 4118
3323,7455, 290,1656,1317, 789, 827,2360,7456,3758,4352, 562, 581,3901,7457, 401, # 4134
4353,2248, 94,4354,1399,2781,7458,1463,2024,4355,3187,1943,7459, 828,1105,4101, # 4150
1262,1394,7460,4102, 605,4356,7461,1783,2862,7462,2822, 819,2101, 578,2197,2937, # 4166
7463,1502, 436,3254,4103,3255,2823,3902,2905,3425,3426,7464,2712,2315,7465,7466, # 4182
2332,2067, 23,4357, 193, 826,3759,2102, 699,1630,4104,3075, 390,1793,1064,3526, # 4198
7467,1579,3076,3077,1400,7468,4105,1838,1640,2863,7469,4358,4359, 137,4106, 598, # 4214
3078,1966, 780, 104, 974,2938,7470, 278, 899, 253, 402, 572, 504, 493,1339,7471, # 4230
3903,1275,4360,2574,2550,7472,3640,3029,3079,2249, 565,1334,2713, 863, 41,7473, # 4246
7474,4361,7475,1657,2333, 19, 463,2750,4107, 606,7476,2981,3256,1087,2084,1323, # 4262
2652,2982,7477,1631,1623,1750,4108,2682,7478,2864, 791,2714,2653,2334, 232,2416, # 4278
7479,2983,1498,7480,2654,2620, 755,1366,3641,3257,3126,2025,1609, 119,1917,3427, # 4294
862,1026,4109,7481,3904,3760,4362,3905,4363,2260,1951,2470,7482,1125, 817,4110, # 4310
4111,3906,1513,1766,2040,1487,4112,3030,3258,2824,3761,3127,7483,7484,1507,7485, # 4326
2683, 733, 40,1632,1106,2865, 345,4113, 841,2524, 230,4364,2984,1846,3259,3428, # 4342
7486,1263, 986,3429,7487, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562,3907, # 4358
3908,2939, 967,2751,2655,1349, 592,2133,1692,3324,2985,1994,4114,1679,3909,1901, # 4374
2185,7488, 739,3642,2715,1296,1290,7489,4115,2198,2199,1921,1563,2595,2551,1870, # 4390
2752,2986,7490, 435,7491, 343,1108, 596, 17,1751,4365,2235,3430,3643,7492,4366, # 4406
294,3527,2940,1693, 477, 979, 281,2041,3528, 643,2042,3644,2621,2782,2261,1031, # 4422
2335,2134,2298,3529,4367, 367,1249,2552,7493,3530,7494,4368,1283,3325,2004, 240, # 4438
1762,3326,4369,4370, 836,1069,3128, 474,7495,2148,2525, 268,3531,7496,3188,1521, # 4454
1284,7497,1658,1546,4116,7498,3532,3533,7499,4117,3327,2684,1685,4118, 961,1673, # 4470
2622, 190,2005,2200,3762,4371,4372,7500, 570,2497,3645,1490,7501,4373,2623,3260, # 4486
1956,4374, 584,1514, 396,1045,1944,7502,4375,1967,2444,7503,7504,4376,3910, 619, # 4502
7505,3129,3261, 215,2006,2783,2553,3189,4377,3190,4378, 763,4119,3763,4379,7506, # 4518
7507,1957,1767,2941,3328,3646,1174, 452,1477,4380,3329,3130,7508,2825,1253,2382, # 4534
2186,1091,2285,4120, 492,7509, 638,1169,1824,2135,1752,3911, 648, 926,1021,1324, # 4550
4381, 520,4382, 997, 847,1007, 892,4383,3764,2262,1871,3647,7510,2400,1784,4384, # 4566
1952,2942,3080,3191,1728,4121,2043,3648,4385,2007,1701,3131,1551, 30,2263,4122, # 4582
7511,2026,4386,3534,7512, 501,7513,4123, 594,3431,2165,1821,3535,3432,3536,3192, # 4598
829,2826,4124,7514,1680,3132,1225,4125,7515,3262,4387,4126,3133,2336,7516,4388, # 4614
4127,7517,3912,3913,7518,1847,2383,2596,3330,7519,4389, 374,3914, 652,4128,4129, # 4630
375,1140, 798,7520,7521,7522,2361,4390,2264, 546,1659, 138,3031,2445,4391,7523, # 4646
2250, 612,1848, 910, 796,3765,1740,1371, 825,3766,3767,7524,2906,2554,7525, 692, # 4662
444,3032,2624, 801,4392,4130,7526,1491, 244,1053,3033,4131,4132, 340,7527,3915, # 4678
1041,2987, 293,1168, 87,1357,7528,1539, 959,7529,2236, 721, 694,4133,3768, 219, # 4694
1478, 644,1417,3331,2656,1413,1401,1335,1389,3916,7530,7531,2988,2362,3134,1825, # 4710
730,1515, 184,2827, 66,4393,7532,1660,2943, 246,3332, 378,1457, 226,3433, 975, # 4726
3917,2944,1264,3537, 674, 696,7533, 163,7534,1141,2417,2166, 713,3538,3333,4394, # 4742
3918,7535,7536,1186, 15,7537,1079,1070,7538,1522,3193,3539, 276,1050,2716, 758, # 4758
1126, 653,2945,3263,7539,2337, 889,3540,3919,3081,2989, 903,1250,4395,3920,3434, # 4774
3541,1342,1681,1718, 766,3264, 286, 89,2946,3649,7540,1713,7541,2597,3334,2990, # 4790
7542,2947,2215,3194,2866,7543,4396,2498,2526, 181, 387,1075,3921, 731,2187,3335, # 4806
7544,3265, 310, 313,3435,2299, 770,4134, 54,3034, 189,4397,3082,3769,3922,7545, # 4822
1230,1617,1849, 355,3542,4135,4398,3336, 111,4136,3650,1350,3135,3436,3035,4137, # 4838
2149,3266,3543,7546,2784,3923,3924,2991, 722,2008,7547,1071, 247,1207,2338,2471, # 4854
1378,4399,2009, 864,1437,1214,4400, 373,3770,1142,2216, 667,4401, 442,2753,2555, # 4870
3771,3925,1968,4138,3267,1839, 837, 170,1107, 934,1336,1882,7548,7549,2118,4139, # 4886
2828, 743,1569,7550,4402,4140, 582,2384,1418,3437,7551,1802,7552, 357,1395,1729, # 4902
3651,3268,2418,1564,2237,7553,3083,3772,1633,4403,1114,2085,4141,1532,7554, 482, # 4918
2446,4404,7555,7556,1492, 833,1466,7557,2717,3544,1641,2829,7558,1526,1272,3652, # 4934
4142,1686,1794, 416,2556,1902,1953,1803,7559,3773,2785,3774,1159,2316,7560,2867, # 4950
4405,1610,1584,3036,2419,2754, 443,3269,1163,3136,7561,7562,3926,7563,4143,2499, # 4966
3037,4406,3927,3137,2103,1647,3545,2010,1872,4144,7564,4145, 431,3438,7565, 250, # 4982
97, 81,4146,7566,1648,1850,1558, 160, 848,7567, 866, 740,1694,7568,2201,2830, # 4998
3195,4147,4407,3653,1687, 950,2472, 426, 469,3196,3654,3655,3928,7569,7570,1188, # 5014
424,1995, 861,3546,4148,3775,2202,2685, 168,1235,3547,4149,7571,2086,1674,4408, # 5030
3337,3270, 220,2557,1009,7572,3776, 670,2992, 332,1208, 717,7573,7574,3548,2447, # 5046
3929,3338,7575, 513,7576,1209,2868,3339,3138,4409,1080,7577,7578,7579,7580,2527, # 5062
3656,3549, 815,1587,3930,3931,7581,3550,3439,3777,1254,4410,1328,3038,1390,3932, # 5078
1741,3933,3778,3934,7582, 236,3779,2448,3271,7583,7584,3657,3780,1273,3781,4411, # 5094
7585, 308,7586,4412, 245,4413,1851,2473,1307,2575, 430, 715,2136,2449,7587, 270, # 5110
199,2869,3935,7588,3551,2718,1753, 761,1754, 725,1661,1840,4414,3440,3658,7589, # 5126
7590, 587, 14,3272, 227,2598, 326, 480,2265, 943,2755,3552, 291, 650,1883,7591, # 5142
1702,1226, 102,1547, 62,3441, 904,4415,3442,1164,4150,7592,7593,1224,1548,2756, # 5158
391, 498,1493,7594,1386,1419,7595,2055,1177,4416, 813, 880,1081,2363, 566,1145, # 5174
4417,2286,1001,1035,2558,2599,2238, 394,1286,7596,7597,2068,7598, 86,1494,1730, # 5190
3936, 491,1588, 745, 897,2948, 843,3340,3937,2757,2870,3273,1768, 998,2217,2069, # 5206
397,1826,1195,1969,3659,2993,3341, 284,7599,3782,2500,2137,2119,1903,7600,3938, # 5222
2150,3939,4151,1036,3443,1904, 114,2559,4152, 209,1527,7601,7602,2949,2831,2625, # 5238
2385,2719,3139, 812,2560,7603,3274,7604,1559, 737,1884,3660,1210, 885, 28,2686, # 5254
3553,3783,7605,4153,1004,1779,4418,7606, 346,1981,2218,2687,4419,3784,1742, 797, # 5270
1642,3940,1933,1072,1384,2151, 896,3941,3275,3661,3197,2871,3554,7607,2561,1958, # 5286
4420,2450,1785,7608,7609,7610,3942,4154,1005,1308,3662,4155,2720,4421,4422,1528, # 5302
2600, 161,1178,4156,1982, 987,4423,1101,4157, 631,3943,1157,3198,2420,1343,1241, # 5318
1016,2239,2562, 372, 877,2339,2501,1160, 555,1934, 911,3944,7611, 466,1170, 169, # 5334
1051,2907,2688,3663,2474,2994,1182,2011,2563,1251,2626,7612, 992,2340,3444,1540, # 5350
2721,1201,2070,2401,1996,2475,7613,4424, 528,1922,2188,1503,1873,1570,2364,3342, # 5366
3276,7614, 557,1073,7615,1827,3445,2087,2266,3140,3039,3084, 767,3085,2786,4425, # 5382
1006,4158,4426,2341,1267,2176,3664,3199, 778,3945,3200,2722,1597,2657,7616,4427, # 5398
7617,3446,7618,7619,7620,3277,2689,1433,3278, 131, 95,1504,3946, 723,4159,3141, # 5414
1841,3555,2758,2189,3947,2027,2104,3665,7621,2995,3948,1218,7622,3343,3201,3949, # 5430
4160,2576, 248,1634,3785, 912,7623,2832,3666,3040,3786, 654, 53,7624,2996,7625, # 5446
1688,4428, 777,3447,1032,3950,1425,7626, 191, 820,2120,2833, 971,4429, 931,3202, # 5462
135, 664, 783,3787,1997, 772,2908,1935,3951,3788,4430,2909,3203, 282,2723, 640, # 5478
1372,3448,1127, 922, 325,3344,7627,7628, 711,2044,7629,7630,3952,2219,2787,1936, # 5494
3953,3345,2220,2251,3789,2300,7631,4431,3790,1258,3279,3954,3204,2138,2950,3955, # 5510
3956,7632,2221, 258,3205,4432, 101,1227,7633,3280,1755,7634,1391,3281,7635,2910, # 5526
2056, 893,7636,7637,7638,1402,4161,2342,7639,7640,3206,3556,7641,7642, 878,1325, # 5542
1780,2788,4433, 259,1385,2577, 744,1183,2267,4434,7643,3957,2502,7644, 684,1024, # 5558
4162,7645, 472,3557,3449,1165,3282,3958,3959, 322,2152, 881, 455,1695,1152,1340, # 5574
660, 554,2153,4435,1058,4436,4163, 830,1065,3346,3960,4437,1923,7646,1703,1918, # 5590
7647, 932,2268, 122,7648,4438, 947, 677,7649,3791,2627, 297,1905,1924,2269,4439, # 5606
2317,3283,7650,7651,4164,7652,4165, 84,4166, 112, 989,7653, 547,1059,3961, 701, # 5622
3558,1019,7654,4167,7655,3450, 942, 639, 457,2301,2451, 993,2951, 407, 851, 494, # 5638
4440,3347, 927,7656,1237,7657,2421,3348, 573,4168, 680, 921,2911,1279,1874, 285, # 5654
790,1448,1983, 719,2167,7658,7659,4441,3962,3963,1649,7660,1541, 563,7661,1077, # 5670
7662,3349,3041,3451, 511,2997,3964,3965,3667,3966,1268,2564,3350,3207,4442,4443, # 5686
7663, 535,1048,1276,1189,2912,2028,3142,1438,1373,2834,2952,1134,2012,7664,4169, # 5702
1238,2578,3086,1259,7665, 700,7666,2953,3143,3668,4170,7667,4171,1146,1875,1906, # 5718
4444,2601,3967, 781,2422, 132,1589, 203, 147, 273,2789,2402, 898,1786,2154,3968, # 5734
3969,7668,3792,2790,7669,7670,4445,4446,7671,3208,7672,1635,3793, 965,7673,1804, # 5750
2690,1516,3559,1121,1082,1329,3284,3970,1449,3794, 65,1128,2835,2913,2759,1590, # 5766
3795,7674,7675, 12,2658, 45, 976,2579,3144,4447, 517,2528,1013,1037,3209,7676, # 5782
3796,2836,7677,3797,7678,3452,7679,2602, 614,1998,2318,3798,3087,2724,2628,7680, # 5798
2580,4172, 599,1269,7681,1810,3669,7682,2691,3088, 759,1060, 489,1805,3351,3285, # 5814
1358,7683,7684,2386,1387,1215,2629,2252, 490,7685,7686,4173,1759,2387,2343,7687, # 5830
4448,3799,1907,3971,2630,1806,3210,4449,3453,3286,2760,2344, 874,7688,7689,3454, # 5846
3670,1858, 91,2914,3671,3042,3800,4450,7690,3145,3972,2659,7691,3455,1202,1403, # 5862
3801,2954,2529,1517,2503,4451,3456,2504,7692,4452,7693,2692,1885,1495,1731,3973, # 5878
2365,4453,7694,2029,7695,7696,3974,2693,1216, 237,2581,4174,2319,3975,3802,4454, # 5894
4455,2694,3560,3457, 445,4456,7697,7698,7699,7700,2761, 61,3976,3672,1822,3977, # 5910
7701, 687,2045, 935, 925, 405,2660, 703,1096,1859,2725,4457,3978,1876,1367,2695, # 5926
3352, 918,2105,1781,2476, 334,3287,1611,1093,4458, 564,3146,3458,3673,3353, 945, # 5942
2631,2057,4459,7702,1925, 872,4175,7703,3459,2696,3089, 349,4176,3674,3979,4460, # 5958
3803,4177,3675,2155,3980,4461,4462,4178,4463,2403,2046, 782,3981, 400, 251,4179, # 5974
1624,7704,7705, 277,3676, 299,1265, 476,1191,3804,2121,4180,4181,1109, 205,7706, # 5990
2582,1000,2156,3561,1860,7707,7708,7709,4464,7710,4465,2565, 107,2477,2157,3982, # 6006
3460,3147,7711,1533, 541,1301, 158, 753,4182,2872,3562,7712,1696, 370,1088,4183, # 6022
4466,3563, 579, 327, 440, 162,2240, 269,1937,1374,3461, 968,3043, 56,1396,3090, # 6038
2106,3288,3354,7713,1926,2158,4467,2998,7714,3564,7715,7716,3677,4468,2478,7717, # 6054
2791,7718,1650,4469,7719,2603,7720,7721,3983,2661,3355,1149,3356,3984,3805,3985, # 6070
7722,1076, 49,7723, 951,3211,3289,3290, 450,2837, 920,7724,1811,2792,2366,4184, # 6086
1908,1138,2367,3806,3462,7725,3212,4470,1909,1147,1518,2423,4471,3807,7726,4472, # 6102
2388,2604, 260,1795,3213,7727,7728,3808,3291, 708,7729,3565,1704,7730,3566,1351, # 6118
1618,3357,2999,1886, 944,4185,3358,4186,3044,3359,4187,7731,3678, 422, 413,1714, # 6134
3292, 500,2058,2345,4188,2479,7732,1344,1910, 954,7733,1668,7734,7735,3986,2404, # 6150
4189,3567,3809,4190,7736,2302,1318,2505,3091, 133,3092,2873,4473, 629, 31,2838, # 6166
2697,3810,4474, 850, 949,4475,3987,2955,1732,2088,4191,1496,1852,7737,3988, 620, # 6182
3214, 981,1242,3679,3360,1619,3680,1643,3293,2139,2452,1970,1719,3463,2168,7738, # 6198
3215,7739,7740,3361,1828,7741,1277,4476,1565,2047,7742,1636,3568,3093,7743, 869, # 6214
2839, 655,3811,3812,3094,3989,3000,3813,1310,3569,4477,7744,7745,7746,1733, 558, # 6230
4478,3681, 335,1549,3045,1756,4192,3682,1945,3464,1829,1291,1192, 470,2726,2107, # 6246
2793, 913,1054,3990,7747,1027,7748,3046,3991,4479, 982,2662,3362,3148,3465,3216, # 6262
3217,1946,2794,7749, 571,4480,7750,1830,7751,3570,2583,1523,2424,7752,2089, 984, # 6278
4481,3683,1959,7753,3684, 852, 923,2795,3466,3685, 969,1519, 999,2048,2320,1705, # 6294
7754,3095, 615,1662, 151, 597,3992,2405,2321,1049, 275,4482,3686,4193, 568,3687, # 6310
3571,2480,4194,3688,7755,2425,2270, 409,3218,7756,1566,2874,3467,1002, 769,2840, # 6326
194,2090,3149,3689,2222,3294,4195, 628,1505,7757,7758,1763,2177,3001,3993, 521, # 6342
1161,2584,1787,2203,2406,4483,3994,1625,4196,4197, 412, 42,3096, 464,7759,2632, # 6358
4484,3363,1760,1571,2875,3468,2530,1219,2204,3814,2633,2140,2368,4485,4486,3295, # 6374
1651,3364,3572,7760,7761,3573,2481,3469,7762,3690,7763,7764,2271,2091, 460,7765, # 6390
4487,7766,3002, 962, 588,3574, 289,3219,2634,1116, 52,7767,3047,1796,7768,7769, # 6406
7770,1467,7771,1598,1143,3691,4198,1984,1734,1067,4488,1280,3365, 465,4489,1572, # 6422
510,7772,1927,2241,1812,1644,3575,7773,4490,3692,7774,7775,2663,1573,1534,7776, # 6438
7777,4199, 536,1807,1761,3470,3815,3150,2635,7778,7779,7780,4491,3471,2915,1911, # 6454
2796,7781,3296,1122, 377,3220,7782, 360,7783,7784,4200,1529, 551,7785,2059,3693, # 6470
1769,2426,7786,2916,4201,3297,3097,2322,2108,2030,4492,1404, 136,1468,1479, 672, # 6486
1171,3221,2303, 271,3151,7787,2762,7788,2049, 678,2727, 865,1947,4493,7789,2013, # 6502
3995,2956,7790,2728,2223,1397,3048,3694,4494,4495,1735,2917,3366,3576,7791,3816, # 6518
509,2841,2453,2876,3817,7792,7793,3152,3153,4496,4202,2531,4497,2304,1166,1010, # 6534
552, 681,1887,7794,7795,2957,2958,3996,1287,1596,1861,3154, 358, 453, 736, 175, # 6550
478,1117, 905,1167,1097,7796,1853,1530,7797,1706,7798,2178,3472,2287,3695,3473, # 6566
3577,4203,2092,4204,7799,3367,1193,2482,4205,1458,2190,2205,1862,1888,1421,3298, # 6582
2918,3049,2179,3474, 595,2122,7800,3997,7801,7802,4206,1707,2636, 223,3696,1359, # 6598
751,3098, 183,3475,7803,2797,3003, 419,2369, 633, 704,3818,2389, 241,7804,7805, # 6614
7806, 838,3004,3697,2272,2763,2454,3819,1938,2050,3998,1309,3099,2242,1181,7807, # 6630
1136,2206,3820,2370,1446,4207,2305,4498,7808,7809,4208,1055,2605, 484,3698,7810, # 6646
3999, 625,4209,2273,3368,1499,4210,4000,7811,4001,4211,3222,2274,2275,3476,7812, # 6662
7813,2764, 808,2606,3699,3369,4002,4212,3100,2532, 526,3370,3821,4213, 955,7814, # 6678
1620,4214,2637,2427,7815,1429,3700,1669,1831, 994, 928,7816,3578,1260,7817,7818, # 6694
7819,1948,2288, 741,2919,1626,4215,2729,2455, 867,1184, 362,3371,1392,7820,7821, # 6710
4003,4216,1770,1736,3223,2920,4499,4500,1928,2698,1459,1158,7822,3050,3372,2877, # 6726
1292,1929,2506,2842,3701,1985,1187,2071,2014,2607,4217,7823,2566,2507,2169,3702, # 6742
2483,3299,7824,3703,4501,7825,7826, 666,1003,3005,1022,3579,4218,7827,4502,1813, # 6758
2253, 574,3822,1603, 295,1535, 705,3823,4219, 283, 858, 417,7828,7829,3224,4503, # 6774
4504,3051,1220,1889,1046,2276,2456,4004,1393,1599, 689,2567, 388,4220,7830,2484, # 6790
802,7831,2798,3824,2060,1405,2254,7832,4505,3825,2109,1052,1345,3225,1585,7833, # 6806
809,7834,7835,7836, 575,2730,3477, 956,1552,1469,1144,2323,7837,2324,1560,2457, # 6822
3580,3226,4005, 616,2207,3155,2180,2289,7838,1832,7839,3478,4506,7840,1319,3704, # 6838
3705,1211,3581,1023,3227,1293,2799,7841,7842,7843,3826, 607,2306,3827, 762,2878, # 6854
1439,4221,1360,7844,1485,3052,7845,4507,1038,4222,1450,2061,2638,4223,1379,4508, # 6870
2585,7846,7847,4224,1352,1414,2325,2921,1172,7848,7849,3828,3829,7850,1797,1451, # 6886
7851,7852,7853,7854,2922,4006,4007,2485,2346, 411,4008,4009,3582,3300,3101,4509, # 6902
1561,2664,1452,4010,1375,7855,7856, 47,2959, 316,7857,1406,1591,2923,3156,7858, # 6918
1025,2141,3102,3157, 354,2731, 884,2224,4225,2407, 508,3706, 726,3583, 996,2428, # 6934
3584, 729,7859, 392,2191,1453,4011,4510,3707,7860,7861,2458,3585,2608,1675,2800, # 6950
919,2347,2960,2348,1270,4511,4012, 73,7862,7863, 647,7864,3228,2843,2255,1550, # 6966
1346,3006,7865,1332, 883,3479,7866,7867,7868,7869,3301,2765,7870,1212, 831,1347, # 6982
4226,4512,2326,3830,1863,3053, 720,3831,4513,4514,3832,7871,4227,7872,7873,4515, # 6998
7874,7875,1798,4516,3708,2609,4517,3586,1645,2371,7876,7877,2924, 669,2208,2665, # 7014
2429,7878,2879,7879,7880,1028,3229,7881,4228,2408,7882,2256,1353,7883,7884,4518, # 7030
3158, 518,7885,4013,7886,4229,1960,7887,2142,4230,7888,7889,3007,2349,2350,3833, # 7046
516,1833,1454,4014,2699,4231,4519,2225,2610,1971,1129,3587,7890,2766,7891,2961, # 7062
1422, 577,1470,3008,1524,3373,7892,7893, 432,4232,3054,3480,7894,2586,1455,2508, # 7078
2226,1972,1175,7895,1020,2732,4015,3481,4520,7896,2733,7897,1743,1361,3055,3482, # 7094
2639,4016,4233,4521,2290, 895, 924,4234,2170, 331,2243,3056, 166,1627,3057,1098, # 7110
7898,1232,2880,2227,3374,4522, 657, 403,1196,2372, 542,3709,3375,1600,4235,3483, # 7126
7899,4523,2767,3230, 576, 530,1362,7900,4524,2533,2666,3710,4017,7901, 842,3834, # 7142
7902,2801,2031,1014,4018, 213,2700,3376, 665, 621,4236,7903,3711,2925,2430,7904, # 7158
2431,3302,3588,3377,7905,4237,2534,4238,4525,3589,1682,4239,3484,1380,7906, 724, # 7174
2277, 600,1670,7907,1337,1233,4526,3103,2244,7908,1621,4527,7909, 651,4240,7910, # 7190
1612,4241,2611,7911,2844,7912,2734,2307,3058,7913, 716,2459,3059, 174,1255,2701, # 7206
4019,3590, 548,1320,1398, 728,4020,1574,7914,1890,1197,3060,4021,7915,3061,3062, # 7222
3712,3591,3713, 747,7916, 635,4242,4528,7917,7918,7919,4243,7920,7921,4529,7922, # 7238
3378,4530,2432, 451,7923,3714,2535,2072,4244,2735,4245,4022,7924,1764,4531,7925, # 7254
4246, 350,7926,2278,2390,2486,7927,4247,4023,2245,1434,4024, 488,4532, 458,4248, # 7270
4025,3715, 771,1330,2391,3835,2568,3159,2159,2409,1553,2667,3160,4249,7928,2487, # 7286
2881,2612,1720,2702,4250,3379,4533,7929,2536,4251,7930,3231,4252,2768,7931,2015, # 7302
2736,7932,1155,1017,3716,3836,7933,3303,2308, 201,1864,4253,1430,7934,4026,7935, # 7318
7936,7937,7938,7939,4254,1604,7940, 414,1865, 371,2587,4534,4535,3485,2016,3104, # 7334
4536,1708, 960,4255, 887, 389,2171,1536,1663,1721,7941,2228,4027,2351,2926,1580, # 7350
7942,7943,7944,1744,7945,2537,4537,4538,7946,4539,7947,2073,7948,7949,3592,3380, # 7366
2882,4256,7950,4257,2640,3381,2802, 673,2703,2460, 709,3486,4028,3593,4258,7951, # 7382
1148, 502, 634,7952,7953,1204,4540,3594,1575,4541,2613,3717,7954,3718,3105, 948, # 7398
3232, 121,1745,3837,1110,7955,4259,3063,2509,3009,4029,3719,1151,1771,3838,1488, # 7414
4030,1986,7956,2433,3487,7957,7958,2093,7959,4260,3839,1213,1407,2803, 531,2737, # 7430
2538,3233,1011,1537,7960,2769,4261,3106,1061,7961,3720,3721,1866,2883,7962,2017, # 7446
120,4262,4263,2062,3595,3234,2309,3840,2668,3382,1954,4542,7963,7964,3488,1047, # 7462
2704,1266,7965,1368,4543,2845, 649,3383,3841,2539,2738,1102,2846,2669,7966,7967, # 7478
1999,7968,1111,3596,2962,7969,2488,3842,3597,2804,1854,3384,3722,7970,7971,3385, # 7494
2410,2884,3304,3235,3598,7972,2569,7973,3599,2805,4031,1460, 856,7974,3600,7975, # 7510
2885,2963,7976,2886,3843,7977,4264, 632,2510, 875,3844,1697,3845,2291,7978,7979, # 7526
4544,3010,1239, 580,4545,4265,7980, 914, 936,2074,1190,4032,1039,2123,7981,7982, # 7542
7983,3386,1473,7984,1354,4266,3846,7985,2172,3064,4033, 915,3305,4267,4268,3306, # 7558
1605,1834,7986,2739, 398,3601,4269,3847,4034, 328,1912,2847,4035,3848,1331,4270, # 7574
3011, 937,4271,7987,3602,4036,4037,3387,2160,4546,3388, 524, 742, 538,3065,1012, # 7590
7988,7989,3849,2461,7990, 658,1103, 225,3850,7991,7992,4547,7993,4548,7994,3236, # 7606
1243,7995,4038, 963,2246,4549,7996,2705,3603,3161,7997,7998,2588,2327,7999,4550, # 7622
8000,8001,8002,3489,3307, 957,3389,2540,2032,1930,2927,2462, 870,2018,3604,1746, # 7638
2770,2771,2434,2463,8003,3851,8004,3723,3107,3724,3490,3390,3725,8005,1179,3066, # 7654
8006,3162,2373,4272,3726,2541,3163,3108,2740,4039,8007,3391,1556,2542,2292, 977, # 7670
2887,2033,4040,1205,3392,8008,1765,3393,3164,2124,1271,1689, 714,4551,3491,8009, # 7686
2328,3852, 533,4273,3605,2181, 617,8010,2464,3308,3492,2310,8011,8012,3165,8013, # 7702
8014,3853,1987, 618, 427,2641,3493,3394,8015,8016,1244,1690,8017,2806,4274,4552, # 7718
8018,3494,8019,8020,2279,1576, 473,3606,4275,3395, 972,8021,3607,8022,3067,8023, # 7734
8024,4553,4554,8025,3727,4041,4042,8026, 153,4555, 356,8027,1891,2888,4276,2143, # 7750
408, 803,2352,8028,3854,8029,4277,1646,2570,2511,4556,4557,3855,8030,3856,4278, # 7766
8031,2411,3396, 752,8032,8033,1961,2964,8034, 746,3012,2465,8035,4279,3728, 698, # 7782
4558,1892,4280,3608,2543,4559,3609,3857,8036,3166,3397,8037,1823,1302,4043,2706, # 7798
3858,1973,4281,8038,4282,3167, 823,1303,1288,1236,2848,3495,4044,3398, 774,3859, # 7814
8039,1581,4560,1304,2849,3860,4561,8040,2435,2161,1083,3237,4283,4045,4284, 344, # 7830
1173, 288,2311, 454,1683,8041,8042,1461,4562,4046,2589,8043,8044,4563, 985, 894, # 7846
8045,3399,3168,8046,1913,2928,3729,1988,8047,2110,1974,8048,4047,8049,2571,1194, # 7862
425,8050,4564,3169,1245,3730,4285,8051,8052,2850,8053, 636,4565,1855,3861, 760, # 7878
1799,8054,4286,2209,1508,4566,4048,1893,1684,2293,8055,8056,8057,4287,4288,2210, # 7894
479,8058,8059, 832,8060,4049,2489,8061,2965,2490,3731, 990,3109, 627,1814,2642, # 7910
4289,1582,4290,2125,2111,3496,4567,8062, 799,4291,3170,8063,4568,2112,1737,3013, # 7926
1018, 543, 754,4292,3309,1676,4569,4570,4050,8064,1489,8065,3497,8066,2614,2889, # 7942
4051,8067,8068,2966,8069,8070,8071,8072,3171,4571,4572,2182,1722,8073,3238,3239, # 7958
1842,3610,1715, 481, 365,1975,1856,8074,8075,1962,2491,4573,8076,2126,3611,3240, # 7974
433,1894,2063,2075,8077, 602,2741,8078,8079,8080,8081,8082,3014,1628,3400,8083, # 7990
3172,4574,4052,2890,4575,2512,8084,2544,2772,8085,8086,8087,3310,4576,2891,8088, # 8006
4577,8089,2851,4578,4579,1221,2967,4053,2513,8090,8091,8092,1867,1989,8093,8094, # 8022
8095,1895,8096,8097,4580,1896,4054, 318,8098,2094,4055,4293,8099,8100, 485,8101, # 8038
938,3862, 553,2670, 116,8102,3863,3612,8103,3498,2671,2773,3401,3311,2807,8104, # 8054
3613,2929,4056,1747,2930,2968,8105,8106, 207,8107,8108,2672,4581,2514,8109,3015, # 8070
890,3614,3864,8110,1877,3732,3402,8111,2183,2353,3403,1652,8112,8113,8114, 941, # 8086
2294, 208,3499,4057,2019, 330,4294,3865,2892,2492,3733,4295,8115,8116,8117,8118, # 8102
)
| lgpl-2.1 |
nvoron23/arangodb | 3rdParty/V8-4.3.61/third_party/python_26/Lib/site-packages/win32/Demos/win32netdemo.py | 18 | 8343 | import sys
import win32api
import win32net
import win32netcon
import win32security
import getopt
import traceback
verbose_level = 0
server = None # Run on local machine.
def verbose(msg):
if verbose_level:
print msg
def CreateUser():
"Creates a new test user, then deletes the user"
testName = "PyNetTestUser"
try:
win32net.NetUserDel(server, testName)
print "Warning - deleted user before creating it!"
except win32net.error:
pass
d = {}
d['name'] = testName
d['password'] = 'deleteme'
d['priv'] = win32netcon.USER_PRIV_USER
d['comment'] = "Delete me - created by Python test code"
d['flags'] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT
win32net.NetUserAdd(server, 1, d)
try:
try:
win32net.NetUserChangePassword(server, testName, "wrong", "new")
print "ERROR: NetUserChangePassword worked with a wrong password!"
except win32net.error:
pass
win32net.NetUserChangePassword(server, testName, "deleteme", "new")
finally:
win32net.NetUserDel(server, testName)
print "Created a user, changed their password, and deleted them!"
def UserEnum():
"Enumerates all the local users"
resume = 0
nuser = 0
while 1:
data, total, resume = win32net.NetUserEnum(server, 3, win32netcon.FILTER_NORMAL_ACCOUNT, resume)
verbose("Call to NetUserEnum obtained %d entries of %d total" % (len(data), total))
for user in data:
verbose("Found user %s" % user['name'])
nuser = nuser + 1
if not resume:
break
assert nuser, "Could not find any users!"
print "Enumerated all the local users"
def GroupEnum():
"Enumerates all the domain groups"
nmembers = 0
resume = 0
while 1:
data, total, resume = win32net.NetGroupEnum(server, 1, resume)
# print "Call to NetGroupEnum obtained %d entries of %d total" % (len(data), total)
for group in data:
verbose("Found group %(name)s:%(comment)s " % group)
memberresume = 0
while 1:
memberdata, total, memberresume = win32net.NetGroupGetUsers(server, group['name'], 0, resume)
for member in memberdata:
verbose(" Member %(name)s" % member)
nmembers = nmembers + 1
if memberresume==0:
break
if not resume:
break
assert nmembers, "Couldnt find a single member in a single group!"
print "Enumerated all the groups"
def LocalGroupEnum():
"Enumerates all the local groups"
resume = 0
nmembers = 0
while 1:
data, total, resume = win32net.NetLocalGroupEnum(server, 1, resume)
for group in data:
verbose("Found group %(name)s:%(comment)s " % group)
memberresume = 0
while 1:
memberdata, total, memberresume = win32net.NetLocalGroupGetMembers(server, group['name'], 2, resume)
for member in memberdata:
# Just for the sake of it, we convert the SID to a username
username, domain, type = win32security.LookupAccountSid(server, member['sid'])
nmembers = nmembers + 1
verbose(" Member %s (%s)" % (username, member['domainandname']))
if memberresume==0:
break
if not resume:
break
assert nmembers, "Couldnt find a single member in a single group!"
print "Enumerated all the local groups"
def ServerEnum():
"Enumerates all servers on the network"
resume = 0
while 1:
data, total, resume = win32net.NetServerEnum(server, 100, win32netcon.SV_TYPE_ALL, None, resume)
for s in data:
verbose("Found server %s" % s['name'])
# Now loop over the shares.
shareresume=0
while 1:
sharedata, total, shareresume = win32net.NetShareEnum(server, 2, shareresume)
for share in sharedata:
verbose(" %(netname)s (%(path)s):%(remark)s - in use by %(current_uses)d users" % share)
if not shareresume:
break
if not resume:
break
print "Enumerated all the servers on the network"
def LocalGroup(uname=None):
"Creates a local group, adds some members, deletes them, then removes the group"
level = 3
if uname is None: uname=win32api.GetUserName()
if uname.find("\\")<0:
uname = win32api.GetDomainName() + "\\" + uname
group = 'python_test_group'
# delete the group if it already exists
try:
win32net.NetLocalGroupDel(server, group)
print "WARNING: existing local group '%s' has been deleted."
except win32net.error:
pass
group_data = {'name': group}
win32net.NetLocalGroupAdd(server, 1, group_data)
try:
u={'domainandname': uname}
win32net.NetLocalGroupAddMembers(server, group, level, [u])
mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level)
print "members are", mem
if mem[0]['domainandname'] != uname:
print "ERROR: LocalGroup just added %s, but members are %r" % (uname, mem)
# Convert the list of dicts to a list of strings.
win32net.NetLocalGroupDelMembers(server, group, [m['domainandname'] for m in mem])
finally:
win32net.NetLocalGroupDel(server, group)
print "Created a local group, added and removed members, then deleted the group"
def GetInfo(userName=None):
"Dumps level 3 information about the current user"
if userName is None: userName=win32api.GetUserName()
print "Dumping level 3 information about user"
info = win32net.NetUserGetInfo(server, userName, 3)
for key, val in info.items():
verbose("%s=%s" % (key,val))
def SetInfo(userName=None):
"Attempts to change the current users comment, then set it back"
if userName is None: userName=win32api.GetUserName()
oldData = win32net.NetUserGetInfo(server, userName, 3)
try:
d = oldData.copy()
d["usr_comment"] = "Test comment"
win32net.NetUserSetInfo(server, userName, 3, d)
new = win32net.NetUserGetInfo(server, userName, 3)['usr_comment']
if str(new) != "Test comment":
raise RuntimeError, "Could not read the same comment back - got %s" % new
print "Changed the data for the user"
finally:
win32net.NetUserSetInfo(server, userName, 3, oldData)
def SetComputerInfo():
"Doesnt actually change anything, just make sure we could ;-)"
info = win32net.NetWkstaGetInfo(None, 502)
# *sob* - but we can't! Why not!!!
# win32net.NetWkstaSetInfo(None, 502, info)
def usage(tests):
import os
print "Usage: %s [-s server ] [-v] [Test ...]" % os.path.basename(sys.argv[0])
print " -v : Verbose - print more information"
print " -s : server - execute the tests against the named server"
print "where Test is one of:"
for t in tests:
print t.__name__,":", t.__doc__
print
print "If not tests are specified, all tests are run"
sys.exit(1)
def main():
tests = []
for ob in globals().values():
if type(ob)==type(main) and ob.__doc__:
tests.append(ob)
opts, args = getopt.getopt(sys.argv[1:], "s:hv")
for opt, val in opts:
if opt=="-s":
global server
server = val
if opt=="-h":
usage(tests)
if opt=="-v":
global verbose_level
verbose_level = verbose_level + 1
if len(args)==0:
print "Running all tests - use '-h' to see command-line options..."
dotests = tests
else:
dotests = []
for arg in args:
for t in tests:
if t.__name__==arg:
dotests.append(t)
break
else:
print "Test '%s' unknown - skipping" % arg
if not len(dotests):
print "Nothing to do!"
usage(tests)
for test in dotests:
try:
test()
except:
print "Test %s failed" % test.__name__
traceback.print_exc()
if __name__=='__main__':
main()
| apache-2.0 |
mbrubeck/servo | tests/wpt/web-platform-tests/referrer-policy/generic/subresource/image.py | 55 | 3859 | import os, sys, array, json, math, StringIO
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import subresource
class Image:
"""This class partially implements the interface of the PIL.Image.Image.
One day in the future WPT might support the PIL module or another imaging
library, so this hacky BMP implementation will no longer be required.
"""
def __init__(self, width, height):
self.width = width
self.height = height
self.img = bytearray([0 for i in range(3 * width * height)])
@staticmethod
def new(mode, size, color=0):
return Image(size[0], size[1])
def _int_to_bytes(self, number):
packed_bytes = [0, 0, 0, 0]
for i in range(4):
packed_bytes[i] = number & 0xFF
number >>= 8
return packed_bytes
def putdata(self, color_data):
for y in range(self.height):
for x in range(self.width):
i = x + y * self.width
if i > len(color_data) - 1:
return
self.img[i * 3: i * 3 + 3] = color_data[i][::-1]
def save(self, f, type):
assert type == "BMP"
# 54 bytes of preambule + image color data.
filesize = 54 + 3 * self.width * self.height;
# 14 bytes of header.
bmpfileheader = bytearray(['B', 'M'] + self._int_to_bytes(filesize) +
[0, 0, 0, 0, 54, 0, 0, 0])
# 40 bytes of info.
bmpinfoheader = bytearray([40, 0, 0, 0] +
self._int_to_bytes(self.width) +
self._int_to_bytes(self.height) +
[1, 0, 24] + (25 * [0]))
padlength = (4 - (self.width * 3) % 4) % 4
bmppad = bytearray([0, 0, 0]);
padding = bmppad[0 : padlength]
f.write(bmpfileheader)
f.write(bmpinfoheader)
for i in range(self.height):
offset = self.width * (self.height - i - 1) * 3
f.write(self.img[offset : offset + 3 * self.width])
f.write(padding)
def encode_string_as_bmp_image(string_data):
data_bytes = array.array("B", string_data)
num_bytes = len(data_bytes)
# Convert data bytes to color data (RGB).
color_data = []
num_components = 3
rgb = [0] * num_components
i = 0
for byte in data_bytes:
component_index = i % num_components
rgb[component_index] = byte
if component_index == (num_components - 1) or i == (num_bytes - 1):
color_data.append(tuple(rgb))
rgb = [0] * num_components
i += 1
# Render image.
num_pixels = len(color_data)
sqrt = int(math.ceil(math.sqrt(num_pixels)))
img = Image.new("RGB", (sqrt, sqrt), "black")
img.putdata(color_data)
# Flush image to string.
f = StringIO.StringIO()
img.save(f, "BMP")
f.seek(0)
return f.read()
def generate_payload(request, server_data):
data = ('{"headers": %(headers)s}') % server_data
if "id" in request.GET:
request.server.stash.put(request.GET["id"], data)
data = encode_string_as_bmp_image(data)
return data
def generate_report_headers_payload(request, server_data):
stashed_data = request.server.stash.take(request.GET["id"])
return stashed_data
def main(request, response):
handler = lambda data: generate_payload(request, data)
content_type = 'image/bmp'
if "report-headers" in request.GET:
handler = lambda data: generate_report_headers_payload(request, data)
content_type = 'application/json'
subresource.respond(request,
response,
payload_generator = handler,
content_type = content_type,
access_control_allow_origin = "*")
| mpl-2.0 |
azumimuo/family-xbmc-addon | plugin.video.hulubox/requests/packages/chardet/utf8prober.py | 2919 | 2652 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from . import constants
from .charsetprober import CharSetProber
from .codingstatemachine import CodingStateMachine
from .mbcssm import UTF8SMModel
ONE_CHAR_PROB = 0.5
class UTF8Prober(CharSetProber):
def __init__(self):
CharSetProber.__init__(self)
self._mCodingSM = CodingStateMachine(UTF8SMModel)
self.reset()
def reset(self):
CharSetProber.reset(self)
self._mCodingSM.reset()
self._mNumOfMBChar = 0
def get_charset_name(self):
return "utf-8"
def feed(self, aBuf):
for c in aBuf:
codingState = self._mCodingSM.next_state(c)
if codingState == constants.eError:
self._mState = constants.eNotMe
break
elif codingState == constants.eItsMe:
self._mState = constants.eFoundIt
break
elif codingState == constants.eStart:
if self._mCodingSM.get_current_charlen() >= 2:
self._mNumOfMBChar += 1
if self.get_state() == constants.eDetecting:
if self.get_confidence() > constants.SHORTCUT_THRESHOLD:
self._mState = constants.eFoundIt
return self.get_state()
def get_confidence(self):
unlike = 0.99
if self._mNumOfMBChar < 6:
for i in range(0, self._mNumOfMBChar):
unlike = unlike * ONE_CHAR_PROB
return 1.0 - unlike
else:
return unlike
| gpl-2.0 |
xiandiancloud/edx-platform-Y | common/djangoapps/course_modes/tests/test_models.py | 7 | 4937 | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from datetime import datetime, timedelta
import pytz
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from django.test import TestCase
from course_modes.models import CourseMode, Mode
class CourseModeModelTest(TestCase):
"""
Tests for the CourseMode model
"""
def setUp(self):
self.course_key = SlashSeparatedCourseKey('Test', 'TestCourse', 'TestCourseRun')
CourseMode.objects.all().delete()
def create_mode(self, mode_slug, mode_name, min_price=0, suggested_prices='', currency='usd'):
"""
Create a new course mode
"""
return CourseMode.objects.get_or_create(
course_id=self.course_key,
mode_display_name=mode_name,
mode_slug=mode_slug,
min_price=min_price,
suggested_prices=suggested_prices,
currency=currency,
)
def test_modes_for_course_empty(self):
"""
If we can't find any modes, we should get back the default mode
"""
# shouldn't be able to find a corresponding course
modes = CourseMode.modes_for_course(self.course_key)
self.assertEqual([CourseMode.DEFAULT_MODE], modes)
def test_nodes_for_course_single(self):
"""
Find the modes for a course with only one mode
"""
self.create_mode('verified', 'Verified Certificate')
modes = CourseMode.modes_for_course(self.course_key)
mode = Mode(u'verified', u'Verified Certificate', 0, '', 'usd', None, None)
self.assertEqual([mode], modes)
modes_dict = CourseMode.modes_for_course_dict(self.course_key)
self.assertEqual(modes_dict['verified'], mode)
self.assertEqual(CourseMode.mode_for_course(self.course_key, 'verified'),
mode)
def test_modes_for_course_multiple(self):
"""
Finding the modes when there's multiple modes
"""
mode1 = Mode(u'honor', u'Honor Code Certificate', 0, '', 'usd', None, None)
mode2 = Mode(u'verified', u'Verified Certificate', 0, '', 'usd', None, None)
set_modes = [mode1, mode2]
for mode in set_modes:
self.create_mode(mode.slug, mode.name, mode.min_price, mode.suggested_prices)
modes = CourseMode.modes_for_course(self.course_key)
self.assertEqual(modes, set_modes)
self.assertEqual(mode1, CourseMode.mode_for_course(self.course_key, u'honor'))
self.assertEqual(mode2, CourseMode.mode_for_course(self.course_key, u'verified'))
self.assertIsNone(CourseMode.mode_for_course(self.course_key, 'DNE'))
def test_min_course_price_for_currency(self):
"""
Get the min course price for a course according to currency
"""
# no modes, should get 0
self.assertEqual(0, CourseMode.min_course_price_for_currency(self.course_key, 'usd'))
# create some modes
mode1 = Mode(u'honor', u'Honor Code Certificate', 10, '', 'usd', None, None)
mode2 = Mode(u'verified', u'Verified Certificate', 20, '', 'usd', None, None)
mode3 = Mode(u'honor', u'Honor Code Certificate', 80, '', 'cny', None, None)
set_modes = [mode1, mode2, mode3]
for mode in set_modes:
self.create_mode(mode.slug, mode.name, mode.min_price, mode.suggested_prices, mode.currency)
self.assertEqual(10, CourseMode.min_course_price_for_currency(self.course_key, 'usd'))
self.assertEqual(80, CourseMode.min_course_price_for_currency(self.course_key, 'cny'))
def test_modes_for_course_expired(self):
expired_mode, _status = self.create_mode('verified', 'Verified Certificate')
expired_mode.expiration_datetime = datetime.now(pytz.UTC) + timedelta(days=-1)
expired_mode.save()
modes = CourseMode.modes_for_course(self.course_key)
self.assertEqual([CourseMode.DEFAULT_MODE], modes)
mode1 = Mode(u'honor', u'Honor Code Certificate', 0, '', 'usd', None, None)
self.create_mode(mode1.slug, mode1.name, mode1.min_price, mode1.suggested_prices)
modes = CourseMode.modes_for_course(self.course_key)
self.assertEqual([mode1], modes)
expiration_datetime = datetime.now(pytz.UTC) + timedelta(days=1)
expired_mode.expiration_datetime = expiration_datetime
expired_mode.save()
expired_mode_value = Mode(u'verified', u'Verified Certificate', 0, '', 'usd', expiration_datetime, None)
modes = CourseMode.modes_for_course(self.course_key)
self.assertEqual([expired_mode_value, mode1], modes)
modes = CourseMode.modes_for_course(SlashSeparatedCourseKey('TestOrg', 'TestCourse', 'TestRun'))
self.assertEqual([CourseMode.DEFAULT_MODE], modes)
| agpl-3.0 |
theheros/kbengine | kbe/src/lib/python/Lib/cgitb.py | 48 | 11947 | """More comprehensive traceback formatting for Python scripts.
To enable this module, do:
import cgitb; cgitb.enable()
at the top of your script. The optional arguments to enable() are:
display - if true, tracebacks are displayed in the web browser
logdir - if set, tracebacks are written to files in this directory
context - number of lines of source code to show for each stack frame
format - 'text' or 'html' controls the output format
By default, tracebacks are displayed but not saved, the context is 5 lines
and the output format is 'html' (for backwards compatibility with the
original use of this module)
Alternatively, if you have caught an exception and want cgitb to display it
for you, call cgitb.handler(). The optional argument to handler() is a
3-item tuple (etype, evalue, etb) just like the value of sys.exc_info().
The default handler displays output as HTML.
"""
import inspect
import keyword
import linecache
import os
import pydoc
import sys
import tempfile
import time
import tokenize
import traceback
import types
def reset():
"""Return a string that resets the CGI and browser to a known state."""
return '''<!--: spam
Content-Type: text/html
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
</font> </font> </font> </script> </object> </blockquote> </pre>
</table> </table> </table> </table> </table> </font> </font> </font>'''
__UNDEF__ = [] # a special sentinel object
def small(text):
if text:
return '<small>' + text + '</small>'
else:
return ''
def strong(text):
if text:
return '<strong>' + text + '</strong>'
else:
return ''
def grey(text):
if text:
return '<font color="#909090">' + text + '</font>'
else:
return ''
def lookup(name, frame, locals):
"""Find the value for a given name in the given environment."""
if name in locals:
return 'local', locals[name]
if name in frame.f_globals:
return 'global', frame.f_globals[name]
if '__builtins__' in frame.f_globals:
builtins = frame.f_globals['__builtins__']
if type(builtins) is type({}):
if name in builtins:
return 'builtin', builtins[name]
else:
if hasattr(builtins, name):
return 'builtin', getattr(builtins, name)
return None, __UNDEF__
def scanvars(reader, frame, locals):
"""Scan one logical line of Python and look up values of variables used."""
vars, lasttoken, parent, prefix, value = [], None, None, '', __UNDEF__
for ttype, token, start, end, line in tokenize.generate_tokens(reader):
if ttype == tokenize.NEWLINE: break
if ttype == tokenize.NAME and token not in keyword.kwlist:
if lasttoken == '.':
if parent is not __UNDEF__:
value = getattr(parent, token, __UNDEF__)
vars.append((prefix + token, prefix, value))
else:
where, value = lookup(token, frame, locals)
vars.append((token, where, value))
elif token == '.':
prefix += lasttoken + '.'
parent = value
else:
parent, prefix = None, ''
lasttoken = token
return vars
def html(einfo, context=5):
"""Return a nice HTML document describing a given traceback."""
etype, evalue, etb = einfo
if isinstance(etype, type):
etype = etype.__name__
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())
head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
'<big><big>%s</big></big>' %
strong(pydoc.html.escape(str(etype))),
'#ffffff', '#6622aa', pyver + '<br>' + date) + '''
<p>A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.</p>'''
indent = '<tt>' + small(' ' * 5) + ' </tt>'
frames = []
records = inspect.getinnerframes(etb, context)
for frame, file, lnum, func, lines, index in records:
if file:
file = os.path.abspath(file)
link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
else:
file = link = '?'
args, varargs, varkw, locals = inspect.getargvalues(frame)
call = ''
if func != '?':
call = 'in ' + strong(func) + \
inspect.formatargvalues(args, varargs, varkw, locals,
formatvalue=lambda value: '=' + pydoc.html.repr(value))
highlight = {}
def reader(lnum=[lnum]):
highlight[lnum[0]] = 1
try: return linecache.getline(file, lnum[0])
finally: lnum[0] += 1
vars = scanvars(reader, frame, locals)
rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
('<big> </big>', link, call)]
if index is not None:
i = lnum - index
for line in lines:
num = small(' ' * (5-len(str(i))) + str(i)) + ' '
if i in highlight:
line = '<tt>=>%s%s</tt>' % (num, pydoc.html.preformat(line))
rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
else:
line = '<tt> %s%s</tt>' % (num, pydoc.html.preformat(line))
rows.append('<tr><td>%s</td></tr>' % grey(line))
i += 1
done, dump = {}, []
for name, where, value in vars:
if name in done: continue
done[name] = 1
if value is not __UNDEF__:
if where in ('global', 'builtin'):
name = ('<em>%s</em> ' % where) + strong(name)
elif where == 'local':
name = strong(name)
else:
name = where + strong(name.split('.')[-1])
dump.append('%s = %s' % (name, pydoc.html.repr(value)))
else:
dump.append(name + ' <em>undefined</em>')
rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
frames.append('''
<table width="100%%" cellspacing=0 cellpadding=0 border=0>
%s</table>''' % '\n'.join(rows))
exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
pydoc.html.escape(str(evalue)))]
for name in dir(evalue):
if name[:1] == '_': continue
value = pydoc.html.repr(getattr(evalue, name))
exception.append('\n<br>%s%s =\n%s' % (indent, name, value))
return head + ''.join(frames) + ''.join(exception) + '''
<!-- The above is a description of an error in a Python program, formatted
for a Web browser because the 'cgitb' module was enabled. In case you
are not reading this in a Web browser, here is the original traceback:
%s
-->
''' % pydoc.html.escape(
''.join(traceback.format_exception(etype, evalue, etb)))
def text(einfo, context=5):
"""Return a plain text document describing a given traceback."""
etype, evalue, etb = einfo
if isinstance(etype, type):
etype = etype.__name__
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())
head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.
'''
frames = []
records = inspect.getinnerframes(etb, context)
for frame, file, lnum, func, lines, index in records:
file = file and os.path.abspath(file) or '?'
args, varargs, varkw, locals = inspect.getargvalues(frame)
call = ''
if func != '?':
call = 'in ' + func + \
inspect.formatargvalues(args, varargs, varkw, locals,
formatvalue=lambda value: '=' + pydoc.text.repr(value))
highlight = {}
def reader(lnum=[lnum]):
highlight[lnum[0]] = 1
try: return linecache.getline(file, lnum[0])
finally: lnum[0] += 1
vars = scanvars(reader, frame, locals)
rows = [' %s %s' % (file, call)]
if index is not None:
i = lnum - index
for line in lines:
num = '%5d ' % i
rows.append(num+line.rstrip())
i += 1
done, dump = {}, []
for name, where, value in vars:
if name in done: continue
done[name] = 1
if value is not __UNDEF__:
if where == 'global': name = 'global ' + name
elif where != 'local': name = where + name.split('.')[-1]
dump.append('%s = %s' % (name, pydoc.text.repr(value)))
else:
dump.append(name + ' undefined')
rows.append('\n'.join(dump))
frames.append('\n%s\n' % '\n'.join(rows))
exception = ['%s: %s' % (str(etype), str(evalue))]
for name in dir(evalue):
value = pydoc.text.repr(getattr(evalue, name))
exception.append('\n%s%s = %s' % (" "*4, name, value))
return head + ''.join(frames) + ''.join(exception) + '''
The above is a description of an error in a Python program. Here is
the original traceback:
%s
''' % ''.join(traceback.format_exception(etype, evalue, etb))
class Hook:
"""A hook to replace sys.excepthook that shows tracebacks in HTML."""
def __init__(self, display=1, logdir=None, context=5, file=None,
format="html"):
self.display = display # send tracebacks to browser if true
self.logdir = logdir # log tracebacks to files if not None
self.context = context # number of source code lines per frame
self.file = file or sys.stdout # place to send the output
self.format = format
def __call__(self, etype, evalue, etb):
self.handle((etype, evalue, etb))
def handle(self, info=None):
info = info or sys.exc_info()
if self.format == "html":
self.file.write(reset())
formatter = (self.format=="html") and html or text
plain = False
try:
doc = formatter(info, self.context)
except: # just in case something goes wrong
doc = ''.join(traceback.format_exception(*info))
plain = True
if self.display:
if plain:
doc = doc.replace('&', '&').replace('<', '<')
self.file.write('<pre>' + doc + '</pre>\n')
else:
self.file.write(doc + '\n')
else:
self.file.write('<p>A problem occurred in a Python script.\n')
if self.logdir is not None:
suffix = ['.txt', '.html'][self.format=="html"]
(fd, path) = tempfile.mkstemp(suffix=suffix, dir=self.logdir)
try:
file = os.fdopen(fd, 'w')
file.write(doc)
file.close()
msg = '<p> %s contains the description of this error.' % path
except:
msg = '<p> Tried to save traceback to %s, but failed.' % path
self.file.write(msg + '\n')
try:
self.file.flush()
except: pass
handler = Hook().handle
def enable(display=1, logdir=None, context=5, format="html"):
"""Install an exception handler that formats tracebacks as HTML.
The optional argument 'display' can be set to 0 to suppress sending the
traceback to the browser, and 'logdir' can be set to a directory to cause
tracebacks to be written to files there."""
sys.excepthook = Hook(display=display, logdir=logdir,
context=context, format=format)
| lgpl-3.0 |
AlexOugh/horizon | openstack_dashboard/dashboards/project/data_processing/job_binaries/tabs.py | 38 | 1474 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from openstack_dashboard.api import sahara as saharaclient
LOG = logging.getLogger(__name__)
class JobBinaryDetailsTab(tabs.Tab):
name = _("General Info")
slug = "job_binaries_details_tab"
template_name = ("project/data_processing.job_binaries/_details.html")
def get_context_data(self, request):
job_binary_id = self.tab_group.kwargs['job_binary_id']
try:
job_binary = saharaclient.job_binary_get(request, job_binary_id)
except Exception:
job_binary = {}
exceptions.handle(request,
_("Unable to fetch job binary."))
return {"job_binary": job_binary}
class JobBinaryDetailsTabs(tabs.TabGroup):
slug = "job_binary_details"
tabs = (JobBinaryDetailsTab,)
sticky = True
| apache-2.0 |
direvus/ansible | lib/ansible/modules/network/f5/bigip_smtp.py | 8 | 16396 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: bigip_smtp
short_description: Manages SMTP settings on the BIG-IP
description:
- Allows configuring of the BIG-IP to send mail via an SMTP server by
configuring the parameters of an SMTP server.
version_added: 2.6
options:
name:
description:
- Specifies the name of the SMTP server configuration.
required: True
partition:
description:
- Device partition to manage resources on.
default: Common
smtp_server:
description:
- SMTP server host name in the format of a fully qualified domain name.
- This value is required when create a new SMTP configuration.
smtp_server_port:
description:
- Specifies the SMTP port number.
- When creating a new SMTP configuration, the default is C(25) when
C(encryption) is C(none) or C(tls). The default is C(465) when C(ssl)
is selected.
local_host_name:
description:
- Host name used in SMTP headers in the format of a fully qualified
domain name. This setting does not refer to the BIG-IP system's hostname.
from_address:
description:
- Email address that the email is being sent from. This is the "Reply-to"
address that the recipient sees.
encryption:
description:
- Specifies whether the SMTP server requires an encrypted connection in
order to send mail.
choices:
- none
- ssl
- tls
authentication:
description:
- Credentials can be set on an SMTP server's configuration even if that
authentication is not used (think staging configs or emergency changes).
This parameter acts as a switch to make the specified C(smtp_server_username)
and C(smtp_server_password) parameters active or not.
- When C(yes), the authentication parameters will be active.
- When C(no), the authentication parameters will be inactive.
type: bool
smtp_server_username:
description:
- User name that the SMTP server requires when validating a user.
smtp_server_password:
description:
- Password that the SMTP server requires when validating a user.
state:
description:
- When C(present), ensures that the SMTP configuration exists.
- When C(absent), ensures that the SMTP configuration does not exist.
required: False
default: present
choices:
- present
- absent
update_password:
description:
- Passwords are stored encrypted, so the module cannot know if the supplied
C(smtp_server_password) is the same or different than the existing password.
This parameter controls the updating of the C(smtp_server_password)
credential.
- When C(always), will always update the password.
- When C(on_create), will only set the password for newly created SMTP server
configurations.
default: always
choices:
- always
- on_create
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = r'''
- name: Create a base SMTP server configuration
bigip_smtp:
name: my-smtp
smtp_server: 1.1.1.1
smtp_server_username: mail-admin
smtp_server_password: mail-secret
local_host_name: smtp.mydomain.com
from_address: no-reply@mydomain.com
password: secret
server: lb.mydomain.com
state: present
user: admin
delegate_to: localhost
'''
RETURN = r'''
smtp_server:
description: The new C(smtp_server) value of the SMTP configuration.
returned: changed
type: string
sample: mail.mydomain.com
smtp_server_port:
description: The new C(smtp_server_port) value of the SMTP configuration.
returned: changed
type: int
sample: 25
local_host_name:
description: The new C(local_host_name) value of the SMTP configuration.
returned: changed
type: string
sample: smtp.mydomain.com
from_address:
description: The new C(from_address) value of the SMTP configuration.
returned: changed
type: string
sample: no-reply@mydomain.com
encryption:
description: The new C(encryption) value of the SMTP configuration.
returned: changed
type: string
sample: tls
authentication:
description: Whether the authentication parameters are active or not.
returned: changed
type: bool
sample: yes
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
try:
from library.module_utils.network.f5.bigip import HAS_F5SDK
from library.module_utils.network.f5.bigip import F5Client
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import is_valid_hostname
from library.module_utils.network.f5.common import f5_argument_spec
from library.module_utils.network.f5.ipaddress import is_valid_ip
try:
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
except ImportError:
HAS_F5SDK = False
except ImportError:
from ansible.module_utils.network.f5.bigip import HAS_F5SDK
from ansible.module_utils.network.f5.bigip import F5Client
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import is_valid_hostname
from ansible.module_utils.network.f5.common import f5_argument_spec
from ansible.module_utils.network.f5.ipaddress import is_valid_ip
try:
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
except ImportError:
HAS_F5SDK = False
class Parameters(AnsibleF5Parameters):
api_map = {
'username': 'smtp_server_username',
'passwordEncrypted': 'smtp_server_password',
'localHostName': 'local_host_name',
'smtpServerHostName': 'smtp_server',
'smtpServerPort': 'smtp_server_port',
'encryptedConnection': 'encryption',
'authenticationEnabled': 'authentication_enabled',
'authenticationDisabled': 'authentication_disabled',
'fromAddress': 'from_address'
}
api_attributes = [
'username', 'passwordEncrypted', 'localHostName', 'smtpServerHostName',
'smtpServerPort', 'encryptedConnection', 'authenticationEnabled',
'authenticationDisabled', 'fromAddress'
]
returnables = [
'smtp_server_username', 'smtp_server_password', 'local_host_name',
'smtp_server', 'smtp_server_port', 'encryption', 'authentication',
'from_address'
]
updatables = [
'smtp_server_username', 'smtp_server_password', 'local_host_name',
'smtp_server', 'smtp_server_port', 'encryption', 'authentication',
'from_address'
]
class ApiParameters(Parameters):
pass
class ModuleParameters(Parameters):
@property
def local_host_name(self):
if self._values['local_host_name'] is None:
return None
if is_valid_ip(self._values['local_host_name']):
return self._values['local_host_name']
elif is_valid_hostname(self._values['local_host_name']):
# else fallback to checking reasonably well formatted hostnames
return str(self._values['local_host_name'])
raise F5ModuleError(
"The provided 'local_host_name' value {0} is not a valid IP or hostname".format(
str(self._values['local_host_name'])
)
)
@property
def authentication_enabled(self):
if self._values['authentication'] is None:
return None
if self._values['authentication']:
return True
@property
def authentication_disabled(self):
if self._values['authentication'] is None:
return None
if not self._values['authentication']:
return True
@property
def smtp_server_port(self):
if self._values['smtp_server_port'] is None:
return None
return int(self._values['smtp_server_port'])
class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class UsableChanges(Changes):
pass
class ReportableChanges(Changes):
@property
def smtp_server_password(self):
return None
@property
def smtp_server_username(self):
return None
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
@property
def smtp_server_password(self):
if self.want.update_password == 'on_create':
return None
return self.want.smtp_server_password
@property
def authentication(self):
if self.want.authentication_enabled:
if self.want.authentication_enabled != self.have.authentication_enabled:
return dict(
authentication_enabled=self.want.authentication_enabled
)
if self.want.authentication_disabled:
if self.want.authentication_disabled != self.have.authentication_disabled:
return dict(
authentication_disable=self.want.authentication_disabled
)
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.want = ModuleParameters(params=self.module.params)
self.have = ApiParameters()
self.changes = UsableChanges()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def exec_module(self):
changed = False
result = dict()
state = self.want.state
try:
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def exists(self):
result = self.client.api.tm.sys.smtp_servers.smtp_server.exists(
name=self.want.name,
partition=self.want.partition
)
return result
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def remove(self):
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource.")
return True
def create(self):
self._set_changed_options()
if self.module.check_mode:
return True
self.create_on_device()
return True
def create_on_device(self):
params = self.want.api_params()
self.client.api.tm.sys.smtp_servers.smtp_server.create(
name=self.want.name,
partition=self.want.partition,
**params
)
def update_on_device(self):
params = self.want.api_params()
resource = self.client.api.tm.sys.smtp_servers.smtp_server.load(
name=self.want.name,
partition=self.want.partition
)
resource.modify(**params)
def absent(self):
if self.exists():
return self.remove()
return False
def remove_from_device(self):
resource = self.client.api.tm.sys.smtp_servers.smtp_server.load(
name=self.want.name,
partition=self.want.partition
)
if resource:
resource.delete()
def read_current_from_device(self):
resource = self.client.api.tm.sys.smtp_servers.smtp_server.load(
name=self.want.name,
partition=self.want.partition
)
result = resource.attrs
return ApiParameters(params=result)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
name=dict(required=True),
smtp_server=dict(),
smtp_server_port=dict(type='int'),
smtp_server_username=dict(no_log=True),
smtp_server_password=dict(no_log=True),
local_host_name=dict(),
encryption=dict(choices=['none', 'ssl', 'tls']),
update_password=dict(
default='always',
choices=['always', 'on_create']
),
from_address=dict(),
authentication=dict(type='bool'),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
),
state=dict(
default='present',
choices=['present', 'absent']
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
try:
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
module.fail_json(msg=str(ex))
if __name__ == '__main__':
main()
| gpl-3.0 |
googleapis/googleapis-gen | google/ads/googleads/v6/googleads-py/google/ads/googleads/v6/enums/types/google_ads_field_data_type.py | 1 | 1368 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package='google.ads.googleads.v6.enums',
marshal='google.ads.googleads.v6',
manifest={
'GoogleAdsFieldDataTypeEnum',
},
)
class GoogleAdsFieldDataTypeEnum(proto.Message):
r"""Container holding the various data types. """
class GoogleAdsFieldDataType(proto.Enum):
r"""These are the various types a GoogleAdsService artifact may
take on.
"""
UNSPECIFIED = 0
UNKNOWN = 1
BOOLEAN = 2
DATE = 3
DOUBLE = 4
ENUM = 5
FLOAT = 6
INT32 = 7
INT64 = 8
MESSAGE = 9
RESOURCE_NAME = 10
STRING = 11
UINT64 = 12
__all__ = tuple(sorted(__protobuf__.manifest))
| apache-2.0 |
photoninger/ansible | lib/ansible/module_utils/univention_umc.py | 118 | 8767 | # -*- coding: UTF-8 -*-
# This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Copyright (c) 2016, Adfinis SyGroup AG
# Tobias Rueetschi <tobias.ruetschi@adfinis-sygroup.ch>
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
"""Univention Corporate Server (UCS) access module.
Provides the following functions for working with an UCS server.
- ldap_search(filter, base=None, attr=None)
Search the LDAP via Univention's LDAP wrapper (ULDAP)
- config_registry()
Return the UCR registry object
- base_dn()
Return the configured Base DN according to the UCR
- uldap()
Return a handle to the ULDAP LDAP wrapper
- umc_module_for_add(module, container_dn, superordinate=None)
Return a UMC module for creating a new object of the given type
- umc_module_for_edit(module, object_dn, superordinate=None)
Return a UMC module for editing an existing object of the given type
Any other module is not part of the "official" API and may change at any time.
"""
import re
__all__ = [
'ldap_search',
'config_registry',
'base_dn',
'uldap',
'umc_module_for_add',
'umc_module_for_edit',
]
_singletons = {}
def ldap_module():
import ldap as orig_ldap
return orig_ldap
def _singleton(name, constructor):
if name in _singletons:
return _singletons[name]
_singletons[name] = constructor()
return _singletons[name]
def config_registry():
def construct():
import univention.config_registry
ucr = univention.config_registry.ConfigRegistry()
ucr.load()
return ucr
return _singleton('config_registry', construct)
def base_dn():
return config_registry()['ldap/base']
def uldap():
"Return a configured univention uldap object"
def construct():
try:
secret_file = open('/etc/ldap.secret', 'r')
bind_dn = 'cn=admin,{0}'.format(base_dn())
except IOError: # pragma: no cover
secret_file = open('/etc/machine.secret', 'r')
bind_dn = config_registry()["ldap/hostdn"]
pwd_line = secret_file.readline()
pwd = re.sub('\n', '', pwd_line)
import univention.admin.uldap
return univention.admin.uldap.access(
host=config_registry()['ldap/master'],
base=base_dn(),
binddn=bind_dn,
bindpw=pwd,
start_tls=1,
)
return _singleton('uldap', construct)
def config():
def construct():
import univention.admin.config
return univention.admin.config.config()
return _singleton('config', construct)
def init_modules():
def construct():
import univention.admin.modules
univention.admin.modules.update()
return True
return _singleton('modules_initialized', construct)
def position_base_dn():
def construct():
import univention.admin.uldap
return univention.admin.uldap.position(base_dn())
return _singleton('position_base_dn', construct)
def ldap_dn_tree_parent(dn, count=1):
dn_array = dn.split(',')
dn_array[0:count] = []
return ','.join(dn_array)
def ldap_search(filter, base=None, attr=None):
"""Replaces uldaps search and uses a generator.
!! Arguments are not the same."""
if base is None:
base = base_dn()
msgid = uldap().lo.lo.search(
base,
ldap_module().SCOPE_SUBTREE,
filterstr=filter,
attrlist=attr
)
# I used to have a try: finally: here but there seems to be a bug in python
# which swallows the KeyboardInterrupt
# The abandon now doesn't make too much sense
while True:
result_type, result_data = uldap().lo.lo.result(msgid, all=0)
if not result_data:
break
if result_type is ldap_module().RES_SEARCH_RESULT: # pragma: no cover
break
else:
if result_type is ldap_module().RES_SEARCH_ENTRY:
for res in result_data:
yield res
uldap().lo.lo.abandon(msgid)
def module_by_name(module_name_):
"""Returns an initialized UMC module, identified by the given name.
The module is a module specification according to the udm commandline.
Example values are:
* users/user
* shares/share
* groups/group
If the module does not exist, a KeyError is raised.
The modules are cached, so they won't be re-initialized
in subsequent calls.
"""
def construct():
import univention.admin.modules
init_modules()
module = univention.admin.modules.get(module_name_)
univention.admin.modules.init(uldap(), position_base_dn(), module)
return module
return _singleton('module/%s' % module_name_, construct)
def get_umc_admin_objects():
"""Convenience accessor for getting univention.admin.objects.
This implements delayed importing, so the univention.* modules
are not loaded until this function is called.
"""
import univention.admin
return univention.admin.objects
def umc_module_for_add(module, container_dn, superordinate=None):
"""Returns an UMC module object prepared for creating a new entry.
The module is a module specification according to the udm commandline.
Example values are:
* users/user
* shares/share
* groups/group
The container_dn MUST be the dn of the container (not of the object to
be created itself!).
"""
mod = module_by_name(module)
position = position_base_dn()
position.setDn(container_dn)
# config, ldap objects from common module
obj = mod.object(config(), uldap(), position, superordinate=superordinate)
obj.open()
return obj
def umc_module_for_edit(module, object_dn, superordinate=None):
"""Returns an UMC module object prepared for editing an existing entry.
The module is a module specification according to the udm commandline.
Example values are:
* users/user
* shares/share
* groups/group
The object_dn MUST be the dn of the object itself, not the container!
"""
mod = module_by_name(module)
objects = get_umc_admin_objects()
position = position_base_dn()
position.setDn(ldap_dn_tree_parent(object_dn))
obj = objects.get(
mod,
config(),
uldap(),
position=position,
superordinate=superordinate,
dn=object_dn
)
obj.open()
return obj
def create_containers_and_parents(container_dn):
"""Create a container and if needed the parents containers"""
import univention.admin.uexceptions as uexcp
if not container_dn.startswith("cn="):
raise AssertionError()
try:
parent = ldap_dn_tree_parent(container_dn)
obj = umc_module_for_add(
'container/cn',
parent
)
obj['name'] = container_dn.split(',')[0].split('=')[1]
obj['description'] = "container created by import"
except uexcp.ldapError:
create_containers_and_parents(parent)
obj = umc_module_for_add(
'container/cn',
parent
)
obj['name'] = container_dn.split(',')[0].split('=')[1]
obj['description'] = "container created by import"
| gpl-3.0 |
SyncFree/riak_pb | msgcodegen.py | 7 | 9369 | # Copyright 2014 Basho Technologies, Inc.
#
# This file is provided to you under the Apache License,
# Version 2.0 (the "License"); you may not use this file
# except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
distutils commands for generating protocol message-code mappings.
"""
__all__ = ['build_messages', 'clean_messages']
import re
import csv
import os
from os.path import isfile
from distutils import log
from distutils.core import Command
from distutils.file_util import write_file
from datetime import date
LICENSE = """# Copyright {0} Basho Technologies, Inc.
#
# This file is provided to you under the Apache License,
# Version 2.0 (the "License"); you may not use this file
# except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""".format(date.today().year)
class ComparableMixin(object):
def _compare(self, other, method):
try:
return method(self._cmpkey(), other._cmpkey())
except (AttributeError, TypeError):
# _cmpkey not implemented, or return different type,
# so I can't compare with "other".
return NotImplemented
def __lt__(self, other):
return self._compare(other, lambda s, o: s < o)
def __le__(self, other):
return self._compare(other, lambda s, o: s <= o)
def __eq__(self, other):
return self._compare(other, lambda s, o: s == o)
def __ge__(self, other):
return self._compare(other, lambda s, o: s >= o)
def __gt__(self, other):
return self._compare(other, lambda s, o: s > o)
def __ne__(self, other):
return self._compare(other, lambda s, o: s != o)
class MessageCodeMapping(ComparableMixin):
def __init__(self, code, message, proto):
self.code = int(code)
self.message = message
self.proto = proto
self.message_code_name = self._message_code_name()
self.module_name = 'riak_pb.{0}_pb2'.format(self.proto)
self.message_class = self._message_class()
def _cmpkey(self):
return self.code
def __hash__(self):
return self.code
def _message_code_name(self):
strip_rpb = re.sub(r"^Rpb", "", self.message)
word = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', strip_rpb)
word = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', word)
word = word.replace("-", "_")
return "MSG_CODE_" + word.upper()
def _message_class(self):
try:
pbmod = __import__(self.module_name, globals(), locals(),
[self.message])
klass = pbmod.__dict__[self.message]
return klass
except KeyError:
log.debug("Did not find '{0}' message class in module '{1}'",
self.message, self.module_name)
except ImportError:
log.debug("Could not import module '{0}'", self.module_name)
return None
class clean_messages(Command):
"""
Cleans generated message code mappings. Add to the build process
using::
setup(cmd_class={'clean_messages': clean_messages})
"""
description = "clean generated protocol message code mappings"
user_options = [
('destination=', None, 'destination Python source file')
]
def initialize_options(self):
self.destination = None
def finalize_options(self):
self.set_undefined_options('build_messages',
('destination', 'destination'))
def run(self):
if isfile(self.destination):
self.execute(os.remove, [self.destination],
msg="removing {0}".format(self.destination))
class build_messages(Command):
"""
Generates message code mappings. Add to the build process using::
setup(cmd_class={'build_messages': build_messages})
"""
description = "generate protocol message code mappings"
user_options = [
('source=', None, 'source CSV file containing message code mappings'),
('destination=', None, 'destination Python source file')
]
# Used in loading and generating
_pb_imports = set()
_messages = set()
_linesep = os.linesep
_indented_item_sep = ',{0} '.format(_linesep)
_docstring = [
''
'# This is a generated file. DO NOT EDIT.',
'',
'"""',
'Constants and mappings between Riak protocol codes and messages.',
'"""',
''
]
def initialize_options(self):
self.source = None
self.destination = None
self.update_import = None
def finalize_options(self):
if self.source is None:
self.source = 'src/riak_pb_messages.csv'
if self.destination is None:
self.destination = 'riak_pb/messages.py'
def run(self):
self.make_file(self.source, self.destination,
self._load_and_generate, [])
def _load_and_generate(self):
self._format_python2_or_3()
self._load()
self._generate()
def _load(self):
with open(self.source, 'r', buffering=1) as csvfile:
reader = csv.reader(csvfile)
for row in reader:
message = MessageCodeMapping(*row)
self._messages.add(message)
self._pb_imports.add(message.module_name)
def _generate(self):
self._contents = []
self._generate_doc()
self._generate_imports()
self._generate_codes()
self._generate_classes()
write_file(self.destination, self._contents)
def _generate_doc(self):
# Write the license and docstring header
self._contents.append(LICENSE)
self._contents.extend(self._docstring)
def _generate_imports(self):
# Write imports
for im in sorted(self._pb_imports):
self._contents.append("import {0}".format(im))
def _generate_codes(self):
# Write protocol code constants
self._contents.extend(['', "# Protocol codes"])
for message in sorted(self._messages):
self._contents.append("{0} = {1}".format(message.message_code_name,
message.code))
def _generate_classes(self):
# Write message classes
classes = [self._generate_mapping(message)
for message in sorted(self._messages)]
classes = self._indented_item_sep.join(classes)
self._contents.extend(['',
"# Mapping from code to protobuf class",
'MESSAGE_CLASSES = {',
' ' + classes,
'}'])
def _generate_mapping(self, m):
if m.message_class is not None:
klass = "{0}.{1}".format(m.module_name,
m.message_class.__name__)
else:
klass = "None"
pair = "{0}: {1}".format(m.message_code_name, klass)
if len(pair) > 76:
# Try to satisfy PEP8, lulz
pair = (self._linesep + ' ').join(pair.split(' '))
return pair
def _format_python2_or_3(self):
"""
Change the PB files to use full pathnames for Python 3.x
and modify the metaclasses to be version agnostic
"""
pb_files = set()
with open(self.source, 'r', buffering=1) as csvfile:
reader = csv.reader(csvfile)
for row in reader:
_, _, proto = row
pb_files.add('riak_pb/{0}_pb2.py'.format(proto))
for im in sorted(pb_files):
with open(im, 'r', buffering=1) as pbfile:
contents = 'from six import *\n' + pbfile.read()
contents = re.sub(r'riak_pb2',
r'riak_pb.riak_pb2',
contents)
# Look for this pattern in the protoc-generated file:
#
# class RpbCounterGetResp(_message.Message):
# __metaclass__ = _reflection.GeneratedProtocolMessageType
#
# and convert it to:
#
# @add_metaclass(_reflection.GeneratedProtocolMessageType)
# class RpbCounterGetResp(_message.Message):
contents = re.sub(
r'class\s+(\S+)\((\S+)\):\s*\n'
'\s+__metaclass__\s+=\s+(\S+)\s*\n',
r'@add_metaclass(\3)\nclass \1(\2):\n', contents)
with open(im, 'w', buffering=1) as pbfile:
pbfile.write(contents)
| apache-2.0 |
sbalde/edx-platform | lms/djangoapps/verify_student/tests/fake_software_secure.py | 29 | 1657 | """
Fake Software Secure page for use in acceptance tests.
"""
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from edxmako.shortcuts import render_to_response
from verify_student.models import SoftwareSecurePhotoVerification
class SoftwareSecureFakeView(View):
"""
Fake SoftwareSecure view for testing different photo verification statuses
and email functionality.
"""
@method_decorator(login_required)
def get(self, request):
"""
Render a fake Software Secure page that will pick the most recent
attempt for a given user and pass it to the html page.
"""
context_dict = self.response_post_params(request.user)
return render_to_response("verify_student/test/fake_softwaresecure_response.html", context_dict)
@classmethod
def response_post_params(cls, user):
"""
Calculate the POST params we want to send back to the client.
"""
access_key = settings.VERIFY_STUDENT["SOFTWARE_SECURE"]["API_ACCESS_KEY"]
context = {
'receipt_id': None,
'authorization_code': 'SIS {}:0000'.format(access_key),
'results_callback': reverse('verify_student_results_callback')
}
try:
most_recent = SoftwareSecurePhotoVerification.original_verification(user)
context["receipt_id"] = most_recent.receipt_id
except: # pylint: disable=bare-except
pass
return context
| agpl-3.0 |
lgscofield/odoo | addons/account_followup/tests/test_account_followup.py | 247 | 10222 | import datetime
from openerp import tools
from openerp.tests.common import TransactionCase
from openerp.osv import fields
class TestAccountFollowup(TransactionCase):
def setUp(self):
""" setUp ***"""
super(TestAccountFollowup, self).setUp()
cr, uid = self.cr, self.uid
self.user = self.registry('res.users')
self.user_id = self.user.browse(cr, uid, uid)
self.partner = self.registry('res.partner')
self.invoice = self.registry('account.invoice')
self.invoice_line = self.registry('account.invoice.line')
self.wizard = self.registry('account_followup.print')
self.followup_id = self.registry('account_followup.followup')
self.partner_id = self.partner.create(cr, uid, {'name':'Test Company',
'email':'test@localhost',
'is_company': True,
},
context=None)
self.followup_id = self.registry("ir.model.data").get_object_reference(cr, uid, "account_followup", "demo_followup1")[1]
self.account_id = self.registry("ir.model.data").get_object_reference(cr, uid, "account", "a_recv")[1]
self.journal_id = self.registry("ir.model.data").get_object_reference(cr, uid, "account", "bank_journal")[1]
self.pay_account_id = self.registry("ir.model.data").get_object_reference(cr, uid, "account", "cash")[1]
self.period_id = self.registry("ir.model.data").get_object_reference(cr, uid, "account", "period_10")[1]
self.first_followup_line_id = self.registry("ir.model.data").get_object_reference(cr, uid, "account_followup", "demo_followup_line1")[1]
self.last_followup_line_id = self.registry("ir.model.data").get_object_reference(cr, uid, "account_followup", "demo_followup_line3")[1]
self.product_id = self.registry("ir.model.data").get_object_reference(cr, uid, "product", "product_product_6")[1]
self.invoice_id = self.invoice.create(cr, uid, {'partner_id': self.partner_id,
'account_id': self.account_id,
'journal_id': self.journal_id,
'invoice_line': [(0, 0, {
'name': "LCD Screen",
'product_id': self.product_id,
'quantity': 5,
'price_unit':200
})]})
self.registry('account.invoice').signal_workflow(cr, uid, [self.invoice_id], 'invoice_open')
self.voucher = self.registry("account.voucher")
self.current_date = datetime.datetime.strptime(fields.date.context_today(self.user, cr, uid, context={}), tools.DEFAULT_SERVER_DATE_FORMAT)
def test_00_send_followup_after_3_days(self):
""" Send follow up after 3 days and check nothing is done (as first follow-up level is only after 15 days)"""
cr, uid = self.cr, self.uid
delta = datetime.timedelta(days=3)
result = self.current_date + delta
self.wizard_id = self.wizard.create(cr, uid, {'date':result.strftime(tools.DEFAULT_SERVER_DATE_FORMAT),
'followup_id': self.followup_id
}, context={"followup_id": self.followup_id})
self.wizard.do_process(cr, uid, [self.wizard_id], context={"followup_id": self.followup_id})
self.assertFalse(self.partner.browse(cr, uid, self.partner_id).latest_followup_level_id)
def run_wizard_three_times(self):
cr, uid = self.cr, self.uid
delta = datetime.timedelta(days=40)
result = self.current_date + delta
result = self.current_date + delta
self.wizard_id = self.wizard.create(cr, uid, {'date':result.strftime(tools.DEFAULT_SERVER_DATE_FORMAT),
'followup_id': self.followup_id
}, context={"followup_id": self.followup_id})
self.wizard.do_process(cr, uid, [self.wizard_id], context={"followup_id": self.followup_id})
self.wizard_id = self.wizard.create(cr, uid, {'date':result.strftime(tools.DEFAULT_SERVER_DATE_FORMAT),
'followup_id': self.followup_id
}, context={"followup_id": self.followup_id})
self.wizard.do_process(cr, uid, [self.wizard_id], context={"followup_id": self.followup_id})
self.wizard_id = self.wizard.create(cr, uid, {'date':result.strftime(tools.DEFAULT_SERVER_DATE_FORMAT),
'followup_id': self.followup_id,
}, context={"followup_id": self.followup_id})
self.wizard.do_process(cr, uid, [self.wizard_id], context={"followup_id": self.followup_id})
def test_01_send_followup_later_for_upgrade(self):
""" Send one follow-up after 15 days to check it upgrades to level 1"""
cr, uid = self.cr, self.uid
delta = datetime.timedelta(days=15)
result = self.current_date + delta
self.wizard_id = self.wizard.create(cr, uid, {
'date':result.strftime(tools.DEFAULT_SERVER_DATE_FORMAT),
'followup_id': self.followup_id
}, context={"followup_id": self.followup_id})
self.wizard.do_process(cr, uid, [self.wizard_id], context={"followup_id": self.followup_id})
self.assertEqual(self.partner.browse(cr, uid, self.partner_id).latest_followup_level_id.id, self.first_followup_line_id,
"Not updated to the correct follow-up level")
def test_02_check_manual_action(self):
""" Check that when running the wizard three times that the manual action is set"""
cr, uid = self.cr, self.uid
self.run_wizard_three_times()
self.assertEqual(self.partner.browse(cr, uid, self.partner_id).payment_next_action,
"Call the customer on the phone! ", "Manual action not set")
self.assertEqual(self.partner.browse(cr, uid, self.partner_id).payment_next_action_date,
self.current_date.strftime(tools.DEFAULT_SERVER_DATE_FORMAT))
def test_03_filter_on_credit(self):
""" Check the partners can be filtered on having credits """
cr, uid = self.cr, self.uid
ids = self.partner.search(cr, uid, [('payment_amount_due', '>', 0.0)])
self.assertIn(self.partner_id, ids)
def test_04_action_done(self):
""" Run the wizard 3 times, mark it as done, check the action fields are empty"""
cr, uid = self.cr, self.uid
partner_rec = self.partner.browse(cr, uid, self.partner_id)
self.run_wizard_three_times()
self.partner.action_done(cr, uid, self.partner_id)
self.assertFalse(partner_rec.payment_next_action, "Manual action not emptied")
self.assertFalse(partner_rec.payment_responsible_id)
self.assertFalse(partner_rec.payment_next_action_date)
def test_05_litigation(self):
""" Set the account move line as litigation, run the wizard 3 times and check nothing happened.
Turn litigation off. Run the wizard 3 times and check it is in the right follow-up level.
"""
cr, uid = self.cr, self.uid
aml_id = self.partner.browse(cr, uid, self.partner_id).unreconciled_aml_ids[0].id
self.registry('account.move.line').write(cr, uid, aml_id, {'blocked': True})
self.run_wizard_three_times()
self.assertFalse(self.partner.browse(cr, uid, self.partner_id).latest_followup_level_id, "Litigation does not work")
self.registry('account.move.line').write(cr, uid, aml_id, {'blocked': False})
self.run_wizard_three_times()
self.assertEqual(self.partner.browse(cr, uid, self.partner_id).latest_followup_level_id.id,
self.last_followup_line_id, "Lines are not equal")
def test_06_pay_the_invoice(self):
"""Run wizard until manual action, pay the invoice and check that partner has no follow-up level anymore and after running the wizard the action is empty"""
cr, uid = self.cr, self.uid
self.test_02_check_manual_action()
delta = datetime.timedelta(days=1)
result = self.current_date + delta
self.invoice.pay_and_reconcile(cr, uid, [self.invoice_id], 1000.0, self.pay_account_id,
self.period_id, self.journal_id, self.pay_account_id,
self.period_id, self.journal_id,
name = "Payment for test customer invoice follow-up")
self.assertFalse(self.partner.browse(cr, uid, self.partner_id).latest_followup_level_id, "Level not empty")
self.wizard_id = self.wizard.create(cr, uid, {'date':result.strftime(tools.DEFAULT_SERVER_DATE_FORMAT),
'followup_id': self.followup_id
}, context={"followup_id": self.followup_id})
self.wizard.do_process(cr, uid, [self.wizard_id], context={"followup_id": self.followup_id})
self.assertEqual(0, self.partner.browse(cr, uid, self.partner_id).payment_amount_due, "Amount Due != 0")
self.assertFalse(self.partner.browse(cr, uid, self.partner_id).payment_next_action_date, "Next action date not cleared")
| agpl-3.0 |
apbard/scipy | scipy/stats/_distn_infrastructure.py | 6 | 119658 | #
# Author: Travis Oliphant 2002-2011 with contributions from
# SciPy Developers 2004-2011
#
from __future__ import division, print_function, absolute_import
from scipy._lib.six import string_types, exec_, PY3
from scipy._lib._util import getargspec_no_self as _getargspec
import sys
import keyword
import re
import types
import warnings
from scipy.misc import doccer
from ._distr_params import distcont, distdiscrete
from scipy._lib._util import check_random_state, _lazywhere, _lazyselect
from scipy._lib._util import _valarray as valarray
from scipy.special import (comb, chndtr, entr, rel_entr, kl_div, xlogy, ive)
# for root finding for discrete distribution ppf, and max likelihood estimation
from scipy import optimize
# for functions of continuous distributions (e.g. moments, entropy, cdf)
from scipy import integrate
# to approximate the pdf of a continuous distribution given its cdf
from scipy.misc import derivative
from numpy import (arange, putmask, ravel, take, ones, shape, ndarray,
product, reshape, zeros, floor, logical_and, log, sqrt, exp)
from numpy import (place, argsort, argmax, vectorize,
asarray, nan, inf, isinf, NINF, empty)
import numpy as np
from ._constants import _XMAX
if PY3:
def instancemethod(func, obj, cls):
return types.MethodType(func, obj)
else:
instancemethod = types.MethodType
# These are the docstring parts used for substitution in specific
# distribution docstrings
docheaders = {'methods': """\nMethods\n-------\n""",
'notes': """\nNotes\n-----\n""",
'examples': """\nExamples\n--------\n"""}
_doc_rvs = """\
``rvs(%(shapes)s, loc=0, scale=1, size=1, random_state=None)``
Random variates.
"""
_doc_pdf = """\
``pdf(x, %(shapes)s, loc=0, scale=1)``
Probability density function.
"""
_doc_logpdf = """\
``logpdf(x, %(shapes)s, loc=0, scale=1)``
Log of the probability density function.
"""
_doc_pmf = """\
``pmf(k, %(shapes)s, loc=0, scale=1)``
Probability mass function.
"""
_doc_logpmf = """\
``logpmf(k, %(shapes)s, loc=0, scale=1)``
Log of the probability mass function.
"""
_doc_cdf = """\
``cdf(x, %(shapes)s, loc=0, scale=1)``
Cumulative distribution function.
"""
_doc_logcdf = """\
``logcdf(x, %(shapes)s, loc=0, scale=1)``
Log of the cumulative distribution function.
"""
_doc_sf = """\
``sf(x, %(shapes)s, loc=0, scale=1)``
Survival function (also defined as ``1 - cdf``, but `sf` is sometimes more accurate).
"""
_doc_logsf = """\
``logsf(x, %(shapes)s, loc=0, scale=1)``
Log of the survival function.
"""
_doc_ppf = """\
``ppf(q, %(shapes)s, loc=0, scale=1)``
Percent point function (inverse of ``cdf`` --- percentiles).
"""
_doc_isf = """\
``isf(q, %(shapes)s, loc=0, scale=1)``
Inverse survival function (inverse of ``sf``).
"""
_doc_moment = """\
``moment(n, %(shapes)s, loc=0, scale=1)``
Non-central moment of order n
"""
_doc_stats = """\
``stats(%(shapes)s, loc=0, scale=1, moments='mv')``
Mean('m'), variance('v'), skew('s'), and/or kurtosis('k').
"""
_doc_entropy = """\
``entropy(%(shapes)s, loc=0, scale=1)``
(Differential) entropy of the RV.
"""
_doc_fit = """\
``fit(data, %(shapes)s, loc=0, scale=1)``
Parameter estimates for generic data.
"""
_doc_expect = """\
``expect(func, args=(%(shapes_)s), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)``
Expected value of a function (of one argument) with respect to the distribution.
"""
_doc_expect_discrete = """\
``expect(func, args=(%(shapes_)s), loc=0, lb=None, ub=None, conditional=False)``
Expected value of a function (of one argument) with respect to the distribution.
"""
_doc_median = """\
``median(%(shapes)s, loc=0, scale=1)``
Median of the distribution.
"""
_doc_mean = """\
``mean(%(shapes)s, loc=0, scale=1)``
Mean of the distribution.
"""
_doc_var = """\
``var(%(shapes)s, loc=0, scale=1)``
Variance of the distribution.
"""
_doc_std = """\
``std(%(shapes)s, loc=0, scale=1)``
Standard deviation of the distribution.
"""
_doc_interval = """\
``interval(alpha, %(shapes)s, loc=0, scale=1)``
Endpoints of the range that contains alpha percent of the distribution
"""
_doc_allmethods = ''.join([docheaders['methods'], _doc_rvs, _doc_pdf,
_doc_logpdf, _doc_cdf, _doc_logcdf, _doc_sf,
_doc_logsf, _doc_ppf, _doc_isf, _doc_moment,
_doc_stats, _doc_entropy, _doc_fit,
_doc_expect, _doc_median,
_doc_mean, _doc_var, _doc_std, _doc_interval])
_doc_default_longsummary = """\
As an instance of the `rv_continuous` class, `%(name)s` object inherits from it
a collection of generic methods (see below for the full list),
and completes them with details specific for this particular distribution.
"""
_doc_default_frozen_note = """
Alternatively, the object may be called (as a function) to fix the shape,
location, and scale parameters returning a "frozen" continuous RV object:
rv = %(name)s(%(shapes)s, loc=0, scale=1)
- Frozen RV object with the same methods but holding the given shape,
location, and scale fixed.
"""
_doc_default_example = """\
Examples
--------
>>> from scipy.stats import %(name)s
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(1, 1)
Calculate a few first moments:
%(set_vals_stmt)s
>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')
Display the probability density function (``pdf``):
>>> x = np.linspace(%(name)s.ppf(0.01, %(shapes)s),
... %(name)s.ppf(0.99, %(shapes)s), 100)
>>> ax.plot(x, %(name)s.pdf(x, %(shapes)s),
... 'r-', lw=5, alpha=0.6, label='%(name)s pdf')
Alternatively, the distribution object can be called (as a function)
to fix the shape, location and scale parameters. This returns a "frozen"
RV object holding the given parameters fixed.
Freeze the distribution and display the frozen ``pdf``:
>>> rv = %(name)s(%(shapes)s)
>>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
Check accuracy of ``cdf`` and ``ppf``:
>>> vals = %(name)s.ppf([0.001, 0.5, 0.999], %(shapes)s)
>>> np.allclose([0.001, 0.5, 0.999], %(name)s.cdf(vals, %(shapes)s))
True
Generate random numbers:
>>> r = %(name)s.rvs(%(shapes)s, size=1000)
And compare the histogram:
>>> ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2)
>>> ax.legend(loc='best', frameon=False)
>>> plt.show()
"""
_doc_default_locscale = """\
The probability density above is defined in the "standardized" form. To shift
and/or scale the distribution use the ``loc`` and ``scale`` parameters.
Specifically, ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically
equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with
``y = (x - loc) / scale``.
"""
_doc_default = ''.join([_doc_default_longsummary,
_doc_allmethods,
'\n',
_doc_default_example])
_doc_default_before_notes = ''.join([_doc_default_longsummary,
_doc_allmethods])
docdict = {
'rvs': _doc_rvs,
'pdf': _doc_pdf,
'logpdf': _doc_logpdf,
'cdf': _doc_cdf,
'logcdf': _doc_logcdf,
'sf': _doc_sf,
'logsf': _doc_logsf,
'ppf': _doc_ppf,
'isf': _doc_isf,
'stats': _doc_stats,
'entropy': _doc_entropy,
'fit': _doc_fit,
'moment': _doc_moment,
'expect': _doc_expect,
'interval': _doc_interval,
'mean': _doc_mean,
'std': _doc_std,
'var': _doc_var,
'median': _doc_median,
'allmethods': _doc_allmethods,
'longsummary': _doc_default_longsummary,
'frozennote': _doc_default_frozen_note,
'example': _doc_default_example,
'default': _doc_default,
'before_notes': _doc_default_before_notes,
'after_notes': _doc_default_locscale
}
# Reuse common content between continuous and discrete docs, change some
# minor bits.
docdict_discrete = docdict.copy()
docdict_discrete['pmf'] = _doc_pmf
docdict_discrete['logpmf'] = _doc_logpmf
docdict_discrete['expect'] = _doc_expect_discrete
_doc_disc_methods = ['rvs', 'pmf', 'logpmf', 'cdf', 'logcdf', 'sf', 'logsf',
'ppf', 'isf', 'stats', 'entropy', 'expect', 'median',
'mean', 'var', 'std', 'interval']
for obj in _doc_disc_methods:
docdict_discrete[obj] = docdict_discrete[obj].replace(', scale=1', '')
_doc_disc_methods_err_varname = ['cdf', 'logcdf', 'sf', 'logsf']
for obj in _doc_disc_methods_err_varname:
docdict_discrete[obj] = docdict_discrete[obj].replace('(x, ', '(k, ')
docdict_discrete.pop('pdf')
docdict_discrete.pop('logpdf')
_doc_allmethods = ''.join([docdict_discrete[obj] for obj in _doc_disc_methods])
docdict_discrete['allmethods'] = docheaders['methods'] + _doc_allmethods
docdict_discrete['longsummary'] = _doc_default_longsummary.replace(
'rv_continuous', 'rv_discrete')
_doc_default_frozen_note = """
Alternatively, the object may be called (as a function) to fix the shape and
location parameters returning a "frozen" discrete RV object:
rv = %(name)s(%(shapes)s, loc=0)
- Frozen RV object with the same methods but holding the given shape and
location fixed.
"""
docdict_discrete['frozennote'] = _doc_default_frozen_note
_doc_default_discrete_example = """\
Examples
--------
>>> from scipy.stats import %(name)s
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(1, 1)
Calculate a few first moments:
%(set_vals_stmt)s
>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')
Display the probability mass function (``pmf``):
>>> x = np.arange(%(name)s.ppf(0.01, %(shapes)s),
... %(name)s.ppf(0.99, %(shapes)s))
>>> ax.plot(x, %(name)s.pmf(x, %(shapes)s), 'bo', ms=8, label='%(name)s pmf')
>>> ax.vlines(x, 0, %(name)s.pmf(x, %(shapes)s), colors='b', lw=5, alpha=0.5)
Alternatively, the distribution object can be called (as a function)
to fix the shape and location. This returns a "frozen" RV object holding
the given parameters fixed.
Freeze the distribution and display the frozen ``pmf``:
>>> rv = %(name)s(%(shapes)s)
>>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1,
... label='frozen pmf')
>>> ax.legend(loc='best', frameon=False)
>>> plt.show()
Check accuracy of ``cdf`` and ``ppf``:
>>> prob = %(name)s.cdf(x, %(shapes)s)
>>> np.allclose(x, %(name)s.ppf(prob, %(shapes)s))
True
Generate random numbers:
>>> r = %(name)s.rvs(%(shapes)s, size=1000)
"""
_doc_default_discrete_locscale = """\
The probability mass function above is defined in the "standardized" form.
To shift distribution use the ``loc`` parameter.
Specifically, ``%(name)s.pmf(k, %(shapes)s, loc)`` is identically
equivalent to ``%(name)s.pmf(k - loc, %(shapes)s)``.
"""
docdict_discrete['example'] = _doc_default_discrete_example
docdict_discrete['after_notes'] = _doc_default_discrete_locscale
_doc_default_before_notes = ''.join([docdict_discrete['longsummary'],
docdict_discrete['allmethods']])
docdict_discrete['before_notes'] = _doc_default_before_notes
_doc_default_disc = ''.join([docdict_discrete['longsummary'],
docdict_discrete['allmethods'],
docdict_discrete['frozennote'],
docdict_discrete['example']])
docdict_discrete['default'] = _doc_default_disc
# clean up all the separate docstring elements, we do not need them anymore
for obj in [s for s in dir() if s.startswith('_doc_')]:
exec('del ' + obj)
del obj
try:
del s
except NameError:
# in Python 3, loop variables are not visible after the loop
pass
def _moment(data, n, mu=None):
if mu is None:
mu = data.mean()
return ((data - mu)**n).mean()
def _moment_from_stats(n, mu, mu2, g1, g2, moment_func, args):
if (n == 0):
return 1.0
elif (n == 1):
if mu is None:
val = moment_func(1, *args)
else:
val = mu
elif (n == 2):
if mu2 is None or mu is None:
val = moment_func(2, *args)
else:
val = mu2 + mu*mu
elif (n == 3):
if g1 is None or mu2 is None or mu is None:
val = moment_func(3, *args)
else:
mu3 = g1 * np.power(mu2, 1.5) # 3rd central moment
val = mu3+3*mu*mu2+mu*mu*mu # 3rd non-central moment
elif (n == 4):
if g1 is None or g2 is None or mu2 is None or mu is None:
val = moment_func(4, *args)
else:
mu4 = (g2+3.0)*(mu2**2.0) # 4th central moment
mu3 = g1*np.power(mu2, 1.5) # 3rd central moment
val = mu4+4*mu*mu3+6*mu*mu*mu2+mu*mu*mu*mu
else:
val = moment_func(n, *args)
return val
def _skew(data):
"""
skew is third central moment / variance**(1.5)
"""
data = np.ravel(data)
mu = data.mean()
m2 = ((data - mu)**2).mean()
m3 = ((data - mu)**3).mean()
return m3 / np.power(m2, 1.5)
def _kurtosis(data):
"""
kurtosis is fourth central moment / variance**2 - 3
"""
data = np.ravel(data)
mu = data.mean()
m2 = ((data - mu)**2).mean()
m4 = ((data - mu)**4).mean()
return m4 / m2**2 - 3
# Frozen RV class
class rv_frozen(object):
def __init__(self, dist, *args, **kwds):
self.args = args
self.kwds = kwds
# create a new instance
self.dist = dist.__class__(**dist._updated_ctor_param())
# a, b may be set in _argcheck, depending on *args, **kwds. Ouch.
shapes, _, _ = self.dist._parse_args(*args, **kwds)
self.dist._argcheck(*shapes)
self.a, self.b = self.dist.a, self.dist.b
@property
def random_state(self):
return self.dist._random_state
@random_state.setter
def random_state(self, seed):
self.dist._random_state = check_random_state(seed)
def pdf(self, x): # raises AttributeError in frozen discrete distribution
return self.dist.pdf(x, *self.args, **self.kwds)
def logpdf(self, x):
return self.dist.logpdf(x, *self.args, **self.kwds)
def cdf(self, x):
return self.dist.cdf(x, *self.args, **self.kwds)
def logcdf(self, x):
return self.dist.logcdf(x, *self.args, **self.kwds)
def ppf(self, q):
return self.dist.ppf(q, *self.args, **self.kwds)
def isf(self, q):
return self.dist.isf(q, *self.args, **self.kwds)
def rvs(self, size=None, random_state=None):
kwds = self.kwds.copy()
kwds.update({'size': size, 'random_state': random_state})
return self.dist.rvs(*self.args, **kwds)
def sf(self, x):
return self.dist.sf(x, *self.args, **self.kwds)
def logsf(self, x):
return self.dist.logsf(x, *self.args, **self.kwds)
def stats(self, moments='mv'):
kwds = self.kwds.copy()
kwds.update({'moments': moments})
return self.dist.stats(*self.args, **kwds)
def median(self):
return self.dist.median(*self.args, **self.kwds)
def mean(self):
return self.dist.mean(*self.args, **self.kwds)
def var(self):
return self.dist.var(*self.args, **self.kwds)
def std(self):
return self.dist.std(*self.args, **self.kwds)
def moment(self, n):
return self.dist.moment(n, *self.args, **self.kwds)
def entropy(self):
return self.dist.entropy(*self.args, **self.kwds)
def pmf(self, k):
return self.dist.pmf(k, *self.args, **self.kwds)
def logpmf(self, k):
return self.dist.logpmf(k, *self.args, **self.kwds)
def interval(self, alpha):
return self.dist.interval(alpha, *self.args, **self.kwds)
def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds):
# expect method only accepts shape parameters as positional args
# hence convert self.args, self.kwds, also loc/scale
# See the .expect method docstrings for the meaning of
# other parameters.
a, loc, scale = self.dist._parse_args(*self.args, **self.kwds)
if isinstance(self.dist, rv_discrete):
return self.dist.expect(func, a, loc, lb, ub, conditional, **kwds)
else:
return self.dist.expect(func, a, loc, scale, lb, ub,
conditional, **kwds)
# This should be rewritten
def argsreduce(cond, *args):
"""Return the sequence of ravel(args[i]) where ravel(condition) is
True in 1D.
Examples
--------
>>> import numpy as np
>>> rand = np.random.random_sample
>>> A = rand((4, 5))
>>> B = 2
>>> C = rand((1, 5))
>>> cond = np.ones(A.shape)
>>> [A1, B1, C1] = argsreduce(cond, A, B, C)
>>> B1.shape
(20,)
>>> cond[2,:] = 0
>>> [A2, B2, C2] = argsreduce(cond, A, B, C)
>>> B2.shape
(15,)
"""
newargs = np.atleast_1d(*args)
if not isinstance(newargs, list):
newargs = [newargs, ]
expand_arr = (cond == cond)
return [np.extract(cond, arr1 * expand_arr) for arr1 in newargs]
parse_arg_template = """
def _parse_args(self, %(shape_arg_str)s %(locscale_in)s):
return (%(shape_arg_str)s), %(locscale_out)s
def _parse_args_rvs(self, %(shape_arg_str)s %(locscale_in)s, size=None):
return self._argcheck_rvs(%(shape_arg_str)s %(locscale_out)s, size=size)
def _parse_args_stats(self, %(shape_arg_str)s %(locscale_in)s, moments='mv'):
return (%(shape_arg_str)s), %(locscale_out)s, moments
"""
# Both the continuous and discrete distributions depend on ncx2.
# I think the function name ncx2 is an abbreviation for noncentral chi squared.
def _ncx2_log_pdf(x, df, nc):
# We use (xs**2 + ns**2)/2 = (xs - ns)**2/2 + xs*ns, and include the factor
# of exp(-xs*ns) into the ive function to improve numerical stability
# at large values of xs. See also `rice.pdf`.
df2 = df/2.0 - 1.0
xs, ns = np.sqrt(x), np.sqrt(nc)
res = xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2
res += np.log(ive(df2, xs*ns) / 2.0)
return res
def _ncx2_pdf(x, df, nc):
return np.exp(_ncx2_log_pdf(x, df, nc))
def _ncx2_cdf(x, df, nc):
return chndtr(x, df, nc)
class rv_generic(object):
"""Class which encapsulates common functionality between rv_discrete
and rv_continuous.
"""
def __init__(self, seed=None):
super(rv_generic, self).__init__()
# figure out if _stats signature has 'moments' keyword
sign = _getargspec(self._stats)
self._stats_has_moments = ((sign[2] is not None) or
('moments' in sign[0]))
self._random_state = check_random_state(seed)
@property
def random_state(self):
""" Get or set the RandomState object for generating random variates.
This can be either None or an existing RandomState object.
If None (or np.random), use the RandomState singleton used by np.random.
If already a RandomState instance, use it.
If an int, use a new RandomState instance seeded with seed.
"""
return self._random_state
@random_state.setter
def random_state(self, seed):
self._random_state = check_random_state(seed)
def __getstate__(self):
return self._updated_ctor_param(), self._random_state
def __setstate__(self, state):
ctor_param, r = state
self.__init__(**ctor_param)
self._random_state = r
return self
def _construct_argparser(
self, meths_to_inspect, locscale_in, locscale_out):
"""Construct the parser for the shape arguments.
Generates the argument-parsing functions dynamically and attaches
them to the instance.
Is supposed to be called in __init__ of a class for each distribution.
If self.shapes is a non-empty string, interprets it as a
comma-separated list of shape parameters.
Otherwise inspects the call signatures of `meths_to_inspect`
and constructs the argument-parsing functions from these.
In this case also sets `shapes` and `numargs`.
"""
if self.shapes:
# sanitize the user-supplied shapes
if not isinstance(self.shapes, string_types):
raise TypeError('shapes must be a string.')
shapes = self.shapes.replace(',', ' ').split()
for field in shapes:
if keyword.iskeyword(field):
raise SyntaxError('keywords cannot be used as shapes.')
if not re.match('^[_a-zA-Z][_a-zA-Z0-9]*$', field):
raise SyntaxError(
'shapes must be valid python identifiers')
else:
# find out the call signatures (_pdf, _cdf etc), deduce shape
# arguments. Generic methods only have 'self, x', any further args
# are shapes.
shapes_list = []
for meth in meths_to_inspect:
shapes_args = _getargspec(meth) # NB: does not contain self
args = shapes_args.args[1:] # peel off 'x', too
if args:
shapes_list.append(args)
# *args or **kwargs are not allowed w/automatic shapes
if shapes_args.varargs is not None:
raise TypeError(
'*args are not allowed w/out explicit shapes')
if shapes_args.keywords is not None:
raise TypeError(
'**kwds are not allowed w/out explicit shapes')
if shapes_args.defaults is not None:
raise TypeError('defaults are not allowed for shapes')
if shapes_list:
shapes = shapes_list[0]
# make sure the signatures are consistent
for item in shapes_list:
if item != shapes:
raise TypeError('Shape arguments are inconsistent.')
else:
shapes = []
# have the arguments, construct the method from template
shapes_str = ', '.join(shapes) + ', ' if shapes else '' # NB: not None
dct = dict(shape_arg_str=shapes_str,
locscale_in=locscale_in,
locscale_out=locscale_out,
)
ns = {}
exec_(parse_arg_template % dct, ns)
# NB: attach to the instance, not class
for name in ['_parse_args', '_parse_args_stats', '_parse_args_rvs']:
setattr(self, name,
instancemethod(ns[name], self, self.__class__)
)
self.shapes = ', '.join(shapes) if shapes else None
if not hasattr(self, 'numargs'):
# allows more general subclassing with *args
self.numargs = len(shapes)
def _construct_doc(self, docdict, shapes_vals=None):
"""Construct the instance docstring with string substitutions."""
tempdict = docdict.copy()
tempdict['name'] = self.name or 'distname'
tempdict['shapes'] = self.shapes or ''
if shapes_vals is None:
shapes_vals = ()
vals = ', '.join('%.3g' % val for val in shapes_vals)
tempdict['vals'] = vals
tempdict['shapes_'] = self.shapes or ''
if self.shapes and self.numargs == 1:
tempdict['shapes_'] += ','
if self.shapes:
tempdict['set_vals_stmt'] = '>>> %s = %s' % (self.shapes, vals)
else:
tempdict['set_vals_stmt'] = ''
if self.shapes is None:
# remove shapes from call parameters if there are none
for item in ['default', 'before_notes']:
tempdict[item] = tempdict[item].replace(
"\n%(shapes)s : array_like\n shape parameters", "")
for i in range(2):
if self.shapes is None:
# necessary because we use %(shapes)s in two forms (w w/o ", ")
self.__doc__ = self.__doc__.replace("%(shapes)s, ", "")
self.__doc__ = doccer.docformat(self.__doc__, tempdict)
# correct for empty shapes
self.__doc__ = self.__doc__.replace('(, ', '(').replace(', )', ')')
def _construct_default_doc(self, longname=None, extradoc=None,
docdict=None, discrete='continuous'):
"""Construct instance docstring from the default template."""
if longname is None:
longname = 'A'
if extradoc is None:
extradoc = ''
if extradoc.startswith('\n\n'):
extradoc = extradoc[2:]
self.__doc__ = ''.join(['%s %s random variable.' % (longname, discrete),
'\n\n%(before_notes)s\n', docheaders['notes'],
extradoc, '\n%(example)s'])
self._construct_doc(docdict)
def freeze(self, *args, **kwds):
"""Freeze the distribution for the given arguments.
Parameters
----------
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution. Should include all
the non-optional arguments, may include ``loc`` and ``scale``.
Returns
-------
rv_frozen : rv_frozen instance
The frozen distribution.
"""
return rv_frozen(self, *args, **kwds)
def __call__(self, *args, **kwds):
return self.freeze(*args, **kwds)
__call__.__doc__ = freeze.__doc__
# The actual calculation functions (no basic checking need be done)
# If these are defined, the others won't be looked at.
# Otherwise, the other set can be defined.
def _stats(self, *args, **kwds):
return None, None, None, None
# Central moments
def _munp(self, n, *args):
# Silence floating point warnings from integration.
olderr = np.seterr(all='ignore')
vals = self.generic_moment(n, *args)
np.seterr(**olderr)
return vals
def _argcheck_rvs(self, *args, **kwargs):
# Handle broadcasting and size validation of the rvs method.
# Subclasses should not have to override this method.
# The rule is that if `size` is not None, then `size` gives the
# shape of the result (integer values of `size` are treated as
# tuples with length 1; i.e. `size=3` is the same as `size=(3,)`.)
#
# `args` is expected to contain the shape parameters (if any), the
# location and the scale in a flat tuple (e.g. if there are two
# shape parameters `a` and `b`, `args` will be `(a, b, loc, scale)`).
# The only keyword argument expected is 'size'.
size = kwargs.get('size', None)
all_bcast = np.broadcast_arrays(*args)
def squeeze_left(a):
while a.ndim > 0 and a.shape[0] == 1:
a = a[0]
return a
# Eliminate trivial leading dimensions. In the convention
# used by numpy's random variate generators, trivial leading
# dimensions are effectively ignored. In other words, when `size`
# is given, trivial leading dimensions of the broadcast parameters
# in excess of the number of dimensions in size are ignored, e.g.
# >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]], size=3)
# array([ 1.00104267, 3.00422496, 4.99799278])
# If `size` is not given, the exact broadcast shape is preserved:
# >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]])
# array([[[[ 1.00862899, 3.00061431, 4.99867122]]]])
#
all_bcast = [squeeze_left(a) for a in all_bcast]
bcast_shape = all_bcast[0].shape
bcast_ndim = all_bcast[0].ndim
if size is None:
size_ = bcast_shape
else:
size_ = tuple(np.atleast_1d(size))
# Check compatibility of size_ with the broadcast shape of all
# the parameters. This check is intended to be consistent with
# how the numpy random variate generators (e.g. np.random.normal,
# np.random.beta) handle their arguments. The rule is that, if size
# is given, it determines the shape of the output. Broadcasting
# can't change the output size.
# This is the standard broadcasting convention of extending the
# shape with fewer dimensions with enough dimensions of length 1
# so that the two shapes have the same number of dimensions.
ndiff = bcast_ndim - len(size_)
if ndiff < 0:
bcast_shape = (1,)*(-ndiff) + bcast_shape
elif ndiff > 0:
size_ = (1,)*ndiff + size_
# This compatibility test is not standard. In "regular" broadcasting,
# two shapes are compatible if for each dimension, the lengths are the
# same or one of the lengths is 1. Here, the length of a dimension in
# size_ must not be less than the corresponding length in bcast_shape.
ok = all([bcdim == 1 or bcdim == szdim
for (bcdim, szdim) in zip(bcast_shape, size_)])
if not ok:
raise ValueError("size does not match the broadcast shape of "
"the parameters.")
param_bcast = all_bcast[:-2]
loc_bcast = all_bcast[-2]
scale_bcast = all_bcast[-1]
return param_bcast, loc_bcast, scale_bcast, size_
## These are the methods you must define (standard form functions)
## NB: generic _pdf, _logpdf, _cdf are different for
## rv_continuous and rv_discrete hence are defined in there
def _argcheck(self, *args):
"""Default check for correct values on args and keywords.
Returns condition array of 1's where arguments are correct and
0's where they are not.
"""
cond = 1
for arg in args:
cond = logical_and(cond, (asarray(arg) > 0))
return cond
def _support_mask(self, x):
return (self.a <= x) & (x <= self.b)
def _open_support_mask(self, x):
return (self.a < x) & (x < self.b)
def _rvs(self, *args):
# This method must handle self._size being a tuple, and it must
# properly broadcast *args and self._size. self._size might be
# an empty tuple, which means a scalar random variate is to be
# generated.
## Use basic inverse cdf algorithm for RV generation as default.
U = self._random_state.random_sample(self._size)
Y = self._ppf(U, *args)
return Y
def _logcdf(self, x, *args):
return log(self._cdf(x, *args))
def _sf(self, x, *args):
return 1.0-self._cdf(x, *args)
def _logsf(self, x, *args):
return log(self._sf(x, *args))
def _ppf(self, q, *args):
return self._ppfvec(q, *args)
def _isf(self, q, *args):
return self._ppf(1.0-q, *args) # use correct _ppf for subclasses
# These are actually called, and should not be overwritten if you
# want to keep error checking.
def rvs(self, *args, **kwds):
"""
Random variates of given type.
Parameters
----------
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter (default=0).
scale : array_like, optional
Scale parameter (default=1).
size : int or tuple of ints, optional
Defining number of random variates (default is 1).
random_state : None or int or ``np.random.RandomState`` instance, optional
If int or RandomState, use it for drawing the random variates.
If None, rely on ``self.random_state``.
Default is None.
Returns
-------
rvs : ndarray or scalar
Random variates of given `size`.
"""
discrete = kwds.pop('discrete', None)
rndm = kwds.pop('random_state', None)
args, loc, scale, size = self._parse_args_rvs(*args, **kwds)
cond = logical_and(self._argcheck(*args), (scale >= 0))
if not np.all(cond):
raise ValueError("Domain error in arguments.")
if np.all(scale == 0):
return loc*ones(size, 'd')
# extra gymnastics needed for a custom random_state
if rndm is not None:
random_state_saved = self._random_state
self._random_state = check_random_state(rndm)
# `size` should just be an argument to _rvs(), but for, um,
# historical reasons, it is made an attribute that is read
# by _rvs().
self._size = size
vals = self._rvs(*args)
vals = vals * scale + loc
# do not forget to restore the _random_state
if rndm is not None:
self._random_state = random_state_saved
# Cast to int if discrete
if discrete:
if size == ():
vals = int(vals)
else:
vals = vals.astype(int)
return vals
def stats(self, *args, **kwds):
"""
Some statistics of the given RV.
Parameters
----------
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional (continuous RVs only)
scale parameter (default=1)
moments : str, optional
composed of letters ['mvsk'] defining which moments to compute:
'm' = mean,
'v' = variance,
's' = (Fisher's) skew,
'k' = (Fisher's) kurtosis.
(default is 'mv')
Returns
-------
stats : sequence
of requested moments.
"""
args, loc, scale, moments = self._parse_args_stats(*args, **kwds)
# scale = 1 by construction for discrete RVs
loc, scale = map(asarray, (loc, scale))
args = tuple(map(asarray, args))
cond = self._argcheck(*args) & (scale > 0) & (loc == loc)
output = []
default = valarray(shape(cond), self.badvalue)
# Use only entries that are valid in calculation
if np.any(cond):
goodargs = argsreduce(cond, *(args+(scale, loc)))
scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]
if self._stats_has_moments:
mu, mu2, g1, g2 = self._stats(*goodargs,
**{'moments': moments})
else:
mu, mu2, g1, g2 = self._stats(*goodargs)
if g1 is None:
mu3 = None
else:
if mu2 is None:
mu2 = self._munp(2, *goodargs)
if g2 is None:
# (mu2**1.5) breaks down for nan and inf
mu3 = g1 * np.power(mu2, 1.5)
if 'm' in moments:
if mu is None:
mu = self._munp(1, *goodargs)
out0 = default.copy()
place(out0, cond, mu * scale + loc)
output.append(out0)
if 'v' in moments:
if mu2 is None:
mu2p = self._munp(2, *goodargs)
if mu is None:
mu = self._munp(1, *goodargs)
mu2 = mu2p - mu * mu
if np.isinf(mu):
# if mean is inf then var is also inf
mu2 = np.inf
out0 = default.copy()
place(out0, cond, mu2 * scale * scale)
output.append(out0)
if 's' in moments:
if g1 is None:
mu3p = self._munp(3, *goodargs)
if mu is None:
mu = self._munp(1, *goodargs)
if mu2 is None:
mu2p = self._munp(2, *goodargs)
mu2 = mu2p - mu * mu
mu3 = mu3p - 3 * mu * mu2 - mu**3
g1 = mu3 / np.power(mu2, 1.5)
out0 = default.copy()
place(out0, cond, g1)
output.append(out0)
if 'k' in moments:
if g2 is None:
mu4p = self._munp(4, *goodargs)
if mu is None:
mu = self._munp(1, *goodargs)
if mu2 is None:
mu2p = self._munp(2, *goodargs)
mu2 = mu2p - mu * mu
if mu3 is None:
mu3p = self._munp(3, *goodargs)
mu3 = mu3p - 3 * mu * mu2 - mu**3
mu4 = mu4p - 4 * mu * mu3 - 6 * mu * mu * mu2 - mu**4
g2 = mu4 / mu2**2.0 - 3.0
out0 = default.copy()
place(out0, cond, g2)
output.append(out0)
else: # no valid args
output = []
for _ in moments:
out0 = default.copy()
output.append(out0)
if len(output) == 1:
return output[0]
else:
return tuple(output)
def entropy(self, *args, **kwds):
"""
Differential entropy of the RV.
Parameters
----------
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter (default=0).
scale : array_like, optional (continuous distributions only).
Scale parameter (default=1).
Notes
-----
Entropy is defined base `e`:
>>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
>>> np.allclose(drv.entropy(), np.log(2.0))
True
"""
args, loc, scale = self._parse_args(*args, **kwds)
# NB: for discrete distributions scale=1 by construction in _parse_args
args = tuple(map(asarray, args))
cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
output = zeros(shape(cond0), 'd')
place(output, (1-cond0), self.badvalue)
goodargs = argsreduce(cond0, *args)
place(output, cond0, self.vecentropy(*goodargs) + log(scale))
return output
def moment(self, n, *args, **kwds):
"""
n-th order non-central moment of distribution.
Parameters
----------
n : int, n >= 1
Order of moment.
arg1, arg2, arg3,... : float
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
"""
args, loc, scale = self._parse_args(*args, **kwds)
if not (self._argcheck(*args) and (scale > 0)):
return nan
if (floor(n) != n):
raise ValueError("Moment must be an integer.")
if (n < 0):
raise ValueError("Moment must be positive.")
mu, mu2, g1, g2 = None, None, None, None
if (n > 0) and (n < 5):
if self._stats_has_moments:
mdict = {'moments': {1: 'm', 2: 'v', 3: 'vs', 4: 'vk'}[n]}
else:
mdict = {}
mu, mu2, g1, g2 = self._stats(*args, **mdict)
val = _moment_from_stats(n, mu, mu2, g1, g2, self._munp, args)
# Convert to transformed X = L + S*Y
# E[X^n] = E[(L+S*Y)^n] = L^n sum(comb(n, k)*(S/L)^k E[Y^k], k=0...n)
if loc == 0:
return scale**n * val
else:
result = 0
fac = float(scale) / float(loc)
for k in range(n):
valk = _moment_from_stats(k, mu, mu2, g1, g2, self._munp, args)
result += comb(n, k, exact=True)*(fac**k) * valk
result += fac**n * val
return result * loc**n
def median(self, *args, **kwds):
"""
Median of the distribution.
Parameters
----------
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
Location parameter, Default is 0.
scale : array_like, optional
Scale parameter, Default is 1.
Returns
-------
median : float
The median of the distribution.
See Also
--------
stats.distributions.rv_discrete.ppf
Inverse of the CDF
"""
return self.ppf(0.5, *args, **kwds)
def mean(self, *args, **kwds):
"""
Mean of the distribution.
Parameters
----------
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
mean : float
the mean of the distribution
"""
kwds['moments'] = 'm'
res = self.stats(*args, **kwds)
if isinstance(res, ndarray) and res.ndim == 0:
return res[()]
return res
def var(self, *args, **kwds):
"""
Variance of the distribution.
Parameters
----------
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
var : float
the variance of the distribution
"""
kwds['moments'] = 'v'
res = self.stats(*args, **kwds)
if isinstance(res, ndarray) and res.ndim == 0:
return res[()]
return res
def std(self, *args, **kwds):
"""
Standard deviation of the distribution.
Parameters
----------
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
std : float
standard deviation of the distribution
"""
kwds['moments'] = 'v'
res = sqrt(self.stats(*args, **kwds))
return res
def interval(self, alpha, *args, **kwds):
"""
Confidence interval with equal areas around the median.
Parameters
----------
alpha : array_like of float
Probability that an rv will be drawn from the returned range.
Each value should be in the range [0, 1].
arg1, arg2, ... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
location parameter, Default is 0.
scale : array_like, optional
scale parameter, Default is 1.
Returns
-------
a, b : ndarray of float
end-points of range that contain ``100 * alpha %`` of the rv's
possible values.
"""
alpha = asarray(alpha)
if np.any((alpha > 1) | (alpha < 0)):
raise ValueError("alpha must be between 0 and 1 inclusive")
q1 = (1.0-alpha)/2
q2 = (1.0+alpha)/2
a = self.ppf(q1, *args, **kwds)
b = self.ppf(q2, *args, **kwds)
return a, b
## continuous random variables: implement maybe later
##
## hf --- Hazard Function (PDF / SF)
## chf --- Cumulative hazard function (-log(SF))
## psf --- Probability sparsity function (reciprocal of the pdf) in
## units of percent-point-function (as a function of q).
## Also, the derivative of the percent-point function.
class rv_continuous(rv_generic):
"""
A generic continuous random variable class meant for subclassing.
`rv_continuous` is a base class to construct specific distribution classes
and instances for continuous random variables. It cannot be used
directly as a distribution.
Parameters
----------
momtype : int, optional
The type of generic moment calculation to use: 0 for pdf, 1 (default)
for ppf.
a : float, optional
Lower bound of the support of the distribution, default is minus
infinity.
b : float, optional
Upper bound of the support of the distribution, default is plus
infinity.
xtol : float, optional
The tolerance for fixed point calculation for generic ppf.
badvalue : float, optional
The value in a result arrays that indicates a value that for which
some argument restriction is violated, default is np.nan.
name : str, optional
The name of the instance. This string is used to construct the default
example for distributions.
longname : str, optional
This string is used as part of the first line of the docstring returned
when a subclass has no docstring of its own. Note: `longname` exists
for backwards compatibility, do not use for new subclasses.
shapes : str, optional
The shape of the distribution. For example ``"m, n"`` for a
distribution that takes two integers as the two shape arguments for all
its methods. If not provided, shape parameters will be inferred from
the signature of the private methods, ``_pdf`` and ``_cdf`` of the
instance.
extradoc : str, optional, deprecated
This string is used as the last part of the docstring returned when a
subclass has no docstring of its own. Note: `extradoc` exists for
backwards compatibility, do not use for new subclasses.
seed : None or int or ``numpy.random.RandomState`` instance, optional
This parameter defines the RandomState object to use for drawing
random variates.
If None (or np.random), the global np.random state is used.
If integer, it is used to seed the local RandomState instance.
Default is None.
Methods
-------
rvs
pdf
logpdf
cdf
logcdf
sf
logsf
ppf
isf
moment
stats
entropy
expect
median
mean
std
var
interval
__call__
fit
fit_loc_scale
nnlf
Notes
-----
Public methods of an instance of a distribution class (e.g., ``pdf``,
``cdf``) check their arguments and pass valid arguments to private,
computational methods (``_pdf``, ``_cdf``). For ``pdf(x)``, ``x`` is valid
if it is within the support of a distribution, ``self.a <= x <= self.b``.
Whether a shape parameter is valid is decided by an ``_argcheck`` method
(which defaults to checking that its arguments are strictly positive.)
**Subclassing**
New random variables can be defined by subclassing the `rv_continuous` class
and re-defining at least the ``_pdf`` or the ``_cdf`` method (normalized
to location 0 and scale 1).
If positive argument checking is not correct for your RV
then you will also need to re-define the ``_argcheck`` method.
Correct, but potentially slow defaults exist for the remaining
methods but for speed and/or accuracy you can over-ride::
_logpdf, _cdf, _logcdf, _ppf, _rvs, _isf, _sf, _logsf
Rarely would you override ``_isf``, ``_sf`` or ``_logsf``, but you could.
**Methods that can be overwritten by subclasses**
::
_rvs
_pdf
_cdf
_sf
_ppf
_isf
_stats
_munp
_entropy
_argcheck
There are additional (internal and private) generic methods that can
be useful for cross-checking and for debugging, but might work in all
cases when directly called.
A note on ``shapes``: subclasses need not specify them explicitly. In this
case, `shapes` will be automatically deduced from the signatures of the
overridden methods (`pdf`, `cdf` etc).
If, for some reason, you prefer to avoid relying on introspection, you can
specify ``shapes`` explicitly as an argument to the instance constructor.
**Frozen Distributions**
Normally, you must provide shape parameters (and, optionally, location and
scale parameters to each call of a method of a distribution.
Alternatively, the object may be called (as a function) to fix the shape,
location, and scale parameters returning a "frozen" continuous RV object:
rv = generic(<shape(s)>, loc=0, scale=1)
frozen RV object with the same methods but holding the given shape,
location, and scale fixed
**Statistics**
Statistics are computed using numerical integration by default.
For speed you can redefine this using ``_stats``:
- take shape parameters and return mu, mu2, g1, g2
- If you can't compute one of these, return it as None
- Can also be defined with a keyword argument ``moments``, which is a
string composed of "m", "v", "s", and/or "k".
Only the components appearing in string should be computed and
returned in the order "m", "v", "s", or "k" with missing values
returned as None.
Alternatively, you can override ``_munp``, which takes ``n`` and shape
parameters and returns the n-th non-central moment of the distribution.
Examples
--------
To create a new Gaussian distribution, we would do the following:
>>> from scipy.stats import rv_continuous
>>> class gaussian_gen(rv_continuous):
... "Gaussian distribution"
... def _pdf(self, x):
... return np.exp(-x**2 / 2.) / np.sqrt(2.0 * np.pi)
>>> gaussian = gaussian_gen(name='gaussian')
``scipy.stats`` distributions are *instances*, so here we subclass
`rv_continuous` and create an instance. With this, we now have
a fully functional distribution with all relevant methods automagically
generated by the framework.
Note that above we defined a standard normal distribution, with zero mean
and unit variance. Shifting and scaling of the distribution can be done
by using ``loc`` and ``scale`` parameters: ``gaussian.pdf(x, loc, scale)``
essentially computes ``y = (x - loc) / scale`` and
``gaussian._pdf(y) / scale``.
"""
def __init__(self, momtype=1, a=None, b=None, xtol=1e-14,
badvalue=None, name=None, longname=None,
shapes=None, extradoc=None, seed=None):
super(rv_continuous, self).__init__(seed)
# save the ctor parameters, cf generic freeze
self._ctor_param = dict(
momtype=momtype, a=a, b=b, xtol=xtol,
badvalue=badvalue, name=name, longname=longname,
shapes=shapes, extradoc=extradoc, seed=seed)
if badvalue is None:
badvalue = nan
if name is None:
name = 'Distribution'
self.badvalue = badvalue
self.name = name
self.a = a
self.b = b
if a is None:
self.a = -inf
if b is None:
self.b = inf
self.xtol = xtol
self.moment_type = momtype
self.shapes = shapes
self._construct_argparser(meths_to_inspect=[self._pdf, self._cdf],
locscale_in='loc=0, scale=1',
locscale_out='loc, scale')
# nin correction
self._ppfvec = vectorize(self._ppf_single, otypes='d')
self._ppfvec.nin = self.numargs + 1
self.vecentropy = vectorize(self._entropy, otypes='d')
self._cdfvec = vectorize(self._cdf_single, otypes='d')
self._cdfvec.nin = self.numargs + 1
self.extradoc = extradoc
if momtype == 0:
self.generic_moment = vectorize(self._mom0_sc, otypes='d')
else:
self.generic_moment = vectorize(self._mom1_sc, otypes='d')
# Because of the *args argument of _mom0_sc, vectorize cannot count the
# number of arguments correctly.
self.generic_moment.nin = self.numargs + 1
if longname is None:
if name[0] in ['aeiouAEIOU']:
hstr = "An "
else:
hstr = "A "
longname = hstr + name
if sys.flags.optimize < 2:
# Skip adding docstrings if interpreter is run with -OO
if self.__doc__ is None:
self._construct_default_doc(longname=longname,
extradoc=extradoc,
docdict=docdict,
discrete='continuous')
else:
dct = dict(distcont)
self._construct_doc(docdict, dct.get(self.name))
def _updated_ctor_param(self):
""" Return the current version of _ctor_param, possibly updated by user.
Used by freezing and pickling.
Keep this in sync with the signature of __init__.
"""
dct = self._ctor_param.copy()
dct['a'] = self.a
dct['b'] = self.b
dct['xtol'] = self.xtol
dct['badvalue'] = self.badvalue
dct['name'] = self.name
dct['shapes'] = self.shapes
dct['extradoc'] = self.extradoc
return dct
def _ppf_to_solve(self, x, q, *args):
return self.cdf(*(x, )+args)-q
def _ppf_single(self, q, *args):
left = right = None
if self.a > -np.inf:
left = self.a
if self.b < np.inf:
right = self.b
factor = 10.
if not left: # i.e. self.a = -inf
left = -1.*factor
while self._ppf_to_solve(left, q, *args) > 0.:
right = left
left *= factor
# left is now such that cdf(left) < q
if not right: # i.e. self.b = inf
right = factor
while self._ppf_to_solve(right, q, *args) < 0.:
left = right
right *= factor
# right is now such that cdf(right) > q
return optimize.brentq(self._ppf_to_solve,
left, right, args=(q,)+args, xtol=self.xtol)
# moment from definition
def _mom_integ0(self, x, m, *args):
return x**m * self.pdf(x, *args)
def _mom0_sc(self, m, *args):
return integrate.quad(self._mom_integ0, self.a, self.b,
args=(m,)+args)[0]
# moment calculated using ppf
def _mom_integ1(self, q, m, *args):
return (self.ppf(q, *args))**m
def _mom1_sc(self, m, *args):
return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0]
def _pdf(self, x, *args):
return derivative(self._cdf, x, dx=1e-5, args=args, order=5)
## Could also define any of these
def _logpdf(self, x, *args):
return log(self._pdf(x, *args))
def _cdf_single(self, x, *args):
return integrate.quad(self._pdf, self.a, x, args=args)[0]
def _cdf(self, x, *args):
return self._cdfvec(x, *args)
## generic _argcheck, _logcdf, _sf, _logsf, _ppf, _isf, _rvs are defined
## in rv_generic
def pdf(self, x, *args, **kwds):
"""
Probability density function at x of the given RV.
Parameters
----------
x : array_like
quantiles
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
pdf : ndarray
Probability density function evaluated at x
"""
args, loc, scale = self._parse_args(*args, **kwds)
x, loc, scale = map(asarray, (x, loc, scale))
args = tuple(map(asarray, args))
dtyp = np.find_common_type([x.dtype, np.float64], [])
x = np.asarray((x - loc)/scale, dtype=dtyp)
cond0 = self._argcheck(*args) & (scale > 0)
cond1 = self._support_mask(x) & (scale > 0)
cond = cond0 & cond1
output = zeros(shape(cond), dtyp)
putmask(output, (1-cond0)+np.isnan(x), self.badvalue)
if np.any(cond):
goodargs = argsreduce(cond, *((x,)+args+(scale,)))
scale, goodargs = goodargs[-1], goodargs[:-1]
place(output, cond, self._pdf(*goodargs) / scale)
if output.ndim == 0:
return output[()]
return output
def logpdf(self, x, *args, **kwds):
"""
Log of the probability density function at x of the given RV.
This uses a more numerically accurate calculation if available.
Parameters
----------
x : array_like
quantiles
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
logpdf : array_like
Log of the probability density function evaluated at x
"""
args, loc, scale = self._parse_args(*args, **kwds)
x, loc, scale = map(asarray, (x, loc, scale))
args = tuple(map(asarray, args))
dtyp = np.find_common_type([x.dtype, np.float64], [])
x = np.asarray((x - loc)/scale, dtype=dtyp)
cond0 = self._argcheck(*args) & (scale > 0)
cond1 = self._support_mask(x) & (scale > 0)
cond = cond0 & cond1
output = empty(shape(cond), dtyp)
output.fill(NINF)
putmask(output, (1-cond0)+np.isnan(x), self.badvalue)
if np.any(cond):
goodargs = argsreduce(cond, *((x,)+args+(scale,)))
scale, goodargs = goodargs[-1], goodargs[:-1]
place(output, cond, self._logpdf(*goodargs) - log(scale))
if output.ndim == 0:
return output[()]
return output
def cdf(self, x, *args, **kwds):
"""
Cumulative distribution function of the given RV.
Parameters
----------
x : array_like
quantiles
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
cdf : ndarray
Cumulative distribution function evaluated at `x`
"""
args, loc, scale = self._parse_args(*args, **kwds)
x, loc, scale = map(asarray, (x, loc, scale))
args = tuple(map(asarray, args))
dtyp = np.find_common_type([x.dtype, np.float64], [])
x = np.asarray((x - loc)/scale, dtype=dtyp)
cond0 = self._argcheck(*args) & (scale > 0)
cond1 = self._open_support_mask(x) & (scale > 0)
cond2 = (x >= self.b) & cond0
cond = cond0 & cond1
output = zeros(shape(cond), dtyp)
place(output, (1-cond0)+np.isnan(x), self.badvalue)
place(output, cond2, 1.0)
if np.any(cond): # call only if at least 1 entry
goodargs = argsreduce(cond, *((x,)+args))
place(output, cond, self._cdf(*goodargs))
if output.ndim == 0:
return output[()]
return output
def logcdf(self, x, *args, **kwds):
"""
Log of the cumulative distribution function at x of the given RV.
Parameters
----------
x : array_like
quantiles
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
logcdf : array_like
Log of the cumulative distribution function evaluated at x
"""
args, loc, scale = self._parse_args(*args, **kwds)
x, loc, scale = map(asarray, (x, loc, scale))
args = tuple(map(asarray, args))
dtyp = np.find_common_type([x.dtype, np.float64], [])
x = np.asarray((x - loc)/scale, dtype=dtyp)
cond0 = self._argcheck(*args) & (scale > 0)
cond1 = self._open_support_mask(x) & (scale > 0)
cond2 = (x >= self.b) & cond0
cond = cond0 & cond1
output = empty(shape(cond), dtyp)
output.fill(NINF)
place(output, (1-cond0)*(cond1 == cond1)+np.isnan(x), self.badvalue)
place(output, cond2, 0.0)
if np.any(cond): # call only if at least 1 entry
goodargs = argsreduce(cond, *((x,)+args))
place(output, cond, self._logcdf(*goodargs))
if output.ndim == 0:
return output[()]
return output
def sf(self, x, *args, **kwds):
"""
Survival function (1 - `cdf`) at x of the given RV.
Parameters
----------
x : array_like
quantiles
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
sf : array_like
Survival function evaluated at x
"""
args, loc, scale = self._parse_args(*args, **kwds)
x, loc, scale = map(asarray, (x, loc, scale))
args = tuple(map(asarray, args))
dtyp = np.find_common_type([x.dtype, np.float64], [])
x = np.asarray((x - loc)/scale, dtype=dtyp)
cond0 = self._argcheck(*args) & (scale > 0)
cond1 = self._open_support_mask(x) & (scale > 0)
cond2 = cond0 & (x <= self.a)
cond = cond0 & cond1
output = zeros(shape(cond), dtyp)
place(output, (1-cond0)+np.isnan(x), self.badvalue)
place(output, cond2, 1.0)
if np.any(cond):
goodargs = argsreduce(cond, *((x,)+args))
place(output, cond, self._sf(*goodargs))
if output.ndim == 0:
return output[()]
return output
def logsf(self, x, *args, **kwds):
"""
Log of the survival function of the given RV.
Returns the log of the "survival function," defined as (1 - `cdf`),
evaluated at `x`.
Parameters
----------
x : array_like
quantiles
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
logsf : ndarray
Log of the survival function evaluated at `x`.
"""
args, loc, scale = self._parse_args(*args, **kwds)
x, loc, scale = map(asarray, (x, loc, scale))
args = tuple(map(asarray, args))
dtyp = np.find_common_type([x.dtype, np.float64], [])
x = np.asarray((x - loc)/scale, dtype=dtyp)
cond0 = self._argcheck(*args) & (scale > 0)
cond1 = self._open_support_mask(x) & (scale > 0)
cond2 = cond0 & (x <= self.a)
cond = cond0 & cond1
output = empty(shape(cond), dtyp)
output.fill(NINF)
place(output, (1-cond0)+np.isnan(x), self.badvalue)
place(output, cond2, 0.0)
if np.any(cond):
goodargs = argsreduce(cond, *((x,)+args))
place(output, cond, self._logsf(*goodargs))
if output.ndim == 0:
return output[()]
return output
def ppf(self, q, *args, **kwds):
"""
Percent point function (inverse of `cdf`) at q of the given RV.
Parameters
----------
q : array_like
lower tail probability
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
x : array_like
quantile corresponding to the lower tail probability q.
"""
args, loc, scale = self._parse_args(*args, **kwds)
q, loc, scale = map(asarray, (q, loc, scale))
args = tuple(map(asarray, args))
cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
cond1 = (0 < q) & (q < 1)
cond2 = cond0 & (q == 0)
cond3 = cond0 & (q == 1)
cond = cond0 & cond1
output = valarray(shape(cond), value=self.badvalue)
lower_bound = self.a * scale + loc
upper_bound = self.b * scale + loc
place(output, cond2, argsreduce(cond2, lower_bound)[0])
place(output, cond3, argsreduce(cond3, upper_bound)[0])
if np.any(cond): # call only if at least 1 entry
goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))
scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]
place(output, cond, self._ppf(*goodargs) * scale + loc)
if output.ndim == 0:
return output[()]
return output
def isf(self, q, *args, **kwds):
"""
Inverse survival function (inverse of `sf`) at q of the given RV.
Parameters
----------
q : array_like
upper tail probability
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
location parameter (default=0)
scale : array_like, optional
scale parameter (default=1)
Returns
-------
x : ndarray or scalar
Quantile corresponding to the upper tail probability q.
"""
args, loc, scale = self._parse_args(*args, **kwds)
q, loc, scale = map(asarray, (q, loc, scale))
args = tuple(map(asarray, args))
cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
cond1 = (0 < q) & (q < 1)
cond2 = cond0 & (q == 1)
cond3 = cond0 & (q == 0)
cond = cond0 & cond1
output = valarray(shape(cond), value=self.badvalue)
lower_bound = self.a * scale + loc
upper_bound = self.b * scale + loc
place(output, cond2, argsreduce(cond2, lower_bound)[0])
place(output, cond3, argsreduce(cond3, upper_bound)[0])
if np.any(cond):
goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))
scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]
place(output, cond, self._isf(*goodargs) * scale + loc)
if output.ndim == 0:
return output[()]
return output
def _nnlf(self, x, *args):
return -np.sum(self._logpdf(x, *args), axis=0)
def _unpack_loc_scale(self, theta):
try:
loc = theta[-2]
scale = theta[-1]
args = tuple(theta[:-2])
except IndexError:
raise ValueError("Not enough input arguments.")
return loc, scale, args
def nnlf(self, theta, x):
'''Return negative loglikelihood function.
Notes
-----
This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the
parameters (including loc and scale).
'''
loc, scale, args = self._unpack_loc_scale(theta)
if not self._argcheck(*args) or scale <= 0:
return inf
x = asarray((x-loc) / scale)
n_log_scale = len(x) * log(scale)
if np.any(~self._support_mask(x)):
return inf
return self._nnlf(x, *args) + n_log_scale
def _nnlf_and_penalty(self, x, args):
cond0 = ~self._support_mask(x)
n_bad = np.count_nonzero(cond0, axis=0)
if n_bad > 0:
x = argsreduce(~cond0, x)[0]
logpdf = self._logpdf(x, *args)
finite_logpdf = np.isfinite(logpdf)
n_bad += np.sum(~finite_logpdf, axis=0)
if n_bad > 0:
penalty = n_bad * log(_XMAX) * 100
return -np.sum(logpdf[finite_logpdf], axis=0) + penalty
return -np.sum(logpdf, axis=0)
def _penalized_nnlf(self, theta, x):
''' Return penalized negative loglikelihood function,
i.e., - sum (log pdf(x, theta), axis=0) + penalty
where theta are the parameters (including loc and scale)
'''
loc, scale, args = self._unpack_loc_scale(theta)
if not self._argcheck(*args) or scale <= 0:
return inf
x = asarray((x-loc) / scale)
n_log_scale = len(x) * log(scale)
return self._nnlf_and_penalty(x, args) + n_log_scale
# return starting point for fit (shape arguments + loc + scale)
def _fitstart(self, data, args=None):
if args is None:
args = (1.0,)*self.numargs
loc, scale = self._fit_loc_scale_support(data, *args)
return args + (loc, scale)
# Return the (possibly reduced) function to optimize in order to find MLE
# estimates for the .fit method
def _reduce_func(self, args, kwds):
# First of all, convert fshapes params to fnum: eg for stats.beta,
# shapes='a, b'. To fix `a`, can specify either `f1` or `fa`.
# Convert the latter into the former.
if self.shapes:
shapes = self.shapes.replace(',', ' ').split()
for j, s in enumerate(shapes):
val = kwds.pop('f' + s, None) or kwds.pop('fix_' + s, None)
if val is not None:
key = 'f%d' % j
if key in kwds:
raise ValueError("Duplicate entry for %s." % key)
else:
kwds[key] = val
args = list(args)
Nargs = len(args)
fixedn = []
names = ['f%d' % n for n in range(Nargs - 2)] + ['floc', 'fscale']
x0 = []
for n, key in enumerate(names):
if key in kwds:
fixedn.append(n)
args[n] = kwds.pop(key)
else:
x0.append(args[n])
if len(fixedn) == 0:
func = self._penalized_nnlf
restore = None
else:
if len(fixedn) == Nargs:
raise ValueError(
"All parameters fixed. There is nothing to optimize.")
def restore(args, theta):
# Replace with theta for all numbers not in fixedn
# This allows the non-fixed values to vary, but
# we still call self.nnlf with all parameters.
i = 0
for n in range(Nargs):
if n not in fixedn:
args[n] = theta[i]
i += 1
return args
def func(theta, x):
newtheta = restore(args[:], theta)
return self._penalized_nnlf(newtheta, x)
return x0, func, restore, args
def fit(self, data, *args, **kwds):
"""
Return MLEs for shape (if applicable), location, and scale
parameters from data.
MLE stands for Maximum Likelihood Estimate. Starting estimates for
the fit are given by input arguments; for any arguments not provided
with starting estimates, ``self._fitstart(data)`` is called to generate
such.
One can hold some parameters fixed to specific values by passing in
keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)
and ``floc`` and ``fscale`` (for location and scale parameters,
respectively).
Parameters
----------
data : array_like
Data to use in calculating the MLEs.
args : floats, optional
Starting value(s) for any shape-characterizing arguments (those not
provided will be determined by a call to ``_fitstart(data)``).
No default value.
kwds : floats, optional
Starting values for the location and scale parameters; no default.
Special keyword arguments are recognized as holding certain
parameters fixed:
- f0...fn : hold respective shape parameters fixed.
Alternatively, shape parameters to fix can be specified by name.
For example, if ``self.shapes == "a, b"``, ``fa``and ``fix_a``
are equivalent to ``f0``, and ``fb`` and ``fix_b`` are
equivalent to ``f1``.
- floc : hold location parameter fixed to specified value.
- fscale : hold scale parameter fixed to specified value.
- optimizer : The optimizer to use. The optimizer must take ``func``,
and starting position as the first two arguments,
plus ``args`` (for extra arguments to pass to the
function to be optimized) and ``disp=0`` to suppress
output as keyword arguments.
Returns
-------
mle_tuple : tuple of floats
MLEs for any shape parameters (if applicable), followed by those
for location and scale. For most random variables, shape statistics
will be returned, but there are exceptions (e.g. ``norm``).
Notes
-----
This fit is computed by maximizing a log-likelihood function, with
penalty applied for samples outside of range of the distribution. The
returned answer is not guaranteed to be the globally optimal MLE, it
may only be locally optimal, or the optimization may fail altogether.
Examples
--------
Generate some data to fit: draw random variates from the `beta`
distribution
>>> from scipy.stats import beta
>>> a, b = 1., 2.
>>> x = beta.rvs(a, b, size=1000)
Now we can fit all four parameters (``a``, ``b``, ``loc`` and ``scale``):
>>> a1, b1, loc1, scale1 = beta.fit(x)
We can also use some prior knowledge about the dataset: let's keep
``loc`` and ``scale`` fixed:
>>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1)
>>> loc1, scale1
(0, 1)
We can also keep shape parameters fixed by using ``f``-keywords. To
keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or,
equivalently, ``fa=1``:
>>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1)
>>> a1
1
Not all distributions return estimates for the shape parameters.
``norm`` for example just returns estimates for location and scale:
>>> from scipy.stats import norm
>>> x = norm.rvs(a, b, size=1000, random_state=123)
>>> loc1, scale1 = norm.fit(x)
>>> loc1, scale1
(0.92087172783841631, 2.0015750750324668)
"""
Narg = len(args)
if Narg > self.numargs:
raise TypeError("Too many input arguments.")
start = [None]*2
if (Narg < self.numargs) or not ('loc' in kwds and
'scale' in kwds):
# get distribution specific starting locations
start = self._fitstart(data)
args += start[Narg:-2]
loc = kwds.pop('loc', start[-2])
scale = kwds.pop('scale', start[-1])
args += (loc, scale)
x0, func, restore, args = self._reduce_func(args, kwds)
optimizer = kwds.pop('optimizer', optimize.fmin)
# convert string to function in scipy.optimize
if not callable(optimizer) and isinstance(optimizer, string_types):
if not optimizer.startswith('fmin_'):
optimizer = "fmin_"+optimizer
if optimizer == 'fmin_':
optimizer = 'fmin'
try:
optimizer = getattr(optimize, optimizer)
except AttributeError:
raise ValueError("%s is not a valid optimizer" % optimizer)
# by now kwds must be empty, since everybody took what they needed
if kwds:
raise TypeError("Unknown arguments: %s." % kwds)
vals = optimizer(func, x0, args=(ravel(data),), disp=0)
if restore is not None:
vals = restore(args, vals)
vals = tuple(vals)
return vals
def _fit_loc_scale_support(self, data, *args):
"""
Estimate loc and scale parameters from data accounting for support.
Parameters
----------
data : array_like
Data to fit.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
Returns
-------
Lhat : float
Estimated location parameter for the data.
Shat : float
Estimated scale parameter for the data.
"""
data = np.asarray(data)
# Estimate location and scale according to the method of moments.
loc_hat, scale_hat = self.fit_loc_scale(data, *args)
# Compute the support according to the shape parameters.
self._argcheck(*args)
a, b = self.a, self.b
support_width = b - a
# If the support is empty then return the moment-based estimates.
if support_width <= 0:
return loc_hat, scale_hat
# Compute the proposed support according to the loc and scale estimates.
a_hat = loc_hat + a * scale_hat
b_hat = loc_hat + b * scale_hat
# Use the moment-based estimates if they are compatible with the data.
data_a = np.min(data)
data_b = np.max(data)
if a_hat < data_a and data_b < b_hat:
return loc_hat, scale_hat
# Otherwise find other estimates that are compatible with the data.
data_width = data_b - data_a
rel_margin = 0.1
margin = data_width * rel_margin
# For a finite interval, both the location and scale
# should have interesting values.
if support_width < np.inf:
loc_hat = (data_a - a) - margin
scale_hat = (data_width + 2 * margin) / support_width
return loc_hat, scale_hat
# For a one-sided interval, use only an interesting location parameter.
if a > -np.inf:
return (data_a - a) - margin, 1
elif b < np.inf:
return (data_b - b) + margin, 1
else:
raise RuntimeError
def fit_loc_scale(self, data, *args):
"""
Estimate loc and scale parameters from data using 1st and 2nd moments.
Parameters
----------
data : array_like
Data to fit.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
Returns
-------
Lhat : float
Estimated location parameter for the data.
Shat : float
Estimated scale parameter for the data.
"""
mu, mu2 = self.stats(*args, **{'moments': 'mv'})
tmp = asarray(data)
muhat = tmp.mean()
mu2hat = tmp.var()
Shat = sqrt(mu2hat / mu2)
Lhat = muhat - Shat*mu
if not np.isfinite(Lhat):
Lhat = 0
if not (np.isfinite(Shat) and (0 < Shat)):
Shat = 1
return Lhat, Shat
def _entropy(self, *args):
def integ(x):
val = self._pdf(x, *args)
return entr(val)
# upper limit is often inf, so suppress warnings when integrating
olderr = np.seterr(over='ignore')
h = integrate.quad(integ, self.a, self.b)[0]
np.seterr(**olderr)
if not np.isnan(h):
return h
else:
# try with different limits if integration problems
low, upp = self.ppf([1e-10, 1. - 1e-10], *args)
if np.isinf(self.b):
upper = upp
else:
upper = self.b
if np.isinf(self.a):
lower = low
else:
lower = self.a
return integrate.quad(integ, lower, upper)[0]
def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None,
conditional=False, **kwds):
"""Calculate expected value of a function with respect to the
distribution.
The expected value of a function ``f(x)`` with respect to a
distribution ``dist`` is defined as::
ubound
E[x] = Integral(f(x) * dist.pdf(x))
lbound
Parameters
----------
func : callable, optional
Function for which integral is calculated. Takes only one argument.
The default is the identity mapping f(x) = x.
args : tuple, optional
Shape parameters of the distribution.
loc : float, optional
Location parameter (default=0).
scale : float, optional
Scale parameter (default=1).
lb, ub : scalar, optional
Lower and upper bound for integration. Default is set to the
support of the distribution.
conditional : bool, optional
If True, the integral is corrected by the conditional probability
of the integration interval. The return value is the expectation
of the function, conditional on being in the given interval.
Default is False.
Additional keyword arguments are passed to the integration routine.
Returns
-------
expect : float
The calculated expected value.
Notes
-----
The integration behavior of this function is inherited from
`integrate.quad`.
"""
lockwds = {'loc': loc,
'scale': scale}
self._argcheck(*args)
if func is None:
def fun(x, *args):
return x * self.pdf(x, *args, **lockwds)
else:
def fun(x, *args):
return func(x) * self.pdf(x, *args, **lockwds)
if lb is None:
lb = loc + self.a * scale
if ub is None:
ub = loc + self.b * scale
if conditional:
invfac = (self.sf(lb, *args, **lockwds)
- self.sf(ub, *args, **lockwds))
else:
invfac = 1.0
kwds['args'] = args
# Silence floating point warnings from integration.
olderr = np.seterr(all='ignore')
vals = integrate.quad(fun, lb, ub, **kwds)[0] / invfac
np.seterr(**olderr)
return vals
# Helpers for the discrete distributions
def _drv2_moment(self, n, *args):
"""Non-central moment of discrete distribution."""
def fun(x):
return np.power(x, n) * self._pmf(x, *args)
return _expect(fun, self.a, self.b, self.ppf(0.5, *args), self.inc)
def _drv2_ppfsingle(self, q, *args): # Use basic bisection algorithm
b = self.b
a = self.a
if isinf(b): # Be sure ending point is > q
b = int(max(100*q, 10))
while 1:
if b >= self.b:
qb = 1.0
break
qb = self._cdf(b, *args)
if (qb < q):
b += 10
else:
break
else:
qb = 1.0
if isinf(a): # be sure starting point < q
a = int(min(-100*q, -10))
while 1:
if a <= self.a:
qb = 0.0
break
qa = self._cdf(a, *args)
if (qa > q):
a -= 10
else:
break
else:
qa = self._cdf(a, *args)
while 1:
if (qa == q):
return a
if (qb == q):
return b
if b <= a+1:
# testcase: return wrong number at lower index
# python -c "from scipy.stats import zipf;print zipf.ppf(0.01, 2)" wrong
# python -c "from scipy.stats import zipf;print zipf.ppf([0.01, 0.61, 0.77, 0.83], 2)"
# python -c "from scipy.stats import logser;print logser.ppf([0.1, 0.66, 0.86, 0.93], 0.6)"
if qa > q:
return a
else:
return b
c = int((a+b)/2.0)
qc = self._cdf(c, *args)
if (qc < q):
if a != c:
a = c
else:
raise RuntimeError('updating stopped, endless loop')
qa = qc
elif (qc > q):
if b != c:
b = c
else:
raise RuntimeError('updating stopped, endless loop')
qb = qc
else:
return c
def entropy(pk, qk=None, base=None):
"""Calculate the entropy of a distribution for given probability values.
If only probabilities `pk` are given, the entropy is calculated as
``S = -sum(pk * log(pk), axis=0)``.
If `qk` is not None, then compute the Kullback-Leibler divergence
``S = sum(pk * log(pk / qk), axis=0)``.
This routine will normalize `pk` and `qk` if they don't sum to 1.
Parameters
----------
pk : sequence
Defines the (discrete) distribution. ``pk[i]`` is the (possibly
unnormalized) probability of event ``i``.
qk : sequence, optional
Sequence against which the relative entropy is computed. Should be in
the same format as `pk`.
base : float, optional
The logarithmic base to use, defaults to ``e`` (natural logarithm).
Returns
-------
S : float
The calculated entropy.
"""
pk = asarray(pk)
pk = 1.0*pk / np.sum(pk, axis=0)
if qk is None:
vec = entr(pk)
else:
qk = asarray(qk)
if len(qk) != len(pk):
raise ValueError("qk and pk must have same length.")
qk = 1.0*qk / np.sum(qk, axis=0)
vec = rel_entr(pk, qk)
S = np.sum(vec, axis=0)
if base is not None:
S /= log(base)
return S
# Must over-ride one of _pmf or _cdf or pass in
# x_k, p(x_k) lists in initialization
class rv_discrete(rv_generic):
"""
A generic discrete random variable class meant for subclassing.
`rv_discrete` is a base class to construct specific distribution classes
and instances for discrete random variables. It can also be used
to construct an arbitrary distribution defined by a list of support
points and corresponding probabilities.
Parameters
----------
a : float, optional
Lower bound of the support of the distribution, default: 0
b : float, optional
Upper bound of the support of the distribution, default: plus infinity
moment_tol : float, optional
The tolerance for the generic calculation of moments.
values : tuple of two array_like, optional
``(xk, pk)`` where ``xk`` are integers with non-zero
probabilities ``pk`` with ``sum(pk) = 1``.
inc : integer, optional
Increment for the support of the distribution.
Default is 1. (other values have not been tested)
badvalue : float, optional
The value in a result arrays that indicates a value that for which
some argument restriction is violated, default is np.nan.
name : str, optional
The name of the instance. This string is used to construct the default
example for distributions.
longname : str, optional
This string is used as part of the first line of the docstring returned
when a subclass has no docstring of its own. Note: `longname` exists
for backwards compatibility, do not use for new subclasses.
shapes : str, optional
The shape of the distribution. For example "m, n" for a distribution
that takes two integers as the two shape arguments for all its methods
If not provided, shape parameters will be inferred from
the signatures of the private methods, ``_pmf`` and ``_cdf`` of
the instance.
extradoc : str, optional
This string is used as the last part of the docstring returned when a
subclass has no docstring of its own. Note: `extradoc` exists for
backwards compatibility, do not use for new subclasses.
seed : None or int or ``numpy.random.RandomState`` instance, optional
This parameter defines the RandomState object to use for drawing
random variates.
If None, the global np.random state is used.
If integer, it is used to seed the local RandomState instance.
Default is None.
Methods
-------
rvs
pmf
logpmf
cdf
logcdf
sf
logsf
ppf
isf
moment
stats
entropy
expect
median
mean
std
var
interval
__call__
Notes
-----
This class is similar to `rv_continuous`. Whether a shape parameter is
valid is decided by an ``_argcheck`` method (which defaults to checking
that its arguments are strictly positive.)
The main differences are:
- the support of the distribution is a set of integers
- instead of the probability density function, ``pdf`` (and the
corresponding private ``_pdf``), this class defines the
*probability mass function*, `pmf` (and the corresponding
private ``_pmf``.)
- scale parameter is not defined.
To create a new discrete distribution, we would do the following:
>>> from scipy.stats import rv_discrete
>>> class poisson_gen(rv_discrete):
... "Poisson distribution"
... def _pmf(self, k, mu):
... return exp(-mu) * mu**k / factorial(k)
and create an instance::
>>> poisson = poisson_gen(name="poisson")
Note that above we defined the Poisson distribution in the standard form.
Shifting the distribution can be done by providing the ``loc`` parameter
to the methods of the instance. For example, ``poisson.pmf(x, mu, loc)``
delegates the work to ``poisson._pmf(x-loc, mu)``.
**Discrete distributions from a list of probabilities**
Alternatively, you can construct an arbitrary discrete rv defined
on a finite set of values ``xk`` with ``Prob{X=xk} = pk`` by using the
``values`` keyword argument to the `rv_discrete` constructor.
Examples
--------
Custom made discrete distribution:
>>> from scipy import stats
>>> xk = np.arange(7)
>>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)
>>> custm = stats.rv_discrete(name='custm', values=(xk, pk))
>>>
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(1, 1)
>>> ax.plot(xk, custm.pmf(xk), 'ro', ms=12, mec='r')
>>> ax.vlines(xk, 0, custm.pmf(xk), colors='r', lw=4)
>>> plt.show()
Random number generation:
>>> R = custm.rvs(size=100)
"""
def __new__(cls, a=0, b=inf, name=None, badvalue=None,
moment_tol=1e-8, values=None, inc=1, longname=None,
shapes=None, extradoc=None, seed=None):
if values is not None:
# dispatch to a subclass
return super(rv_discrete, cls).__new__(rv_sample)
else:
# business as usual
return super(rv_discrete, cls).__new__(cls)
def __init__(self, a=0, b=inf, name=None, badvalue=None,
moment_tol=1e-8, values=None, inc=1, longname=None,
shapes=None, extradoc=None, seed=None):
super(rv_discrete, self).__init__(seed)
# cf generic freeze
self._ctor_param = dict(
a=a, b=b, name=name, badvalue=badvalue,
moment_tol=moment_tol, values=values, inc=inc,
longname=longname, shapes=shapes, extradoc=extradoc, seed=seed)
if badvalue is None:
badvalue = nan
self.badvalue = badvalue
self.a = a
self.b = b
self.moment_tol = moment_tol
self.inc = inc
self._cdfvec = vectorize(self._cdf_single, otypes='d')
self.vecentropy = vectorize(self._entropy)
self.shapes = shapes
if values is not None:
raise ValueError("rv_discrete.__init__(..., values != None, ...)")
self._construct_argparser(meths_to_inspect=[self._pmf, self._cdf],
locscale_in='loc=0',
# scale=1 for discrete RVs
locscale_out='loc, 1')
# nin correction needs to be after we know numargs
# correct nin for generic moment vectorization
_vec_generic_moment = vectorize(_drv2_moment, otypes='d')
_vec_generic_moment.nin = self.numargs + 2
self.generic_moment = instancemethod(_vec_generic_moment,
self, rv_discrete)
# correct nin for ppf vectorization
_vppf = vectorize(_drv2_ppfsingle, otypes='d')
_vppf.nin = self.numargs + 2
self._ppfvec = instancemethod(_vppf,
self, rv_discrete)
# now that self.numargs is defined, we can adjust nin
self._cdfvec.nin = self.numargs + 1
self._construct_docstrings(name, longname, extradoc)
def _construct_docstrings(self, name, longname, extradoc):
if name is None:
name = 'Distribution'
self.name = name
self.extradoc = extradoc
# generate docstring for subclass instances
if longname is None:
if name[0] in ['aeiouAEIOU']:
hstr = "An "
else:
hstr = "A "
longname = hstr + name
if sys.flags.optimize < 2:
# Skip adding docstrings if interpreter is run with -OO
if self.__doc__ is None:
self._construct_default_doc(longname=longname,
extradoc=extradoc,
docdict=docdict_discrete,
discrete='discrete')
else:
dct = dict(distdiscrete)
self._construct_doc(docdict_discrete, dct.get(self.name))
# discrete RV do not have the scale parameter, remove it
self.__doc__ = self.__doc__.replace(
'\n scale : array_like, '
'optional\n scale parameter (default=1)', '')
@property
@np.deprecate(message="`return_integers` attribute is not used anywhere any "
" longer and is deprecated in scipy 0.18.")
def return_integers(self):
return 1
def _updated_ctor_param(self):
""" Return the current version of _ctor_param, possibly updated by user.
Used by freezing and pickling.
Keep this in sync with the signature of __init__.
"""
dct = self._ctor_param.copy()
dct['a'] = self.a
dct['b'] = self.b
dct['badvalue'] = self.badvalue
dct['moment_tol'] = self.moment_tol
dct['inc'] = self.inc
dct['name'] = self.name
dct['shapes'] = self.shapes
dct['extradoc'] = self.extradoc
return dct
def _nonzero(self, k, *args):
return floor(k) == k
def _pmf(self, k, *args):
return self._cdf(k, *args) - self._cdf(k-1, *args)
def _logpmf(self, k, *args):
return log(self._pmf(k, *args))
def _cdf_single(self, k, *args):
m = arange(int(self.a), k+1)
return np.sum(self._pmf(m, *args), axis=0)
def _cdf(self, x, *args):
k = floor(x)
return self._cdfvec(k, *args)
# generic _logcdf, _sf, _logsf, _ppf, _isf, _rvs defined in rv_generic
def rvs(self, *args, **kwargs):
"""
Random variates of given type.
Parameters
----------
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter (default=0).
size : int or tuple of ints, optional
Defining number of random variates (Default is 1). Note that `size`
has to be given as keyword, not as positional argument.
random_state : None or int or ``np.random.RandomState`` instance, optional
If int or RandomState, use it for drawing the random variates.
If None, rely on ``self.random_state``.
Default is None.
Returns
-------
rvs : ndarray or scalar
Random variates of given `size`.
"""
kwargs['discrete'] = True
return super(rv_discrete, self).rvs(*args, **kwargs)
def pmf(self, k, *args, **kwds):
"""
Probability mass function at k of the given RV.
Parameters
----------
k : array_like
Quantiles.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information)
loc : array_like, optional
Location parameter (default=0).
Returns
-------
pmf : array_like
Probability mass function evaluated at k
"""
args, loc, _ = self._parse_args(*args, **kwds)
k, loc = map(asarray, (k, loc))
args = tuple(map(asarray, args))
k = asarray((k-loc))
cond0 = self._argcheck(*args)
cond1 = (k >= self.a) & (k <= self.b) & self._nonzero(k, *args)
cond = cond0 & cond1
output = zeros(shape(cond), 'd')
place(output, (1-cond0) + np.isnan(k), self.badvalue)
if np.any(cond):
goodargs = argsreduce(cond, *((k,)+args))
place(output, cond, np.clip(self._pmf(*goodargs), 0, 1))
if output.ndim == 0:
return output[()]
return output
def logpmf(self, k, *args, **kwds):
"""
Log of the probability mass function at k of the given RV.
Parameters
----------
k : array_like
Quantiles.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter. Default is 0.
Returns
-------
logpmf : array_like
Log of the probability mass function evaluated at k.
"""
args, loc, _ = self._parse_args(*args, **kwds)
k, loc = map(asarray, (k, loc))
args = tuple(map(asarray, args))
k = asarray((k-loc))
cond0 = self._argcheck(*args)
cond1 = (k >= self.a) & (k <= self.b) & self._nonzero(k, *args)
cond = cond0 & cond1
output = empty(shape(cond), 'd')
output.fill(NINF)
place(output, (1-cond0) + np.isnan(k), self.badvalue)
if np.any(cond):
goodargs = argsreduce(cond, *((k,)+args))
place(output, cond, self._logpmf(*goodargs))
if output.ndim == 0:
return output[()]
return output
def cdf(self, k, *args, **kwds):
"""
Cumulative distribution function of the given RV.
Parameters
----------
k : array_like, int
Quantiles.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter (default=0).
Returns
-------
cdf : ndarray
Cumulative distribution function evaluated at `k`.
"""
args, loc, _ = self._parse_args(*args, **kwds)
k, loc = map(asarray, (k, loc))
args = tuple(map(asarray, args))
k = asarray((k-loc))
cond0 = self._argcheck(*args)
cond1 = (k >= self.a) & (k < self.b)
cond2 = (k >= self.b)
cond = cond0 & cond1
output = zeros(shape(cond), 'd')
place(output, (1-cond0) + np.isnan(k), self.badvalue)
place(output, cond2*(cond0 == cond0), 1.0)
if np.any(cond):
goodargs = argsreduce(cond, *((k,)+args))
place(output, cond, np.clip(self._cdf(*goodargs), 0, 1))
if output.ndim == 0:
return output[()]
return output
def logcdf(self, k, *args, **kwds):
"""
Log of the cumulative distribution function at k of the given RV.
Parameters
----------
k : array_like, int
Quantiles.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter (default=0).
Returns
-------
logcdf : array_like
Log of the cumulative distribution function evaluated at k.
"""
args, loc, _ = self._parse_args(*args, **kwds)
k, loc = map(asarray, (k, loc))
args = tuple(map(asarray, args))
k = asarray((k-loc))
cond0 = self._argcheck(*args)
cond1 = (k >= self.a) & (k < self.b)
cond2 = (k >= self.b)
cond = cond0 & cond1
output = empty(shape(cond), 'd')
output.fill(NINF)
place(output, (1-cond0) + np.isnan(k), self.badvalue)
place(output, cond2*(cond0 == cond0), 0.0)
if np.any(cond):
goodargs = argsreduce(cond, *((k,)+args))
place(output, cond, self._logcdf(*goodargs))
if output.ndim == 0:
return output[()]
return output
def sf(self, k, *args, **kwds):
"""
Survival function (1 - `cdf`) at k of the given RV.
Parameters
----------
k : array_like
Quantiles.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter (default=0).
Returns
-------
sf : array_like
Survival function evaluated at k.
"""
args, loc, _ = self._parse_args(*args, **kwds)
k, loc = map(asarray, (k, loc))
args = tuple(map(asarray, args))
k = asarray(k-loc)
cond0 = self._argcheck(*args)
cond1 = (k >= self.a) & (k < self.b)
cond2 = (k < self.a) & cond0
cond = cond0 & cond1
output = zeros(shape(cond), 'd')
place(output, (1-cond0) + np.isnan(k), self.badvalue)
place(output, cond2, 1.0)
if np.any(cond):
goodargs = argsreduce(cond, *((k,)+args))
place(output, cond, np.clip(self._sf(*goodargs), 0, 1))
if output.ndim == 0:
return output[()]
return output
def logsf(self, k, *args, **kwds):
"""
Log of the survival function of the given RV.
Returns the log of the "survival function," defined as 1 - `cdf`,
evaluated at `k`.
Parameters
----------
k : array_like
Quantiles.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter (default=0).
Returns
-------
logsf : ndarray
Log of the survival function evaluated at `k`.
"""
args, loc, _ = self._parse_args(*args, **kwds)
k, loc = map(asarray, (k, loc))
args = tuple(map(asarray, args))
k = asarray(k-loc)
cond0 = self._argcheck(*args)
cond1 = (k >= self.a) & (k < self.b)
cond2 = (k < self.a) & cond0
cond = cond0 & cond1
output = empty(shape(cond), 'd')
output.fill(NINF)
place(output, (1-cond0) + np.isnan(k), self.badvalue)
place(output, cond2, 0.0)
if np.any(cond):
goodargs = argsreduce(cond, *((k,)+args))
place(output, cond, self._logsf(*goodargs))
if output.ndim == 0:
return output[()]
return output
def ppf(self, q, *args, **kwds):
"""
Percent point function (inverse of `cdf`) at q of the given RV.
Parameters
----------
q : array_like
Lower tail probability.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter (default=0).
Returns
-------
k : array_like
Quantile corresponding to the lower tail probability, q.
"""
args, loc, _ = self._parse_args(*args, **kwds)
q, loc = map(asarray, (q, loc))
args = tuple(map(asarray, args))
cond0 = self._argcheck(*args) & (loc == loc)
cond1 = (q > 0) & (q < 1)
cond2 = (q == 1) & cond0
cond = cond0 & cond1
output = valarray(shape(cond), value=self.badvalue, typecode='d')
# output type 'd' to handle nin and inf
place(output, (q == 0)*(cond == cond), self.a-1)
place(output, cond2, self.b)
if np.any(cond):
goodargs = argsreduce(cond, *((q,)+args+(loc,)))
loc, goodargs = goodargs[-1], goodargs[:-1]
place(output, cond, self._ppf(*goodargs) + loc)
if output.ndim == 0:
return output[()]
return output
def isf(self, q, *args, **kwds):
"""
Inverse survival function (inverse of `sf`) at q of the given RV.
Parameters
----------
q : array_like
Upper tail probability.
arg1, arg2, arg3,... : array_like
The shape parameter(s) for the distribution (see docstring of the
instance object for more information).
loc : array_like, optional
Location parameter (default=0).
Returns
-------
k : ndarray or scalar
Quantile corresponding to the upper tail probability, q.
"""
args, loc, _ = self._parse_args(*args, **kwds)
q, loc = map(asarray, (q, loc))
args = tuple(map(asarray, args))
cond0 = self._argcheck(*args) & (loc == loc)
cond1 = (q > 0) & (q < 1)
cond2 = (q == 1) & cond0
cond = cond0 & cond1
# same problem as with ppf; copied from ppf and changed
output = valarray(shape(cond), value=self.badvalue, typecode='d')
# output type 'd' to handle nin and inf
place(output, (q == 0)*(cond == cond), self.b)
place(output, cond2, self.a-1)
# call place only if at least 1 valid argument
if np.any(cond):
goodargs = argsreduce(cond, *((q,)+args+(loc,)))
loc, goodargs = goodargs[-1], goodargs[:-1]
# PB same as ticket 766
place(output, cond, self._isf(*goodargs) + loc)
if output.ndim == 0:
return output[()]
return output
def _entropy(self, *args):
if hasattr(self, 'pk'):
return entropy(self.pk)
else:
return _expect(lambda x: entr(self.pmf(x, *args)),
self.a, self.b, self.ppf(0.5, *args), self.inc)
def expect(self, func=None, args=(), loc=0, lb=None, ub=None,
conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32):
"""
Calculate expected value of a function with respect to the distribution
for discrete distribution.
Parameters
----------
func : callable, optional
Function for which the expectation value is calculated.
Takes only one argument.
The default is the identity mapping f(k) = k.
args : tuple, optional
Shape parameters of the distribution.
loc : float, optional
Location parameter.
Default is 0.
lb, ub : int, optional
Lower and upper bound for the summation, default is set to the
support of the distribution, inclusive (``ul <= k <= ub``).
conditional : bool, optional
If true then the expectation is corrected by the conditional
probability of the summation interval. The return value is the
expectation of the function, `func`, conditional on being in
the given interval (k such that ``ul <= k <= ub``).
Default is False.
maxcount : int, optional
Maximal number of terms to evaluate (to avoid an endless loop for
an infinite sum). Default is 1000.
tolerance : float, optional
Absolute tolerance for the summation. Default is 1e-10.
chunksize : int, optional
Iterate over the support of a distributions in chunks of this size.
Default is 32.
Returns
-------
expect : float
Expected value.
Notes
-----
For heavy-tailed distributions, the expected value may or may not exist,
depending on the function, `func`. If it does exist, but the sum converges
slowly, the accuracy of the result may be rather low. For instance, for
``zipf(4)``, accuracy for mean, variance in example is only 1e-5.
increasing `maxcount` and/or `chunksize` may improve the result, but may also
make zipf very slow.
The function is not vectorized.
"""
if func is None:
def fun(x):
# loc and args from outer scope
return (x+loc)*self._pmf(x, *args)
else:
def fun(x):
# loc and args from outer scope
return func(x+loc)*self._pmf(x, *args)
# used pmf because _pmf does not check support in randint and there
# might be problems(?) with correct self.a, self.b at this stage maybe
# not anymore, seems to work now with _pmf
self._argcheck(*args) # (re)generate scalar self.a and self.b
if lb is None:
lb = self.a
else:
lb = lb - loc # convert bound for standardized distribution
if ub is None:
ub = self.b
else:
ub = ub - loc # convert bound for standardized distribution
if conditional:
invfac = self.sf(lb-1, *args) - self.sf(ub, *args)
else:
invfac = 1.0
# iterate over the support, starting from the median
x0 = self.ppf(0.5, *args)
res = _expect(fun, lb, ub, x0, self.inc, maxcount, tolerance, chunksize)
return res / invfac
def _expect(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10,
chunksize=32):
"""Helper for computing the expectation value of `fun`."""
# short-circuit if the support size is small enough
if (ub - lb) <= chunksize:
supp = np.arange(lb, ub+1, inc)
vals = fun(supp)
return np.sum(vals)
# otherwise, iterate starting from x0
if x0 < lb:
x0 = lb
if x0 > ub:
x0 = ub
count, tot = 0, 0.
# iterate over [x0, ub] inclusive
for x in _iter_chunked(x0, ub+1, chunksize=chunksize, inc=inc):
count += x.size
delta = np.sum(fun(x))
tot += delta
if abs(delta) < tolerance * x.size:
break
if count > maxcount:
warnings.warn('expect(): sum did not converge', RuntimeWarning)
return tot
# iterate over [lb, x0)
for x in _iter_chunked(x0-1, lb-1, chunksize=chunksize, inc=-inc):
count += x.size
delta = np.sum(fun(x))
tot += delta
if abs(delta) < tolerance * x.size:
break
if count > maxcount:
warnings.warn('expect(): sum did not converge', RuntimeWarning)
break
return tot
def _iter_chunked(x0, x1, chunksize=4, inc=1):
"""Iterate from x0 to x1 in chunks of chunksize and steps inc.
x0 must be finite, x1 need not be. In the latter case, the iterator is infinite.
Handles both x0 < x1 and x0 > x1. In the latter case, iterates downwards
(make sure to set inc < 0.)
>>> [x for x in _iter_chunked(2, 5, inc=2)]
[array([2, 4])]
>>> [x for x in _iter_chunked(2, 11, inc=2)]
[array([2, 4, 6, 8]), array([10])]
>>> [x for x in _iter_chunked(2, -5, inc=-2)]
[array([ 2, 0, -2, -4])]
>>> [x for x in _iter_chunked(2, -9, inc=-2)]
[array([ 2, 0, -2, -4]), array([-6, -8])]
"""
if inc == 0:
raise ValueError('Cannot increment by zero.')
if chunksize <= 0:
raise ValueError('Chunk size must be positive; got %s.' % chunksize)
s = 1 if inc > 0 else -1
stepsize = abs(chunksize * inc)
x = x0
while (x - x1) * inc < 0:
delta = min(stepsize, abs(x - x1))
step = delta * s
supp = np.arange(x, x + step, inc)
x += step
yield supp
class rv_sample(rv_discrete):
"""A 'sample' discrete distribution defined by the support and values.
The ctor ignores most of the arguments, only needs the `values` argument.
"""
def __init__(self, a=0, b=inf, name=None, badvalue=None,
moment_tol=1e-8, values=None, inc=1, longname=None,
shapes=None, extradoc=None, seed=None):
super(rv_discrete, self).__init__(seed)
if values is None:
raise ValueError("rv_sample.__init__(..., values=None,...)")
# cf generic freeze
self._ctor_param = dict(
a=a, b=b, name=name, badvalue=badvalue,
moment_tol=moment_tol, values=values, inc=inc,
longname=longname, shapes=shapes, extradoc=extradoc, seed=seed)
if badvalue is None:
badvalue = nan
self.badvalue = badvalue
self.moment_tol = moment_tol
self.inc = inc
self.shapes = shapes
self.vecentropy = self._entropy
xk, pk = values
if len(xk) != len(pk):
raise ValueError("xk and pk need to have the same length.")
if not np.allclose(np.sum(pk), 1):
raise ValueError("The sum of provided pk is not 1.")
indx = np.argsort(np.ravel(xk))
self.xk = np.take(np.ravel(xk), indx, 0)
self.pk = np.take(np.ravel(pk), indx, 0)
self.a = self.xk[0]
self.b = self.xk[-1]
self.qvals = np.cumsum(self.pk, axis=0)
self.shapes = ' ' # bypass inspection
self._construct_argparser(meths_to_inspect=[self._pmf],
locscale_in='loc=0',
# scale=1 for discrete RVs
locscale_out='loc, 1')
self._construct_docstrings(name, longname, extradoc)
@property
@np.deprecate(message="`return_integers` attribute is not used anywhere any"
" longer and is deprecated in scipy 0.18.")
def return_integers(self):
return 0
def _pmf(self, x):
return np.select([x == k for k in self.xk],
[np.broadcast_arrays(p, x)[0] for p in self.pk], 0)
def _cdf(self, x):
xx, xxk = np.broadcast_arrays(x[:, None], self.xk)
indx = np.argmax(xxk > xx, axis=-1) - 1
return self.qvals[indx]
def _ppf(self, q):
qq, sqq = np.broadcast_arrays(q[..., None], self.qvals)
indx = argmax(sqq >= qq, axis=-1)
return self.xk[indx]
def _rvs(self):
# Need to define it explicitly, otherwise .rvs() with size=None
# fails due to explicit broadcasting in _ppf
U = self._random_state.random_sample(self._size)
if self._size is None:
U = np.array(U, ndmin=1)
Y = self._ppf(U)[0]
else:
Y = self._ppf(U)
return Y
def _entropy(self):
return entropy(self.pk)
def generic_moment(self, n):
n = asarray(n)
return np.sum(self.xk**n[np.newaxis, ...] * self.pk, axis=0)
@np.deprecate(message="moment_gen method is not used anywhere any more "
"and is deprecated in scipy 0.18.")
def moment_gen(self, t):
t = asarray(t)
return np.sum(exp(self.xk * t[np.newaxis, ...]) * self.pk, axis=0)
@property
@np.deprecate(message="F attribute is not used anywhere any longer and "
"is deprecated in scipy 0.18.")
def F(self):
return dict(zip(self.xk, self.qvals))
@property
@np.deprecate(message="Finv attribute is not used anywhere any longer and "
"is deprecated in scipy 0.18.")
def Finv(self):
decreasing_keys = sorted(self.F.keys(), reverse=True)
return dict((self.F[k], k) for k in decreasing_keys)
def get_distribution_names(namespace_pairs, rv_base_class):
"""
Collect names of statistical distributions and their generators.
Parameters
----------
namespace_pairs : sequence
A snapshot of (name, value) pairs in the namespace of a module.
rv_base_class : class
The base class of random variable generator classes in a module.
Returns
-------
distn_names : list of strings
Names of the statistical distributions.
distn_gen_names : list of strings
Names of the generators of the statistical distributions.
Note that these are not simply the names of the statistical
distributions, with a _gen suffix added.
"""
distn_names = []
distn_gen_names = []
for name, value in namespace_pairs:
if name.startswith('_'):
continue
if name.endswith('_gen') and issubclass(value, rv_base_class):
distn_gen_names.append(name)
if isinstance(value, rv_base_class):
distn_names.append(name)
return distn_names, distn_gen_names
| bsd-3-clause |
tkem/mopidy | tests/http/test_handlers.py | 17 | 3205 | from __future__ import absolute_import, unicode_literals
import os
import mock
import tornado.testing
import tornado.web
import tornado.websocket
import mopidy
from mopidy.http import handlers
class StaticFileHandlerTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
return tornado.web.Application([
(r'/(.*)', handlers.StaticFileHandler, {
'path': os.path.dirname(__file__),
'default_filename': 'test_handlers.py'
})
])
def test_static_handler(self):
response = self.fetch('/test_handlers.py', method='GET')
self.assertEqual(200, response.code)
self.assertEqual(
response.headers['X-Mopidy-Version'], mopidy.__version__)
self.assertEqual(
response.headers['Cache-Control'], 'no-cache')
def test_static_default_filename(self):
response = self.fetch('/', method='GET')
self.assertEqual(200, response.code)
self.assertEqual(
response.headers['X-Mopidy-Version'], mopidy.__version__)
self.assertEqual(
response.headers['Cache-Control'], 'no-cache')
# We aren't bothering with skipIf as then we would need to "backport" gen_test
if hasattr(tornado.websocket, 'websocket_connect'):
class WebSocketHandlerTest(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
self.core = mock.Mock()
return tornado.web.Application([
(r'/ws/?', handlers.WebSocketHandler, {'core': self.core})
])
def connection(self):
url = self.get_url('/ws').replace('http', 'ws')
return tornado.websocket.websocket_connect(url, self.io_loop)
@tornado.testing.gen_test
def test_invalid_json_rpc_request_doesnt_crash_handler(self):
# An uncaught error would result in no message, so this is just a
# simplistic test to verify this.
conn = yield self.connection()
conn.write_message('invalid request')
message = yield conn.read_message()
self.assertTrue(message)
@tornado.testing.gen_test
def test_broadcast_makes_it_to_client(self):
conn = yield self.connection()
handlers.WebSocketHandler.broadcast('message')
message = yield conn.read_message()
self.assertEqual(message, 'message')
@tornado.testing.gen_test
def test_broadcast_to_client_that_just_closed_connection(self):
conn = yield self.connection()
conn.stream.close()
handlers.WebSocketHandler.broadcast('message')
@tornado.testing.gen_test
def test_broadcast_to_client_without_ws_connection_present(self):
yield self.connection()
# Tornado checks for ws_connection and raises WebSocketClosedError
# if it is missing, this test case simulates winning a race were
# this has happened but we have not yet been removed from clients.
for client in handlers.WebSocketHandler.clients:
client.ws_connection = None
handlers.WebSocketHandler.broadcast('message')
| apache-2.0 |
egbertbouman/decentralized-mortgage-market | internetofmoney/managers/dummy/DummyManager.py | 2 | 4219 | from twisted.internet import reactor
from twisted.internet.defer import succeed
from twisted.internet.task import deferLater
from internetofmoney.RequiredField import RequiredField
from internetofmoney.RequiredInput import RequiredInput
from internetofmoney.managers.BaseManager import BaseManager
from internetofmoney.moneycommunity import generate_txid
class DummyManager(BaseManager):
def __init__(self, database, cache_dir='cache'):
super(DummyManager, self).__init__(database, cache_dir)
self.registered = True
self.logged_in = False
self.balance = 750
self.transactions = []
def persistent_storage_filename(self):
return '%s.json' % self.get_bank_id()
def registered_account(self):
return self.registered
def is_logged_in(self):
return self.logged_in
@staticmethod
def get_payment_info_fields():
"""
Return the fields required for making a payment in a Dummy manager.
"""
amount_field = RequiredField('amount', 'text', 'Please enter the amount of money to transfer')
destination_field = RequiredField('destination_account', 'text', 'Please enter the destination dummy IBAN')
description_field = RequiredField('description', 'text', 'Please an optional payment description')
return [amount_field, destination_field, description_field]
def register(self):
self.database.log_event('info', 'Starting registration sequence for %s' % self.get_bank_name())
def on_register_done():
self.registered = True
return self.login() # Immediately login
return deferLater(reactor, 2, on_register_done)
def login(self):
self.database.log_event('info', 'Starting login sequence for %s' % self.get_bank_name())
def on_login_done():
self.logged_in = True
return deferLater(reactor, 1, on_login_done)
def get_balance(self):
self.database.log_event('info', 'Fetching balance for %s, account %s' %
(self.get_bank_name(), self.get_address()))
return succeed({"available": self.balance, "pending": 0.0, "currency": "EUR"})
def make_payment(self):
"""
Initiate a new payment by asking the user for payment details.
"""
required_input = RequiredInput('dummy_payment_info', DummyManager.get_payment_info_fields())
return self.input_handler(required_input).addCallback(self.on_entered_payment_details)
def on_entered_payment_details(self, input):
return self.perform_payment(float(input['amount']), input['destination_account'], input['description'])
def perform_payment(self, amount, destination_account, description):
self.database.log_event('info', 'Starting %s payment with amount %f to %s (description: %s)' %
(self.get_bank_name(), amount, destination_account, description))
txid = generate_txid()
self.database.add_transaction(txid, self.get_address(), destination_account, amount, description)
self.transactions.append({"amount": amount})
return succeed(txid)
def get_transactions(self):
self.database.log_event('info', 'Fetching %s transactions of account %s' %
(self.get_bank_name(), self.get_address()))
return succeed(self.transactions)
def monitor_transactions(self, transaction_id):
return succeed({"amount": 50})
def get_address(self):
raise NotImplementedError('Please implement this method')
class Dummy1Manager(DummyManager):
def get_bank_name(self):
return 'Dummy1'
def get_bank_id(self):
return 'DUMA'
def get_address(self):
return 'NL68DUMA0111111111'
class Dummy2Manager(DummyManager):
def get_bank_name(self):
return 'Dummy2'
def get_bank_id(self):
return 'DUMB'
def get_address(self):
return 'NL06DUMB0111111111'
class Dummy3Manager(DummyManager):
def get_bank_name(self):
return 'Dummy3'
def get_bank_id(self):
return 'DUMC'
def get_address(self):
return 'NL41DUMC0111111111'
| gpl-3.0 |
codeaudit/Theano-Lights | models/draw_at_lstm1.py | 6 | 6348 | import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams
from theano.tensor.nnet.conv import conv2d
from theano.tensor.signal.downsample import max_pool_2d
from theano.tensor.shared_randomstreams import RandomStreams
import numpy as np
import scipy.io
import time
import sys
import logging
import copy
from toolbox import *
from modelbase import *
class Draw_at_lstm1(ModelULBase):
'''
Draw with Attention and LSTM (Scan version)
'''
def __init__(self, data, hp):
super(Draw_at_lstm1, self).__init__(self.__class__.__name__, data, hp)
self.sample_steps = True
self.n_h = 256
self.n_t = 32
self.n_zpt = 100
self.n_z = self.n_t * self.n_zpt
self.gates = 4
self.params = Parameters()
n_x = self.data['n_x']
n_h = self.n_h
n_z = self.n_z
n_zpt = self.n_zpt
n_t = self.n_t
gates = self.gates
scale = hp.init_scale
# Attention
read_n = 3
self.reader = AttentionDraw(self.data['shape_x'][0], self.data['shape_x'][1], read_n)
write_n = 3
self.writer = AttentionDraw(self.data['shape_x'][0], self.data['shape_x'][1], write_n)
if hp.load_model and os.path.isfile(self.filename):
self.params.load(self.filename)
else:
with self.params:
AR = shared_normal((n_h, self.reader.n_att_params), scale=scale)
AW_l = shared_normal((n_h, self.writer.n_att_params), scale=scale)
AW_w = shared_normal((n_h, self.writer.N**2), scale=scale)
baw_l = shared_zeros((self.writer.n_att_params,))
baw_w = shared_zeros((self.writer.N**2,))
W1 = shared_normal((self.reader.N**2 * 2 + n_h, n_h*gates), scale=scale)
W11 = shared_normal((n_h, n_h*gates), scale=scale)
W4 = shared_normal((n_zpt, n_h*gates), scale=scale)
W44 = shared_normal((n_h, n_h*gates), scale=scale)
b1 = shared_zeros((n_h*gates,))
b4 = shared_zeros((n_h*gates,))
b10_h = shared_zeros((n_h,))
b40_h = shared_zeros((n_h,))
b10_c = shared_zeros((n_h,))
b40_c = shared_zeros((n_h,))
W2 = shared_normal((n_h, n_zpt), scale=scale)
W3 = shared_normal((n_h, n_zpt), scale=scale)
b2 = shared_zeros((n_zpt,))
b3 = shared_zeros((n_zpt,))
ex0 = shared_zeros((n_x,))
def lstm(X, h, c, W, U, b, t):
g_on = T.dot(X,W) + T.dot(h,U) + b
i_on = T.nnet.sigmoid(g_on[:,:n_h])
f_on = T.nnet.sigmoid(g_on[:,n_h:2*n_h])
o_on = T.nnet.sigmoid(g_on[:,2*n_h:3*n_h])
c = f_on * c + i_on * T.tanh(g_on[:,3*n_h:])
h = o_on * T.tanh(c)
return h, c
def attreader(x, x_e, h_decoder, t, p):
l = T.dot(h_decoder, p.AR)
rx = self.reader.read(x, l)
rx_e = self.reader.read(x_e, l)
return concatenate([rx, rx_e, h_decoder], axis=1)
def attwriter(h_decoder, t, p):
w = T.dot(h_decoder, p.AW_w) + p.baw_w
l = T.dot(h_decoder, p.AW_l) + p.baw_l
c_update = self.writer.write(w, l)
return c_update
# Encoder
p = self.params
frnn = lstm
#x = binomial(self.X)
x = self.X
input_size = x.shape[0]
outputs_info = [T.zeros((input_size, p.ex0.shape[0])) + p.ex0,
0.0,
T.zeros((input_size, p.b10_h.shape[0])) + p.b10_h,
T.zeros((input_size, p.b40_h.shape[0])) + p.b40_h,
T.zeros((input_size, p.b10_c.shape[0])) + p.b10_c,
T.zeros((input_size, p.b40_c.shape[0])) + p.b40_c]
eps = srnd.normal((n_t, input_size, n_zpt), dtype=theano.config.floatX)
def stepFull(t, ex, log_qpz, h_encoder, h_decoder, c_encoder, c_decoder, x, eps):
x_e = x - T.nnet.sigmoid(ex)
r_x = attreader(x, x_e, h_decoder, t, p)
h_encoder, c_encoder = frnn(r_x, h_encoder, c_encoder, p.W1, p.W11, p.b1, t)
mu_encoder_t = T.dot(h_encoder, p.W2) + p.b2
log_sigma_encoder_t = 0.5*(T.dot(h_encoder, p.W3) + p.b3)
log_qpz += -0.5* T.sum(1 + 2*log_sigma_encoder_t - mu_encoder_t**2 - T.exp(2*log_sigma_encoder_t))
z = mu_encoder_t + eps[t]*T.exp(log_sigma_encoder_t)
h_decoder, c_decoder = frnn(z, h_decoder, c_decoder, p.W4, p.W44, p.b4, t)
ex += attwriter(h_decoder, t, p)
return ex, log_qpz, h_encoder, h_decoder, c_encoder, c_decoder
[lex, llog_qpz, _, _, _, _], _ = theano.scan(stepFull, n_steps=n_t, sequences=[T.arange(n_t)], non_sequences=[x, eps], outputs_info=outputs_info)
ex = lex[-1]
log_qpz = llog_qpz[-1]
pxz = T.nnet.sigmoid(ex)
log_pxz = T.nnet.binary_crossentropy(pxz, x).sum()
cost = log_pxz + log_qpz
# Generate
z = self.Z.reshape((-1, n_t, n_zpt), ndim=3)
input_size = z.shape[0]
outputs_info = [T.zeros((input_size, p.ex0.shape[0])) + p.ex0,
T.zeros((input_size, p.b40_h.shape[0])) + p.b40_h,
T.zeros((input_size, p.b40_c.shape[0])) + p.b40_c]
def stepGenerate(t, s_ex, s_h_decoder_h, s_h_decoder_c):
s_h_decoder_h, s_h_decoder_c = frnn(z[:,t,:], s_h_decoder_h, s_h_decoder_c, p.W4, p.W44, p.b4, t)
s_ex += attwriter(s_h_decoder_h, t, p)
return s_ex, s_h_decoder_h, s_h_decoder_c
[s_ex, _, _], _ = theano.scan(stepGenerate, n_steps=n_t, sequences=[T.arange(n_t)], outputs_info=outputs_info)
if self.sample_steps:
a_pxz = T.zeros((n_t + 1, input_size, n_x))
for t in xrange(n_t):
a_pxz = T.set_subtensor(a_pxz[t,:,:], T.nnet.sigmoid(s_ex[t]))
else:
a_pxz = T.zeros((1, input_size, n_x))
a_pxz = T.set_subtensor(a_pxz[-1,:,:], T.nnet.sigmoid(s_ex[-1]))
self.compile(log_pxz, log_qpz, cost, a_pxz)
| mit |
wanderine/nipype | nipype/pipeline/plugins/tests/test_multiproc_nondaemon.py | 9 | 4203 | import os
from tempfile import mkdtemp
from shutil import rmtree
from nipype.testing import assert_equal, assert_true
import nipype.pipeline.engine as pe
from nipype.interfaces.utility import Function
def mytestFunction(insum=0):
'''
Run a multiprocessing job and spawn child processes.
'''
# need to import here since this is executed as an external process
import multiprocessing
import tempfile
import time
import os
numberOfThreads = 2
# list of processes
t = [None] * numberOfThreads
# list of alive flags
a = [None] * numberOfThreads
# list of tempFiles
f = [None] * numberOfThreads
def dummyFunction(filename):
'''
This function writes the value 45 to the given filename.
'''
j = 0
for i in range(0, 10):
j += i
# j is now 45 (0+1+2+3+4+5+6+7+8+9)
with open(filename, 'w') as f:
f.write(str(j))
for n in xrange(numberOfThreads):
# mark thread as alive
a[n] = True
# create a temp file to use as the data exchange container
tmpFile = tempfile.mkstemp('.txt', 'test_engine_')[1]
f[n] = tmpFile # keep track of the temp file
t[n] = multiprocessing.Process(target=dummyFunction,
args=(tmpFile,))
# fire up the job
t[n].start()
# block until all processes are done
allDone = False
while not allDone:
time.sleep(1)
for n in xrange(numberOfThreads):
a[n] = t[n].is_alive()
if not any(a):
# if no thread is alive
allDone = True
# here, all processes are done
# read in all temp files and sum them up
total = insum
for file in f:
with open(file) as fd:
total += int(fd.read())
os.remove(file)
return total
def run_multiproc_nondaemon_with_flag(nondaemon_flag):
'''
Start a pipe with two nodes using the multiproc plugin and passing the nondaemon_flag.
'''
cur_dir = os.getcwd()
temp_dir = mkdtemp(prefix='test_engine_')
os.chdir(temp_dir)
pipe = pe.Workflow(name='pipe')
f1 = pe.Node(interface=Function(function=mytestFunction,
input_names=['insum'],
output_names=['sum_out']),
name='f1')
f2 = pe.Node(interface=Function(function=mytestFunction,
input_names=['insum'],
output_names=['sum_out']),
name='f2')
pipe.connect([(f1, f2, [('sum_out', 'insum')])])
pipe.base_dir = os.getcwd()
f1.inputs.insum = 0
pipe.config['execution']['stop_on_first_crash'] = True
pipe.config['execution']['poll_sleep_duration'] = 2
# execute the pipe using the MultiProc plugin with 2 processes and the non_daemon flag
# to enable child processes which start other multiprocessing jobs
execgraph = pipe.run(plugin="MultiProc",
plugin_args={'n_procs': 2,
'non_daemon': nondaemon_flag})
names = ['.'.join((node._hierarchy,node.name)) for node in execgraph.nodes()]
node = execgraph.nodes()[names.index('pipe.f2')]
result = node.get_output('sum_out')
os.chdir(cur_dir)
rmtree(temp_dir)
return result
def test_run_multiproc_nondaemon_false():
'''
This is the entry point for the test. Two times a pipe of several multiprocessing jobs gets
executed. First, without the nondaemon flag. Second, with the nondaemon flag.
Since the processes of the pipe start child processes, the execution only succeeds when the
non_daemon flag is on.
'''
shouldHaveFailed = False
try:
# with nondaemon_flag = False, the execution should fail
run_multiproc_nondaemon_with_flag(False)
except:
shouldHaveFailed = True
yield assert_true, shouldHaveFailed
def test_run_multiproc_nondaemon_true():
# with nondaemon_flag = True, the execution should succeed
result = run_multiproc_nondaemon_with_flag(True)
yield assert_equal, result, 180 # n_procs (2) * numberOfThreads (2) * 45 == 180
| bsd-3-clause |
Antojitos/chalupas | setup.py | 1 | 1090 | from setuptools import setup
with open('README.md') as file:
long_description = file.read()
setup(
name="chalupas-files",
version="0.1.1",
author="Antonin Messinger",
author_email="antonin.messinger@gmail.com",
description=" Convert any document",
long_description=long_description,
license="MIT License",
url="https://github.com/Antojitos/chalupas",
download_url="https://github.com/Antojitos/chalupas/archive/0.1.1.tar.gz",
keywords=["chalupas", "convert", "document"],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Flask',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP',
],
packages=['chalupas'],
install_requires=[
'Flask==0.12.3',
'pypandoc==1.1.3'
],
tests_require=[
'python-magic==0.4.11',
],
test_suite='tests.main'
)
| mit |
BIMobject-Ben/test | Treehouse/students.py | 1 | 1766 | from peewee import *
mysql_db = MySQLDatabase('treehouse', user ='Ben', password='12345678' ,
host='35.195.241.67', port=3306 )
class Student(Model):
username = CharField(max_length=255, unique=True)
points = IntegerField(default=0)
password = IntegerField(default=0)
class Meta:
database = mysql_db
students = [
{'username': 'bennyb',
'points': 90210, 'password': 90210},
{'username': 'johand',
'points': 4567, 'password': 556687},
{'username': 'kallek',
'points': 8910, 'password': 902100},
{'username': 'tommyt',
'points': 1011, 'password': 5599777},
]
def add_students():
for student in students:
try:
Student.create(username=student['username'],
points=student['points'],
password=student['password'])
except IntegrityError:
student_record = Student.get(username=student['username'])
student_record.points = student['points']
student_record.password = student['password']
def top_student():
student = Student.select().order_by(Student.points.desc()).get()
return student
if __name__ == '__main__':
mysql_db.connect()
mysql_db.create_tables([Student], safe=True)
add_students()
print("Our top of the line student At the Moment is: {0.username}.".format(top_student()))
#_________________________________________________________
#create() - creates a new instance all at once
#.select() - finds records in a table
#.save() - updates an existing row in the database
#.get() - finds a single record in a table
#.delete_instance() - deletes a single record from the table
#.order_by() - specify how to sort the records | bsd-3-clause |
Nitaco/ansible | lib/ansible/modules/storage/netapp/na_cdot_volume.py | 23 | 15029 | #!/usr/bin/python
# (c) 2017, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: na_cdot_volume
short_description: Manage NetApp cDOT volumes
extends_documentation_fragment:
- netapp.ontap
version_added: '2.3'
author: Sumit Kumar (sumit4@netapp.com)
description:
- Create or destroy volumes on NetApp cDOT
options:
state:
description:
- Whether the specified volume should exist or not.
required: true
choices: ['present', 'absent']
name:
description:
- The name of the volume to manage.
required: true
infinite:
description:
- Set True if the volume is an Infinite Volume.
type: bool
default: 'no'
online:
description:
- Whether the specified volume is online, or not.
type: bool
default: 'yes'
aggregate_name:
description:
- The name of the aggregate the flexvol should exist on. Required when C(state=present).
size:
description:
- The size of the volume in (size_unit). Required when C(state=present).
size_unit:
description:
- The unit used to interpret the size parameter.
choices: ['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb']
default: 'gb'
vserver:
description:
- Name of the vserver to use.
required: true
junction_path:
description:
- Junction path where to mount the volume
required: false
version_added: '2.6'
export_policy:
description:
- Export policy to set for the specified junction path.
required: false
default: default
version_added: '2.6'
snapshot_policy:
description:
- Snapshot policy to set for the specified volume.
required: false
default: default
version_added: '2.6'
'''
EXAMPLES = """
- name: Create FlexVol
na_cdot_volume:
state: present
name: ansibleVolume
infinite: False
aggregate_name: aggr1
size: 20
size_unit: mb
vserver: ansibleVServer
hostname: "{{ netapp_hostname }}"
username: "{{ netapp_username }}"
password: "{{ netapp_password }}"
junction_path: /ansibleVolume
export_policy: all_nfs_networks
snapshot_policy: daily
- name: Make FlexVol offline
na_cdot_volume:
state: present
name: ansibleVolume
infinite: False
online: False
vserver: ansibleVServer
hostname: "{{ netapp_hostname }}"
username: "{{ netapp_username }}"
password: "{{ netapp_password }}"
"""
RETURN = """
"""
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
import ansible.module_utils.netapp as netapp_utils
HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
class NetAppCDOTVolume(object):
def __init__(self):
self._size_unit_map = dict(
bytes=1,
b=1,
kb=1024,
mb=1024 ** 2,
gb=1024 ** 3,
tb=1024 ** 4,
pb=1024 ** 5,
eb=1024 ** 6,
zb=1024 ** 7,
yb=1024 ** 8
)
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'),
is_infinite=dict(required=False, type='bool', default=False, aliases=['infinite']),
is_online=dict(required=False, type='bool', default=True, aliases=['online']),
size=dict(type='int'),
size_unit=dict(default='gb',
choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb',
'pb', 'eb', 'zb', 'yb'], type='str'),
aggregate_name=dict(type='str'),
vserver=dict(required=True, type='str', default=None),
junction_path=dict(required=False, type='str', default=None),
export_policy=dict(required=False, type='str', default='default'),
snapshot_policy=dict(required=False, type='str', default='default'),
))
self.module = AnsibleModule(
argument_spec=self.argument_spec,
required_if=[
('state', 'present', ['aggregate_name', 'size'])
],
supports_check_mode=True
)
p = self.module.params
# set up state variables
self.state = p['state']
self.name = p['name']
self.is_infinite = p['is_infinite']
self.is_online = p['is_online']
self.size_unit = p['size_unit']
self.vserver = p['vserver']
self.junction_path = p['junction_path']
self.export_policy = p['export_policy']
self.snapshot_policy = p['snapshot_policy']
if p['size'] is not None:
self.size = p['size'] * self._size_unit_map[self.size_unit]
else:
self.size = None
self.aggregate_name = p['aggregate_name']
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, vserver=self.vserver)
def get_volume(self):
"""
Return details about the volume
:param:
name : Name of the volume
:return: Details about the volume. None if not found.
:rtype: dict
"""
volume_info = netapp_utils.zapi.NaElement('volume-get-iter')
volume_attributes = netapp_utils.zapi.NaElement('volume-attributes')
volume_id_attributes = netapp_utils.zapi.NaElement('volume-id-attributes')
volume_id_attributes.add_new_child('name', self.name)
volume_attributes.add_child_elem(volume_id_attributes)
query = netapp_utils.zapi.NaElement('query')
query.add_child_elem(volume_attributes)
volume_info.add_child_elem(query)
result = self.server.invoke_successfully(volume_info, True)
return_value = None
if result.get_child_by_name('num-records') and \
int(result.get_child_content('num-records')) >= 1:
volume_attributes = result.get_child_by_name(
'attributes-list').get_child_by_name(
'volume-attributes')
# Get volume's current size
volume_space_attributes = volume_attributes.get_child_by_name(
'volume-space-attributes')
current_size = volume_space_attributes.get_child_content('size')
# Get volume's state (online/offline)
volume_state_attributes = volume_attributes.get_child_by_name(
'volume-state-attributes')
current_state = volume_state_attributes.get_child_content('state')
is_online = None
if current_state == "online":
is_online = True
elif current_state == "offline":
is_online = False
return_value = {
'name': self.name,
'size': current_size,
'is_online': is_online,
}
return return_value
def create_volume(self):
create_parameters = {'volume': self.name,
'containing-aggr-name': self.aggregate_name,
'size': str(self.size),
}
if self.junction_path:
create_parameters['junction-path'] = str(self.junction_path)
if self.export_policy != 'default':
create_parameters['export-policy'] = str(self.export_policy)
if self.snapshot_policy != 'default':
create_parameters['snapshot-policy'] = str(self.snapshot_policy)
volume_create = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-create', **create_parameters)
try:
self.server.invoke_successfully(volume_create,
enable_tunneling=True)
except netapp_utils.zapi.NaApiError as e:
self.module.fail_json(msg='Error provisioning volume %s of size %s: %s' % (self.name, self.size, to_native(e)),
exception=traceback.format_exc())
def delete_volume(self):
if self.is_infinite:
volume_delete = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-destroy-async', **{'volume-name': self.name})
else:
volume_delete = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-destroy', **{'name': self.name, 'unmount-and-offline':
'true'})
try:
self.server.invoke_successfully(volume_delete,
enable_tunneling=True)
except netapp_utils.zapi.NaApiError as e:
self.module.fail_json(msg='Error deleting volume %s: %s' % (self.name, to_native(e)),
exception=traceback.format_exc())
def rename_volume(self):
"""
Rename the volume.
Note: 'is_infinite' needs to be set to True in order to rename an
Infinite Volume.
"""
if self.is_infinite:
volume_rename = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-rename-async',
**{'volume-name': self.name, 'new-volume-name': str(
self.name)})
else:
volume_rename = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-rename', **{'volume': self.name, 'new-volume-name': str(
self.name)})
try:
self.server.invoke_successfully(volume_rename,
enable_tunneling=True)
except netapp_utils.zapi.NaApiError as e:
self.module.fail_json(msg='Error renaming volume %s: %s' % (self.name, to_native(e)),
exception=traceback.format_exc())
def resize_volume(self):
"""
Re-size the volume.
Note: 'is_infinite' needs to be set to True in order to rename an
Infinite Volume.
"""
if self.is_infinite:
volume_resize = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-size-async',
**{'volume-name': self.name, 'new-size': str(
self.size)})
else:
volume_resize = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-size', **{'volume': self.name, 'new-size': str(
self.size)})
try:
self.server.invoke_successfully(volume_resize,
enable_tunneling=True)
except netapp_utils.zapi.NaApiError as e:
self.module.fail_json(msg='Error re-sizing volume %s: %s' % (self.name, to_native(e)),
exception=traceback.format_exc())
def change_volume_state(self):
"""
Change volume's state (offline/online).
Note: 'is_infinite' needs to be set to True in order to change the
state of an Infinite Volume.
"""
state_requested = None
if self.is_online:
# Requested state is 'online'.
state_requested = "online"
if self.is_infinite:
volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-online-async',
**{'volume-name': self.name})
else:
volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-online',
**{'name': self.name})
else:
# Requested state is 'offline'.
state_requested = "offline"
if self.is_infinite:
volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-offline-async',
**{'volume-name': self.name})
else:
volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children(
'volume-offline',
**{'name': self.name})
try:
self.server.invoke_successfully(volume_change_state,
enable_tunneling=True)
except netapp_utils.zapi.NaApiError as e:
self.module.fail_json(msg='Error changing the state of volume %s to %s: %s' %
(self.name, state_requested, to_native(e)),
exception=traceback.format_exc())
def apply(self):
changed = False
volume_exists = False
rename_volume = False
resize_volume = False
volume_detail = self.get_volume()
if volume_detail:
volume_exists = True
if self.state == 'absent':
changed = True
elif self.state == 'present':
if str(volume_detail['size']) != str(self.size):
resize_volume = True
changed = True
if (volume_detail['is_online'] is not None) and (volume_detail['is_online'] != self.is_online):
changed = True
if self.is_online is False:
# Volume is online, but requested state is offline
pass
else:
# Volume is offline but requested state is online
pass
else:
if self.state == 'present':
changed = True
if changed:
if self.module.check_mode:
pass
else:
if self.state == 'present':
if not volume_exists:
self.create_volume()
else:
if resize_volume:
self.resize_volume()
if volume_detail['is_online'] is not \
None and volume_detail['is_online'] != \
self.is_online:
self.change_volume_state()
# Ensure re-naming is the last change made.
if rename_volume:
self.rename_volume()
elif self.state == 'absent':
self.delete_volume()
self.module.exit_json(changed=changed)
def main():
v = NetAppCDOTVolume()
v.apply()
if __name__ == '__main__':
main()
| gpl-3.0 |
WhySoGeeky/DroidPot | venv/lib/python2.7/site-packages/pygments/lexers/installers.py | 72 | 12866 | # -*- coding: utf-8 -*-
"""
pygments.lexers.installers
~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexers for installer/packager DSLs and formats.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, bygroups, using, this, default
from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Punctuation, Generic, Number, Whitespace
__all__ = ['NSISLexer', 'RPMSpecLexer', 'SourcesListLexer',
'DebianControlLexer']
class NSISLexer(RegexLexer):
"""
For `NSIS <http://nsis.sourceforge.net/>`_ scripts.
.. versionadded:: 1.6
"""
name = 'NSIS'
aliases = ['nsis', 'nsi', 'nsh']
filenames = ['*.nsi', '*.nsh']
mimetypes = ['text/x-nsis']
flags = re.IGNORECASE
tokens = {
'root': [
(r'[;#].*\n', Comment),
(r"'.*?'", String.Single),
(r'"', String.Double, 'str_double'),
(r'`', String.Backtick, 'str_backtick'),
include('macro'),
include('interpol'),
include('basic'),
(r'\$\{[a-z_|][\w|]*\}', Keyword.Pseudo),
(r'/[a-z_]\w*', Name.Attribute),
('.', Text),
],
'basic': [
(r'(\n)(Function)(\s+)([._a-z][.\w]*)\b',
bygroups(Text, Keyword, Text, Name.Function)),
(r'\b([_a-z]\w*)(::)([a-z][a-z0-9]*)\b',
bygroups(Keyword.Namespace, Punctuation, Name.Function)),
(r'\b([_a-z]\w*)(:)', bygroups(Name.Label, Punctuation)),
(r'(\b[ULS]|\B)([!<>=]?=|\<\>?|\>)\B', Operator),
(r'[|+-]', Operator),
(r'\\', Punctuation),
(r'\b(Abort|Add(?:BrandingImage|Size)|'
r'Allow(?:RootDirInstall|SkipFiles)|AutoCloseWindow|'
r'BG(?:Font|Gradient)|BrandingText|BringToFront|Call(?:InstDLL)?|'
r'(?:Sub)?Caption|ChangeUI|CheckBitmap|ClearErrors|CompletedText|'
r'ComponentText|CopyFiles|CRCCheck|'
r'Create(?:Directory|Font|Shortcut)|Delete(?:INI(?:Sec|Str)|'
r'Reg(?:Key|Value))?|DetailPrint|DetailsButtonText|'
r'Dir(?:Show|Text|Var|Verify)|(?:Disabled|Enabled)Bitmap|'
r'EnableWindow|EnumReg(?:Key|Value)|Exch|Exec(?:Shell|Wait)?|'
r'ExpandEnvStrings|File(?:BufSize|Close|ErrorText|Open|'
r'Read(?:Byte)?|Seek|Write(?:Byte)?)?|'
r'Find(?:Close|First|Next|Window)|FlushINI|Function(?:End)?|'
r'Get(?:CurInstType|CurrentAddress|DlgItem|DLLVersion(?:Local)?|'
r'ErrorLevel|FileTime(?:Local)?|FullPathName|FunctionAddress|'
r'InstDirError|LabelAddress|TempFileName)|'
r'Goto|HideWindow|Icon|'
r'If(?:Abort|Errors|FileExists|RebootFlag|Silent)|'
r'InitPluginsDir|Install(?:ButtonText|Colors|Dir(?:RegKey)?)|'
r'Inst(?:ProgressFlags|Type(?:[GS]etText)?)|Int(?:CmpU?|Fmt|Op)|'
r'IsWindow|LangString(?:UP)?|'
r'License(?:BkColor|Data|ForceSelection|LangString|Text)|'
r'LoadLanguageFile|LockWindow|Log(?:Set|Text)|MessageBox|'
r'MiscButtonText|Name|Nop|OutFile|(?:Uninst)?Page(?:Ex(?:End)?)?|'
r'PluginDir|Pop|Push|Quit|Read(?:(?:Env|INI|Reg)Str|RegDWORD)|'
r'Reboot|(?:Un)?RegDLL|Rename|RequestExecutionLevel|ReserveFile|'
r'Return|RMDir|SearchPath|Section(?:Divider|End|'
r'(?:(?:Get|Set)(?:Flags|InstTypes|Size|Text))|Group(?:End)?|In)?|'
r'SendMessage|Set(?:AutoClose|BrandingImage|Compress(?:ionLevel|'
r'or(?:DictSize)?)?|CtlColors|CurInstType|DatablockOptimize|'
r'DateSave|Details(?:Print|View)|Error(?:s|Level)|FileAttributes|'
r'Font|OutPath|Overwrite|PluginUnload|RebootFlag|ShellVarContext|'
r'Silent|StaticBkColor)|'
r'Show(?:(?:I|Uni)nstDetails|Window)|Silent(?:Un)?Install|Sleep|'
r'SpaceTexts|Str(?:CmpS?|Cpy|Len)|SubSection(?:End)?|'
r'Uninstall(?:ButtonText|(?:Sub)?Caption|EXEName|Icon|Text)|'
r'UninstPage|Var|VI(?:AddVersionKey|ProductVersion)|WindowIcon|'
r'Write(?:INIStr|Reg(:?Bin|DWORD|(?:Expand)?Str)|Uninstaller)|'
r'XPStyle)\b', Keyword),
(r'\b(CUR|END|(?:FILE_ATTRIBUTE_)?'
r'(?:ARCHIVE|HIDDEN|NORMAL|OFFLINE|READONLY|SYSTEM|TEMPORARY)|'
r'HK(CC|CR|CU|DD|LM|PD|U)|'
r'HKEY_(?:CLASSES_ROOT|CURRENT_(?:CONFIG|USER)|DYN_DATA|'
r'LOCAL_MACHINE|PERFORMANCE_DATA|USERS)|'
r'ID(?:ABORT|CANCEL|IGNORE|NO|OK|RETRY|YES)|'
r'MB_(?:ABORTRETRYIGNORE|DEFBUTTON[1-4]|'
r'ICON(?:EXCLAMATION|INFORMATION|QUESTION|STOP)|'
r'OK(?:CANCEL)?|RETRYCANCEL|RIGHT|SETFOREGROUND|TOPMOST|USERICON|'
r'YESNO(?:CANCEL)?)|SET|SHCTX|'
r'SW_(?:HIDE|SHOW(?:MAXIMIZED|MINIMIZED|NORMAL))|'
r'admin|all|auto|both|bottom|bzip2|checkbox|colored|current|false|'
r'force|hide|highest|if(?:diff|newer)|lastused|leave|left|'
r'listonly|lzma|nevershow|none|normal|off|on|pop|push|'
r'radiobuttons|right|show|silent|silentlog|smooth|textonly|top|'
r'true|try|user|zlib)\b', Name.Constant),
],
'macro': [
(r'\!(addincludedir(?:dir)?|addplugindir|appendfile|cd|define|'
r'delfilefile|echo(?:message)?|else|endif|error|execute|'
r'if(?:macro)?n?(?:def)?|include|insertmacro|macro(?:end)?|packhdr|'
r'search(?:parse|replace)|system|tempfilesymbol|undef|verbose|'
r'warning)\b', Comment.Preproc),
],
'interpol': [
(r'\$(R?[0-9])', Name.Builtin.Pseudo), # registers
(r'\$(ADMINTOOLS|APPDATA|CDBURN_AREA|COOKIES|COMMONFILES(?:32|64)|'
r'DESKTOP|DOCUMENTS|EXE(?:DIR|FILE|PATH)|FAVORITES|FONTS|HISTORY|'
r'HWNDPARENT|INTERNET_CACHE|LOCALAPPDATA|MUSIC|NETHOOD|PICTURES|'
r'PLUGINSDIR|PRINTHOOD|PROFILE|PROGRAMFILES(?:32|64)|QUICKLAUNCH|'
r'RECENT|RESOURCES(?:_LOCALIZED)?|SENDTO|SM(?:PROGRAMS|STARTUP)|'
r'STARTMENU|SYSDIR|TEMP(?:LATES)?|VIDEOS|WINDIR|\{NSISDIR\})',
Name.Builtin),
(r'\$(CMDLINE|INSTDIR|OUTDIR|LANGUAGE)', Name.Variable.Global),
(r'\$[a-z_]\w*', Name.Variable),
],
'str_double': [
(r'"', String, '#pop'),
(r'\$(\\[nrt"]|\$)', String.Escape),
include('interpol'),
(r'.', String.Double),
],
'str_backtick': [
(r'`', String, '#pop'),
(r'\$(\\[nrt"]|\$)', String.Escape),
include('interpol'),
(r'.', String.Double),
],
}
class RPMSpecLexer(RegexLexer):
"""
For RPM ``.spec`` files.
.. versionadded:: 1.6
"""
name = 'RPMSpec'
aliases = ['spec']
filenames = ['*.spec']
mimetypes = ['text/x-rpm-spec']
_directives = ('(?:package|prep|build|install|clean|check|pre[a-z]*|'
'post[a-z]*|trigger[a-z]*|files)')
tokens = {
'root': [
(r'#.*\n', Comment),
include('basic'),
],
'description': [
(r'^(%' + _directives + ')(.*)$',
bygroups(Name.Decorator, Text), '#pop'),
(r'\n', Text),
(r'.', Text),
],
'changelog': [
(r'\*.*\n', Generic.Subheading),
(r'^(%' + _directives + ')(.*)$',
bygroups(Name.Decorator, Text), '#pop'),
(r'\n', Text),
(r'.', Text),
],
'string': [
(r'"', String.Double, '#pop'),
(r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape),
include('interpol'),
(r'.', String.Double),
],
'basic': [
include('macro'),
(r'(?i)^(Name|Version|Release|Epoch|Summary|Group|License|Packager|'
r'Vendor|Icon|URL|Distribution|Prefix|Patch[0-9]*|Source[0-9]*|'
r'Requires\(?[a-z]*\)?|[a-z]+Req|Obsoletes|Suggests|Provides|Conflicts|'
r'Build[a-z]+|[a-z]+Arch|Auto[a-z]+)(:)(.*)$',
bygroups(Generic.Heading, Punctuation, using(this))),
(r'^%description', Name.Decorator, 'description'),
(r'^%changelog', Name.Decorator, 'changelog'),
(r'^(%' + _directives + ')(.*)$', bygroups(Name.Decorator, Text)),
(r'%(attr|defattr|dir|doc(?:dir)?|setup|config(?:ure)?|'
r'make(?:install)|ghost|patch[0-9]+|find_lang|exclude|verify)',
Keyword),
include('interpol'),
(r"'.*?'", String.Single),
(r'"', String.Double, 'string'),
(r'.', Text),
],
'macro': [
(r'%define.*\n', Comment.Preproc),
(r'%\{\!\?.*%define.*\}', Comment.Preproc),
(r'(%(?:if(?:n?arch)?|else(?:if)?|endif))(.*)$',
bygroups(Comment.Preproc, Text)),
],
'interpol': [
(r'%\{?__[a-z_]+\}?', Name.Function),
(r'%\{?_([a-z_]+dir|[a-z_]+path|prefix)\}?', Keyword.Pseudo),
(r'%\{\?\w+\}', Name.Variable),
(r'\$\{?RPM_[A-Z0-9_]+\}?', Name.Variable.Global),
(r'%\{[a-zA-Z]\w+\}', Keyword.Constant),
]
}
class SourcesListLexer(RegexLexer):
"""
Lexer that highlights debian sources.list files.
.. versionadded:: 0.7
"""
name = 'Debian Sourcelist'
aliases = ['sourceslist', 'sources.list', 'debsources']
filenames = ['sources.list']
mimetype = ['application/x-debian-sourceslist']
tokens = {
'root': [
(r'\s+', Text),
(r'#.*?$', Comment),
(r'^(deb(?:-src)?)(\s+)',
bygroups(Keyword, Text), 'distribution')
],
'distribution': [
(r'#.*?$', Comment, '#pop'),
(r'\$\(ARCH\)', Name.Variable),
(r'[^\s$[]+', String),
(r'\[', String.Other, 'escaped-distribution'),
(r'\$', String),
(r'\s+', Text, 'components')
],
'escaped-distribution': [
(r'\]', String.Other, '#pop'),
(r'\$\(ARCH\)', Name.Variable),
(r'[^\]$]+', String.Other),
(r'\$', String.Other)
],
'components': [
(r'#.*?$', Comment, '#pop:2'),
(r'$', Text, '#pop:2'),
(r'\s+', Text),
(r'\S+', Keyword.Pseudo),
]
}
def analyse_text(text):
for line in text.splitlines():
line = line.strip()
if line.startswith('deb ') or line.startswith('deb-src '):
return True
class DebianControlLexer(RegexLexer):
"""
Lexer for Debian ``control`` files and ``apt-cache show <pkg>`` outputs.
.. versionadded:: 0.9
"""
name = 'Debian Control file'
aliases = ['control', 'debcontrol']
filenames = ['control']
tokens = {
'root': [
(r'^(Description)', Keyword, 'description'),
(r'^(Maintainer)(:\s*)', bygroups(Keyword, Text), 'maintainer'),
(r'^((Build-)?Depends)', Keyword, 'depends'),
(r'^((?:Python-)?Version)(:\s*)(\S+)$',
bygroups(Keyword, Text, Number)),
(r'^((?:Installed-)?Size)(:\s*)(\S+)$',
bygroups(Keyword, Text, Number)),
(r'^(MD5Sum|SHA1|SHA256)(:\s*)(\S+)$',
bygroups(Keyword, Text, Number)),
(r'^([a-zA-Z\-0-9\.]*?)(:\s*)(.*?)$',
bygroups(Keyword, Whitespace, String)),
],
'maintainer': [
(r'<[^>]+>', Generic.Strong),
(r'<[^>]+>$', Generic.Strong, '#pop'),
(r',\n?', Text),
(r'.', Text),
],
'description': [
(r'(.*)(Homepage)(: )(\S+)',
bygroups(Text, String, Name, Name.Class)),
(r':.*\n', Generic.Strong),
(r' .*\n', Text),
default('#pop'),
],
'depends': [
(r':\s*', Text),
(r'(\$)(\{)(\w+\s*:\s*\w+)', bygroups(Operator, Text, Name.Entity)),
(r'\(', Text, 'depend_vers'),
(r',', Text),
(r'\|', Operator),
(r'[\s]+', Text),
(r'[})]\s*$', Text, '#pop'),
(r'\}', Text),
(r'[^,]$', Name.Function, '#pop'),
(r'([+.a-zA-Z0-9-])(\s*)', bygroups(Name.Function, Text)),
(r'\[.*?\]', Name.Entity),
],
'depend_vers': [
(r'\),', Text, '#pop'),
(r'\)[^,]', Text, '#pop:2'),
(r'([><=]+)(\s*)([^)]+)', bygroups(Operator, Text, Number))
]
}
| mit |
jakobworldpeace/scikit-learn | sklearn/metrics/classification.py | 2 | 72558 | """Metrics to assess performance on classification task given class prediction
Functions named as ``*_score`` return a scalar value to maximize: the higher
the better
Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize:
the lower the better
"""
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Mathieu Blondel <mathieu@mblondel.org>
# Olivier Grisel <olivier.grisel@ensta.org>
# Arnaud Joly <a.joly@ulg.ac.be>
# Jochen Wersdorfer <jochen@wersdoerfer.de>
# Lars Buitinck
# Joel Nothman <joel.nothman@gmail.com>
# Noel Dawe <noel@dawe.me>
# Jatin Shah <jatindshah@gmail.com>
# Saurabh Jha <saurabh.jhaa@gmail.com>
# Bernardo Stein <bernardovstein@gmail.com>
# License: BSD 3 clause
from __future__ import division
import warnings
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse import csr_matrix
from ..preprocessing import LabelBinarizer, label_binarize
from ..preprocessing import LabelEncoder
from ..utils import assert_all_finite
from ..utils import check_array
from ..utils import check_consistent_length
from ..utils import column_or_1d
from ..utils.multiclass import unique_labels
from ..utils.multiclass import type_of_target
from ..utils.validation import _num_samples
from ..utils.sparsefuncs import count_nonzero
from ..utils.fixes import bincount
from ..exceptions import UndefinedMetricWarning
def _check_targets(y_true, y_pred):
"""Check that y_true and y_pred belong to the same classification task
This converts multiclass or binary types to a common shape, and raises a
ValueError for a mix of multilabel and multiclass targets, a mix of
multilabel formats, for the presence of continuous-valued or multioutput
targets, or for targets of different lengths.
Column vectors are squeezed to 1d, while multilabel formats are returned
as CSR sparse label indicators.
Parameters
----------
y_true : array-like
y_pred : array-like
Returns
-------
type_true : one of {'multilabel-indicator', 'multiclass', 'binary'}
The type of the true target data, as output by
``utils.multiclass.type_of_target``
y_true : array or indicator matrix
y_pred : array or indicator matrix
"""
check_consistent_length(y_true, y_pred)
type_true = type_of_target(y_true)
type_pred = type_of_target(y_pred)
y_type = set([type_true, type_pred])
if y_type == set(["binary", "multiclass"]):
y_type = set(["multiclass"])
if len(y_type) > 1:
raise ValueError("Can't handle mix of {0} and {1}"
"".format(type_true, type_pred))
# We can't have more than one value on y_type => The set is no more needed
y_type = y_type.pop()
# No metrics support "multiclass-multioutput" format
if (y_type not in ["binary", "multiclass", "multilabel-indicator"]):
raise ValueError("{0} is not supported".format(y_type))
if y_type in ["binary", "multiclass"]:
y_true = column_or_1d(y_true)
y_pred = column_or_1d(y_pred)
if y_type.startswith('multilabel'):
y_true = csr_matrix(y_true)
y_pred = csr_matrix(y_pred)
y_type = 'multilabel-indicator'
return y_type, y_true, y_pred
def _weighted_sum(sample_score, sample_weight, normalize=False):
if normalize:
return np.average(sample_score, weights=sample_weight)
elif sample_weight is not None:
return np.dot(sample_score, sample_weight)
else:
return sample_score.sum()
def accuracy_score(y_true, y_pred, normalize=True, sample_weight=None):
"""Accuracy classification score.
In multilabel classification, this function computes subset accuracy:
the set of labels predicted for a sample must *exactly* match the
corresponding set of labels in y_true.
Read more in the :ref:`User Guide <accuracy_score>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) labels.
y_pred : 1d array-like, or label indicator array / sparse matrix
Predicted labels, as returned by a classifier.
normalize : bool, optional (default=True)
If ``False``, return the number of correctly classified samples.
Otherwise, return the fraction of correctly classified samples.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
score : float
If ``normalize == True``, return the correctly classified samples
(float), else it returns the number of correctly classified samples
(int).
The best performance is 1 with ``normalize == True`` and the number
of samples with ``normalize == False``.
See also
--------
jaccard_similarity_score, hamming_loss, zero_one_loss
Notes
-----
In binary and multiclass classification, this function is equal
to the ``jaccard_similarity_score`` function.
Examples
--------
>>> import numpy as np
>>> from sklearn.metrics import accuracy_score
>>> y_pred = [0, 2, 1, 3]
>>> y_true = [0, 1, 2, 3]
>>> accuracy_score(y_true, y_pred)
0.5
>>> accuracy_score(y_true, y_pred, normalize=False)
2
In the multilabel case with binary label indicators:
>>> accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2)))
0.5
"""
# Compute accuracy for each possible representation
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
if y_type.startswith('multilabel'):
differing_labels = count_nonzero(y_true - y_pred, axis=1)
score = differing_labels == 0
else:
score = y_true == y_pred
return _weighted_sum(score, sample_weight, normalize)
def confusion_matrix(y_true, y_pred, labels=None, sample_weight=None):
"""Compute confusion matrix to evaluate the accuracy of a classification
By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}`
is equal to the number of observations known to be in group :math:`i` but
predicted to be in group :math:`j`.
Thus in binary classification, the count of true negatives is
:math:`C_{0,0}`, false negatives is :math:`C_{1,0}`, true positives is
:math:`C_{1,1}` and false positives is :math:`C_{0,1}`.
Read more in the :ref:`User Guide <confusion_matrix>`.
Parameters
----------
y_true : array, shape = [n_samples]
Ground truth (correct) target values.
y_pred : array, shape = [n_samples]
Estimated targets as returned by a classifier.
labels : array, shape = [n_classes], optional
List of labels to index the matrix. This may be used to reorder
or select a subset of labels.
If none is given, those that appear at least once
in ``y_true`` or ``y_pred`` are used in sorted order.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
C : array, shape = [n_classes, n_classes]
Confusion matrix
References
----------
.. [1] `Wikipedia entry for the Confusion matrix
<https://en.wikipedia.org/wiki/Confusion_matrix>`_
Examples
--------
>>> from sklearn.metrics import confusion_matrix
>>> y_true = [2, 0, 2, 2, 0, 1]
>>> y_pred = [0, 0, 2, 2, 0, 2]
>>> confusion_matrix(y_true, y_pred)
array([[2, 0, 0],
[0, 0, 1],
[1, 0, 2]])
>>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
>>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
>>> confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"])
array([[2, 0, 0],
[0, 0, 1],
[1, 0, 2]])
In the binary case, we can extract true positives, etc as follows:
>>> tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel()
>>> (tn, fp, fn, tp)
(0, 2, 1, 1)
"""
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
if y_type not in ("binary", "multiclass"):
raise ValueError("%s is not supported" % y_type)
if labels is None:
labels = unique_labels(y_true, y_pred)
else:
labels = np.asarray(labels)
if np.all([l not in y_true for l in labels]):
raise ValueError("At least one label specified must be in y_true")
if sample_weight is None:
sample_weight = np.ones(y_true.shape[0], dtype=np.int)
else:
sample_weight = np.asarray(sample_weight)
check_consistent_length(sample_weight, y_true, y_pred)
n_labels = labels.size
label_to_ind = dict((y, x) for x, y in enumerate(labels))
# convert yt, yp into index
y_pred = np.array([label_to_ind.get(x, n_labels + 1) for x in y_pred])
y_true = np.array([label_to_ind.get(x, n_labels + 1) for x in y_true])
# intersect y_pred, y_true with labels, eliminate items not in labels
ind = np.logical_and(y_pred < n_labels, y_true < n_labels)
y_pred = y_pred[ind]
y_true = y_true[ind]
# also eliminate weights of eliminated items
sample_weight = sample_weight[ind]
CM = coo_matrix((sample_weight, (y_true, y_pred)),
shape=(n_labels, n_labels)
).toarray()
return CM
def cohen_kappa_score(y1, y2, labels=None, weights=None, sample_weight=None):
"""Cohen's kappa: a statistic that measures inter-annotator agreement.
This function computes Cohen's kappa [1]_, a score that expresses the level
of agreement between two annotators on a classification problem. It is
defined as
.. math::
\kappa = (p_o - p_e) / (1 - p_e)
where :math:`p_o` is the empirical probability of agreement on the label
assigned to any sample (the observed agreement ratio), and :math:`p_e` is
the expected agreement when both annotators assign labels randomly.
:math:`p_e` is estimated using a per-annotator empirical prior over the
class labels [2]_.
Read more in the :ref:`User Guide <cohen_kappa>`.
Parameters
----------
y1 : array, shape = [n_samples]
Labels assigned by the first annotator.
y2 : array, shape = [n_samples]
Labels assigned by the second annotator. The kappa statistic is
symmetric, so swapping ``y1`` and ``y2`` doesn't change the value.
labels : array, shape = [n_classes], optional
List of labels to index the matrix. This may be used to select a
subset of labels. If None, all labels that appear at least once in
``y1`` or ``y2`` are used.
weights : str, optional
List of weighting type to calculate the score. None means no weighted;
"linear" means linear weighted; "quadratic" means quadratic weighted.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
kappa : float
The kappa statistic, which is a number between -1 and 1. The maximum
value means complete agreement; zero or lower means chance agreement.
References
----------
.. [1] J. Cohen (1960). "A coefficient of agreement for nominal scales".
Educational and Psychological Measurement 20(1):37-46.
doi:10.1177/001316446002000104.
.. [2] `R. Artstein and M. Poesio (2008). "Inter-coder agreement for
computational linguistics". Computational Linguistics 34(4):555-596.
<http://www.mitpressjournals.org/doi/abs/10.1162/coli.07-034-R2#.V0J1MJMrIWo>`_
.. [3] `Wikipedia entry for the Cohen's kappa.
<https://en.wikipedia.org/wiki/Cohen%27s_kappa>`_
"""
confusion = confusion_matrix(y1, y2, labels=labels,
sample_weight=sample_weight)
n_classes = confusion.shape[0]
sum0 = np.sum(confusion, axis=0)
sum1 = np.sum(confusion, axis=1)
expected = np.outer(sum0, sum1) / np.sum(sum0)
if weights is None:
w_mat = np.ones([n_classes, n_classes], dtype=np.int)
w_mat.flat[:: n_classes + 1] = 0
elif weights == "linear" or weights == "quadratic":
w_mat = np.zeros([n_classes, n_classes], dtype=np.int)
w_mat += np.arange(n_classes)
if weights == "linear":
w_mat = np.abs(w_mat - w_mat.T)
else:
w_mat = (w_mat - w_mat.T) ** 2
else:
raise ValueError("Unknown kappa weighting type.")
k = np.sum(w_mat * confusion) / np.sum(w_mat * expected)
return 1 - k
def jaccard_similarity_score(y_true, y_pred, normalize=True,
sample_weight=None):
"""Jaccard similarity coefficient score
The Jaccard index [1], or Jaccard similarity coefficient, defined as
the size of the intersection divided by the size of the union of two label
sets, is used to compare set of predicted labels for a sample to the
corresponding set of labels in ``y_true``.
Read more in the :ref:`User Guide <jaccard_similarity_score>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) labels.
y_pred : 1d array-like, or label indicator array / sparse matrix
Predicted labels, as returned by a classifier.
normalize : bool, optional (default=True)
If ``False``, return the sum of the Jaccard similarity coefficient
over the sample set. Otherwise, return the average of Jaccard
similarity coefficient.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
score : float
If ``normalize == True``, return the average Jaccard similarity
coefficient, else it returns the sum of the Jaccard similarity
coefficient over the sample set.
The best performance is 1 with ``normalize == True`` and the number
of samples with ``normalize == False``.
See also
--------
accuracy_score, hamming_loss, zero_one_loss
Notes
-----
In binary and multiclass classification, this function is equivalent
to the ``accuracy_score``. It differs in the multilabel classification
problem.
References
----------
.. [1] `Wikipedia entry for the Jaccard index
<https://en.wikipedia.org/wiki/Jaccard_index>`_
Examples
--------
>>> import numpy as np
>>> from sklearn.metrics import jaccard_similarity_score
>>> y_pred = [0, 2, 1, 3]
>>> y_true = [0, 1, 2, 3]
>>> jaccard_similarity_score(y_true, y_pred)
0.5
>>> jaccard_similarity_score(y_true, y_pred, normalize=False)
2
In the multilabel case with binary label indicators:
>>> jaccard_similarity_score(np.array([[0, 1], [1, 1]]),\
np.ones((2, 2)))
0.75
"""
# Compute accuracy for each possible representation
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
if y_type.startswith('multilabel'):
with np.errstate(divide='ignore', invalid='ignore'):
# oddly, we may get an "invalid" rather than a "divide" error here
pred_or_true = count_nonzero(y_true + y_pred, axis=1)
pred_and_true = count_nonzero(y_true.multiply(y_pred), axis=1)
score = pred_and_true / pred_or_true
score[pred_or_true == 0.0] = 1.0
else:
score = y_true == y_pred
return _weighted_sum(score, sample_weight, normalize)
def matthews_corrcoef(y_true, y_pred, sample_weight=None):
"""Compute the Matthews correlation coefficient (MCC) for binary classes
The Matthews correlation coefficient is used in machine learning as a
measure of the quality of binary (two-class) classifications. It takes into
account true and false positives and negatives and is generally regarded as
a balanced measure which can be used even if the classes are of very
different sizes. The MCC is in essence a correlation coefficient value
between -1 and +1. A coefficient of +1 represents a perfect prediction, 0
an average random prediction and -1 an inverse prediction. The statistic
is also known as the phi coefficient. [source: Wikipedia]
Only in the binary case does this relate to information about true and
false positives and negatives. See references below.
Read more in the :ref:`User Guide <matthews_corrcoef>`.
Parameters
----------
y_true : array, shape = [n_samples]
Ground truth (correct) target values.
y_pred : array, shape = [n_samples]
Estimated targets as returned by a classifier.
sample_weight : array-like of shape = [n_samples], default None
Sample weights.
Returns
-------
mcc : float
The Matthews correlation coefficient (+1 represents a perfect
prediction, 0 an average random prediction and -1 and inverse
prediction).
References
----------
.. [1] `Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the
accuracy of prediction algorithms for classification: an overview
<http://dx.doi.org/10.1093/bioinformatics/16.5.412>`_
.. [2] `Wikipedia entry for the Matthews Correlation Coefficient
<https://en.wikipedia.org/wiki/Matthews_correlation_coefficient>`_
Examples
--------
>>> from sklearn.metrics import matthews_corrcoef
>>> y_true = [+1, +1, +1, -1]
>>> y_pred = [+1, -1, +1, +1]
>>> matthews_corrcoef(y_true, y_pred) # doctest: +ELLIPSIS
-0.33...
"""
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
if y_type != "binary":
raise ValueError("%s is not supported" % y_type)
lb = LabelEncoder()
lb.fit(np.hstack([y_true, y_pred]))
y_true = lb.transform(y_true)
y_pred = lb.transform(y_pred)
mean_yt = np.average(y_true, weights=sample_weight)
mean_yp = np.average(y_pred, weights=sample_weight)
y_true_u_cent = y_true - mean_yt
y_pred_u_cent = y_pred - mean_yp
cov_ytyp = np.average(y_true_u_cent * y_pred_u_cent, weights=sample_weight)
var_yt = np.average(y_true_u_cent ** 2, weights=sample_weight)
var_yp = np.average(y_pred_u_cent ** 2, weights=sample_weight)
mcc = cov_ytyp / np.sqrt(var_yt * var_yp)
if np.isnan(mcc):
return 0.
else:
return mcc
def zero_one_loss(y_true, y_pred, normalize=True, sample_weight=None):
"""Zero-one classification loss.
If normalize is ``True``, return the fraction of misclassifications
(float), else it returns the number of misclassifications (int). The best
performance is 0.
Read more in the :ref:`User Guide <zero_one_loss>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) labels.
y_pred : 1d array-like, or label indicator array / sparse matrix
Predicted labels, as returned by a classifier.
normalize : bool, optional (default=True)
If ``False``, return the number of misclassifications.
Otherwise, return the fraction of misclassifications.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
loss : float or int,
If ``normalize == True``, return the fraction of misclassifications
(float), else it returns the number of misclassifications (int).
Notes
-----
In multilabel classification, the zero_one_loss function corresponds to
the subset zero-one loss: for each sample, the entire set of labels must be
correctly predicted, otherwise the loss for that sample is equal to one.
See also
--------
accuracy_score, hamming_loss, jaccard_similarity_score
Examples
--------
>>> from sklearn.metrics import zero_one_loss
>>> y_pred = [1, 2, 3, 4]
>>> y_true = [2, 2, 3, 4]
>>> zero_one_loss(y_true, y_pred)
0.25
>>> zero_one_loss(y_true, y_pred, normalize=False)
1
In the multilabel case with binary label indicators:
>>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2)))
0.5
"""
score = accuracy_score(y_true, y_pred,
normalize=normalize,
sample_weight=sample_weight)
if normalize:
return 1 - score
else:
if sample_weight is not None:
n_samples = np.sum(sample_weight)
else:
n_samples = _num_samples(y_true)
return n_samples - score
def f1_score(y_true, y_pred, labels=None, pos_label=1, average='binary',
sample_weight=None):
"""Compute the F1 score, also known as balanced F-score or F-measure
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score are
equal. The formula for the F1 score is::
F1 = 2 * (precision * recall) / (precision + recall)
In the multi-class and multi-label case, this is the weighted average of
the F1 score of each class.
Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) target values.
y_pred : 1d array-like, or label indicator array / sparse matrix
Estimated targets as returned by a classifier.
labels : list, optional
The set of labels to include when ``average != 'binary'``, and their
order if ``average is None``. Labels present in the data can be
excluded, for example to calculate a multiclass average ignoring a
majority negative class, while labels not present in the data will
result in 0 components in a macro average. For multilabel targets,
labels are column indices. By default, all labels in ``y_true`` and
``y_pred`` are used in sorted order.
.. versionchanged:: 0.17
parameter *labels* improved for multiclass problem.
pos_label : str or int, 1 by default
The class to report if ``average='binary'`` and the data is binary.
If the data are multiclass or multilabel, this will be ignored;
setting ``labels=[pos_label]`` and ``average != 'binary'`` will report
scores for that label only.
average : string, [None, 'binary' (default), 'micro', 'macro', 'samples', \
'weighted']
This parameter is required for multiclass/multilabel targets.
If ``None``, the scores for each class are returned. Otherwise, this
determines the type of averaging performed on the data:
``'binary'``:
Only report results for the class specified by ``pos_label``.
This is applicable only if targets (``y_{true,pred}``) are binary.
``'micro'``:
Calculate metrics globally by counting the total true positives,
false negatives and false positives.
``'macro'``:
Calculate metrics for each label, and find their unweighted
mean. This does not take label imbalance into account.
``'weighted'``:
Calculate metrics for each label, and find their average, weighted
by support (the number of true instances for each label). This
alters 'macro' to account for label imbalance; it can result in an
F-score that is not between precision and recall.
``'samples'``:
Calculate metrics for each instance, and find their average (only
meaningful for multilabel classification where this differs from
:func:`accuracy_score`).
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
f1_score : float or array of float, shape = [n_unique_labels]
F1 score of the positive class in binary classification or weighted
average of the F1 scores of each class for the multiclass task.
References
----------
.. [1] `Wikipedia entry for the F1-score
<https://en.wikipedia.org/wiki/F1_score>`_
Examples
--------
>>> from sklearn.metrics import f1_score
>>> y_true = [0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 2, 1, 0, 0, 1]
>>> f1_score(y_true, y_pred, average='macro') # doctest: +ELLIPSIS
0.26...
>>> f1_score(y_true, y_pred, average='micro') # doctest: +ELLIPSIS
0.33...
>>> f1_score(y_true, y_pred, average='weighted') # doctest: +ELLIPSIS
0.26...
>>> f1_score(y_true, y_pred, average=None)
array([ 0.8, 0. , 0. ])
"""
return fbeta_score(y_true, y_pred, 1, labels=labels,
pos_label=pos_label, average=average,
sample_weight=sample_weight)
def fbeta_score(y_true, y_pred, beta, labels=None, pos_label=1,
average='binary', sample_weight=None):
"""Compute the F-beta score
The F-beta score is the weighted harmonic mean of precision and recall,
reaching its optimal value at 1 and its worst value at 0.
The `beta` parameter determines the weight of precision in the combined
score. ``beta < 1`` lends more weight to precision, while ``beta > 1``
favors recall (``beta -> 0`` considers only precision, ``beta -> inf``
only recall).
Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) target values.
y_pred : 1d array-like, or label indicator array / sparse matrix
Estimated targets as returned by a classifier.
beta : float
Weight of precision in harmonic mean.
labels : list, optional
The set of labels to include when ``average != 'binary'``, and their
order if ``average is None``. Labels present in the data can be
excluded, for example to calculate a multiclass average ignoring a
majority negative class, while labels not present in the data will
result in 0 components in a macro average. For multilabel targets,
labels are column indices. By default, all labels in ``y_true`` and
``y_pred`` are used in sorted order.
.. versionchanged:: 0.17
parameter *labels* improved for multiclass problem.
pos_label : str or int, 1 by default
The class to report if ``average='binary'`` and the data is binary.
If the data are multiclass or multilabel, this will be ignored;
setting ``labels=[pos_label]`` and ``average != 'binary'`` will report
scores for that label only.
average : string, [None, 'binary' (default), 'micro', 'macro', 'samples', \
'weighted']
This parameter is required for multiclass/multilabel targets.
If ``None``, the scores for each class are returned. Otherwise, this
determines the type of averaging performed on the data:
``'binary'``:
Only report results for the class specified by ``pos_label``.
This is applicable only if targets (``y_{true,pred}``) are binary.
``'micro'``:
Calculate metrics globally by counting the total true positives,
false negatives and false positives.
``'macro'``:
Calculate metrics for each label, and find their unweighted
mean. This does not take label imbalance into account.
``'weighted'``:
Calculate metrics for each label, and find their average, weighted
by support (the number of true instances for each label). This
alters 'macro' to account for label imbalance; it can result in an
F-score that is not between precision and recall.
``'samples'``:
Calculate metrics for each instance, and find their average (only
meaningful for multilabel classification where this differs from
:func:`accuracy_score`).
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
fbeta_score : float (if average is not None) or array of float, shape =\
[n_unique_labels]
F-beta score of the positive class in binary classification or weighted
average of the F-beta score of each class for the multiclass task.
References
----------
.. [1] R. Baeza-Yates and B. Ribeiro-Neto (2011).
Modern Information Retrieval. Addison Wesley, pp. 327-328.
.. [2] `Wikipedia entry for the F1-score
<https://en.wikipedia.org/wiki/F1_score>`_
Examples
--------
>>> from sklearn.metrics import fbeta_score
>>> y_true = [0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 2, 1, 0, 0, 1]
>>> fbeta_score(y_true, y_pred, average='macro', beta=0.5)
... # doctest: +ELLIPSIS
0.23...
>>> fbeta_score(y_true, y_pred, average='micro', beta=0.5)
... # doctest: +ELLIPSIS
0.33...
>>> fbeta_score(y_true, y_pred, average='weighted', beta=0.5)
... # doctest: +ELLIPSIS
0.23...
>>> fbeta_score(y_true, y_pred, average=None, beta=0.5)
... # doctest: +ELLIPSIS
array([ 0.71..., 0. , 0. ])
"""
_, _, f, _ = precision_recall_fscore_support(y_true, y_pred,
beta=beta,
labels=labels,
pos_label=pos_label,
average=average,
warn_for=('f-score',),
sample_weight=sample_weight)
return f
def _prf_divide(numerator, denominator, metric, modifier, average, warn_for):
"""Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements to zero
and raises a warning.
The metric, modifier and average arguments are used only for determining
an appropriate warning.
"""
result = numerator / denominator
mask = denominator == 0.0
if not np.any(mask):
return result
# remove infs
result[mask] = 0.0
# build appropriate warning
# E.g. "Precision and F-score are ill-defined and being set to 0.0 in
# labels with no predicted samples"
axis0 = 'sample'
axis1 = 'label'
if average == 'samples':
axis0, axis1 = axis1, axis0
if metric in warn_for and 'f-score' in warn_for:
msg_start = '{0} and F-score are'.format(metric.title())
elif metric in warn_for:
msg_start = '{0} is'.format(metric.title())
elif 'f-score' in warn_for:
msg_start = 'F-score is'
else:
return result
msg = ('{0} ill-defined and being set to 0.0 {{0}} '
'no {1} {2}s.'.format(msg_start, modifier, axis0))
if len(mask) == 1:
msg = msg.format('due to')
else:
msg = msg.format('in {0}s with'.format(axis1))
warnings.warn(msg, UndefinedMetricWarning, stacklevel=2)
return result
def precision_recall_fscore_support(y_true, y_pred, beta=1.0, labels=None,
pos_label=1, average=None,
warn_for=('precision', 'recall',
'f-score'),
sample_weight=None):
"""Compute precision, recall, F-measure and support for each class
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability of the classifier not to label as positive a sample
that is negative.
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives. The recall is
intuitively the ability of the classifier to find all the positive samples.
The F-beta score can be interpreted as a weighted harmonic mean of
the precision and recall, where an F-beta score reaches its best
value at 1 and worst score at 0.
The F-beta score weights recall more than precision by a factor of
``beta``. ``beta == 1.0`` means recall and precision are equally important.
The support is the number of occurrences of each class in ``y_true``.
If ``pos_label is None`` and in binary classification, this function
returns the average precision, recall and F-measure if ``average``
is one of ``'micro'``, ``'macro'``, ``'weighted'`` or ``'samples'``.
Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) target values.
y_pred : 1d array-like, or label indicator array / sparse matrix
Estimated targets as returned by a classifier.
beta : float, 1.0 by default
The strength of recall versus precision in the F-score.
labels : list, optional
The set of labels to include when ``average != 'binary'``, and their
order if ``average is None``. Labels present in the data can be
excluded, for example to calculate a multiclass average ignoring a
majority negative class, while labels not present in the data will
result in 0 components in a macro average. For multilabel targets,
labels are column indices. By default, all labels in ``y_true`` and
``y_pred`` are used in sorted order.
pos_label : str or int, 1 by default
The class to report if ``average='binary'`` and the data is binary.
If the data are multiclass or multilabel, this will be ignored;
setting ``labels=[pos_label]`` and ``average != 'binary'`` will report
scores for that label only.
average : string, [None (default), 'binary', 'micro', 'macro', 'samples', \
'weighted']
If ``None``, the scores for each class are returned. Otherwise, this
determines the type of averaging performed on the data:
``'binary'``:
Only report results for the class specified by ``pos_label``.
This is applicable only if targets (``y_{true,pred}``) are binary.
``'micro'``:
Calculate metrics globally by counting the total true positives,
false negatives and false positives.
``'macro'``:
Calculate metrics for each label, and find their unweighted
mean. This does not take label imbalance into account.
``'weighted'``:
Calculate metrics for each label, and find their average, weighted
by support (the number of true instances for each label). This
alters 'macro' to account for label imbalance; it can result in an
F-score that is not between precision and recall.
``'samples'``:
Calculate metrics for each instance, and find their average (only
meaningful for multilabel classification where this differs from
:func:`accuracy_score`).
warn_for : tuple or set, for internal use
This determines which warnings will be made in the case that this
function is being used to return only one of its metrics.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
precision : float (if average is not None) or array of float, shape =\
[n_unique_labels]
recall : float (if average is not None) or array of float, , shape =\
[n_unique_labels]
fbeta_score : float (if average is not None) or array of float, shape =\
[n_unique_labels]
support : int (if average is not None) or array of int, shape =\
[n_unique_labels]
The number of occurrences of each label in ``y_true``.
References
----------
.. [1] `Wikipedia entry for the Precision and recall
<https://en.wikipedia.org/wiki/Precision_and_recall>`_
.. [2] `Wikipedia entry for the F1-score
<https://en.wikipedia.org/wiki/F1_score>`_
.. [3] `Discriminative Methods for Multi-labeled Classification Advances
in Knowledge Discovery and Data Mining (2004), pp. 22-30 by Shantanu
Godbole, Sunita Sarawagi
<http://www.godbole.net/shantanu/pubs/multilabelsvm-pakdd04.pdf>`
Examples
--------
>>> from sklearn.metrics import precision_recall_fscore_support
>>> y_true = np.array(['cat', 'dog', 'pig', 'cat', 'dog', 'pig'])
>>> y_pred = np.array(['cat', 'pig', 'dog', 'cat', 'cat', 'dog'])
>>> precision_recall_fscore_support(y_true, y_pred, average='macro')
... # doctest: +ELLIPSIS
(0.22..., 0.33..., 0.26..., None)
>>> precision_recall_fscore_support(y_true, y_pred, average='micro')
... # doctest: +ELLIPSIS
(0.33..., 0.33..., 0.33..., None)
>>> precision_recall_fscore_support(y_true, y_pred, average='weighted')
... # doctest: +ELLIPSIS
(0.22..., 0.33..., 0.26..., None)
It is possible to compute per-label precisions, recalls, F1-scores and
supports instead of averaging:
>>> precision_recall_fscore_support(y_true, y_pred, average=None,
... labels=['pig', 'dog', 'cat'])
... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
(array([ 0. , 0. , 0.66...]),
array([ 0., 0., 1.]),
array([ 0. , 0. , 0.8]),
array([2, 2, 2]))
"""
average_options = (None, 'micro', 'macro', 'weighted', 'samples')
if average not in average_options and average != 'binary':
raise ValueError('average has to be one of ' +
str(average_options))
if beta <= 0:
raise ValueError("beta should be >0 in the F-beta score")
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
present_labels = unique_labels(y_true, y_pred)
if average == 'binary':
if y_type == 'binary':
if pos_label not in present_labels:
if len(present_labels) < 2:
# Only negative labels
return (0., 0., 0., 0)
else:
raise ValueError("pos_label=%r is not a valid label: %r" %
(pos_label, present_labels))
labels = [pos_label]
else:
raise ValueError("Target is %s but average='binary'. Please "
"choose another average setting." % y_type)
elif pos_label not in (None, 1):
warnings.warn("Note that pos_label (set to %r) is ignored when "
"average != 'binary' (got %r). You may use "
"labels=[pos_label] to specify a single positive class."
% (pos_label, average), UserWarning)
if labels is None:
labels = present_labels
n_labels = None
else:
n_labels = len(labels)
labels = np.hstack([labels, np.setdiff1d(present_labels, labels,
assume_unique=True)])
# Calculate tp_sum, pred_sum, true_sum ###
if y_type.startswith('multilabel'):
sum_axis = 1 if average == 'samples' else 0
# All labels are index integers for multilabel.
# Select labels:
if not np.all(labels == present_labels):
if np.max(labels) > np.max(present_labels):
raise ValueError('All labels must be in [0, n labels). '
'Got %d > %d' %
(np.max(labels), np.max(present_labels)))
if np.min(labels) < 0:
raise ValueError('All labels must be in [0, n labels). '
'Got %d < 0' % np.min(labels))
y_true = y_true[:, labels[:n_labels]]
y_pred = y_pred[:, labels[:n_labels]]
# calculate weighted counts
true_and_pred = y_true.multiply(y_pred)
tp_sum = count_nonzero(true_and_pred, axis=sum_axis,
sample_weight=sample_weight)
pred_sum = count_nonzero(y_pred, axis=sum_axis,
sample_weight=sample_weight)
true_sum = count_nonzero(y_true, axis=sum_axis,
sample_weight=sample_weight)
elif average == 'samples':
raise ValueError("Sample-based precision, recall, fscore is "
"not meaningful outside multilabel "
"classification. See the accuracy_score instead.")
else:
le = LabelEncoder()
le.fit(labels)
y_true = le.transform(y_true)
y_pred = le.transform(y_pred)
sorted_labels = le.classes_
# labels are now from 0 to len(labels) - 1 -> use bincount
tp = y_true == y_pred
tp_bins = y_true[tp]
if sample_weight is not None:
tp_bins_weights = np.asarray(sample_weight)[tp]
else:
tp_bins_weights = None
if len(tp_bins):
tp_sum = bincount(tp_bins, weights=tp_bins_weights,
minlength=len(labels))
else:
# Pathological case
true_sum = pred_sum = tp_sum = np.zeros(len(labels))
if len(y_pred):
pred_sum = bincount(y_pred, weights=sample_weight,
minlength=len(labels))
if len(y_true):
true_sum = bincount(y_true, weights=sample_weight,
minlength=len(labels))
# Retain only selected labels
indices = np.searchsorted(sorted_labels, labels[:n_labels])
tp_sum = tp_sum[indices]
true_sum = true_sum[indices]
pred_sum = pred_sum[indices]
if average == 'micro':
tp_sum = np.array([tp_sum.sum()])
pred_sum = np.array([pred_sum.sum()])
true_sum = np.array([true_sum.sum()])
# Finally, we have all our sufficient statistics. Divide! #
beta2 = beta ** 2
with np.errstate(divide='ignore', invalid='ignore'):
# Divide, and on zero-division, set scores to 0 and warn:
# Oddly, we may get an "invalid" rather than a "divide" error
# here.
precision = _prf_divide(tp_sum, pred_sum,
'precision', 'predicted', average, warn_for)
recall = _prf_divide(tp_sum, true_sum,
'recall', 'true', average, warn_for)
# Don't need to warn for F: either P or R warned, or tp == 0 where pos
# and true are nonzero, in which case, F is well-defined and zero
f_score = ((1 + beta2) * precision * recall /
(beta2 * precision + recall))
f_score[tp_sum == 0] = 0.0
# Average the results
if average == 'weighted':
weights = true_sum
if weights.sum() == 0:
return 0, 0, 0, None
elif average == 'samples':
weights = sample_weight
else:
weights = None
if average is not None:
assert average != 'binary' or len(precision) == 1
precision = np.average(precision, weights=weights)
recall = np.average(recall, weights=weights)
f_score = np.average(f_score, weights=weights)
true_sum = None # return no support
return precision, recall, f_score, true_sum
def precision_score(y_true, y_pred, labels=None, pos_label=1,
average='binary', sample_weight=None):
"""Compute the precision
The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
true positives and ``fp`` the number of false positives. The precision is
intuitively the ability of the classifier not to label as positive a sample
that is negative.
The best value is 1 and the worst value is 0.
Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) target values.
y_pred : 1d array-like, or label indicator array / sparse matrix
Estimated targets as returned by a classifier.
labels : list, optional
The set of labels to include when ``average != 'binary'``, and their
order if ``average is None``. Labels present in the data can be
excluded, for example to calculate a multiclass average ignoring a
majority negative class, while labels not present in the data will
result in 0 components in a macro average. For multilabel targets,
labels are column indices. By default, all labels in ``y_true`` and
``y_pred`` are used in sorted order.
.. versionchanged:: 0.17
parameter *labels* improved for multiclass problem.
pos_label : str or int, 1 by default
The class to report if ``average='binary'`` and the data is binary.
If the data are multiclass or multilabel, this will be ignored;
setting ``labels=[pos_label]`` and ``average != 'binary'`` will report
scores for that label only.
average : string, [None, 'binary' (default), 'micro', 'macro', 'samples', \
'weighted']
This parameter is required for multiclass/multilabel targets.
If ``None``, the scores for each class are returned. Otherwise, this
determines the type of averaging performed on the data:
``'binary'``:
Only report results for the class specified by ``pos_label``.
This is applicable only if targets (``y_{true,pred}``) are binary.
``'micro'``:
Calculate metrics globally by counting the total true positives,
false negatives and false positives.
``'macro'``:
Calculate metrics for each label, and find their unweighted
mean. This does not take label imbalance into account.
``'weighted'``:
Calculate metrics for each label, and find their average, weighted
by support (the number of true instances for each label). This
alters 'macro' to account for label imbalance; it can result in an
F-score that is not between precision and recall.
``'samples'``:
Calculate metrics for each instance, and find their average (only
meaningful for multilabel classification where this differs from
:func:`accuracy_score`).
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
precision : float (if average is not None) or array of float, shape =\
[n_unique_labels]
Precision of the positive class in binary classification or weighted
average of the precision of each class for the multiclass task.
Examples
--------
>>> from sklearn.metrics import precision_score
>>> y_true = [0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 2, 1, 0, 0, 1]
>>> precision_score(y_true, y_pred, average='macro') # doctest: +ELLIPSIS
0.22...
>>> precision_score(y_true, y_pred, average='micro') # doctest: +ELLIPSIS
0.33...
>>> precision_score(y_true, y_pred, average='weighted')
... # doctest: +ELLIPSIS
0.22...
>>> precision_score(y_true, y_pred, average=None) # doctest: +ELLIPSIS
array([ 0.66..., 0. , 0. ])
"""
p, _, _, _ = precision_recall_fscore_support(y_true, y_pred,
labels=labels,
pos_label=pos_label,
average=average,
warn_for=('precision',),
sample_weight=sample_weight)
return p
def recall_score(y_true, y_pred, labels=None, pos_label=1, average='binary',
sample_weight=None):
"""Compute the recall
The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
true positives and ``fn`` the number of false negatives. The recall is
intuitively the ability of the classifier to find all the positive samples.
The best value is 1 and the worst value is 0.
Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) target values.
y_pred : 1d array-like, or label indicator array / sparse matrix
Estimated targets as returned by a classifier.
labels : list, optional
The set of labels to include when ``average != 'binary'``, and their
order if ``average is None``. Labels present in the data can be
excluded, for example to calculate a multiclass average ignoring a
majority negative class, while labels not present in the data will
result in 0 components in a macro average. For multilabel targets,
labels are column indices. By default, all labels in ``y_true`` and
``y_pred`` are used in sorted order.
.. versionchanged:: 0.17
parameter *labels* improved for multiclass problem.
pos_label : str or int, 1 by default
The class to report if ``average='binary'`` and the data is binary.
If the data are multiclass or multilabel, this will be ignored;
setting ``labels=[pos_label]`` and ``average != 'binary'`` will report
scores for that label only.
average : string, [None, 'binary' (default), 'micro', 'macro', 'samples', \
'weighted']
This parameter is required for multiclass/multilabel targets.
If ``None``, the scores for each class are returned. Otherwise, this
determines the type of averaging performed on the data:
``'binary'``:
Only report results for the class specified by ``pos_label``.
This is applicable only if targets (``y_{true,pred}``) are binary.
``'micro'``:
Calculate metrics globally by counting the total true positives,
false negatives and false positives.
``'macro'``:
Calculate metrics for each label, and find their unweighted
mean. This does not take label imbalance into account.
``'weighted'``:
Calculate metrics for each label, and find their average, weighted
by support (the number of true instances for each label). This
alters 'macro' to account for label imbalance; it can result in an
F-score that is not between precision and recall.
``'samples'``:
Calculate metrics for each instance, and find their average (only
meaningful for multilabel classification where this differs from
:func:`accuracy_score`).
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
recall : float (if average is not None) or array of float, shape =\
[n_unique_labels]
Recall of the positive class in binary classification or weighted
average of the recall of each class for the multiclass task.
Examples
--------
>>> from sklearn.metrics import recall_score
>>> y_true = [0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 2, 1, 0, 0, 1]
>>> recall_score(y_true, y_pred, average='macro') # doctest: +ELLIPSIS
0.33...
>>> recall_score(y_true, y_pred, average='micro') # doctest: +ELLIPSIS
0.33...
>>> recall_score(y_true, y_pred, average='weighted') # doctest: +ELLIPSIS
0.33...
>>> recall_score(y_true, y_pred, average=None)
array([ 1., 0., 0.])
"""
_, r, _, _ = precision_recall_fscore_support(y_true, y_pred,
labels=labels,
pos_label=pos_label,
average=average,
warn_for=('recall',),
sample_weight=sample_weight)
return r
def classification_report(y_true, y_pred, labels=None, target_names=None,
sample_weight=None, digits=2):
"""Build a text report showing the main classification metrics
Read more in the :ref:`User Guide <classification_report>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) target values.
y_pred : 1d array-like, or label indicator array / sparse matrix
Estimated targets as returned by a classifier.
labels : array, shape = [n_labels]
Optional list of label indices to include in the report.
target_names : list of strings
Optional display names matching the labels (same order).
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
digits : int
Number of digits for formatting output floating point values
Returns
-------
report : string
Text summary of the precision, recall, F1 score for each class.
The reported averages are a prevalence-weighted macro-average across
classes (equivalent to :func:`precision_recall_fscore_support` with
``average='weighted'``).
Note that in binary classification, recall of the positive class
is also known as "sensitivity"; recall of the negative class is
"specificity".
Examples
--------
>>> from sklearn.metrics import classification_report
>>> y_true = [0, 1, 2, 2, 2]
>>> y_pred = [0, 0, 2, 2, 1]
>>> target_names = ['class 0', 'class 1', 'class 2']
>>> print(classification_report(y_true, y_pred, target_names=target_names))
precision recall f1-score support
<BLANKLINE>
class 0 0.50 1.00 0.67 1
class 1 0.00 0.00 0.00 1
class 2 1.00 0.67 0.80 3
<BLANKLINE>
avg / total 0.70 0.60 0.61 5
<BLANKLINE>
"""
if labels is None:
labels = unique_labels(y_true, y_pred)
else:
labels = np.asarray(labels)
if target_names is not None and len(labels) != len(target_names):
warnings.warn(
"labels size, {0}, does not match size of target_names, {1}"
.format(len(labels), len(target_names))
)
last_line_heading = 'avg / total'
if target_names is None:
target_names = [u'%s' % l for l in labels]
name_width = max(len(cn) for cn in target_names)
width = max(name_width, len(last_line_heading), digits)
headers = ["precision", "recall", "f1-score", "support"]
head_fmt = u'{:>{width}s} ' + u' {:>9}' * len(headers)
report = head_fmt.format(u'', *headers, width=width)
report += u'\n\n'
p, r, f1, s = precision_recall_fscore_support(y_true, y_pred,
labels=labels,
average=None,
sample_weight=sample_weight)
row_fmt = u'{:>{width}s} ' + u' {:>9.{digits}f}' * 3 + u' {:>9}\n'
rows = zip(target_names, p, r, f1, s)
for row in rows:
report += row_fmt.format(*row, width=width, digits=digits)
report += u'\n'
# compute averages
report += row_fmt.format(last_line_heading,
np.average(p, weights=s),
np.average(r, weights=s),
np.average(f1, weights=s),
np.sum(s),
width=width, digits=digits)
return report
def hamming_loss(y_true, y_pred, labels=None, sample_weight=None,
classes=None):
"""Compute the average Hamming loss.
The Hamming loss is the fraction of labels that are incorrectly predicted.
Read more in the :ref:`User Guide <hamming_loss>`.
Parameters
----------
y_true : 1d array-like, or label indicator array / sparse matrix
Ground truth (correct) labels.
y_pred : 1d array-like, or label indicator array / sparse matrix
Predicted labels, as returned by a classifier.
labels : array, shape = [n_labels], optional (default=None)
Integer array of labels. If not provided, labels will be inferred
from y_true and y_pred.
.. versionadded:: 0.18
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
.. versionadded:: 0.18
classes : array, shape = [n_labels], optional
(deprecated) Integer array of labels. This parameter has been
renamed to ``labels`` in version 0.18 and will be removed in 0.20.
Returns
-------
loss : float or int,
Return the average Hamming loss between element of ``y_true`` and
``y_pred``.
See Also
--------
accuracy_score, jaccard_similarity_score, zero_one_loss
Notes
-----
In multiclass classification, the Hamming loss correspond to the Hamming
distance between ``y_true`` and ``y_pred`` which is equivalent to the
subset ``zero_one_loss`` function.
In multilabel classification, the Hamming loss is different from the
subset zero-one loss. The zero-one loss considers the entire set of labels
for a given sample incorrect if it does entirely match the true set of
labels. Hamming loss is more forgiving in that it penalizes the individual
labels.
The Hamming loss is upperbounded by the subset zero-one loss. When
normalized over samples, the Hamming loss is always between 0 and 1.
References
----------
.. [1] Grigorios Tsoumakas, Ioannis Katakis. Multi-Label Classification:
An Overview. International Journal of Data Warehousing & Mining,
3(3), 1-13, July-September 2007.
.. [2] `Wikipedia entry on the Hamming distance
<https://en.wikipedia.org/wiki/Hamming_distance>`_
Examples
--------
>>> from sklearn.metrics import hamming_loss
>>> y_pred = [1, 2, 3, 4]
>>> y_true = [2, 2, 3, 4]
>>> hamming_loss(y_true, y_pred)
0.25
In the multilabel case with binary label indicators:
>>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2)))
0.75
"""
if classes is not None:
warnings.warn("'classes' was renamed to 'labels' in version 0.18 and "
"will be removed in 0.20.", DeprecationWarning)
labels = classes
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
if labels is None:
labels = unique_labels(y_true, y_pred)
else:
labels = np.asarray(labels)
if sample_weight is None:
weight_average = 1.
else:
weight_average = np.mean(sample_weight)
if y_type.startswith('multilabel'):
n_differences = count_nonzero(y_true - y_pred,
sample_weight=sample_weight)
return (n_differences /
(y_true.shape[0] * len(labels) * weight_average))
elif y_type in ["binary", "multiclass"]:
return _weighted_sum(y_true != y_pred, sample_weight, normalize=True)
else:
raise ValueError("{0} is not supported".format(y_type))
def log_loss(y_true, y_pred, eps=1e-15, normalize=True, sample_weight=None,
labels=None):
"""Log loss, aka logistic loss or cross-entropy loss.
This is the loss function used in (multinomial) logistic regression
and extensions of it such as neural networks, defined as the negative
log-likelihood of the true labels given a probabilistic classifier's
predictions. The log loss is only defined for two or more labels.
For a single sample with true label yt in {0,1} and
estimated probability yp that yt = 1, the log loss is
-log P(yt|yp) = -(yt log(yp) + (1 - yt) log(1 - yp))
Read more in the :ref:`User Guide <log_loss>`.
Parameters
----------
y_true : array-like or label indicator matrix
Ground truth (correct) labels for n_samples samples.
y_pred : array-like of float, shape = (n_samples, n_classes) or (n_samples,)
Predicted probabilities, as returned by a classifier's
predict_proba method. If ``y_pred.shape = (n_samples,)``
the probabilities provided are assumed to be that of the
positive class. The labels in ``y_pred`` are assumed to be
ordered alphabetically, as done by
:class:`preprocessing.LabelBinarizer`.
eps : float
Log loss is undefined for p=0 or p=1, so probabilities are
clipped to max(eps, min(1 - eps, p)).
normalize : bool, optional (default=True)
If true, return the mean loss per sample.
Otherwise, return the sum of the per-sample losses.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
labels : array-like, optional (default=None)
If not provided, labels will be inferred from y_true. If ``labels``
is ``None`` and ``y_pred`` has shape (n_samples,) the labels are
assumed to be binary and are inferred from ``y_true``.
.. versionadded:: 0.18
Returns
-------
loss : float
Examples
--------
>>> log_loss(["spam", "ham", "ham", "spam"], # doctest: +ELLIPSIS
... [[.1, .9], [.9, .1], [.8, .2], [.35, .65]])
0.21616...
References
----------
C.M. Bishop (2006). Pattern Recognition and Machine Learning. Springer,
p. 209.
Notes
-----
The logarithm used is the natural logarithm (base-e).
"""
y_pred = check_array(y_pred, ensure_2d=False)
check_consistent_length(y_pred, y_true)
lb = LabelBinarizer()
if labels is not None:
lb.fit(labels)
else:
lb.fit(y_true)
if len(lb.classes_) == 1:
if labels is None:
raise ValueError('y_true contains only one label ({0}). Please '
'provide the true labels explicitly through the '
'labels argument.'.format(lb.classes_[0]))
else:
raise ValueError('The labels array needs to contain at least two '
'labels for log_loss, '
'got {0}.'.format(lb.classes_))
transformed_labels = lb.transform(y_true)
if transformed_labels.shape[1] == 1:
transformed_labels = np.append(1 - transformed_labels,
transformed_labels, axis=1)
# Clipping
y_pred = np.clip(y_pred, eps, 1 - eps)
# If y_pred is of single dimension, assume y_true to be binary
# and then check.
if y_pred.ndim == 1:
y_pred = y_pred[:, np.newaxis]
if y_pred.shape[1] == 1:
y_pred = np.append(1 - y_pred, y_pred, axis=1)
# Check if dimensions are consistent.
transformed_labels = check_array(transformed_labels)
if len(lb.classes_) != y_pred.shape[1]:
if labels is None:
raise ValueError("y_true and y_pred contain different number of "
"classes {0}, {1}. Please provide the true "
"labels explicitly through the labels argument. "
"Classes found in "
"y_true: {2}".format(transformed_labels.shape[1],
y_pred.shape[1],
lb.classes_))
else:
raise ValueError('The number of classes in labels is different '
'from that in y_pred. Classes found in '
'labels: {0}'.format(lb.classes_))
# Renormalize
y_pred /= y_pred.sum(axis=1)[:, np.newaxis]
loss = -(transformed_labels * np.log(y_pred)).sum(axis=1)
return _weighted_sum(loss, sample_weight, normalize)
def hinge_loss(y_true, pred_decision, labels=None, sample_weight=None):
"""Average hinge loss (non-regularized)
In binary class case, assuming labels in y_true are encoded with +1 and -1,
when a prediction mistake is made, ``margin = y_true * pred_decision`` is
always negative (since the signs disagree), implying ``1 - margin`` is
always greater than 1. The cumulated hinge loss is therefore an upper
bound of the number of mistakes made by the classifier.
In multiclass case, the function expects that either all the labels are
included in y_true or an optional labels argument is provided which
contains all the labels. The multilabel margin is calculated according
to Crammer-Singer's method. As in the binary case, the cumulated hinge loss
is an upper bound of the number of mistakes made by the classifier.
Read more in the :ref:`User Guide <hinge_loss>`.
Parameters
----------
y_true : array, shape = [n_samples]
True target, consisting of integers of two values. The positive label
must be greater than the negative label.
pred_decision : array, shape = [n_samples] or [n_samples, n_classes]
Predicted decisions, as output by decision_function (floats).
labels : array, optional, default None
Contains all the labels for the problem. Used in multiclass hinge loss.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
Returns
-------
loss : float
References
----------
.. [1] `Wikipedia entry on the Hinge loss
<https://en.wikipedia.org/wiki/Hinge_loss>`_
.. [2] Koby Crammer, Yoram Singer. On the Algorithmic
Implementation of Multiclass Kernel-based Vector
Machines. Journal of Machine Learning Research 2,
(2001), 265-292
.. [3] `L1 AND L2 Regularization for Multiclass Hinge Loss Models
by Robert C. Moore, John DeNero.
<http://www.ttic.edu/sigml/symposium2011/papers/
Moore+DeNero_Regularization.pdf>`_
Examples
--------
>>> from sklearn import svm
>>> from sklearn.metrics import hinge_loss
>>> X = [[0], [1]]
>>> y = [-1, 1]
>>> est = svm.LinearSVC(random_state=0)
>>> est.fit(X, y)
LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,
intercept_scaling=1, loss='squared_hinge', max_iter=1000,
multi_class='ovr', penalty='l2', random_state=0, tol=0.0001,
verbose=0)
>>> pred_decision = est.decision_function([[-2], [3], [0.5]])
>>> pred_decision # doctest: +ELLIPSIS
array([-2.18..., 2.36..., 0.09...])
>>> hinge_loss([-1, 1, 1], pred_decision) # doctest: +ELLIPSIS
0.30...
In the multiclass case:
>>> X = np.array([[0], [1], [2], [3]])
>>> Y = np.array([0, 1, 2, 3])
>>> labels = np.array([0, 1, 2, 3])
>>> est = svm.LinearSVC()
>>> est.fit(X, Y)
LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,
intercept_scaling=1, loss='squared_hinge', max_iter=1000,
multi_class='ovr', penalty='l2', random_state=None, tol=0.0001,
verbose=0)
>>> pred_decision = est.decision_function([[-1], [2], [3]])
>>> y_true = [0, 2, 3]
>>> hinge_loss(y_true, pred_decision, labels) #doctest: +ELLIPSIS
0.56...
"""
check_consistent_length(y_true, pred_decision, sample_weight)
pred_decision = check_array(pred_decision, ensure_2d=False)
y_true = column_or_1d(y_true)
y_true_unique = np.unique(y_true)
if y_true_unique.size > 2:
if (labels is None and pred_decision.ndim > 1 and
(np.size(y_true_unique) != pred_decision.shape[1])):
raise ValueError("Please include all labels in y_true "
"or pass labels as third argument")
if labels is None:
labels = y_true_unique
le = LabelEncoder()
le.fit(labels)
y_true = le.transform(y_true)
mask = np.ones_like(pred_decision, dtype=bool)
mask[np.arange(y_true.shape[0]), y_true] = False
margin = pred_decision[~mask]
margin -= np.max(pred_decision[mask].reshape(y_true.shape[0], -1),
axis=1)
else:
# Handles binary class case
# this code assumes that positive and negative labels
# are encoded as +1 and -1 respectively
pred_decision = column_or_1d(pred_decision)
pred_decision = np.ravel(pred_decision)
lbin = LabelBinarizer(neg_label=-1)
y_true = lbin.fit_transform(y_true)[:, 0]
try:
margin = y_true * pred_decision
except TypeError:
raise TypeError("pred_decision should be an array of floats.")
losses = 1 - margin
# The hinge_loss doesn't penalize good enough predictions.
losses[losses <= 0] = 0
return np.average(losses, weights=sample_weight)
def _check_binary_probabilistic_predictions(y_true, y_prob):
"""Check that y_true is binary and y_prob contains valid probabilities"""
check_consistent_length(y_true, y_prob)
labels = np.unique(y_true)
if len(labels) > 2:
raise ValueError("Only binary classification is supported. "
"Provided labels %s." % labels)
if y_prob.max() > 1:
raise ValueError("y_prob contains values greater than 1.")
if y_prob.min() < 0:
raise ValueError("y_prob contains values less than 0.")
return label_binarize(y_true, labels)[:, 0]
def brier_score_loss(y_true, y_prob, sample_weight=None, pos_label=None):
"""Compute the Brier score.
The smaller the Brier score, the better, hence the naming with "loss".
Across all items in a set N predictions, the Brier score measures the
mean squared difference between (1) the predicted probability assigned
to the possible outcomes for item i, and (2) the actual outcome.
Therefore, the lower the Brier score is for a set of predictions, the
better the predictions are calibrated. Note that the Brier score always
takes on a value between zero and one, since this is the largest
possible difference between a predicted probability (which must be
between zero and one) and the actual outcome (which can take on values
of only 0 and 1).
The Brier score is appropriate for binary and categorical outcomes that
can be structured as true or false, but is inappropriate for ordinal
variables which can take on three or more values (this is because the
Brier score assumes that all possible outcomes are equivalently
"distant" from one another). Which label is considered to be the positive
label is controlled via the parameter pos_label, which defaults to 1.
Read more in the :ref:`User Guide <calibration>`.
Parameters
----------
y_true : array, shape (n_samples,)
True targets.
y_prob : array, shape (n_samples,)
Probabilities of the positive class.
sample_weight : array-like of shape = [n_samples], optional
Sample weights.
pos_label : int or str, default=None
Label of the positive class. If None, the maximum label is used as
positive class
Returns
-------
score : float
Brier score
Examples
--------
>>> import numpy as np
>>> from sklearn.metrics import brier_score_loss
>>> y_true = np.array([0, 1, 1, 0])
>>> y_true_categorical = np.array(["spam", "ham", "ham", "spam"])
>>> y_prob = np.array([0.1, 0.9, 0.8, 0.3])
>>> brier_score_loss(y_true, y_prob) # doctest: +ELLIPSIS
0.037...
>>> brier_score_loss(y_true, 1-y_prob, pos_label=0) # doctest: +ELLIPSIS
0.037...
>>> brier_score_loss(y_true_categorical, y_prob, \
pos_label="ham") # doctest: +ELLIPSIS
0.037...
>>> brier_score_loss(y_true, np.array(y_prob) > 0.5)
0.0
References
----------
.. [1] `Wikipedia entry for the Brier score.
<https://en.wikipedia.org/wiki/Brier_score>`_
"""
y_true = column_or_1d(y_true)
y_prob = column_or_1d(y_prob)
assert_all_finite(y_true)
assert_all_finite(y_prob)
if pos_label is None:
pos_label = y_true.max()
y_true = np.array(y_true == pos_label, int)
y_true = _check_binary_probabilistic_predictions(y_true, y_prob)
return np.average((y_true - y_prob) ** 2, weights=sample_weight)
| bsd-3-clause |
diarmuidcwc/AcraNetwork | AcraNetwork/NPD.py | 1 | 13086 | """
.. module:: NPD
:platform: Unix, Windows
:synopsis: Class to construct and de construct NPD Packets
.. moduleauthor:: Diarmuid Collins <dcollins@curtisswright.com>
"""
__author__ = "Diarmuid Collins"
__copyright__ = "Copyright 2018"
__maintainer__ = "Diarmuid Collins"
__email__ = "dcollins@curtisswright.com"
__status__ = "Production"
import struct
from socket import inet_aton,inet_ntoa
class NPDSegment(object):
"""
NPD Payloads are split into segments. This class will pack and unpack segments
:type timedelta: int
:type segmentlen: int
:type errorcode: int
:type flags: int
:type payload: str
"""
NPD_SEGMENT_HDR_FORMAT = ">IHBB"
NPD_SEGMENT_HDR_LEN = struct.calcsize(NPD_SEGMENT_HDR_FORMAT)
def __init__(self):
self.timedelta = None #: The R-bit in the Flags field of the packet header dictates the format of this field.
self.segmentlen = None #: The length of the segment header and data in bytes excluding padding.
self.errorcode = None #: This field has a zero value if there are no errors
self.flags = None #: [2:1] Fragmentation state flag
self._payload = None #: Payload of segment
@property
def payload(self):
"""
Payload of segment
:return:
"""
return self._payload
@payload.setter
def payload(self, buf):
self._payload = buf
self.segmentlen = len(self.payload) + NPDSegment.NPD_SEGMENT_HDR_LEN
def unpack(self, buffer):
"""
Unpack a string buffer into an NPD segment. Return the remaining buffer so that the next segment can iteratively
be unpacked
:param buffer: A string buffer representing an NPD segment
:type buffer: str
:rtype: str
"""
(self.timedelta, self.segmentlen, self.errorcode, self.flags) = struct.unpack_from(NPDSegment.NPD_SEGMENT_HDR_FORMAT, buffer)
self.payload = buffer[NPDSegment.NPD_SEGMENT_HDR_LEN:self.segmentlen]
if self.segmentlen % 4 == 0:
pad_len = 0
else:
pad_len = 4- (self.segmentlen % 4)
return buffer[(self.segmentlen+pad_len):]
def pack(self):
"""
Pack the NPD object into a binary buffer
:rtype: str
"""
if len(self.payload) % 4 == 0:
pad = b""
else:
pad_len = 4 - len(self.payload) % 4
pad = struct.pack(">B",0xFF) * pad_len
hdr_pack = struct.pack(NPDSegment.NPD_SEGMENT_HDR_FORMAT, self.timedelta, self.segmentlen, self.errorcode, self.flags)
return hdr_pack + self.payload + pad
def __eq__(self, other):
if not isinstance(other, NPDSegment):
return False
for attr in ["timedelta", "segmentlen", "errorcode", "flags", "payload"]:
if getattr(other, attr) != getattr(self, attr):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return "NPD Segment. TimeDelta={} Segment Len={} ErrorCode={} Flags={:#0X}".format(
self.timedelta, self.segmentlen, self.errorcode, self.flags)
class ACQSegment(NPDSegment):
"""
PCM Segments
"""
def __init__(self):
NPDSegment.__init__(self)
self.sfid = 0
self.cal = 0
self.words = []
def unpack(self, buffer):
remaining = NPDSegment.unpack(self, buffer)
(self.sfid, _cal, reserved) = struct.unpack_from(">BBH", self.payload)
self.cal = _cal >> 7
len_words = (len(self.payload) - 4 ) / 2
self.words = list(struct.unpack_from(">{}H".format(len_words), self.payload, 4))
return remaining
def __repr__(self):
return "PCM NPD Segment. TimeDelta={} Segment Len={} ErrorCode={:#0X} Flags={:#0X} sfid={:#0X} " \
"WordCnt={}" \
"".format(self.timedelta, self.segmentlen, self.errorcode, self.flags, self.sfid, len(self.words))
class A429Segment(NPDSegment):
pass
class RS232Segment(NPDSegment):
BSL_CH0 = 0x0
BSL_CH1 = 0x8000
BSL_PAR_ERR = 0x4000
BSL_TWO_STOP_BITS = 0x2000
BSL_EVEN_PAR = 0x1000
BSL_PARN_EN = 0x800
BSL_8BIT = 0x0
BSL_7BIT = 0x200
BSL_6BIT = 0x400
BSL_5BIT = 0x600
BSL_PKT_SYNC_FIXED = 0x0
BSL_PKT_SYNC_VAR = 0x80
BSL_PKT_GAP = 0x100
BSL_PKT_THROUGHPUT = 0x180
BSL_422 = 0x40
BSL_PAD_EN = 0x20
BSL_ENDIAN_BIG = 0x0
BSL_ENDIAN_LITTLE = 0x10
BSL_REL_PKT_CNT = 0x8
BSL_SYNC_COUNT_MASK = 0x7
def __init__(self):
NPDSegment.__init__(self)
self.block_status = None
self.sync_bytes = []
self.data = b""
def unpack(self, buffer):
"""
Unpack a string buffer into an RS232 segment. Return the remaining buffer so that the next segment can iteratively
be unpacked
:param buffer: A string buffer representing an RS232 segment
:type buffer: str
:rtype: str
"""
remaining = NPDSegment.unpack(self, buffer)
(self.block_status,) = struct.unpack_from(">H", self.payload)
sync_word_cnt = self.block_status & RS232Segment.BSL_SYNC_COUNT_MASK
if sync_word_cnt > 0:
self.sync_bytes = list(struct.unpack_from(">{}B".format(sync_word_cnt), self.payload[2:]))
self.data = self.payload[2+sync_word_cnt:]
else:
self.data = self.payload[2:]
return remaining
def pack(self):
"""
Pack the RS232 Segment object into a binary buffer
:rtype: str
"""
if self.block_status is None:
raise Exception("block_status attribute should be defined")
# Build the status word by calculating the sync bytes and adding to the rest of the header
self.block_status = (self.block_status & 0xFFF8) + len(self.sync_bytes)
self.payload = struct.pack(">H", self.block_status)
# Add the sync words
for sync_byte in self.sync_bytes:
self.payload += struct.pack(">B", sync_byte)
self.payload += self.data
return NPDSegment.pack(self)
def __eq__(self, other):
if not isinstance(other, RS232Segment):
return False
for attr in ["timedelta", "segmentlen", "errorcode", "flags", "block_status", "sync_bytes", "data"]:
if getattr(other, attr) != getattr(self, attr):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return "RS232 NPD Segment. TimeDelta={} Segment Len={} ErrorCode={:#0X} Flags={:#0X} Block_Status={:#0X} " \
"DataLen={}" \
"".format(self.timedelta, self.segmentlen, self.errorcode, self.flags, self.block_status, len(self.data))
class MIL1553Segment(NPDSegment):
def __init__(self):
NPDSegment.__init__(self)
self.blockstatus = 0
self.gap1 = 0
self.gap2 = 0
self.data = ""
def unpack(self, buffer):
remaining = NPDSegment.unpack(self, buffer)
(self.blockstatus, self.gap2, self.gap2) = struct.unpack_from(">HBB", self.payload)
self.data = self.payload[4:]
return remaining
def __repr__(self):
return "MIL-STD-1553 Segment. TimeDelta={} Segment Len={} ErrorCode={:#0X} Flags={:#0X} BlockStatus={:#0X} " \
"Gap1={} Gap2={}" \
"".format(self.timedelta, self.segmentlen, self.errorcode, self.flags, self.blockstatus, self.gap1,
self.gap2)
class NPD(object):
"""
Class to pack and unpack NPD payloads.
Capture a UDP packet and unpack the _payload as an NPD packet
>>> import socket
>>>> recv_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> data, addr = recv_socket.recvfrom(2048)
>>> n = NPD()
>>> n.unpack(data)
>>> print n.datatype
6
>>> for segment in n.segments:
... print segment.errorcode
2
:type version: int
:type hdrlen: int
:type datatype: int
:type packetlen: int
:type cfgcnt: int
:type flags: int
:type sequence: int
:type datasrcid: int
:type mcastaddr: str
:type timestamp: int
:type segments: list[NPDSegment|ACQSegment|RS232Segment|A429Segment]
"""
NPD_HEADER_FORMAT = '>BBHBBHIII'
NPD_HEADER_LENGTH = struct.calcsize(NPD_HEADER_FORMAT)
NPD_VERSION = 3
NPD_DT = { 0x50: RS232Segment, 0x38: A429Segment, 0xA1: ACQSegment, 0xD0: MIL1553Segment}
def __init__(self):
'''Creator method for a UDP class'''
self.version = NPD.NPD_VERSION #: Version
self.hdrlen = NPD.NPD_HEADER_LENGTH//4 #: Header Length
self.datatype = None #: A unique identifier for the type of data collected in the packet
self.packetlen = None #: The number of 32-bit words in the data packet including the NPD header and data segments.
self.cfgcnt = None #: Stores an 8-bit number that is incremented (mod 256) each time the network device is configured.
self.flags = None #: Flags [0]-Unlocked timestamp [1]-Packet fragmentation [2]-Relative Time Count Present
self.sequence = None #: Sequence number
self.datasrcid = None #: A unique data source identifier for each data source.
self.mcastaddr = "" #: The 32-bit IP multicast address used as the destination address of the packet.
self.timestamp = None #: The content of this field is based upon the R bit in the flags field of the NPD Packet Protocol header.
self.segments = [] #: List of all the data segments
def unpack(self, buffer):
"""
Unpack a string buffer into an NPD object
:param buffer: A string buffer representing an NPD packet
:type buffer: bytes
:rtype: None
"""
(_ver_hdr, self.datatype, self.packetlen, self.cfgcnt, self.flags, self.sequence, self.datasrcid,
_mcast, self.timestamp) = struct.unpack_from(NPD.NPD_HEADER_FORMAT, buffer)
self.version = _ver_hdr >> 4
self.hdrlen = _ver_hdr & 0xF
self.mcastaddr = inet_ntoa(struct.pack(">I",_mcast))
_payload = buffer[self.hdrlen * 4:]
if self.packetlen * 4 != len(buffer):
raise Exception("The self reported packet length does not match the length of the buffer supplied")
remain_buf = _payload
while remain_buf != b"":
if self.datatype in NPD.NPD_DT:
segment = NPD.NPD_DT[self.datatype]()
else:
segment = NPDSegment()
try:
remain_buf = segment.unpack(remain_buf)
except Exception as e:
raise Exception(e)
else:
self.segments.append(segment)
return True
def pack(self):
"""
Pack the NPD object into a binary buffer
:rtype: str
"""
_ver_hdr = (self.version << 4) + self.hdrlen
(_mc,) = struct.unpack(">I", inet_aton(self.mcastaddr))
_payload = b""
for segment in self.segments:
_payload += segment.pack()
self.packetlen = (NPD.NPD_HEADER_LENGTH + len(_payload))//4
hdr_buf = struct.pack(NPD.NPD_HEADER_FORMAT, _ver_hdr, self.datatype, self.packetlen, self.cfgcnt, self.flags,
self.sequence, self.datasrcid, _mc, self.timestamp)
return hdr_buf + _payload
def __repr__(self):
det = "NPD: DataType={:#0X} Seq={} DataSrcID={:#0X} MCastAddr={}".format(
self.datatype, self.sequence, self.datasrcid, self.mcastaddr)
for seg in self.segments:
det += "\n\t{}".format(repr(seg))
return det
def __eq__(self, other):
if not isinstance(other, NPD):
return False
for attr in ["version", "hdrlen", "datatype", "packetlen", "cfgcnt", "flags", "sequence", "datasrcid",
"mcastaddr", "timestamp", "segments"]:
if getattr(other, attr) != getattr(self, attr):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def __iter__(self):
self._index = 0
return self
def next(self):
if self._index < len(self.segments):
_dw = self.segments[self._index]
self._index += 1
return _dw
else:
raise StopIteration
__next__ = next
def __len__(self):
return len(self.segments)
def __getitem__(self, key):
return self.segments[key]
| gpl-2.0 |
axinging/sky_engine | sky/tools/webkitpy/layout_tests/controllers/layout_test_finder.py | 11 | 7351 | # Copyright (C) 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import errno
import logging
import re
from webkitpy.layout_tests.models import test_expectations
_log = logging.getLogger(__name__)
class LayoutTestFinder(object):
def __init__(self, port, options):
self._port = port
self._options = options
self._filesystem = self._port.host.filesystem
self.LAYOUT_TESTS_DIRECTORY = 'tests'
def find_tests(self, options, args):
paths = self._strip_test_dir_prefixes(args)
if options.test_list:
paths += self._strip_test_dir_prefixes(self._read_test_names_from_file(options.test_list, self._port.TEST_PATH_SEPARATOR))
test_files = self._port.tests(paths)
return (paths, test_files)
def _strip_test_dir_prefixes(self, paths):
return [self._strip_test_dir_prefix(path) for path in paths if path]
def _strip_test_dir_prefix(self, path):
# Handle both "tests/foo/bar.html" and "tests\foo\bar.html" if
# the filesystem uses '\\' as a directory separator.
if path.startswith(self.LAYOUT_TESTS_DIRECTORY + self._port.TEST_PATH_SEPARATOR):
return path[len(self.LAYOUT_TESTS_DIRECTORY + self._port.TEST_PATH_SEPARATOR):]
if path.startswith(self.LAYOUT_TESTS_DIRECTORY + self._filesystem.sep):
return path[len(self.LAYOUT_TESTS_DIRECTORY + self._filesystem.sep):]
return path
def _read_test_names_from_file(self, filenames, test_path_separator):
fs = self._filesystem
tests = []
for filename in filenames:
try:
if test_path_separator != fs.sep:
filename = filename.replace(test_path_separator, fs.sep)
file_contents = fs.read_text_file(filename).split('\n')
for line in file_contents:
line = self._strip_comments(line)
if line:
tests.append(line)
except IOError, e:
if e.errno == errno.ENOENT:
_log.critical('')
_log.critical('--test-list file "%s" not found' % file)
raise
return tests
@staticmethod
def _strip_comments(line):
commentIndex = line.find('//')
if commentIndex is -1:
commentIndex = len(line)
line = re.sub(r'\s+', ' ', line[:commentIndex].strip())
if line == '':
return None
else:
return line
def skip_tests(self, paths, all_tests_list, expectations, http_tests):
all_tests = set(all_tests_list)
tests_to_skip = expectations.get_tests_with_result_type(test_expectations.SKIP)
if self._options.skip_failing_tests:
tests_to_skip.update(expectations.get_tests_with_result_type(test_expectations.FAIL))
tests_to_skip.update(expectations.get_tests_with_result_type(test_expectations.FLAKY))
if self._options.skipped == 'only':
tests_to_skip = all_tests - tests_to_skip
elif self._options.skipped == 'ignore':
tests_to_skip = set()
elif self._options.skipped != 'always':
# make sure we're explicitly running any tests passed on the command line; equivalent to 'default'.
tests_to_skip -= set(paths)
return tests_to_skip
def split_into_chunks(self, test_names):
"""split into a list to run and a set to skip, based on --run-chunk and --run-part."""
if not self._options.run_chunk and not self._options.run_part:
return test_names, set()
# If the user specifies they just want to run a subset of the tests,
# just grab a subset of the non-skipped tests.
chunk_value = self._options.run_chunk or self._options.run_part
try:
(chunk_num, chunk_len) = chunk_value.split(":")
chunk_num = int(chunk_num)
assert(chunk_num >= 0)
test_size = int(chunk_len)
assert(test_size > 0)
except AssertionError:
_log.critical("invalid chunk '%s'" % chunk_value)
return (None, None)
# Get the number of tests
num_tests = len(test_names)
# Get the start offset of the slice.
if self._options.run_chunk:
chunk_len = test_size
# In this case chunk_num can be really large. We need
# to make the slave fit in the current number of tests.
slice_start = (chunk_num * chunk_len) % num_tests
else:
# Validate the data.
assert(test_size <= num_tests)
assert(chunk_num <= test_size)
# To count the chunk_len, and make sure we don't skip
# some tests, we round to the next value that fits exactly
# all the parts.
rounded_tests = num_tests
if rounded_tests % test_size != 0:
rounded_tests = (num_tests + test_size - (num_tests % test_size))
chunk_len = rounded_tests / test_size
slice_start = chunk_len * (chunk_num - 1)
# It does not mind if we go over test_size.
# Get the end offset of the slice.
slice_end = min(num_tests, slice_start + chunk_len)
tests_to_run = test_names[slice_start:slice_end]
_log.debug('chunk slice [%d:%d] of %d is %d tests' % (slice_start, slice_end, num_tests, (slice_end - slice_start)))
# If we reached the end and we don't have enough tests, we run some
# from the beginning.
if slice_end - slice_start < chunk_len:
extra = chunk_len - (slice_end - slice_start)
_log.debug(' last chunk is partial, appending [0:%d]' % extra)
tests_to_run.extend(test_names[0:extra])
return (tests_to_run, set(test_names) - set(tests_to_run))
| bsd-3-clause |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.7/Lib/test/test_urllib2.py | 3 | 48765 | import unittest
from test import test_support
import os
import socket
import StringIO
import urllib2
from urllib2 import Request, OpenerDirector
# XXX
# Request
# CacheFTPHandler (hard to write)
# parse_keqv_list, parse_http_list, HTTPDigestAuthHandler
class TrivialTests(unittest.TestCase):
def test_trivial(self):
# A couple trivial tests
self.assertRaises(ValueError, urllib2.urlopen, 'bogus url')
# XXX Name hacking to get this to work on Windows.
fname = os.path.abspath(urllib2.__file__).replace('\\', '/')
# And more hacking to get it to work on MacOS. This assumes
# urllib.pathname2url works, unfortunately...
if os.name == 'riscos':
import string
fname = os.expand(fname)
fname = fname.translate(string.maketrans("/.", "./"))
if os.name == 'nt':
file_url = "file:///%s" % fname
else:
file_url = "file://%s" % fname
f = urllib2.urlopen(file_url)
buf = f.read()
f.close()
def test_parse_http_list(self):
tests = [('a,b,c', ['a', 'b', 'c']),
('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']),
('a, b, "c", "d", "e,f", g, h', ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']),
('a="b\\"c", d="e\\,f", g="h\\\\i"', ['a="b"c"', 'd="e,f"', 'g="h\\i"'])]
for string, list in tests:
self.assertEquals(urllib2.parse_http_list(string), list)
def test_request_headers_dict():
"""
The Request.headers dictionary is not a documented interface. It should
stay that way, because the complete set of headers are only accessible
through the .get_header(), .has_header(), .header_items() interface.
However, .headers pre-dates those methods, and so real code will be using
the dictionary.
The introduction in 2.4 of those methods was a mistake for the same reason:
code that previously saw all (urllib2 user)-provided headers in .headers
now sees only a subset (and the function interface is ugly and incomplete).
A better change would have been to replace .headers dict with a dict
subclass (or UserDict.DictMixin instance?) that preserved the .headers
interface and also provided access to the "unredirected" headers. It's
probably too late to fix that, though.
Check .capitalize() case normalization:
>>> url = "http://example.com"
>>> Request(url, headers={"Spam-eggs": "blah"}).headers["Spam-eggs"]
'blah'
>>> Request(url, headers={"spam-EggS": "blah"}).headers["Spam-eggs"]
'blah'
Currently, Request(url, "Spam-eggs").headers["Spam-Eggs"] raises KeyError,
but that could be changed in future.
"""
def test_request_headers_methods():
"""
Note the case normalization of header names here, to .capitalize()-case.
This should be preserved for backwards-compatibility. (In the HTTP case,
normalization to .title()-case is done by urllib2 before sending headers to
httplib).
>>> url = "http://example.com"
>>> r = Request(url, headers={"Spam-eggs": "blah"})
>>> r.has_header("Spam-eggs")
True
>>> r.header_items()
[('Spam-eggs', 'blah')]
>>> r.add_header("Foo-Bar", "baz")
>>> items = r.header_items()
>>> items.sort()
>>> items
[('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]
Note that e.g. r.has_header("spam-EggS") is currently False, and
r.get_header("spam-EggS") returns None, but that could be changed in
future.
>>> r.has_header("Not-there")
False
>>> print r.get_header("Not-there")
None
>>> r.get_header("Not-there", "default")
'default'
"""
def test_password_manager(self):
"""
>>> mgr = urllib2.HTTPPasswordMgr()
>>> add = mgr.add_password
>>> add("Some Realm", "http://example.com/", "joe", "password")
>>> add("Some Realm", "http://example.com/ni", "ni", "ni")
>>> add("c", "http://example.com/foo", "foo", "ni")
>>> add("c", "http://example.com/bar", "bar", "nini")
>>> add("b", "http://example.com/", "first", "blah")
>>> add("b", "http://example.com/", "second", "spam")
>>> add("a", "http://example.com", "1", "a")
>>> add("Some Realm", "http://c.example.com:3128", "3", "c")
>>> add("Some Realm", "d.example.com", "4", "d")
>>> add("Some Realm", "e.example.com:3128", "5", "e")
>>> mgr.find_user_password("Some Realm", "example.com")
('joe', 'password')
>>> mgr.find_user_password("Some Realm", "http://example.com")
('joe', 'password')
>>> mgr.find_user_password("Some Realm", "http://example.com/")
('joe', 'password')
>>> mgr.find_user_password("Some Realm", "http://example.com/spam")
('joe', 'password')
>>> mgr.find_user_password("Some Realm", "http://example.com/spam/spam")
('joe', 'password')
>>> mgr.find_user_password("c", "http://example.com/foo")
('foo', 'ni')
>>> mgr.find_user_password("c", "http://example.com/bar")
('bar', 'nini')
Actually, this is really undefined ATM
## Currently, we use the highest-level path where more than one match:
## >>> mgr.find_user_password("Some Realm", "http://example.com/ni")
## ('joe', 'password')
Use latest add_password() in case of conflict:
>>> mgr.find_user_password("b", "http://example.com/")
('second', 'spam')
No special relationship between a.example.com and example.com:
>>> mgr.find_user_password("a", "http://example.com/")
('1', 'a')
>>> mgr.find_user_password("a", "http://a.example.com/")
(None, None)
Ports:
>>> mgr.find_user_password("Some Realm", "c.example.com")
(None, None)
>>> mgr.find_user_password("Some Realm", "c.example.com:3128")
('3', 'c')
>>> mgr.find_user_password("Some Realm", "http://c.example.com:3128")
('3', 'c')
>>> mgr.find_user_password("Some Realm", "d.example.com")
('4', 'd')
>>> mgr.find_user_password("Some Realm", "e.example.com:3128")
('5', 'e')
"""
pass
def test_password_manager_default_port(self):
"""
>>> mgr = urllib2.HTTPPasswordMgr()
>>> add = mgr.add_password
The point to note here is that we can't guess the default port if there's
no scheme. This applies to both add_password and find_user_password.
>>> add("f", "http://g.example.com:80", "10", "j")
>>> add("g", "http://h.example.com", "11", "k")
>>> add("h", "i.example.com:80", "12", "l")
>>> add("i", "j.example.com", "13", "m")
>>> mgr.find_user_password("f", "g.example.com:100")
(None, None)
>>> mgr.find_user_password("f", "g.example.com:80")
('10', 'j')
>>> mgr.find_user_password("f", "g.example.com")
(None, None)
>>> mgr.find_user_password("f", "http://g.example.com:100")
(None, None)
>>> mgr.find_user_password("f", "http://g.example.com:80")
('10', 'j')
>>> mgr.find_user_password("f", "http://g.example.com")
('10', 'j')
>>> mgr.find_user_password("g", "h.example.com")
('11', 'k')
>>> mgr.find_user_password("g", "h.example.com:80")
('11', 'k')
>>> mgr.find_user_password("g", "http://h.example.com:80")
('11', 'k')
>>> mgr.find_user_password("h", "i.example.com")
(None, None)
>>> mgr.find_user_password("h", "i.example.com:80")
('12', 'l')
>>> mgr.find_user_password("h", "http://i.example.com:80")
('12', 'l')
>>> mgr.find_user_password("i", "j.example.com")
('13', 'm')
>>> mgr.find_user_password("i", "j.example.com:80")
(None, None)
>>> mgr.find_user_password("i", "http://j.example.com")
('13', 'm')
>>> mgr.find_user_password("i", "http://j.example.com:80")
(None, None)
"""
class MockOpener:
addheaders = []
def open(self, req, data=None,timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.req, self.data, self.timeout = req, data, timeout
def error(self, proto, *args):
self.proto, self.args = proto, args
class MockFile:
def read(self, count=None): pass
def readline(self, count=None): pass
def close(self): pass
class MockHeaders(dict):
def getheaders(self, name):
return self.values()
class MockResponse(StringIO.StringIO):
def __init__(self, code, msg, headers, data, url=None):
StringIO.StringIO.__init__(self, data)
self.code, self.msg, self.headers, self.url = code, msg, headers, url
def info(self):
return self.headers
def geturl(self):
return self.url
class MockCookieJar:
def add_cookie_header(self, request):
self.ach_req = request
def extract_cookies(self, response, request):
self.ec_req, self.ec_r = request, response
class FakeMethod:
def __init__(self, meth_name, action, handle):
self.meth_name = meth_name
self.handle = handle
self.action = action
def __call__(self, *args):
return self.handle(self.meth_name, self.action, *args)
class MockHTTPResponse:
def __init__(self, fp, msg, status, reason):
self.fp = fp
self.msg = msg
self.status = status
self.reason = reason
def read(self):
return ''
class MockHTTPClass:
def __init__(self):
self.req_headers = []
self.data = None
self.raise_on_endheaders = False
self._tunnel_headers = {}
def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.host = host
self.timeout = timeout
return self
def set_debuglevel(self, level):
self.level = level
def set_tunnel(self, host, port=None, headers=None):
self._tunnel_host = host
self._tunnel_port = port
if headers:
self._tunnel_headers = headers
else:
self._tunnel_headers.clear()
def request(self, method, url, body=None, headers=None):
self.method = method
self.selector = url
if headers is not None:
self.req_headers += headers.items()
self.req_headers.sort()
if body:
self.data = body
if self.raise_on_endheaders:
import socket
raise socket.error()
def getresponse(self):
return MockHTTPResponse(MockFile(), {}, 200, "OK")
class MockHandler:
# useful for testing handler machinery
# see add_ordered_mock_handlers() docstring
handler_order = 500
def __init__(self, methods):
self._define_methods(methods)
def _define_methods(self, methods):
for spec in methods:
if len(spec) == 2: name, action = spec
else: name, action = spec, None
meth = FakeMethod(name, action, self.handle)
setattr(self.__class__, name, meth)
def handle(self, fn_name, action, *args, **kwds):
self.parent.calls.append((self, fn_name, args, kwds))
if action is None:
return None
elif action == "return self":
return self
elif action == "return response":
res = MockResponse(200, "OK", {}, "")
return res
elif action == "return request":
return Request("http://blah/")
elif action.startswith("error"):
code = action[action.rfind(" ")+1:]
try:
code = int(code)
except ValueError:
pass
res = MockResponse(200, "OK", {}, "")
return self.parent.error("http", args[0], res, code, "", {})
elif action == "raise":
raise urllib2.URLError("blah")
assert False
def close(self): pass
def add_parent(self, parent):
self.parent = parent
self.parent.calls = []
def __lt__(self, other):
if not hasattr(other, "handler_order"):
# No handler_order, leave in original order. Yuck.
return True
return self.handler_order < other.handler_order
def add_ordered_mock_handlers(opener, meth_spec):
"""Create MockHandlers and add them to an OpenerDirector.
meth_spec: list of lists of tuples and strings defining methods to define
on handlers. eg:
[["http_error", "ftp_open"], ["http_open"]]
defines methods .http_error() and .ftp_open() on one handler, and
.http_open() on another. These methods just record their arguments and
return None. Using a tuple instead of a string causes the method to
perform some action (see MockHandler.handle()), eg:
[["http_error"], [("http_open", "return request")]]
defines .http_error() on one handler (which simply returns None), and
.http_open() on another handler, which returns a Request object.
"""
handlers = []
count = 0
for meths in meth_spec:
class MockHandlerSubclass(MockHandler): pass
h = MockHandlerSubclass(meths)
h.handler_order += count
h.add_parent(opener)
count = count + 1
handlers.append(h)
opener.add_handler(h)
return handlers
def build_test_opener(*handler_instances):
opener = OpenerDirector()
for h in handler_instances:
opener.add_handler(h)
return opener
class MockHTTPHandler(urllib2.BaseHandler):
# useful for testing redirections and auth
# sends supplied headers and code as first response
# sends 200 OK as second response
def __init__(self, code, headers):
self.code = code
self.headers = headers
self.reset()
def reset(self):
self._count = 0
self.requests = []
def http_open(self, req):
import mimetools, httplib, copy
from StringIO import StringIO
self.requests.append(copy.deepcopy(req))
if self._count == 0:
self._count = self._count + 1
name = httplib.responses[self.code]
msg = mimetools.Message(StringIO(self.headers))
return self.parent.error(
"http", req, MockFile(), self.code, name, msg)
else:
self.req = req
msg = mimetools.Message(StringIO("\r\n\r\n"))
return MockResponse(200, "OK", msg, "", req.get_full_url())
class MockHTTPSHandler(urllib2.AbstractHTTPHandler):
# Useful for testing the Proxy-Authorization request by verifying the
# properties of httpcon
def __init__(self):
urllib2.AbstractHTTPHandler.__init__(self)
self.httpconn = MockHTTPClass()
def https_open(self, req):
return self.do_open(self.httpconn, req)
class MockPasswordManager:
def add_password(self, realm, uri, user, password):
self.realm = realm
self.url = uri
self.user = user
self.password = password
def find_user_password(self, realm, authuri):
self.target_realm = realm
self.target_url = authuri
return self.user, self.password
class OpenerDirectorTests(unittest.TestCase):
def test_add_non_handler(self):
class NonHandler(object):
pass
self.assertRaises(TypeError,
OpenerDirector().add_handler, NonHandler())
def test_badly_named_methods(self):
# test work-around for three methods that accidentally follow the
# naming conventions for handler methods
# (*_open() / *_request() / *_response())
# These used to call the accidentally-named methods, causing a
# TypeError in real code; here, returning self from these mock
# methods would either cause no exception, or AttributeError.
from urllib2 import URLError
o = OpenerDirector()
meth_spec = [
[("do_open", "return self"), ("proxy_open", "return self")],
[("redirect_request", "return self")],
]
handlers = add_ordered_mock_handlers(o, meth_spec)
o.add_handler(urllib2.UnknownHandler())
for scheme in "do", "proxy", "redirect":
self.assertRaises(URLError, o.open, scheme+"://example.com/")
def test_handled(self):
# handler returning non-None means no more handlers will be called
o = OpenerDirector()
meth_spec = [
["http_open", "ftp_open", "http_error_302"],
["ftp_open"],
[("http_open", "return self")],
[("http_open", "return self")],
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("http://example.com/")
r = o.open(req)
# Second .http_open() gets called, third doesn't, since second returned
# non-None. Handlers without .http_open() never get any methods called
# on them.
# In fact, second mock handler defining .http_open() returns self
# (instead of response), which becomes the OpenerDirector's return
# value.
self.assertEqual(r, handlers[2])
calls = [(handlers[0], "http_open"), (handlers[2], "http_open")]
for expected, got in zip(calls, o.calls):
handler, name, args, kwds = got
self.assertEqual((handler, name), expected)
self.assertEqual(args, (req,))
def test_handler_order(self):
o = OpenerDirector()
handlers = []
for meths, handler_order in [
([("http_open", "return self")], 500),
(["http_open"], 0),
]:
class MockHandlerSubclass(MockHandler): pass
h = MockHandlerSubclass(meths)
h.handler_order = handler_order
handlers.append(h)
o.add_handler(h)
r = o.open("http://example.com/")
# handlers called in reverse order, thanks to their sort order
self.assertEqual(o.calls[0][0], handlers[1])
self.assertEqual(o.calls[1][0], handlers[0])
def test_raise(self):
# raising URLError stops processing of request
o = OpenerDirector()
meth_spec = [
[("http_open", "raise")],
[("http_open", "return self")],
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("http://example.com/")
self.assertRaises(urllib2.URLError, o.open, req)
self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})])
## def test_error(self):
## # XXX this doesn't actually seem to be used in standard library,
## # but should really be tested anyway...
def test_http_error(self):
# XXX http_error_default
# http errors are a special case
o = OpenerDirector()
meth_spec = [
[("http_open", "error 302")],
[("http_error_400", "raise"), "http_open"],
[("http_error_302", "return response"), "http_error_303",
"http_error"],
[("http_error_302")],
]
handlers = add_ordered_mock_handlers(o, meth_spec)
class Unknown:
def __eq__(self, other): return True
req = Request("http://example.com/")
r = o.open(req)
assert len(o.calls) == 2
calls = [(handlers[0], "http_open", (req,)),
(handlers[2], "http_error_302",
(req, Unknown(), 302, "", {}))]
for expected, got in zip(calls, o.calls):
handler, method_name, args = expected
self.assertEqual((handler, method_name), got[:2])
self.assertEqual(args, got[2])
def test_processors(self):
# *_request / *_response methods get called appropriately
o = OpenerDirector()
meth_spec = [
[("http_request", "return request"),
("http_response", "return response")],
[("http_request", "return request"),
("http_response", "return response")],
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("http://example.com/")
r = o.open(req)
# processor methods are called on *all* handlers that define them,
# not just the first handler that handles the request
calls = [
(handlers[0], "http_request"), (handlers[1], "http_request"),
(handlers[0], "http_response"), (handlers[1], "http_response")]
for i, (handler, name, args, kwds) in enumerate(o.calls):
if i < 2:
# *_request
self.assertEqual((handler, name), calls[i])
self.assertEqual(len(args), 1)
self.assertIsInstance(args[0], Request)
else:
# *_response
self.assertEqual((handler, name), calls[i])
self.assertEqual(len(args), 2)
self.assertIsInstance(args[0], Request)
# response from opener.open is None, because there's no
# handler that defines http_open to handle it
self.assertTrue(args[1] is None or
isinstance(args[1], MockResponse))
def sanepathname2url(path):
import urllib
urlpath = urllib.pathname2url(path)
if os.name == "nt" and urlpath.startswith("///"):
urlpath = urlpath[2:]
# XXX don't ask me about the mac...
return urlpath
class HandlerTests(unittest.TestCase):
def test_ftp(self):
class MockFTPWrapper:
def __init__(self, data): self.data = data
def retrfile(self, filename, filetype):
self.filename, self.filetype = filename, filetype
return StringIO.StringIO(self.data), len(self.data)
class NullFTPHandler(urllib2.FTPHandler):
def __init__(self, data): self.data = data
def connect_ftp(self, user, passwd, host, port, dirs,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.user, self.passwd = user, passwd
self.host, self.port = host, port
self.dirs = dirs
self.ftpwrapper = MockFTPWrapper(self.data)
return self.ftpwrapper
import ftplib
data = "rheum rhaponicum"
h = NullFTPHandler(data)
o = h.parent = MockOpener()
for url, host, port, type_, dirs, filename, mimetype in [
("ftp://localhost/foo/bar/baz.html",
"localhost", ftplib.FTP_PORT, "I",
["foo", "bar"], "baz.html", "text/html"),
("ftp://localhost:80/foo/bar/",
"localhost", 80, "D",
["foo", "bar"], "", None),
("ftp://localhost/baz.gif;type=a",
"localhost", ftplib.FTP_PORT, "A",
[], "baz.gif", None), # XXX really this should guess image/gif
]:
req = Request(url)
req.timeout = None
r = h.ftp_open(req)
# ftp authentication not yet implemented by FTPHandler
self.assertTrue(h.user == h.passwd == "")
self.assertEqual(h.host, socket.gethostbyname(host))
self.assertEqual(h.port, port)
self.assertEqual(h.dirs, dirs)
self.assertEqual(h.ftpwrapper.filename, filename)
self.assertEqual(h.ftpwrapper.filetype, type_)
headers = r.info()
self.assertEqual(headers.get("Content-type"), mimetype)
self.assertEqual(int(headers["Content-length"]), len(data))
def test_file(self):
import rfc822, socket
h = urllib2.FileHandler()
o = h.parent = MockOpener()
TESTFN = test_support.TESTFN
urlpath = sanepathname2url(os.path.abspath(TESTFN))
towrite = "hello, world\n"
urls = [
"file://localhost%s" % urlpath,
"file://%s" % urlpath,
"file://%s%s" % (socket.gethostbyname('localhost'), urlpath),
]
try:
localaddr = socket.gethostbyname(socket.gethostname())
except socket.gaierror:
localaddr = ''
if localaddr:
urls.append("file://%s%s" % (localaddr, urlpath))
for url in urls:
f = open(TESTFN, "wb")
try:
try:
f.write(towrite)
finally:
f.close()
r = h.file_open(Request(url))
try:
data = r.read()
headers = r.info()
respurl = r.geturl()
finally:
r.close()
stats = os.stat(TESTFN)
modified = rfc822.formatdate(stats.st_mtime)
finally:
os.remove(TESTFN)
self.assertEqual(data, towrite)
self.assertEqual(headers["Content-type"], "text/plain")
self.assertEqual(headers["Content-length"], "13")
self.assertEqual(headers["Last-modified"], modified)
self.assertEqual(respurl, url)
for url in [
"file://localhost:80%s" % urlpath,
"file:///file_does_not_exist.txt",
"file://%s:80%s/%s" % (socket.gethostbyname('localhost'),
os.getcwd(), TESTFN),
"file://somerandomhost.ontheinternet.com%s/%s" %
(os.getcwd(), TESTFN),
]:
try:
f = open(TESTFN, "wb")
try:
f.write(towrite)
finally:
f.close()
self.assertRaises(urllib2.URLError,
h.file_open, Request(url))
finally:
os.remove(TESTFN)
h = urllib2.FileHandler()
o = h.parent = MockOpener()
# XXXX why does // mean ftp (and /// mean not ftp!), and where
# is file: scheme specified? I think this is really a bug, and
# what was intended was to distinguish between URLs like:
# file:/blah.txt (a file)
# file://localhost/blah.txt (a file)
# file:///blah.txt (a file)
# file://ftp.example.com/blah.txt (an ftp URL)
for url, ftp in [
("file://ftp.example.com//foo.txt", True),
("file://ftp.example.com///foo.txt", False),
# XXXX bug: fails with OSError, should be URLError
("file://ftp.example.com/foo.txt", False),
]:
req = Request(url)
try:
h.file_open(req)
# XXXX remove OSError when bug fixed
except (urllib2.URLError, OSError):
self.assertTrue(not ftp)
else:
self.assertTrue(o.req is req)
self.assertEqual(req.type, "ftp")
def test_http(self):
h = urllib2.AbstractHTTPHandler()
o = h.parent = MockOpener()
url = "http://example.com/"
for method, data in [("GET", None), ("POST", "blah")]:
req = Request(url, data, {"Foo": "bar"})
req.timeout = None
req.add_unredirected_header("Spam", "eggs")
http = MockHTTPClass()
r = h.do_open(http, req)
# result attributes
r.read; r.readline # wrapped MockFile methods
r.info; r.geturl # addinfourl methods
r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply()
hdrs = r.info()
hdrs.get; hdrs.has_key # r.info() gives dict from .getreply()
self.assertEqual(r.geturl(), url)
self.assertEqual(http.host, "example.com")
self.assertEqual(http.level, 0)
self.assertEqual(http.method, method)
self.assertEqual(http.selector, "/")
self.assertEqual(http.req_headers,
[("Connection", "close"),
("Foo", "bar"), ("Spam", "eggs")])
self.assertEqual(http.data, data)
# check socket.error converted to URLError
http.raise_on_endheaders = True
self.assertRaises(urllib2.URLError, h.do_open, http, req)
# check adding of standard headers
o.addheaders = [("Spam", "eggs")]
for data in "", None: # POST, GET
req = Request("http://example.com/", data)
r = MockResponse(200, "OK", {}, "")
newreq = h.do_request_(req)
if data is None: # GET
self.assertNotIn("Content-length", req.unredirected_hdrs)
self.assertNotIn("Content-type", req.unredirected_hdrs)
else: # POST
self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
self.assertEqual(req.unredirected_hdrs["Content-type"],
"application/x-www-form-urlencoded")
# XXX the details of Host could be better tested
self.assertEqual(req.unredirected_hdrs["Host"], "example.com")
self.assertEqual(req.unredirected_hdrs["Spam"], "eggs")
# don't clobber existing headers
req.add_unredirected_header("Content-length", "foo")
req.add_unredirected_header("Content-type", "bar")
req.add_unredirected_header("Host", "baz")
req.add_unredirected_header("Spam", "foo")
newreq = h.do_request_(req)
self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
self.assertEqual(req.unredirected_hdrs["Host"], "baz")
self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
def test_http_doubleslash(self):
# Checks that the presence of an unnecessary double slash in a url doesn't break anything
# Previously, a double slash directly after the host could cause incorrect parsing of the url
h = urllib2.AbstractHTTPHandler()
o = h.parent = MockOpener()
data = ""
ds_urls = [
"http://example.com/foo/bar/baz.html",
"http://example.com//foo/bar/baz.html",
"http://example.com/foo//bar/baz.html",
"http://example.com/foo/bar//baz.html",
]
for ds_url in ds_urls:
ds_req = Request(ds_url, data)
# Check whether host is determined correctly if there is no proxy
np_ds_req = h.do_request_(ds_req)
self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com")
# Check whether host is determined correctly if there is a proxy
ds_req.set_proxy("someproxy:3128",None)
p_ds_req = h.do_request_(ds_req)
self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
def test_errors(self):
h = urllib2.HTTPErrorProcessor()
o = h.parent = MockOpener()
url = "http://example.com/"
req = Request(url)
# all 2xx are passed through
r = MockResponse(200, "OK", {}, "", url)
newr = h.http_response(req, r)
self.assertTrue(r is newr)
self.assertTrue(not hasattr(o, "proto")) # o.error not called
r = MockResponse(202, "Accepted", {}, "", url)
newr = h.http_response(req, r)
self.assertTrue(r is newr)
self.assertTrue(not hasattr(o, "proto")) # o.error not called
r = MockResponse(206, "Partial content", {}, "", url)
newr = h.http_response(req, r)
self.assertTrue(r is newr)
self.assertTrue(not hasattr(o, "proto")) # o.error not called
# anything else calls o.error (and MockOpener returns None, here)
r = MockResponse(502, "Bad gateway", {}, "", url)
self.assertTrue(h.http_response(req, r) is None)
self.assertEqual(o.proto, "http") # o.error called
self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
def test_cookies(self):
cj = MockCookieJar()
h = urllib2.HTTPCookieProcessor(cj)
o = h.parent = MockOpener()
req = Request("http://example.com/")
r = MockResponse(200, "OK", {}, "")
newreq = h.http_request(req)
self.assertTrue(cj.ach_req is req is newreq)
self.assertEquals(req.get_origin_req_host(), "example.com")
self.assertTrue(not req.is_unverifiable())
newr = h.http_response(req, r)
self.assertTrue(cj.ec_req is req)
self.assertTrue(cj.ec_r is r is newr)
def test_redirect(self):
from_url = "http://example.com/a.html"
to_url = "http://example.com/b.html"
h = urllib2.HTTPRedirectHandler()
o = h.parent = MockOpener()
# ordinary redirect behaviour
for code in 301, 302, 303, 307:
for data in None, "blah\nblah\n":
method = getattr(h, "http_error_%s" % code)
req = Request(from_url, data)
req.add_header("Nonsense", "viking=withhold")
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
if data is not None:
req.add_header("Content-Length", str(len(data)))
req.add_unredirected_header("Spam", "spam")
try:
method(req, MockFile(), code, "Blah",
MockHeaders({"location": to_url}))
except urllib2.HTTPError:
# 307 in response to POST requires user OK
self.assertTrue(code == 307 and data is not None)
self.assertEqual(o.req.get_full_url(), to_url)
try:
self.assertEqual(o.req.get_method(), "GET")
except AttributeError:
self.assertTrue(not o.req.has_data())
# now it's a GET, there should not be headers regarding content
# (possibly dragged from before being a POST)
headers = [x.lower() for x in o.req.headers]
self.assertNotIn("content-length", headers)
self.assertNotIn("content-type", headers)
self.assertEqual(o.req.headers["Nonsense"],
"viking=withhold")
self.assertNotIn("Spam", o.req.headers)
self.assertNotIn("Spam", o.req.unredirected_hdrs)
# loop detection
req = Request(from_url)
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
def redirect(h, req, url=to_url):
h.http_error_302(req, MockFile(), 302, "Blah",
MockHeaders({"location": url}))
# Note that the *original* request shares the same record of
# redirections with the sub-requests caused by the redirections.
# detect infinite loop redirect of a URL to itself
req = Request(from_url, origin_req_host="example.com")
count = 0
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
try:
while 1:
redirect(h, req, "http://example.com/")
count = count + 1
except urllib2.HTTPError:
# don't stop until max_repeats, because cookies may introduce state
self.assertEqual(count, urllib2.HTTPRedirectHandler.max_repeats)
# detect endless non-repeating chain of redirects
req = Request(from_url, origin_req_host="example.com")
count = 0
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
try:
while 1:
redirect(h, req, "http://example.com/%d" % count)
count = count + 1
except urllib2.HTTPError:
self.assertEqual(count,
urllib2.HTTPRedirectHandler.max_redirections)
def test_cookie_redirect(self):
# cookies shouldn't leak into redirected requests
from cookielib import CookieJar
from test.test_cookielib import interact_netscape
cj = CookieJar()
interact_netscape(cj, "http://www.example.com/", "spam=eggs")
hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n")
hdeh = urllib2.HTTPDefaultErrorHandler()
hrh = urllib2.HTTPRedirectHandler()
cp = urllib2.HTTPCookieProcessor(cj)
o = build_test_opener(hh, hdeh, hrh, cp)
o.open("http://www.example.com/")
self.assertTrue(not hh.req.has_header("Cookie"))
def test_proxy(self):
o = OpenerDirector()
ph = urllib2.ProxyHandler(dict(http="proxy.example.com:3128"))
o.add_handler(ph)
meth_spec = [
[("http_open", "return response")]
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("http://acme.example.com/")
self.assertEqual(req.get_host(), "acme.example.com")
r = o.open(req)
self.assertEqual(req.get_host(), "proxy.example.com:3128")
self.assertEqual([(handlers[0], "http_open")],
[tup[0:2] for tup in o.calls])
def test_proxy_no_proxy(self):
os.environ['no_proxy'] = 'python.org'
o = OpenerDirector()
ph = urllib2.ProxyHandler(dict(http="proxy.example.com"))
o.add_handler(ph)
req = Request("http://www.perl.org/")
self.assertEqual(req.get_host(), "www.perl.org")
r = o.open(req)
self.assertEqual(req.get_host(), "proxy.example.com")
req = Request("http://www.python.org")
self.assertEqual(req.get_host(), "www.python.org")
r = o.open(req)
self.assertEqual(req.get_host(), "www.python.org")
del os.environ['no_proxy']
def test_proxy_https(self):
o = OpenerDirector()
ph = urllib2.ProxyHandler(dict(https='proxy.example.com:3128'))
o.add_handler(ph)
meth_spec = [
[("https_open","return response")]
]
handlers = add_ordered_mock_handlers(o, meth_spec)
req = Request("https://www.example.com/")
self.assertEqual(req.get_host(), "www.example.com")
r = o.open(req)
self.assertEqual(req.get_host(), "proxy.example.com:3128")
self.assertEqual([(handlers[0], "https_open")],
[tup[0:2] for tup in o.calls])
def test_proxy_https_proxy_authorization(self):
o = OpenerDirector()
ph = urllib2.ProxyHandler(dict(https='proxy.example.com:3128'))
o.add_handler(ph)
https_handler = MockHTTPSHandler()
o.add_handler(https_handler)
req = Request("https://www.example.com/")
req.add_header("Proxy-Authorization","FooBar")
req.add_header("User-Agent","Grail")
self.assertEqual(req.get_host(), "www.example.com")
self.assertIsNone(req._tunnel_host)
r = o.open(req)
# Verify Proxy-Authorization gets tunneled to request.
# httpsconn req_headers do not have the Proxy-Authorization header but
# the req will have.
self.assertNotIn(("Proxy-Authorization","FooBar"),
https_handler.httpconn.req_headers)
self.assertIn(("User-Agent","Grail"),
https_handler.httpconn.req_headers)
self.assertIsNotNone(req._tunnel_host)
self.assertEqual(req.get_host(), "proxy.example.com:3128")
self.assertEqual(req.get_header("Proxy-authorization"),"FooBar")
def test_basic_auth(self, quote_char='"'):
opener = OpenerDirector()
password_manager = MockPasswordManager()
auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
realm = "ACME Widget Store"
http_handler = MockHTTPHandler(
401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' %
(quote_char, realm, quote_char) )
opener.add_handler(auth_handler)
opener.add_handler(http_handler)
self._test_basic_auth(opener, auth_handler, "Authorization",
realm, http_handler, password_manager,
"http://acme.example.com/protected",
"http://acme.example.com/protected",
)
def test_basic_auth_with_single_quoted_realm(self):
self.test_basic_auth(quote_char="'")
def test_proxy_basic_auth(self):
opener = OpenerDirector()
ph = urllib2.ProxyHandler(dict(http="proxy.example.com:3128"))
opener.add_handler(ph)
password_manager = MockPasswordManager()
auth_handler = urllib2.ProxyBasicAuthHandler(password_manager)
realm = "ACME Networks"
http_handler = MockHTTPHandler(
407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
opener.add_handler(auth_handler)
opener.add_handler(http_handler)
self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
realm, http_handler, password_manager,
"http://acme.example.com:3128/protected",
"proxy.example.com:3128",
)
def test_basic_and_digest_auth_handlers(self):
# HTTPDigestAuthHandler threw an exception if it couldn't handle a 40*
# response (http://python.org/sf/1479302), where it should instead
# return None to allow another handler (especially
# HTTPBasicAuthHandler) to handle the response.
# Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
# try digest first (since it's the strongest auth scheme), so we record
# order of calls here to check digest comes first:
class RecordingOpenerDirector(OpenerDirector):
def __init__(self):
OpenerDirector.__init__(self)
self.recorded = []
def record(self, info):
self.recorded.append(info)
class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
def http_error_401(self, *args, **kwds):
self.parent.record("digest")
urllib2.HTTPDigestAuthHandler.http_error_401(self,
*args, **kwds)
class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
def http_error_401(self, *args, **kwds):
self.parent.record("basic")
urllib2.HTTPBasicAuthHandler.http_error_401(self,
*args, **kwds)
opener = RecordingOpenerDirector()
password_manager = MockPasswordManager()
digest_handler = TestDigestAuthHandler(password_manager)
basic_handler = TestBasicAuthHandler(password_manager)
realm = "ACME Networks"
http_handler = MockHTTPHandler(
401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
opener.add_handler(basic_handler)
opener.add_handler(digest_handler)
opener.add_handler(http_handler)
# check basic auth isn't blocked by digest handler failing
self._test_basic_auth(opener, basic_handler, "Authorization",
realm, http_handler, password_manager,
"http://acme.example.com/protected",
"http://acme.example.com/protected",
)
# check digest was tried before basic (twice, because
# _test_basic_auth called .open() twice)
self.assertEqual(opener.recorded, ["digest", "basic"]*2)
def _test_basic_auth(self, opener, auth_handler, auth_header,
realm, http_handler, password_manager,
request_url, protected_url):
import base64
user, password = "wile", "coyote"
# .add_password() fed through to password manager
auth_handler.add_password(realm, request_url, user, password)
self.assertEqual(realm, password_manager.realm)
self.assertEqual(request_url, password_manager.url)
self.assertEqual(user, password_manager.user)
self.assertEqual(password, password_manager.password)
r = opener.open(request_url)
# should have asked the password manager for the username/password
self.assertEqual(password_manager.target_realm, realm)
self.assertEqual(password_manager.target_url, protected_url)
# expect one request without authorization, then one with
self.assertEqual(len(http_handler.requests), 2)
self.assertFalse(http_handler.requests[0].has_header(auth_header))
userpass = '%s:%s' % (user, password)
auth_hdr_value = 'Basic '+base64.encodestring(userpass).strip()
self.assertEqual(http_handler.requests[1].get_header(auth_header),
auth_hdr_value)
self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header],
auth_hdr_value)
# if the password manager can't find a password, the handler won't
# handle the HTTP auth error
password_manager.user = password_manager.password = None
http_handler.reset()
r = opener.open(request_url)
self.assertEqual(len(http_handler.requests), 1)
self.assertFalse(http_handler.requests[0].has_header(auth_header))
class MiscTests(unittest.TestCase):
def test_build_opener(self):
class MyHTTPHandler(urllib2.HTTPHandler): pass
class FooHandler(urllib2.BaseHandler):
def foo_open(self): pass
class BarHandler(urllib2.BaseHandler):
def bar_open(self): pass
build_opener = urllib2.build_opener
o = build_opener(FooHandler, BarHandler)
self.opener_has_handler(o, FooHandler)
self.opener_has_handler(o, BarHandler)
# can take a mix of classes and instances
o = build_opener(FooHandler, BarHandler())
self.opener_has_handler(o, FooHandler)
self.opener_has_handler(o, BarHandler)
# subclasses of default handlers override default handlers
o = build_opener(MyHTTPHandler)
self.opener_has_handler(o, MyHTTPHandler)
# a particular case of overriding: default handlers can be passed
# in explicitly
o = build_opener()
self.opener_has_handler(o, urllib2.HTTPHandler)
o = build_opener(urllib2.HTTPHandler)
self.opener_has_handler(o, urllib2.HTTPHandler)
o = build_opener(urllib2.HTTPHandler())
self.opener_has_handler(o, urllib2.HTTPHandler)
# Issue2670: multiple handlers sharing the same base class
class MyOtherHTTPHandler(urllib2.HTTPHandler): pass
o = build_opener(MyHTTPHandler, MyOtherHTTPHandler)
self.opener_has_handler(o, MyHTTPHandler)
self.opener_has_handler(o, MyOtherHTTPHandler)
def opener_has_handler(self, opener, handler_class):
for h in opener.handlers:
if h.__class__ == handler_class:
break
else:
self.assertTrue(False)
class RequestTests(unittest.TestCase):
def setUp(self):
self.get = urllib2.Request("http://www.python.org/~jeremy/")
self.post = urllib2.Request("http://www.python.org/~jeremy/",
"data",
headers={"X-Test": "test"})
def test_method(self):
self.assertEqual("POST", self.post.get_method())
self.assertEqual("GET", self.get.get_method())
def test_add_data(self):
self.assertTrue(not self.get.has_data())
self.assertEqual("GET", self.get.get_method())
self.get.add_data("spam")
self.assertTrue(self.get.has_data())
self.assertEqual("POST", self.get.get_method())
def test_get_full_url(self):
self.assertEqual("http://www.python.org/~jeremy/",
self.get.get_full_url())
def test_selector(self):
self.assertEqual("/~jeremy/", self.get.get_selector())
req = urllib2.Request("http://www.python.org/")
self.assertEqual("/", req.get_selector())
def test_get_type(self):
self.assertEqual("http", self.get.get_type())
def test_get_host(self):
self.assertEqual("www.python.org", self.get.get_host())
def test_get_host_unquote(self):
req = urllib2.Request("http://www.%70ython.org/")
self.assertEqual("www.python.org", req.get_host())
def test_proxy(self):
self.assertTrue(not self.get.has_proxy())
self.get.set_proxy("www.perl.org", "http")
self.assertTrue(self.get.has_proxy())
self.assertEqual("www.python.org", self.get.get_origin_req_host())
self.assertEqual("www.perl.org", self.get.get_host())
def test_main(verbose=None):
from test import test_urllib2
test_support.run_doctest(test_urllib2, verbose)
test_support.run_doctest(urllib2, verbose)
tests = (TrivialTests,
OpenerDirectorTests,
HandlerTests,
MiscTests,
RequestTests)
test_support.run_unittest(*tests)
if __name__ == "__main__":
test_main(verbose=True)
| mit |
Alwnikrotikz/l5rcm | widgets/cost_selection.py | 3 | 5037 | # Copyright (C) 2011 Daniele Simonetti
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
import sys
from PySide import QtCore, QtGui
class XpTextBox(QtGui.QLineEdit):
sub_text = None
def __init__(self, parent = None):
super(XpTextBox, self).__init__(parent)
self.sub_text = self.tr('XP')
def paintEvent(self, event):
super(XpTextBox, self).paintEvent(event)
painter = QtGui.QPainter(self)
painter.save()
# a nice gray pen
pen = QtGui.QPen( QtCore.Qt.darkGray, 1 )
painter.setPen(pen)
right_margin = 5
# measure the string to draw
font_metric = painter.fontMetrics()
tx_rect = font_metric.boundingRect(self.sub_text)
painter.drawText(event.rect().width() - right_margin - tx_rect.width(), event.rect().top() + tx_rect.height(), self.sub_text)
painter.restore()
class CostSelection(QtGui.QWidget):
rb_suggested = None
rb_manual = None
tx_suggested = None
tx_manual = None
vbox = None
suggested = 0
manual = 0
reason = None
def __init__(self, parent = None):
super(CostSelection, self).__init__(parent)
self.rb_suggested = QtGui.QRadioButton(self.tr('Suggested Value'), self)
self.rb_manual = QtGui.QRadioButton(self.tr('Manual Value'),self)
self.tx_suggested = XpTextBox(self)
self.tx_manual = XpTextBox(self)
vbox = QtGui.QVBoxLayout(self)
vbox.addStretch()
vbox.addWidget(self.rb_suggested)
vbox.addWidget(self.tx_suggested)
vbox.addWidget(self.rb_manual)
vbox.addWidget(self.tx_manual)
self.rb_suggested.toggled.connect( self.tx_suggested.setEnabled )
self.rb_manual .toggled.connect( self.tx_manual .setEnabled )
self.rb_manual .toggled.connect( self.tx_manual .selectAll )
self.rb_manual .toggled.connect( self.tx_manual .setFocus )
self.rb_suggested.setChecked(True)
self.tx_manual .setEnabled(False)
self.tx_manual .setContentsMargins(18, 0, 0, 0)
self.tx_suggested.setContentsMargins(18, 0, 0, 0)
self.tx_suggested.setReadOnly(True)
validator = QtGui.QIntValidator(self)
validator.setRange(-9999, 9999)
self.tx_manual.setValidator(validator)
self.tx_manual .setText('0')
self.tx_manual.textChanged.connect( self.on_manual_text_change )
def set_suggested_cost(self, cost):
self.suggested = cost
self.update_suggested_text()
def set_discount_reason(self, reason):
self.reason = reason
self.update_suggested_text()
def update_suggested_text(self):
if self.reason:
self.tx_suggested.setText( '{0} [{1}]'.format(self.suggested, self.reason) )
else:
self.tx_suggested.setText( str(self.suggested) )
def get_suggested_cost(self):
return self.suggested
def get_manual_cost(self):
return self.manual
def set_manual_cost(self, value):
self.tx_manual.setText( str(value) )
def set_manual_only(self, flag):
self.rb_manual.setChecked(flag)
#self.tx_manual.setEnabled(flag)
self.rb_suggested.setChecked(not flag)
self.rb_suggested.setEnabled(not flag)
#self.tx_suggested.setEnabled(not flag)
def on_manual_text_change(self, text):
try:
self.manual = int(text)
except:
self.manual = 0
def get_cost(self):
if self.rb_manual.isChecked():
return self.manual
else:
return self.suggested
def utest():
app = QtGui.QApplication(sys.argv)
dlg = QtGui.QDialog()
vbox = QtGui.QVBoxLayout(dlg)
csel = CostSelection(dlg)
csel.set_suggested_cost(3)
csel.set_discount_reason('crab')
vbox.addWidget( csel )
dlg.show()
app.exec_()
if __name__ == '__main__':
utest()
| gpl-3.0 |
SummerLW/Perf-Insight-Report | third_party/gsutil/gslib/tests/test_trace.py | 20 | 1679 | # -*- coding: utf-8 -*-
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Integration tests for gsutil --trace-token option."""
from __future__ import absolute_import
from gslib.cs_api_map import ApiSelector
import gslib.tests.testcase as testcase
from gslib.tests.testcase.integration_testcase import SkipForS3
from gslib.tests.util import ObjectToURI as suri
@SkipForS3('--trace-token is supported only on GCS JSON API.')
class TestTraceTokenOption(testcase.GsUtilIntegrationTestCase):
"""Integration tests for gsutil --trace-token option."""
def test_minus_tracetoken_cat(self):
"""Tests cat command with trace-token option."""
key_uri = self.CreateObject(contents='0123456789')
(_, stderr) = self.RunGsUtil(
['-D', '--trace-token=THISISATOKEN', 'cat', suri(key_uri)],
return_stdout=True, return_stderr=True)
if self.test_api == ApiSelector.JSON:
self.assertIn('You are running gsutil with trace output enabled.', stderr)
self.assertRegexpMatches(
stderr, r'.*GET.*b/%s/o/%s\?.*&trace=token%%3ATHISISATOKEN' %
(key_uri.bucket_name, key_uri.object_name))
| bsd-3-clause |
ShawnPengxy/Flask-madeBlog | site-packages/setuptools/tests/test_markerlib.py | 449 | 2506 | import os
import unittest
from setuptools.tests.py26compat import skipIf
try:
import ast
except ImportError:
pass
class TestMarkerlib(unittest.TestCase):
@skipIf('ast' not in globals(),
"ast not available (Python < 2.6?)")
def test_markers(self):
from _markerlib import interpret, default_environment, compile
os_name = os.name
self.assertTrue(interpret(""))
self.assertTrue(interpret("os.name != 'buuuu'"))
self.assertTrue(interpret("os_name != 'buuuu'"))
self.assertTrue(interpret("python_version > '1.0'"))
self.assertTrue(interpret("python_version < '5.0'"))
self.assertTrue(interpret("python_version <= '5.0'"))
self.assertTrue(interpret("python_version >= '1.0'"))
self.assertTrue(interpret("'%s' in os.name" % os_name))
self.assertTrue(interpret("'%s' in os_name" % os_name))
self.assertTrue(interpret("'buuuu' not in os.name"))
self.assertFalse(interpret("os.name == 'buuuu'"))
self.assertFalse(interpret("os_name == 'buuuu'"))
self.assertFalse(interpret("python_version < '1.0'"))
self.assertFalse(interpret("python_version > '5.0'"))
self.assertFalse(interpret("python_version >= '5.0'"))
self.assertFalse(interpret("python_version <= '1.0'"))
self.assertFalse(interpret("'%s' not in os.name" % os_name))
self.assertFalse(interpret("'buuuu' in os.name and python_version >= '5.0'"))
self.assertFalse(interpret("'buuuu' in os_name and python_version >= '5.0'"))
environment = default_environment()
environment['extra'] = 'test'
self.assertTrue(interpret("extra == 'test'", environment))
self.assertFalse(interpret("extra == 'doc'", environment))
def raises_nameError():
try:
interpret("python.version == '42'")
except NameError:
pass
else:
raise Exception("Expected NameError")
raises_nameError()
def raises_syntaxError():
try:
interpret("(x for x in (4,))")
except SyntaxError:
pass
else:
raise Exception("Expected SyntaxError")
raises_syntaxError()
statement = "python_version == '5'"
self.assertEqual(compile(statement).__doc__, statement)
| mit |
rahushen/ansible | lib/ansible/modules/network/nxos/nxos_evpn_global.py | 23 | 2812 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
DOCUMENTATION = '''
---
module: nxos_evpn_global
extends_documentation_fragment: nxos
version_added: "2.2"
short_description: Handles the EVPN control plane for VXLAN.
description:
- Handles the EVPN control plane for VXLAN.
author: Gabriele Gerbino (@GGabriele)
notes:
- This module is not supported on Nexus 3000 series of switches.
options:
nv_overlay_evpn:
description:
- EVPN control plane.
required: true
choices: ['true', 'false']
'''
EXAMPLES = '''
- nxos_evpn_global:
nv_overlay_evpn: true
'''
RETURN = '''
commands:
description: The set of commands to be sent to the remote device
returned: always
type: list
sample: ['nv overlay evpn']
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.nxos.nxos import get_config, load_config
from ansible.module_utils.network.nxos.nxos import get_capabilities, nxos_argument_spec
def main():
argument_spec = dict(
nv_overlay_evpn=dict(required=True, type='bool'),
)
argument_spec.update(nxos_argument_spec)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
result = {'changed': False}
warnings = list()
if warnings:
result['warnings'] = warnings
config = get_config(module)
commands = list()
info = get_capabilities(module).get('device_info', {})
os_platform = info.get('network_os_platform', '')
if '3K' in os_platform:
module.fail_json(msg='This module is not supported on Nexus 3000 series')
if module.params['nv_overlay_evpn'] is True:
if 'nv overlay evpn' not in config:
commands.append('nv overlay evpn')
elif 'nv overlay evpn' in config:
commands.append('no nv overlay evpn')
if commands:
if not module.check_mode:
load_config(module, commands)
result['changed'] = True
result['commands'] = commands
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
Bonanashelby/MoodBot | mood_bot/setup.py | 1 | 1439 | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.txt')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt')) as f:
CHANGES = f.read()
requires = [
'pyramid',
'pyramid_jinja2',
'pyramid_debugtoolbar',
'pyramid_tm',
'SQLAlchemy',
'transaction',
'zope.sqlalchemy',
'waitress',
'pyramid_ipython',
'ipython',
'psycopg2',
'passlib',
'requests',
'tweepy',
'textblob',
]
tests_require = [
'WebTest >= 1.3.1', # py3 compat
'pytest',
'pytest-cov',
'tox'
]
setup(
name='mood_bot',
version='0.0',
description='mood_bot',
long_description=README + '\n\n' + CHANGES,
classifiers=[
'Programming Language :: Python',
'Framework :: Pyramid',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
],
author='',
author_email='',
url='',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
extras_require={
'testing': tests_require,
},
install_requires=requires,
entry_points={
'paste.app_factory': [
'main = mood_bot:main',
],
'console_scripts': [
'initializedb = mood_bot.scripts.initializedb:main',
],
},
)
| mit |
EvanK/ansible | test/units/modules/storage/netapp/test_na_ontap_job_schedule.py | 43 | 8947 | # (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
''' unit tests for Ansible module: na_ontap_job_schedule '''
from __future__ import print_function
import json
import pytest
from units.compat import unittest
from units.compat.mock import patch, Mock
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
import ansible.module_utils.netapp as netapp_utils
from ansible.modules.storage.netapp.na_ontap_job_schedule \
import NetAppONTAPJob as job_module # module under test
if not netapp_utils.has_netapp_lib():
pytestmark = pytest.mark.skip('skipping as missing required netapp_lib')
def set_module_args(args):
"""prepare arguments so that they will be picked up during module creation"""
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
basic._ANSIBLE_ARGS = to_bytes(args) # pylint: disable=protected-access
class AnsibleExitJson(Exception):
"""Exception class to be raised by module.exit_json and caught by the test case"""
pass
class AnsibleFailJson(Exception):
"""Exception class to be raised by module.fail_json and caught by the test case"""
pass
def exit_json(*args, **kwargs): # pylint: disable=unused-argument
"""function to patch over exit_json; package return data into an exception"""
if 'changed' not in kwargs:
kwargs['changed'] = False
raise AnsibleExitJson(kwargs)
def fail_json(*args, **kwargs): # pylint: disable=unused-argument
"""function to patch over fail_json; package return data into an exception"""
kwargs['failed'] = True
raise AnsibleFailJson(kwargs)
class MockONTAPConnection(object):
''' mock server connection to ONTAP host '''
def __init__(self, kind=None, data=None):
''' save arguments '''
self.kind = kind
self.params = data
self.xml_in = None
self.xml_out = None
def invoke_successfully(self, xml, enable_tunneling): # pylint: disable=unused-argument
''' mock invoke_successfully returning xml data '''
self.xml_in = xml
if self.kind == 'job':
xml = self.build_job_schedule_cron_info(self.params)
elif self.kind == 'job_multiple':
xml = self.build_job_schedule_multiple_cron_info(self.params)
# TODO: mock invoke_elem for autosupport calls
elif self.kind == 'vserver':
xml = self.build_vserver_info()
self.xml_out = xml
return xml
def autosupport_log(self):
''' Mock autosupport log method, returns None '''
return None
@staticmethod
def build_job_schedule_cron_info(job_details):
''' build xml data for vserser-info '''
xml = netapp_utils.zapi.NaElement('xml')
attributes = {
'num-records': 1,
'attributes-list': {
'job-schedule-cron-info': {
'job-schedule-name': job_details['name'],
'job-schedule-cron-minute': {
'cron-minute': job_details['minutes']
}
}
}
}
xml.translate_struct(attributes)
return xml
@staticmethod
def build_job_schedule_multiple_cron_info(job_details):
''' build xml data for vserser-info '''
print("CALLED MULTIPLE BUILD")
xml = netapp_utils.zapi.NaElement('xml')
attributes = {
'num-records': 1,
'attributes-list': {
'job-schedule-cron-info': {
'job-schedule-name': job_details['name'],
'job-schedule-cron-minute': [
{'cron-minute': '25'},
{'cron-minute': '35'}
],
'job-schedule-cron-month': [
{'cron-month': '5'},
{'cron-month': '10'}
]
}
}
}
xml.translate_struct(attributes)
return xml
class TestMyModule(unittest.TestCase):
''' Unit tests for na_ontap_job_schedule '''
def setUp(self):
self.mock_module_helper = patch.multiple(basic.AnsibleModule,
exit_json=exit_json,
fail_json=fail_json)
self.mock_module_helper.start()
self.addCleanup(self.mock_module_helper.stop)
self.mock_job = {
'name': 'test_job',
'minutes': '25'
}
def mock_args(self):
return {
'name': self.mock_job['name'],
'job_minutes': [self.mock_job['minutes']],
'hostname': 'test',
'username': 'test_user',
'password': 'test_pass!'
}
def get_job_mock_object(self, kind=None):
"""
Helper method to return an na_ontap_job_schedule object
:param kind: passes this param to MockONTAPConnection()
:return: na_ontap_job_schedule object
"""
job_obj = job_module()
job_obj.autosupport_log = Mock(return_value=None)
if kind is None:
job_obj.server = MockONTAPConnection()
else:
job_obj.server = MockONTAPConnection(kind=kind, data=self.mock_job)
return job_obj
def test_module_fail_when_required_args_missing(self):
''' required arguments are reported as errors '''
with pytest.raises(AnsibleFailJson) as exc:
set_module_args({})
job_module()
print('Info: %s' % exc.value.args[0]['msg'])
def test_get_nonexistent_job(self):
''' Test if get_job_schedule returns None for non-existent job '''
set_module_args(self.mock_args())
result = self.get_job_mock_object().get_job_schedule()
assert result is None
def test_get_existing_job(self):
''' Test if get_job_schedule retuns job details for existing job '''
data = self.mock_args()
set_module_args(data)
result = self.get_job_mock_object('job').get_job_schedule()
assert result['name'] == self.mock_job['name']
assert result['job_minutes'] == data['job_minutes']
def test_get_existing_job_multiple_minutes(self):
''' Test if get_job_schedule retuns job details for existing job '''
set_module_args(self.mock_args())
result = self.get_job_mock_object('job_multiple').get_job_schedule()
print(str(result))
assert result['name'] == self.mock_job['name']
assert result['job_minutes'] == ['25', '35']
assert result['job_months'] == ['5', '10']
def test_create_error_missing_param(self):
''' Test if create throws an error if job_minutes is not specified'''
data = self.mock_args()
del data['job_minutes']
set_module_args(data)
with pytest.raises(AnsibleFailJson) as exc:
self.get_job_mock_object('job').create_job_schedule()
msg = 'Error: missing required parameter job_minutes for create'
assert exc.value.args[0]['msg'] == msg
def test_successful_create(self):
''' Test successful create '''
set_module_args(self.mock_args())
with pytest.raises(AnsibleExitJson) as exc:
self.get_job_mock_object().apply()
assert exc.value.args[0]['changed']
def test_create_idempotency(self):
''' Test create idempotency '''
set_module_args(self.mock_args())
with pytest.raises(AnsibleExitJson) as exc:
self.get_job_mock_object('job').apply()
assert not exc.value.args[0]['changed']
def test_successful_delete(self):
''' Test delete existing job '''
data = self.mock_args()
data['state'] = 'absent'
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_job_mock_object('job').apply()
assert exc.value.args[0]['changed']
def test_delete_idempotency(self):
''' Test delete idempotency '''
data = self.mock_args()
data['state'] = 'absent'
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_job_mock_object().apply()
assert not exc.value.args[0]['changed']
def test_successful_modify(self):
''' Test successful modify job_minutes '''
data = self.mock_args()
data['job_minutes'] = ['20']
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_job_mock_object('job').apply()
assert exc.value.args[0]['changed']
def test_modify_idempotency(self):
''' Test modify idempotency '''
data = self.mock_args()
set_module_args(data)
with pytest.raises(AnsibleExitJson) as exc:
self.get_job_mock_object('job').apply()
assert not exc.value.args[0]['changed']
| gpl-3.0 |
AMOboxTV/AMOBox.LegoBuild | plugin.video.specto/resources/lib/libraries/f4mproxy/utils/datefuncs.py | 206 | 2278 | # Author: Trevor Perrin
# See the LICENSE file for legal information regarding use of this file.
import os
#Functions for manipulating datetime objects
#CCYY-MM-DDThh:mm:ssZ
def parseDateClass(s):
year, month, day = s.split("-")
day, tail = day[:2], day[2:]
hour, minute, second = tail[1:].split(":")
second = second[:2]
year, month, day = int(year), int(month), int(day)
hour, minute, second = int(hour), int(minute), int(second)
return createDateClass(year, month, day, hour, minute, second)
if os.name != "java":
from datetime import datetime, timedelta
#Helper functions for working with a date/time class
def createDateClass(year, month, day, hour, minute, second):
return datetime(year, month, day, hour, minute, second)
def printDateClass(d):
#Split off fractional seconds, append 'Z'
return d.isoformat().split(".")[0]+"Z"
def getNow():
return datetime.utcnow()
def getHoursFromNow(hours):
return datetime.utcnow() + timedelta(hours=hours)
def getMinutesFromNow(minutes):
return datetime.utcnow() + timedelta(minutes=minutes)
def isDateClassExpired(d):
return d < datetime.utcnow()
def isDateClassBefore(d1, d2):
return d1 < d2
else:
#Jython 2.1 is missing lots of python 2.3 stuff,
#which we have to emulate here:
import java
import jarray
def createDateClass(year, month, day, hour, minute, second):
c = java.util.Calendar.getInstance()
c.setTimeZone(java.util.TimeZone.getTimeZone("UTC"))
c.set(year, month-1, day, hour, minute, second)
return c
def printDateClass(d):
return "%04d-%02d-%02dT%02d:%02d:%02dZ" % \
(d.get(d.YEAR), d.get(d.MONTH)+1, d.get(d.DATE), \
d.get(d.HOUR_OF_DAY), d.get(d.MINUTE), d.get(d.SECOND))
def getNow():
c = java.util.Calendar.getInstance()
c.setTimeZone(java.util.TimeZone.getTimeZone("UTC"))
c.get(c.HOUR) #force refresh?
return c
def getHoursFromNow(hours):
d = getNow()
d.add(d.HOUR, hours)
return d
def isDateClassExpired(d):
n = getNow()
return d.before(n)
def isDateClassBefore(d1, d2):
return d1.before(d2)
| gpl-2.0 |
shengxinjing/woniu-cmdb | dbutil/dbutil.py | 1 | 1398 | #!/usr/bin/env python
#encoding:utf8
import json
import time,random
import datetime
import MySQLdb
import MySQLdb.cursors
class DB:
conn = None
db = None
host = None
def __init__(self, host, mysql_user, mysql_pass, mysql_db):
self.host = host
self.mysql_user = mysql_user
self.mysql_pass = mysql_pass
self.mysql_db = mysql_db
def connect(self):
self.conn = MySQLdb.connect(host=self.host, user=self.mysql_user, passwd=self.mysql_pass, db=self.mysql_db, charset="utf8", connect_timeout=600, compress=True,cursorclass = MySQLdb.cursors.DictCursor)
self.conn.autocommit(True)
def execute(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
try:
cursor.close()
self.conn.close()
except:
pass
time.sleep(1)
try:
self.connect()
print "reconnect DB"
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
time.sleep(2)
self.connect()
print "reconnect DB"
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
| mit |
happyleavesaoc/home-assistant | tests/components/climate/test_demo.py | 15 | 11861 | """The tests for the demo climate component."""
import unittest
from homeassistant.util.unit_system import (
METRIC_SYSTEM
)
from homeassistant.setup import setup_component
from homeassistant.components import climate
from tests.common import get_test_home_assistant
ENTITY_CLIMATE = 'climate.hvac'
ENTITY_ECOBEE = 'climate.ecobee'
ENTITY_HEATPUMP = 'climate.heatpump'
class TestDemoClimate(unittest.TestCase):
"""Test the demo climate hvac."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.hass.config.units = METRIC_SYSTEM
self.assertTrue(setup_component(self.hass, climate.DOMAIN, {
'climate': {
'platform': 'demo',
}}))
def tearDown(self): # pylint: disable=invalid-name
"""Stop down everything that was started."""
self.hass.stop()
def test_setup_params(self):
"""Test the initial parameters."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(21, state.attributes.get('temperature'))
self.assertEqual('on', state.attributes.get('away_mode'))
self.assertEqual(22, state.attributes.get('current_temperature'))
self.assertEqual("On High", state.attributes.get('fan_mode'))
self.assertEqual(67, state.attributes.get('humidity'))
self.assertEqual(54, state.attributes.get('current_humidity'))
self.assertEqual("Off", state.attributes.get('swing_mode'))
self.assertEqual("cool", state.attributes.get('operation_mode'))
self.assertEqual('off', state.attributes.get('aux_heat'))
def test_default_setup_params(self):
"""Test the setup with default parameters."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(7, state.attributes.get('min_temp'))
self.assertEqual(35, state.attributes.get('max_temp'))
self.assertEqual(30, state.attributes.get('min_humidity'))
self.assertEqual(99, state.attributes.get('max_humidity'))
def test_set_only_target_temp_bad_attr(self):
"""Test setting the target temperature without required attribute."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(21, state.attributes.get('temperature'))
climate.set_temperature(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
self.assertEqual(21, state.attributes.get('temperature'))
def test_set_only_target_temp(self):
"""Test the setting of the target temperature."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(21, state.attributes.get('temperature'))
climate.set_temperature(self.hass, 30, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(30.0, state.attributes.get('temperature'))
def test_set_only_target_temp_with_convert(self):
"""Test the setting of the target temperature."""
state = self.hass.states.get(ENTITY_HEATPUMP)
self.assertEqual(20, state.attributes.get('temperature'))
climate.set_temperature(self.hass, 21, ENTITY_HEATPUMP)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_HEATPUMP)
self.assertEqual(21.0, state.attributes.get('temperature'))
def test_set_target_temp_range(self):
"""Test the setting of the target temperature with range."""
state = self.hass.states.get(ENTITY_ECOBEE)
self.assertEqual(None, state.attributes.get('temperature'))
self.assertEqual(21.0, state.attributes.get('target_temp_low'))
self.assertEqual(24.0, state.attributes.get('target_temp_high'))
climate.set_temperature(self.hass, target_temp_high=25,
target_temp_low=20, entity_id=ENTITY_ECOBEE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_ECOBEE)
self.assertEqual(None, state.attributes.get('temperature'))
self.assertEqual(20.0, state.attributes.get('target_temp_low'))
self.assertEqual(25.0, state.attributes.get('target_temp_high'))
def test_set_target_temp_range_bad_attr(self):
"""Test setting the target temperature range without attribute."""
state = self.hass.states.get(ENTITY_ECOBEE)
self.assertEqual(None, state.attributes.get('temperature'))
self.assertEqual(21.0, state.attributes.get('target_temp_low'))
self.assertEqual(24.0, state.attributes.get('target_temp_high'))
climate.set_temperature(self.hass, temperature=None,
entity_id=ENTITY_ECOBEE, target_temp_low=None,
target_temp_high=None)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_ECOBEE)
self.assertEqual(None, state.attributes.get('temperature'))
self.assertEqual(21.0, state.attributes.get('target_temp_low'))
self.assertEqual(24.0, state.attributes.get('target_temp_high'))
def test_set_target_humidity_bad_attr(self):
"""Test setting the target humidity without required attribute."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(67, state.attributes.get('humidity'))
climate.set_humidity(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(67, state.attributes.get('humidity'))
def test_set_target_humidity(self):
"""Test the setting of the target humidity."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(67, state.attributes.get('humidity'))
climate.set_humidity(self.hass, 64, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual(64.0, state.attributes.get('humidity'))
def test_set_fan_mode_bad_attr(self):
"""Test setting fan mode without required attribute."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("On High", state.attributes.get('fan_mode'))
climate.set_fan_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("On High", state.attributes.get('fan_mode'))
def test_set_fan_mode(self):
"""Test setting of new fan mode."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("On High", state.attributes.get('fan_mode'))
climate.set_fan_mode(self.hass, "On Low", ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("On Low", state.attributes.get('fan_mode'))
def test_set_swing_mode_bad_attr(self):
"""Test setting swing mode without required attribute."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("Off", state.attributes.get('swing_mode'))
climate.set_swing_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("Off", state.attributes.get('swing_mode'))
def test_set_swing(self):
"""Test setting of new swing mode."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("Off", state.attributes.get('swing_mode'))
climate.set_swing_mode(self.hass, "Auto", ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("Auto", state.attributes.get('swing_mode'))
def test_set_operation_bad_attr_and_state(self):
"""Test setting operation mode without required attribute.
Also check the state.
"""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("cool", state.attributes.get('operation_mode'))
self.assertEqual("cool", state.state)
climate.set_operation_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("cool", state.attributes.get('operation_mode'))
self.assertEqual("cool", state.state)
def test_set_operation(self):
"""Test setting of new operation mode."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("cool", state.attributes.get('operation_mode'))
self.assertEqual("cool", state.state)
climate.set_operation_mode(self.hass, "heat", ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual("heat", state.attributes.get('operation_mode'))
self.assertEqual("heat", state.state)
def test_set_away_mode_bad_attr(self):
"""Test setting the away mode without required attribute."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('on', state.attributes.get('away_mode'))
climate.set_away_mode(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
self.assertEqual('on', state.attributes.get('away_mode'))
def test_set_away_mode_on(self):
"""Test setting the away mode on/true."""
climate.set_away_mode(self.hass, True, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('on', state.attributes.get('away_mode'))
def test_set_away_mode_off(self):
"""Test setting the away mode off/false."""
climate.set_away_mode(self.hass, False, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('off', state.attributes.get('away_mode'))
def test_set_hold_mode_home(self):
"""Test setting the hold mode home."""
climate.set_hold_mode(self.hass, 'home', ENTITY_ECOBEE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_ECOBEE)
self.assertEqual('home', state.attributes.get('hold_mode'))
def test_set_hold_mode_away(self):
"""Test setting the hold mode away."""
climate.set_hold_mode(self.hass, 'away', ENTITY_ECOBEE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_ECOBEE)
self.assertEqual('away', state.attributes.get('hold_mode'))
def test_set_hold_mode_none(self):
"""Test setting the hold mode off/false."""
climate.set_hold_mode(self.hass, None, ENTITY_ECOBEE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_ECOBEE)
self.assertEqual(None, state.attributes.get('hold_mode'))
def test_set_aux_heat_bad_attr(self):
"""Test setting the auxillary heater without required attribute."""
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('off', state.attributes.get('aux_heat'))
climate.set_aux_heat(self.hass, None, ENTITY_CLIMATE)
self.hass.block_till_done()
self.assertEqual('off', state.attributes.get('aux_heat'))
def test_set_aux_heat_on(self):
"""Test setting the axillary heater on/true."""
climate.set_aux_heat(self.hass, True, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('on', state.attributes.get('aux_heat'))
def test_set_aux_heat_off(self):
"""Test setting the auxillary heater off/false."""
climate.set_aux_heat(self.hass, False, ENTITY_CLIMATE)
self.hass.block_till_done()
state = self.hass.states.get(ENTITY_CLIMATE)
self.assertEqual('off', state.attributes.get('aux_heat'))
| apache-2.0 |
instagibbs/bitcoin | test/functional/segwit.py | 13 | 39739 | #!/usr/bin/env python3
# Copyright (c) 2016 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 the SegWit changeover logic."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import sha256, CTransaction, CTxIn, COutPoint, CTxOut, COIN, ToHex, FromHex
from test_framework.address import script_to_p2sh, key_to_p2pkh
from test_framework.script import CScript, OP_HASH160, OP_CHECKSIG, OP_0, hash160, OP_EQUAL, OP_DUP, OP_EQUALVERIFY, OP_1, OP_2, OP_CHECKMULTISIG, OP_TRUE
from io import BytesIO
NODE_0 = 0
NODE_1 = 1
NODE_2 = 2
WIT_V0 = 0
WIT_V1 = 1
# Create a scriptPubKey corresponding to either a P2WPKH output for the
# given pubkey, or a P2WSH output of a 1-of-1 multisig for the given
# pubkey. Returns the hex encoding of the scriptPubKey.
def witness_script(use_p2wsh, pubkey):
if (use_p2wsh == False):
# P2WPKH instead
pubkeyhash = hash160(hex_str_to_bytes(pubkey))
pkscript = CScript([OP_0, pubkeyhash])
else:
# 1-of-1 multisig
witness_program = CScript([OP_1, hex_str_to_bytes(pubkey), OP_1, OP_CHECKMULTISIG])
scripthash = sha256(witness_program)
pkscript = CScript([OP_0, scripthash])
return bytes_to_hex_str(pkscript)
# Return a transaction (in hex) that spends the given utxo to a segwit output,
# optionally wrapping the segwit output using P2SH.
def create_witnessprogram(use_p2wsh, utxo, pubkey, encode_p2sh, amount):
pkscript = hex_str_to_bytes(witness_script(use_p2wsh, pubkey))
if (encode_p2sh):
p2sh_hash = hash160(pkscript)
pkscript = CScript([OP_HASH160, p2sh_hash, OP_EQUAL])
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(int(utxo["txid"], 16), utxo["vout"]), b""))
tx.vout.append(CTxOut(int(amount*COIN), pkscript))
return ToHex(tx)
# Create a transaction spending a given utxo to a segwit output corresponding
# to the given pubkey: use_p2wsh determines whether to use P2WPKH or P2WSH;
# encode_p2sh determines whether to wrap in P2SH.
# sign=True will have the given node sign the transaction.
# insert_redeem_script will be added to the scriptSig, if given.
def send_to_witness(use_p2wsh, node, utxo, pubkey, encode_p2sh, amount, sign=True, insert_redeem_script=""):
tx_to_witness = create_witnessprogram(use_p2wsh, utxo, pubkey, encode_p2sh, amount)
if (sign):
signed = node.signrawtransaction(tx_to_witness)
assert("errors" not in signed or len(["errors"]) == 0)
return node.sendrawtransaction(signed["hex"])
else:
if (insert_redeem_script):
tx = FromHex(CTransaction(), tx_to_witness)
tx.vin[0].scriptSig += CScript([hex_str_to_bytes(insert_redeem_script)])
tx_to_witness = ToHex(tx)
return node.sendrawtransaction(tx_to_witness)
def getutxo(txid):
utxo = {}
utxo["vout"] = 0
utxo["txid"] = txid
return utxo
def find_unspent(node, min_value):
for utxo in node.listunspent():
if utxo['amount'] >= min_value:
return utxo
class SegWitTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 3
self.extra_args = [["-walletprematurewitness", "-rpcserialversion=0"],
["-blockversion=4", "-promiscuousmempoolflags=517", "-prematurewitness", "-walletprematurewitness", "-rpcserialversion=1"],
["-blockversion=536870915", "-promiscuousmempoolflags=517", "-prematurewitness", "-walletprematurewitness"]]
def setup_network(self):
super().setup_network()
connect_nodes(self.nodes[0], 2)
self.sync_all()
def success_mine(self, node, txid, sign, redeem_script=""):
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
block = node.generate(1)
assert_equal(len(node.getblock(block[0])["tx"]), 2)
sync_blocks(self.nodes)
def skip_mine(self, node, txid, sign, redeem_script=""):
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
block = node.generate(1)
assert_equal(len(node.getblock(block[0])["tx"]), 1)
sync_blocks(self.nodes)
def fail_accept(self, node, error_msg, txid, sign, redeem_script=""):
assert_raises_jsonrpc(-26, error_msg, send_to_witness, 1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
def fail_mine(self, node, txid, sign, redeem_script=""):
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
assert_raises_jsonrpc(-1, "CreateNewBlock: TestBlockValidity failed", node.generate, 1)
sync_blocks(self.nodes)
def run_test(self):
self.nodes[0].generate(161) #block 161
self.log.info("Verify sigops are counted in GBT with pre-BIP141 rules before the fork")
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
tmpl = self.nodes[0].getblocktemplate({})
assert(tmpl['sizelimit'] == 1000000)
assert('weightlimit' not in tmpl)
assert(tmpl['sigoplimit'] == 20000)
assert(tmpl['transactions'][0]['hash'] == txid)
assert(tmpl['transactions'][0]['sigops'] == 2)
tmpl = self.nodes[0].getblocktemplate({'rules':['segwit']})
assert(tmpl['sizelimit'] == 1000000)
assert('weightlimit' not in tmpl)
assert(tmpl['sigoplimit'] == 20000)
assert(tmpl['transactions'][0]['hash'] == txid)
assert(tmpl['transactions'][0]['sigops'] == 2)
self.nodes[0].generate(1) #block 162
balance_presetup = self.nodes[0].getbalance()
self.pubkey = []
p2sh_ids = [] # p2sh_ids[NODE][VER] is an array of txids that spend to a witness version VER pkscript to an address for NODE embedded in p2sh
wit_ids = [] # wit_ids[NODE][VER] is an array of txids that spend to a witness version VER pkscript to an address for NODE via bare witness
for i in range(3):
newaddress = self.nodes[i].getnewaddress()
self.pubkey.append(self.nodes[i].validateaddress(newaddress)["pubkey"])
multiaddress = self.nodes[i].addmultisigaddress(1, [self.pubkey[-1]])
self.nodes[i].addwitnessaddress(newaddress)
self.nodes[i].addwitnessaddress(multiaddress)
p2sh_ids.append([])
wit_ids.append([])
for v in range(2):
p2sh_ids[i].append([])
wit_ids[i].append([])
for i in range(5):
for n in range(3):
for v in range(2):
wit_ids[n][v].append(send_to_witness(v, self.nodes[0], find_unspent(self.nodes[0], 50), self.pubkey[n], False, Decimal("49.999")))
p2sh_ids[n][v].append(send_to_witness(v, self.nodes[0], find_unspent(self.nodes[0], 50), self.pubkey[n], True, Decimal("49.999")))
self.nodes[0].generate(1) #block 163
sync_blocks(self.nodes)
# Make sure all nodes recognize the transactions as theirs
assert_equal(self.nodes[0].getbalance(), balance_presetup - 60*50 + 20*Decimal("49.999") + 50)
assert_equal(self.nodes[1].getbalance(), 20*Decimal("49.999"))
assert_equal(self.nodes[2].getbalance(), 20*Decimal("49.999"))
self.nodes[0].generate(260) #block 423
sync_blocks(self.nodes)
self.log.info("Verify default node can't accept any witness format txs before fork")
# unsigned, no scriptsig
self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", wit_ids[NODE_0][WIT_V0][0], False)
self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", wit_ids[NODE_0][WIT_V1][0], False)
self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V0][0], False)
self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V1][0], False)
# unsigned with redeem script
self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V0][0], False, witness_script(False, self.pubkey[0]))
self.fail_accept(self.nodes[0], "mandatory-script-verify-flag", p2sh_ids[NODE_0][WIT_V1][0], False, witness_script(True, self.pubkey[0]))
# signed
self.fail_accept(self.nodes[0], "no-witness-yet", wit_ids[NODE_0][WIT_V0][0], True)
self.fail_accept(self.nodes[0], "no-witness-yet", wit_ids[NODE_0][WIT_V1][0], True)
self.fail_accept(self.nodes[0], "no-witness-yet", p2sh_ids[NODE_0][WIT_V0][0], True)
self.fail_accept(self.nodes[0], "no-witness-yet", p2sh_ids[NODE_0][WIT_V1][0], True)
self.log.info("Verify witness txs are skipped for mining before the fork")
self.skip_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][0], True) #block 424
self.skip_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][0], True) #block 425
self.skip_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][0], True) #block 426
self.skip_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][0], True) #block 427
# TODO: An old node would see these txs without witnesses and be able to mine them
self.log.info("Verify unsigned bare witness txs in versionbits-setting blocks are valid before the fork")
self.success_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][1], False) #block 428
self.success_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][1], False) #block 429
self.log.info("Verify unsigned p2sh witness txs without a redeem script are invalid")
self.fail_accept(self.nodes[2], "mandatory-script-verify-flag", p2sh_ids[NODE_2][WIT_V0][1], False)
self.fail_accept(self.nodes[2], "mandatory-script-verify-flag", p2sh_ids[NODE_2][WIT_V1][1], False)
self.log.info("Verify unsigned p2sh witness txs with a redeem script in versionbits-settings blocks are valid before the fork")
self.success_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][1], False, witness_script(False, self.pubkey[2])) #block 430
self.success_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][1], False, witness_script(True, self.pubkey[2])) #block 431
self.log.info("Verify previous witness txs skipped for mining can now be mined")
assert_equal(len(self.nodes[2].getrawmempool()), 4)
block = self.nodes[2].generate(1) #block 432 (first block with new rules; 432 = 144 * 3)
sync_blocks(self.nodes)
assert_equal(len(self.nodes[2].getrawmempool()), 0)
segwit_tx_list = self.nodes[2].getblock(block[0])["tx"]
assert_equal(len(segwit_tx_list), 5)
self.log.info("Verify block and transaction serialization rpcs return differing serializations depending on rpc serialization flag")
assert(self.nodes[2].getblock(block[0], False) != self.nodes[0].getblock(block[0], False))
assert(self.nodes[1].getblock(block[0], False) == self.nodes[2].getblock(block[0], False))
for i in range(len(segwit_tx_list)):
tx = FromHex(CTransaction(), self.nodes[2].gettransaction(segwit_tx_list[i])["hex"])
assert(self.nodes[2].getrawtransaction(segwit_tx_list[i]) != self.nodes[0].getrawtransaction(segwit_tx_list[i]))
assert(self.nodes[1].getrawtransaction(segwit_tx_list[i], 0) == self.nodes[2].getrawtransaction(segwit_tx_list[i]))
assert(self.nodes[0].getrawtransaction(segwit_tx_list[i]) != self.nodes[2].gettransaction(segwit_tx_list[i])["hex"])
assert(self.nodes[1].getrawtransaction(segwit_tx_list[i]) == self.nodes[2].gettransaction(segwit_tx_list[i])["hex"])
assert(self.nodes[0].getrawtransaction(segwit_tx_list[i]) == bytes_to_hex_str(tx.serialize_without_witness()))
self.log.info("Verify witness txs without witness data are invalid after the fork")
self.fail_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][2], False)
self.fail_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][2], False)
self.fail_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][2], False, witness_script(False, self.pubkey[2]))
self.fail_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][2], False, witness_script(True, self.pubkey[2]))
self.log.info("Verify default node can now use witness txs")
self.success_mine(self.nodes[0], wit_ids[NODE_0][WIT_V0][0], True) #block 432
self.success_mine(self.nodes[0], wit_ids[NODE_0][WIT_V1][0], True) #block 433
self.success_mine(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], True) #block 434
self.success_mine(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], True) #block 435
self.log.info("Verify sigops are counted in GBT with BIP141 rules after the fork")
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
tmpl = self.nodes[0].getblocktemplate({'rules':['segwit']})
assert(tmpl['sizelimit'] >= 3999577) # actual maximum size is lower due to minimum mandatory non-witness data
assert(tmpl['weightlimit'] == 4000000)
assert(tmpl['sigoplimit'] == 80000)
assert(tmpl['transactions'][0]['txid'] == txid)
assert(tmpl['transactions'][0]['sigops'] == 8)
self.nodes[0].generate(1) # Mine a block to clear the gbt cache
self.log.info("Non-segwit miners are able to use GBT response after activation.")
# Create a 3-tx chain: tx1 (non-segwit input, paying to a segwit output) ->
# tx2 (segwit input, paying to a non-segwit output) ->
# tx3 (non-segwit input, paying to a non-segwit output).
# tx1 is allowed to appear in the block, but no others.
txid1 = send_to_witness(1, self.nodes[0], find_unspent(self.nodes[0], 50), self.pubkey[0], False, Decimal("49.996"))
hex_tx = self.nodes[0].gettransaction(txid)['hex']
tx = FromHex(CTransaction(), hex_tx)
assert(tx.wit.is_null()) # This should not be a segwit input
assert(txid1 in self.nodes[0].getrawmempool())
# Now create tx2, which will spend from txid1.
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(int(txid1, 16), 0), b''))
tx.vout.append(CTxOut(int(49.99*COIN), CScript([OP_TRUE])))
tx2_hex = self.nodes[0].signrawtransaction(ToHex(tx))['hex']
txid2 = self.nodes[0].sendrawtransaction(tx2_hex)
tx = FromHex(CTransaction(), tx2_hex)
assert(not tx.wit.is_null())
# Now create tx3, which will spend from txid2
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(int(txid2, 16), 0), b""))
tx.vout.append(CTxOut(int(49.95*COIN), CScript([OP_TRUE]))) # Huge fee
tx.calc_sha256()
txid3 = self.nodes[0].sendrawtransaction(ToHex(tx))
assert(tx.wit.is_null())
assert(txid3 in self.nodes[0].getrawmempool())
# Now try calling getblocktemplate() without segwit support.
template = self.nodes[0].getblocktemplate()
# Check that tx1 is the only transaction of the 3 in the template.
template_txids = [ t['txid'] for t in template['transactions'] ]
assert(txid2 not in template_txids and txid3 not in template_txids)
assert(txid1 in template_txids)
# Check that running with segwit support results in all 3 being included.
template = self.nodes[0].getblocktemplate({"rules": ["segwit"]})
template_txids = [ t['txid'] for t in template['transactions'] ]
assert(txid1 in template_txids)
assert(txid2 in template_txids)
assert(txid3 in template_txids)
# Mine a block to clear the gbt cache again.
self.nodes[0].generate(1)
self.log.info("Verify behaviour of importaddress, addwitnessaddress and listunspent")
# Some public keys to be used later
pubkeys = [
"0363D44AABD0F1699138239DF2F042C3282C0671CC7A76826A55C8203D90E39242", # cPiM8Ub4heR9NBYmgVzJQiUH1if44GSBGiqaeJySuL2BKxubvgwb
"02D3E626B3E616FC8662B489C123349FECBFC611E778E5BE739B257EAE4721E5BF", # cPpAdHaD6VoYbW78kveN2bsvb45Q7G5PhaPApVUGwvF8VQ9brD97
"04A47F2CBCEFFA7B9BCDA184E7D5668D3DA6F9079AD41E422FA5FD7B2D458F2538A62F5BD8EC85C2477F39650BD391EA6250207065B2A81DA8B009FC891E898F0E", # 91zqCU5B9sdWxzMt1ca3VzbtVm2YM6Hi5Rxn4UDtxEaN9C9nzXV
"02A47F2CBCEFFA7B9BCDA184E7D5668D3DA6F9079AD41E422FA5FD7B2D458F2538", # cPQFjcVRpAUBG8BA9hzr2yEzHwKoMgLkJZBBtK9vJnvGJgMjzTbd
"036722F784214129FEB9E8129D626324F3F6716555B603FFE8300BBCB882151228", # cQGtcm34xiLjB1v7bkRa4V3aAc9tS2UTuBZ1UnZGeSeNy627fN66
"0266A8396EE936BF6D99D17920DB21C6C7B1AB14C639D5CD72B300297E416FD2EC", # cTW5mR5M45vHxXkeChZdtSPozrFwFgmEvTNnanCW6wrqwaCZ1X7K
"0450A38BD7F0AC212FEBA77354A9B036A32E0F7C81FC4E0C5ADCA7C549C4505D2522458C2D9AE3CEFD684E039194B72C8A10F9CB9D4764AB26FCC2718D421D3B84", # 92h2XPssjBpsJN5CqSP7v9a7cf2kgDunBC6PDFwJHMACM1rrVBJ
]
# Import a compressed key and an uncompressed key, generate some multisig addresses
self.nodes[0].importprivkey("92e6XLo5jVAVwrQKPNTs93oQco8f8sDNBcpv73Dsrs397fQtFQn")
uncompressed_spendable_address = ["mvozP4UwyGD2mGZU4D2eMvMLPB9WkMmMQu"]
self.nodes[0].importprivkey("cNC8eQ5dg3mFAVePDX4ddmPYpPbw41r9bm2jd1nLJT77e6RrzTRR")
compressed_spendable_address = ["mmWQubrDomqpgSYekvsU7HWEVjLFHAakLe"]
assert ((self.nodes[0].validateaddress(uncompressed_spendable_address[0])['iscompressed'] == False))
assert ((self.nodes[0].validateaddress(compressed_spendable_address[0])['iscompressed'] == True))
self.nodes[0].importpubkey(pubkeys[0])
compressed_solvable_address = [key_to_p2pkh(pubkeys[0])]
self.nodes[0].importpubkey(pubkeys[1])
compressed_solvable_address.append(key_to_p2pkh(pubkeys[1]))
self.nodes[0].importpubkey(pubkeys[2])
uncompressed_solvable_address = [key_to_p2pkh(pubkeys[2])]
spendable_anytime = [] # These outputs should be seen anytime after importprivkey and addmultisigaddress
spendable_after_importaddress = [] # These outputs should be seen after importaddress
solvable_after_importaddress = [] # These outputs should be seen after importaddress but not spendable
unsolvable_after_importaddress = [] # These outputs should be unsolvable after importaddress
solvable_anytime = [] # These outputs should be solvable after importpubkey
unseen_anytime = [] # These outputs should never be seen
uncompressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [uncompressed_spendable_address[0], compressed_spendable_address[0]]))
uncompressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [uncompressed_spendable_address[0], uncompressed_spendable_address[0]]))
compressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], compressed_spendable_address[0]]))
uncompressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], uncompressed_solvable_address[0]]))
compressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], compressed_solvable_address[0]]))
compressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_solvable_address[0], compressed_solvable_address[1]]))
unknown_address = ["mtKKyoHabkk6e4ppT7NaM7THqPUt7AzPrT", "2NDP3jLWAFT8NDAiUa9qiE6oBt2awmMq7Dx"]
# Test multisig_without_privkey
# We have 2 public keys without private keys, use addmultisigaddress to add to wallet.
# Money sent to P2SH of multisig of this should only be seen after importaddress with the BASE58 P2SH address.
multisig_without_privkey_address = self.nodes[0].addmultisigaddress(2, [pubkeys[3], pubkeys[4]])
script = CScript([OP_2, hex_str_to_bytes(pubkeys[3]), hex_str_to_bytes(pubkeys[4]), OP_2, OP_CHECKMULTISIG])
solvable_after_importaddress.append(CScript([OP_HASH160, hash160(script), OP_EQUAL]))
for i in compressed_spendable_address:
v = self.nodes[0].validateaddress(i)
if (v['isscript']):
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
# bare and p2sh multisig with compressed keys should always be spendable
spendable_anytime.extend([bare, p2sh])
# P2WSH and P2SH(P2WSH) multisig with compressed keys are spendable after direct importaddress
spendable_after_importaddress.extend([p2wsh, p2sh_p2wsh])
else:
[p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
# normal P2PKH and P2PK with compressed keys should always be spendable
spendable_anytime.extend([p2pkh, p2pk])
# P2SH_P2PK, P2SH_P2PKH, and witness with compressed keys are spendable after direct importaddress
spendable_after_importaddress.extend([p2wpkh, p2sh_p2wpkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh])
for i in uncompressed_spendable_address:
v = self.nodes[0].validateaddress(i)
if (v['isscript']):
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
# bare and p2sh multisig with uncompressed keys should always be spendable
spendable_anytime.extend([bare, p2sh])
# P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
unseen_anytime.extend([p2wsh, p2sh_p2wsh])
else:
[p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
# normal P2PKH and P2PK with uncompressed keys should always be spendable
spendable_anytime.extend([p2pkh, p2pk])
# P2SH_P2PK and P2SH_P2PKH are spendable after direct importaddress
spendable_after_importaddress.extend([p2sh_p2pk, p2sh_p2pkh])
# witness with uncompressed keys are never seen
unseen_anytime.extend([p2wpkh, p2sh_p2wpkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh])
for i in compressed_solvable_address:
v = self.nodes[0].validateaddress(i)
if (v['isscript']):
# Multisig without private is not seen after addmultisigaddress, but seen after importaddress
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
solvable_after_importaddress.extend([bare, p2sh, p2wsh, p2sh_p2wsh])
else:
[p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
# normal P2PKH and P2PK with compressed keys should always be seen
solvable_anytime.extend([p2pkh, p2pk])
# P2SH_P2PK, P2SH_P2PKH, and witness with compressed keys are seen after direct importaddress
solvable_after_importaddress.extend([p2wpkh, p2sh_p2wpkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh])
for i in uncompressed_solvable_address:
v = self.nodes[0].validateaddress(i)
if (v['isscript']):
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
# Base uncompressed multisig without private is not seen after addmultisigaddress, but seen after importaddress
solvable_after_importaddress.extend([bare, p2sh])
# P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
unseen_anytime.extend([p2wsh, p2sh_p2wsh])
else:
[p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
# normal P2PKH and P2PK with uncompressed keys should always be seen
solvable_anytime.extend([p2pkh, p2pk])
# P2SH_P2PK, P2SH_P2PKH with uncompressed keys are seen after direct importaddress
solvable_after_importaddress.extend([p2sh_p2pk, p2sh_p2pkh])
# witness with uncompressed keys are never seen
unseen_anytime.extend([p2wpkh, p2sh_p2wpkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh])
op1 = CScript([OP_1])
op0 = CScript([OP_0])
# 2N7MGY19ti4KDMSzRfPAssP6Pxyuxoi6jLe is the P2SH(P2PKH) version of mjoE3sSrb8ByYEvgnC3Aox86u1CHnfJA4V
unsolvable_address = ["mjoE3sSrb8ByYEvgnC3Aox86u1CHnfJA4V", "2N7MGY19ti4KDMSzRfPAssP6Pxyuxoi6jLe", script_to_p2sh(op1), script_to_p2sh(op0)]
unsolvable_address_key = hex_str_to_bytes("02341AEC7587A51CDE5279E0630A531AEA2615A9F80B17E8D9376327BAEAA59E3D")
unsolvablep2pkh = CScript([OP_DUP, OP_HASH160, hash160(unsolvable_address_key), OP_EQUALVERIFY, OP_CHECKSIG])
unsolvablep2wshp2pkh = CScript([OP_0, sha256(unsolvablep2pkh)])
p2shop0 = CScript([OP_HASH160, hash160(op0), OP_EQUAL])
p2wshop1 = CScript([OP_0, sha256(op1)])
unsolvable_after_importaddress.append(unsolvablep2pkh)
unsolvable_after_importaddress.append(unsolvablep2wshp2pkh)
unsolvable_after_importaddress.append(op1) # OP_1 will be imported as script
unsolvable_after_importaddress.append(p2wshop1)
unseen_anytime.append(op0) # OP_0 will be imported as P2SH address with no script provided
unsolvable_after_importaddress.append(p2shop0)
spendable_txid = []
solvable_txid = []
spendable_txid.append(self.mine_and_test_listunspent(spendable_anytime, 2))
solvable_txid.append(self.mine_and_test_listunspent(solvable_anytime, 1))
self.mine_and_test_listunspent(spendable_after_importaddress + solvable_after_importaddress + unseen_anytime + unsolvable_after_importaddress, 0)
importlist = []
for i in compressed_spendable_address + uncompressed_spendable_address + compressed_solvable_address + uncompressed_solvable_address:
v = self.nodes[0].validateaddress(i)
if (v['isscript']):
bare = hex_str_to_bytes(v['hex'])
importlist.append(bytes_to_hex_str(bare))
importlist.append(bytes_to_hex_str(CScript([OP_0, sha256(bare)])))
else:
pubkey = hex_str_to_bytes(v['pubkey'])
p2pk = CScript([pubkey, OP_CHECKSIG])
p2pkh = CScript([OP_DUP, OP_HASH160, hash160(pubkey), OP_EQUALVERIFY, OP_CHECKSIG])
importlist.append(bytes_to_hex_str(p2pk))
importlist.append(bytes_to_hex_str(p2pkh))
importlist.append(bytes_to_hex_str(CScript([OP_0, hash160(pubkey)])))
importlist.append(bytes_to_hex_str(CScript([OP_0, sha256(p2pk)])))
importlist.append(bytes_to_hex_str(CScript([OP_0, sha256(p2pkh)])))
importlist.append(bytes_to_hex_str(unsolvablep2pkh))
importlist.append(bytes_to_hex_str(unsolvablep2wshp2pkh))
importlist.append(bytes_to_hex_str(op1))
importlist.append(bytes_to_hex_str(p2wshop1))
for i in importlist:
# import all generated addresses. The wallet already has the private keys for some of these, so catch JSON RPC
# exceptions and continue.
try:
self.nodes[0].importaddress(i,"",False,True)
except JSONRPCException as exp:
assert_equal(exp.error["message"], "The wallet already contains the private key for this address or script")
assert_equal(exp.error["code"], -4)
self.nodes[0].importaddress(script_to_p2sh(op0)) # import OP_0 as address only
self.nodes[0].importaddress(multisig_without_privkey_address) # Test multisig_without_privkey
spendable_txid.append(self.mine_and_test_listunspent(spendable_anytime + spendable_after_importaddress, 2))
solvable_txid.append(self.mine_and_test_listunspent(solvable_anytime + solvable_after_importaddress, 1))
self.mine_and_test_listunspent(unsolvable_after_importaddress, 1)
self.mine_and_test_listunspent(unseen_anytime, 0)
# addwitnessaddress should refuse to return a witness address if an uncompressed key is used or the address is
# not in the wallet
# note that no witness address should be returned by unsolvable addresses
# the multisig_without_privkey_address will fail because its keys were not added with importpubkey
for i in uncompressed_spendable_address + uncompressed_solvable_address + unknown_address + unsolvable_address + [multisig_without_privkey_address]:
assert_raises_jsonrpc(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i)
for i in compressed_spendable_address + compressed_solvable_address:
witaddress = self.nodes[0].addwitnessaddress(i)
# addwitnessaddress should return the same address if it is a known P2SH-witness address
assert_equal(witaddress, self.nodes[0].addwitnessaddress(witaddress))
spendable_txid.append(self.mine_and_test_listunspent(spendable_anytime + spendable_after_importaddress, 2))
solvable_txid.append(self.mine_and_test_listunspent(solvable_anytime + solvable_after_importaddress, 1))
self.mine_and_test_listunspent(unsolvable_after_importaddress, 1)
self.mine_and_test_listunspent(unseen_anytime, 0)
# Repeat some tests. This time we don't add witness scripts with importaddress
# Import a compressed key and an uncompressed key, generate some multisig addresses
self.nodes[0].importprivkey("927pw6RW8ZekycnXqBQ2JS5nPyo1yRfGNN8oq74HeddWSpafDJH")
uncompressed_spendable_address = ["mguN2vNSCEUh6rJaXoAVwY3YZwZvEmf5xi"]
self.nodes[0].importprivkey("cMcrXaaUC48ZKpcyydfFo8PxHAjpsYLhdsp6nmtB3E2ER9UUHWnw")
compressed_spendable_address = ["n1UNmpmbVUJ9ytXYXiurmGPQ3TRrXqPWKL"]
self.nodes[0].importpubkey(pubkeys[5])
compressed_solvable_address = [key_to_p2pkh(pubkeys[5])]
self.nodes[0].importpubkey(pubkeys[6])
uncompressed_solvable_address = [key_to_p2pkh(pubkeys[6])]
spendable_after_addwitnessaddress = [] # These outputs should be seen after importaddress
solvable_after_addwitnessaddress=[] # These outputs should be seen after importaddress but not spendable
unseen_anytime = [] # These outputs should never be seen
uncompressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [uncompressed_spendable_address[0], compressed_spendable_address[0]]))
uncompressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [uncompressed_spendable_address[0], uncompressed_spendable_address[0]]))
compressed_spendable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], compressed_spendable_address[0]]))
uncompressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_solvable_address[0], uncompressed_solvable_address[0]]))
compressed_solvable_address.append(self.nodes[0].addmultisigaddress(2, [compressed_spendable_address[0], compressed_solvable_address[0]]))
premature_witaddress = []
for i in compressed_spendable_address:
v = self.nodes[0].validateaddress(i)
if (v['isscript']):
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
# P2WSH and P2SH(P2WSH) multisig with compressed keys are spendable after addwitnessaddress
spendable_after_addwitnessaddress.extend([p2wsh, p2sh_p2wsh])
premature_witaddress.append(script_to_p2sh(p2wsh))
else:
[p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
# P2WPKH, P2SH_P2WPKH are spendable after addwitnessaddress
spendable_after_addwitnessaddress.extend([p2wpkh, p2sh_p2wpkh])
premature_witaddress.append(script_to_p2sh(p2wpkh))
for i in uncompressed_spendable_address + uncompressed_solvable_address:
v = self.nodes[0].validateaddress(i)
if (v['isscript']):
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
# P2WSH and P2SH(P2WSH) multisig with uncompressed keys are never seen
unseen_anytime.extend([p2wsh, p2sh_p2wsh])
else:
[p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
# P2WPKH, P2SH_P2WPKH with uncompressed keys are never seen
unseen_anytime.extend([p2wpkh, p2sh_p2wpkh])
for i in compressed_solvable_address:
v = self.nodes[0].validateaddress(i)
if (v['isscript']):
# P2WSH multisig without private key are seen after addwitnessaddress
[bare, p2sh, p2wsh, p2sh_p2wsh] = self.p2sh_address_to_script(v)
solvable_after_addwitnessaddress.extend([p2wsh, p2sh_p2wsh])
premature_witaddress.append(script_to_p2sh(p2wsh))
else:
[p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh] = self.p2pkh_address_to_script(v)
# P2SH_P2PK, P2SH_P2PKH with compressed keys are seen after addwitnessaddress
solvable_after_addwitnessaddress.extend([p2wpkh, p2sh_p2wpkh])
premature_witaddress.append(script_to_p2sh(p2wpkh))
self.mine_and_test_listunspent(spendable_after_addwitnessaddress + solvable_after_addwitnessaddress + unseen_anytime, 0)
# addwitnessaddress should refuse to return a witness address if an uncompressed key is used
# note that a multisig address returned by addmultisigaddress is not solvable until it is added with importaddress
# premature_witaddress are not accepted until the script is added with addwitnessaddress first
for i in uncompressed_spendable_address + uncompressed_solvable_address + premature_witaddress + [compressed_solvable_address[1]]:
# This will raise an exception
assert_raises_jsonrpc(-4, "Public key or redeemscript not known to wallet, or the key is uncompressed", self.nodes[0].addwitnessaddress, i)
# after importaddress it should pass addwitnessaddress
v = self.nodes[0].validateaddress(compressed_solvable_address[1])
self.nodes[0].importaddress(v['hex'],"",False,True)
for i in compressed_spendable_address + compressed_solvable_address + premature_witaddress:
witaddress = self.nodes[0].addwitnessaddress(i)
assert_equal(witaddress, self.nodes[0].addwitnessaddress(witaddress))
spendable_txid.append(self.mine_and_test_listunspent(spendable_after_addwitnessaddress, 2))
solvable_txid.append(self.mine_and_test_listunspent(solvable_after_addwitnessaddress, 1))
self.mine_and_test_listunspent(unseen_anytime, 0)
# Check that spendable outputs are really spendable
self.create_and_mine_tx_from_txids(spendable_txid)
# import all the private keys so solvable addresses become spendable
self.nodes[0].importprivkey("cPiM8Ub4heR9NBYmgVzJQiUH1if44GSBGiqaeJySuL2BKxubvgwb")
self.nodes[0].importprivkey("cPpAdHaD6VoYbW78kveN2bsvb45Q7G5PhaPApVUGwvF8VQ9brD97")
self.nodes[0].importprivkey("91zqCU5B9sdWxzMt1ca3VzbtVm2YM6Hi5Rxn4UDtxEaN9C9nzXV")
self.nodes[0].importprivkey("cPQFjcVRpAUBG8BA9hzr2yEzHwKoMgLkJZBBtK9vJnvGJgMjzTbd")
self.nodes[0].importprivkey("cQGtcm34xiLjB1v7bkRa4V3aAc9tS2UTuBZ1UnZGeSeNy627fN66")
self.nodes[0].importprivkey("cTW5mR5M45vHxXkeChZdtSPozrFwFgmEvTNnanCW6wrqwaCZ1X7K")
self.create_and_mine_tx_from_txids(solvable_txid)
def mine_and_test_listunspent(self, script_list, ismine):
utxo = find_unspent(self.nodes[0], 50)
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(int('0x'+utxo['txid'],0), utxo['vout'])))
for i in script_list:
tx.vout.append(CTxOut(10000000, i))
tx.rehash()
signresults = self.nodes[0].signrawtransaction(bytes_to_hex_str(tx.serialize_without_witness()))['hex']
txid = self.nodes[0].sendrawtransaction(signresults, True)
self.nodes[0].generate(1)
sync_blocks(self.nodes)
watchcount = 0
spendcount = 0
for i in self.nodes[0].listunspent():
if (i['txid'] == txid):
watchcount += 1
if (i['spendable'] == True):
spendcount += 1
if (ismine == 2):
assert_equal(spendcount, len(script_list))
elif (ismine == 1):
assert_equal(watchcount, len(script_list))
assert_equal(spendcount, 0)
else:
assert_equal(watchcount, 0)
return txid
def p2sh_address_to_script(self,v):
bare = CScript(hex_str_to_bytes(v['hex']))
p2sh = CScript(hex_str_to_bytes(v['scriptPubKey']))
p2wsh = CScript([OP_0, sha256(bare)])
p2sh_p2wsh = CScript([OP_HASH160, hash160(p2wsh), OP_EQUAL])
return([bare, p2sh, p2wsh, p2sh_p2wsh])
def p2pkh_address_to_script(self,v):
pubkey = hex_str_to_bytes(v['pubkey'])
p2wpkh = CScript([OP_0, hash160(pubkey)])
p2sh_p2wpkh = CScript([OP_HASH160, hash160(p2wpkh), OP_EQUAL])
p2pk = CScript([pubkey, OP_CHECKSIG])
p2pkh = CScript(hex_str_to_bytes(v['scriptPubKey']))
p2sh_p2pk = CScript([OP_HASH160, hash160(p2pk), OP_EQUAL])
p2sh_p2pkh = CScript([OP_HASH160, hash160(p2pkh), OP_EQUAL])
p2wsh_p2pk = CScript([OP_0, sha256(p2pk)])
p2wsh_p2pkh = CScript([OP_0, sha256(p2pkh)])
p2sh_p2wsh_p2pk = CScript([OP_HASH160, hash160(p2wsh_p2pk), OP_EQUAL])
p2sh_p2wsh_p2pkh = CScript([OP_HASH160, hash160(p2wsh_p2pkh), OP_EQUAL])
return [p2wpkh, p2sh_p2wpkh, p2pk, p2pkh, p2sh_p2pk, p2sh_p2pkh, p2wsh_p2pk, p2wsh_p2pkh, p2sh_p2wsh_p2pk, p2sh_p2wsh_p2pkh]
def create_and_mine_tx_from_txids(self, txids, success = True):
tx = CTransaction()
for i in txids:
txtmp = CTransaction()
txraw = self.nodes[0].getrawtransaction(i)
f = BytesIO(hex_str_to_bytes(txraw))
txtmp.deserialize(f)
for j in range(len(txtmp.vout)):
tx.vin.append(CTxIn(COutPoint(int('0x'+i,0), j)))
tx.vout.append(CTxOut(0, CScript()))
tx.rehash()
signresults = self.nodes[0].signrawtransaction(bytes_to_hex_str(tx.serialize_without_witness()))['hex']
self.nodes[0].sendrawtransaction(signresults, True)
self.nodes[0].generate(1)
sync_blocks(self.nodes)
if __name__ == '__main__':
SegWitTest().main()
| mit |
wemanuel/smry | server-auth/ls/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/gcloud/gcloud.py | 4 | 7394 | # Copyright 2013 Google Inc. All Rights Reserved.
"""gcloud command line tool."""
import time
START_TIME = time.time()
# pylint:disable=g-bad-import-order
# pylint:disable=g-import-not-at-top, We want to get the start time first.
import os
import signal
import sys
import traceback
# Disable stack traces when people kill a command.
def CTRLCHandler(unused_signal, unused_frame):
"""Custom SIGNINT handler.
Signal handler that doesn't print the stack trace when a command is
killed by keyboard interupt.
"""
try:
log.err.Print('\n\nCommand killed by keyboard interrupt\n')
except NameError:
sys.stderr.write('\n\nCommand killed by keyboard interrupt\n')
# Kill ourselves with SIGINT so our parent can detect that we exited because
# of a signal. SIG_DFL disables further KeyboardInterrupt exceptions.
signal.signal(signal.SIGINT, signal.SIG_DFL)
os.kill(os.getpid(), signal.SIGINT)
# Just in case the kill failed ...
sys.exit(1)
signal.signal(signal.SIGINT, CTRLCHandler)
# Enable normal UNIX handling of SIGPIPE to play nice with grep -q, head, etc.
# See https://mail.python.org/pipermail/python-list/2004-June/273297.html and
# http://utcc.utoronto.ca/~cks/space/blog/python/SignalExceptionSurprise
# for more details.
if hasattr(signal, 'SIGPIPE'):
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def _SetPriorityCloudSDKPath():
"""Put google-cloud-sdk/lib at the beginning of sys.path.
Modifying sys.path in this way allows us to always use our bundled versions
of libraries, even when other versions have been installed. It also allows the
user to install extra libraries that we cannot bundle (ie PyOpenSSL), and
gcloud commands can use those libraries.
"""
def _GetRootContainingGoogle():
path = __file__
while True:
parent, here = os.path.split(path)
if not here:
break
if here == 'googlecloudsdk':
return parent
path = parent
module_root = _GetRootContainingGoogle()
# check if we're already set
if (not module_root) or (sys.path and module_root == sys.path[0]):
return
sys.path.insert(0, module_root)
def _DoStartupChecks():
from googlecloudsdk.core.util import platforms
if not platforms.PythonVersion().IsSupported():
sys.exit(1)
if not platforms.Platform.Current().IsSupported():
sys.exit(1)
_SetPriorityCloudSDKPath()
_DoStartupChecks()
# pylint:disable=g-import-not-at-top, We want the _SetPriorityCloudSDKPath()
# function to be called before we try to import any CloudSDK modules.
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import cli
from googlecloudsdk.core import config
from googlecloudsdk.core import log
from googlecloudsdk.core import metrics
from googlecloudsdk.core import properties
from googlecloudsdk.core.updater import local_state
from googlecloudsdk.core.updater import update_manager
if not config.Paths().sdk_root:
# Don't do update checks if there is no install root.
properties.VALUES.component_manager.disable_update_check.Set(True)
def UpdateCheck():
try:
update_manager.UpdateManager.PerformUpdateCheck()
# pylint:disable=broad-except, We never want this to escape, ever. Only
# messages printed should reach the user.
except Exception:
pass
def VersionFunc():
_cli.Execute(['version'])
def CreateCLI():
"""Generates the gcloud CLI."""
pkg_root = config.GoogleCloudSDKPackageRoot()
loader = cli.CLILoader(
name='gcloud',
command_root_directory=os.path.join(
pkg_root, 'gcloud', 'sdktools', 'root'),
allow_non_existing_modules=True,
version_func=VersionFunc)
loader.AddReleaseTrack(base.ReleaseTrack.ALPHA,
os.path.join(pkg_root, 'gcloud', 'sdktools', 'alpha'),
component='alpha')
loader.AddReleaseTrack(base.ReleaseTrack.BETA,
os.path.join(pkg_root, 'gcloud', 'sdktools', 'beta'),
component='beta')
loader.AddModule('auth', os.path.join(pkg_root, 'gcloud', 'sdktools', 'auth'))
loader.AddModule('bigquery', os.path.join(pkg_root, 'bigquery', 'commands'))
loader.AddModule('bigtable', os.path.join(pkg_root, 'bigtable', 'commands'))
loader.AddModule('components',
os.path.join(pkg_root, 'gcloud', 'sdktools', 'components'))
loader.AddModule('compute', os.path.join(pkg_root, 'compute', 'subcommands'))
loader.AddModule('config',
os.path.join(pkg_root, 'gcloud', 'sdktools', 'config'))
loader.AddModule('container',
os.path.join(pkg_root, 'container', 'commands'))
loader.AddModule('dataflow',
os.path.join(pkg_root, 'dataflow', 'commands'))
loader.AddModule('deployment_manager',
os.path.join(pkg_root, 'deployment_manager', 'commands'))
loader.AddModule('dns', os.path.join(pkg_root, 'dns', 'commands'))
loader.AddModule('endpoints', os.path.join(pkg_root, 'endpoints', 'commands'))
loader.AddModule('internal',
os.path.join(pkg_root, 'internal', 'commands'))
loader.AddModule('meta', os.path.join(pkg_root, 'gcloud', 'sdktools', 'meta'))
loader.AddModule('preview', os.path.join(pkg_root, 'preview', 'commands'),
component='preview')
# Put app and datastore under preview for now.
loader.AddModule('preview.analysis',
os.path.join(pkg_root, 'analysis', 'commands'))
loader.AddModule('preview.app',
os.path.join(pkg_root, 'appengine', 'app_commands'),
component='app')
loader.AddModule('preview.datastore',
os.path.join(pkg_root, 'appengine', 'datastore_commands'),
component='app')
loader.AddModule('genomics',
os.path.join(pkg_root, 'genomics', 'commands'))
# TODO(user): Put logging in preview for now.
loader.AddModule('preview.logging',
os.path.join(pkg_root, 'logging', 'commands'))
loader.AddModule('preview.rolling_updates',
os.path.join(
pkg_root, 'updater', 'commands', 'rolling_updates'))
loader.AddModule('projects',
os.path.join(pkg_root, 'projects', 'commands'))
loader.AddModule('pubsub',
os.path.join(pkg_root, 'pubsub', 'commands'))
loader.AddModule('services',
os.path.join(pkg_root, 'service_management', 'subcommands'))
loader.AddModule('source',
os.path.join(pkg_root, 'source', 'commands'))
loader.AddModule('sql', os.path.join(pkg_root, 'sql', 'tools'))
loader.AddModule('test', os.path.join(pkg_root, 'test', 'commands'))
# Check for updates on shutdown but not for any of the updater commands.
loader.RegisterPostRunHook(UpdateCheck,
exclude_commands=r'gcloud\.components\..*')
return loader.Generate()
_cli = CreateCLI()
def main():
metrics.Started(START_TIME)
# TODO(user): Put a real version number here
metrics.Executions(
'gcloud',
local_state.InstallationState.VersionForInstalledComponent('core'))
try:
_cli.Execute()
except Exception as err: # pylint:disable=broad-except
if isinstance(err, KeyboardInterrupt):
raise
traceback.print_exc()
sys.exit(1)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
CTRLCHandler(None, None)
| apache-2.0 |
jmr0/servo | tests/wpt/web-platform-tests/WebCryptoAPI/tools/generate.py | 45 | 2534 | # script to generate the generateKey tests
import os
here = os.path.dirname(__file__)
successes_html = """<!DOCTYPE html>
<meta charset=utf-8>
<meta name="timeout" content="long">
<title>WebCryptoAPI: generateKey() Successful Calls</title>
<link rel="author" title="Charles Engelke" href="mailto:w3c@engelke.com">
<link rel="help" href="https://www.w3.org/TR/WebCryptoAPI/#dfn-SubtleCrypto-method-generateKey">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/WebCryptoAPI/util/helpers.js"></script>
<script src="successes.js"></script>
<h1>generateKey Tests for Good Parameters</h1>
<p>
<strong>Warning!</strong> RSA key generation is intrinsically
very slow, so the related tests can take up to
several minutes to complete, depending on browser!
</p>
<div id="log"></div>
<script>
run_test([%s]);
</script>"""
failures_html = """<!DOCTYPE html>
<meta charset=utf-8>
<meta name="timeout" content="long">
<title>WebCryptoAPI: generateKey() for Failures</title>
<link rel="author" title="Charles Engelke" href="mailto:w3c@engelke.com">
<link rel="help" href="https://www.w3.org/TR/WebCryptoAPI/#dfn-SubtleCrypto-method-generateKey">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/WebCryptoAPI/util/helpers.js"></script>
<script src="failures.js"></script>
<h1>generateKey Tests for Bad Parameters</h1>
<div id="log"></div>
<script>
run_test([%s]);
</script>
"""
successes_worker = """// <meta> timeout=long
importScripts("/resources/testharness.js");
importScripts("../util/helpers.js");
importScripts("successes.js");
run_test([%s]);
done();"""
failures_worker = """// <meta> timeout=long
importScripts("/resources/testharness.js");
importScripts("../util/helpers.js");
importScripts("failures.js");
run_test([%s]);
done();"""
names = ["AES-CTR", "AES-CBC", "AES-GCM", "AES-KW", "HMAC", "RSASSA-PKCS1-v1_5",
"RSA-PSS", "RSA-OAEP", "ECDSA", "ECDH"]
for filename_pattern, template in [("test_successes_%s.html", successes_html),
("test_failures_%s.html", failures_html),
("successes_%s.worker.js", successes_worker),
("failures_%s.worker.js", failures_worker)]:
for name in names:
path = os.path.join(here, os.pardir, "generateKey", filename_pattern % name)
with open(path, "w") as f:
f.write(template % '"%s"' % name)
| mpl-2.0 |
yoer/hue | apps/beeswax/src/beeswax/migrations/0003_auto__add_field_queryhistory_server_name__add_field_queryhistory_serve.py | 40 | 7185 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'QueryHistory.server_name'
db.add_column('beeswax_queryhistory', 'server_name', self.gf('django.db.models.fields.CharField')(default='', max_length=128), keep_default=False)
# Adding field 'QueryHistory.server_host'
db.add_column('beeswax_queryhistory', 'server_host', self.gf('django.db.models.fields.CharField')(default='', max_length=128), keep_default=False)
# Adding field 'QueryHistory.server_port'
db.add_column('beeswax_queryhistory', 'server_port', self.gf('django.db.models.fields.SmallIntegerField')(default=0), keep_default=False)
# Changing field 'QueryHistory.query'
db.alter_column('beeswax_queryhistory', 'query', self.gf('django.db.models.fields.TextField')())
def backwards(self, orm):
# Deleting field 'QueryHistory.server_name'
db.delete_column('beeswax_queryhistory', 'server_name')
# Deleting field 'QueryHistory.server_host'
db.delete_column('beeswax_queryhistory', 'server_host')
# Deleting field 'QueryHistory.server_port'
db.delete_column('beeswax_queryhistory', 'server_port')
# Changing field 'QueryHistory.query'
db.alter_column('beeswax_queryhistory', 'query', self.gf('django.db.models.fields.CharField')(max_length=1024))
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'beeswax.metainstall': {
'Meta': {'object_name': 'MetaInstall'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'installed_example': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'})
},
'beeswax.queryhistory': {
'Meta': {'object_name': 'QueryHistory'},
'design': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['beeswax.SavedQuery']", 'null': 'True'}),
'has_results': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_state': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'log_context': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True'}),
'notify': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'query': ('django.db.models.fields.TextField', [], {}),
'server_host': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128'}),
'server_id': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True'}),
'server_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128'}),
'server_port': ('django.db.models.fields.SmallIntegerField', [], {'default': "''"}),
'submission_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
'beeswax.savedquery': {
'Meta': {'object_name': 'SavedQuery'},
'data': ('django.db.models.fields.TextField', [], {'max_length': '65536'}),
'desc': ('django.db.models.fields.TextField', [], {'max_length': '1024'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_auto': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True', 'blank': 'True'}),
'mtime': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'type': ('django.db.models.fields.IntegerField', [], {})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['beeswax']
| apache-2.0 |
s9yobena/CSM-ANDROID | tools/perf/scripts/python/check-perf-trace.py | 11214 | 2503 | # perf script event handlers, generated by perf script -g python
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# This script tests basic functionality such as flag and symbol
# strings, common_xxx() calls back into perf, begin, end, unhandled
# events, etc. Basically, if this script runs successfully and
# displays expected results, Python scripting support should be ok.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from Core import *
from perf_trace_context import *
unhandled = autodict()
def trace_begin():
print "trace_begin"
pass
def trace_end():
print_unhandled()
def irq__softirq_entry(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
vec):
print_header(event_name, common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
print_uncommon(context)
print "vec=%s\n" % \
(symbol_str("irq__softirq_entry", "vec", vec)),
def kmem__kmalloc(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
call_site, ptr, bytes_req, bytes_alloc,
gfp_flags):
print_header(event_name, common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
print_uncommon(context)
print "call_site=%u, ptr=%u, bytes_req=%u, " \
"bytes_alloc=%u, gfp_flags=%s\n" % \
(call_site, ptr, bytes_req, bytes_alloc,
flag_str("kmem__kmalloc", "gfp_flags", gfp_flags)),
def trace_unhandled(event_name, context, event_fields_dict):
try:
unhandled[event_name] += 1
except TypeError:
unhandled[event_name] = 1
def print_header(event_name, cpu, secs, nsecs, pid, comm):
print "%-20s %5u %05u.%09u %8u %-20s " % \
(event_name, cpu, secs, nsecs, pid, comm),
# print trace fields not included in handler args
def print_uncommon(context):
print "common_preempt_count=%d, common_flags=%s, common_lock_depth=%d, " \
% (common_pc(context), trace_flag_str(common_flags(context)), \
common_lock_depth(context))
def print_unhandled():
keys = unhandled.keys()
if not keys:
return
print "\nunhandled events:\n\n",
print "%-40s %10s\n" % ("event", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"-----------"),
for event_name in keys:
print "%-40s %10d\n" % (event_name, unhandled[event_name])
| gpl-2.0 |
amotoki/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/panel.py | 38 | 1641 | # Copyright 2013, Mirantis Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from django.utils.translation import ugettext_lazy as _
import horizon
from openstack_dashboard.api import neutron
LOG = logging.getLogger(__name__)
class VPN(horizon.Panel):
name = _("VPN")
slug = 'vpn'
permissions = ('openstack.services.network',)
def allowed(self, context):
request = context['request']
if not request.user.has_perms(self.permissions):
return False
try:
if not neutron.is_service_enabled(request,
config_name='enable_vpn',
ext_name='vpnaas'):
return False
except Exception:
LOG.error("Call to list enabled services failed. This is likely "
"due to a problem communicating with the Neutron "
"endpoint. VPN panel will not be displayed.")
return False
if not super(VPN, self).allowed(context):
return False
return True
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.