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
deconst/submitter
test/content_service_test.py
1
4177
# -*- coding: utf-8 -*- import os import io import tarfile from betamax import Betamax from requests import Session from nose.tools import assert_equal, assert_true, assert_false, assert_in from . import URL, APIKEY from submitter.content_service import ContentService class TestContentService(): def setup(self): session = Session() self.betamax = Betamax(session) self.cs = ContentService(url=URL, apikey=APIKEY, session=session) def test_checkassets(self): # curl -X POST -H "Authorization: deconst ${APIKEY}" \ # http://dockerdev:9000/assets \ # -F aaa=@test/fixtures/assets/foo/aaa.jpg \ # -F bbb=@test/fixtures/assets/bar/bbb.gif with self.betamax.use_cassette('checkassets'): response = self.cs.checkassets({ 'foo/aaa.jpg': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'bar/bbb.gif': '8810ad581e59f2bc3928b261707a71308f7e139eb04820366dc4d5c18d980225', 'baz/missing.css': 'ffa63583dfa6706b87d284b86b0d693a161e4840aad2c5cf6b5d27c3b9621f7d' }) assert_equal(response, { 'foo/aaa.jpg': '/__local_asset__/aaa-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.jpg', 'bar/bbb.gif': None, 'baz/missing.css': None }) def test_bulkasset(self): with self.betamax.use_cassette('bulkasset'): tarball = io.BytesIO() tf = tarfile.open(fileobj=tarball, mode='w:gz') add_tar_entry(tf, 'bar/bbb.gif') add_tar_entry(tf, 'foo/aaa.jpg') tf.close() response = self.cs.bulkasset(tarball.getvalue()) assert_equal(response, { 'bar/bbb.gif': '/__local_asset__/bbb-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.gif', 'foo/aaa.jpg': '/__local_asset__/aaa-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.jpg' }) def test_checkcontent(self): # curl -X PUT -H "Authorization: deconst ${APIKEY}" \ # -H 'Content-Type: application/json' \ # http://dockerdev:9000/content/https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Fone \ # -d '{"title":"one","body":"one"}' # echo -n '{"body":"one","title":"one"}' | shasum -a 256 # curl -X PUT -H "Authorization: deconst ${APIKEY}" \ # -H 'Content-Type: application/json' \ # http://dockerdev:9000/content/https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Ftwo \ # -d '{"title":"two","body":"two"}' # echo -n '{"body":"two","title":"two"}' | shasum -a 256 with self.betamax.use_cassette('checkcontent'): response = self.cs.checkcontent({ 'https://github.com/org/repo/one': '842d36ad29589a39fc4be06157c5c204a360f98981fc905c0b2a114662172bd8', 'https://github.com/org/repo/two': 'f0e62392fc00c71ba3118c91b97c6f2cbfdcd75e8053fe2d9f029ebfcf6c23fe' }) assert_equal(response, { 'https://github.com/org/repo/one': True, 'https://github.com/org/repo/two': False }) def test_bulkcontent(self): with self.betamax.use_cassette('bulkcontent'): tarball = io.BytesIO() tf = tarfile.open(fileobj=tarball, mode='w:gz') add_tar_entry( tf, 'https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Fone.json', b'{"body":"one","title":"one"}') add_tar_entry( tf, 'https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Ftwo.json', b'{"body":"two","title":"two"}') tf.close() response = self.cs.bulkcontent(tarball.getvalue()) assert_equal(response, { 'accepted': 2, 'failed': 0, 'deleted': 0 }) def add_tar_entry(tf, entryname, buf = b''): """ Add a manually constructed TarInfo to a TarFile. """ entry = tarfile.TarInfo(entryname) entry.size = len(buf) tf.addfile(entry, io.BytesIO(buf))
apache-2.0
pasqualguerrero/django
tests/user_commands/tests.py
205
7165
import os from django.apps import apps from django.core import management from django.core.management import BaseCommand, CommandError, find_commands from django.core.management.utils import find_command, popen_wrapper from django.db import connection from django.test import SimpleTestCase, ignore_warnings, override_settings from django.test.utils import captured_stderr, captured_stdout, extend_sys_path from django.utils import translation from django.utils._os import upath from django.utils.deprecation import RemovedInDjango110Warning from django.utils.six import StringIO # A minimal set of apps to avoid system checks running on all apps. @override_settings( INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'user_commands', ], ) class CommandTests(SimpleTestCase): def test_command(self): out = StringIO() management.call_command('dance', stdout=out) self.assertIn("I don't feel like dancing Rock'n'Roll.\n", out.getvalue()) def test_command_style(self): out = StringIO() management.call_command('dance', style='Jive', stdout=out) self.assertIn("I don't feel like dancing Jive.\n", out.getvalue()) # Passing options as arguments also works (thanks argparse) management.call_command('dance', '--style', 'Jive', stdout=out) self.assertIn("I don't feel like dancing Jive.\n", out.getvalue()) def test_language_preserved(self): out = StringIO() with translation.override('fr'): management.call_command('dance', stdout=out) self.assertEqual(translation.get_language(), 'fr') def test_explode(self): """ Test that an unknown command raises CommandError """ self.assertRaises(CommandError, management.call_command, ('explode',)) def test_system_exit(self): """ Exception raised in a command should raise CommandError with call_command, but SystemExit when run from command line """ with self.assertRaises(CommandError): management.call_command('dance', example="raise") with captured_stderr() as stderr, self.assertRaises(SystemExit): management.ManagementUtility(['manage.py', 'dance', '--example=raise']).execute() self.assertIn("CommandError", stderr.getvalue()) def test_deactivate_locale_set(self): # Deactivate translation when set to true out = StringIO() with translation.override('pl'): management.call_command('leave_locale_alone_false', stdout=out) self.assertEqual(out.getvalue(), "") def test_configured_locale_preserved(self): # Leaves locale from settings when set to false out = StringIO() with translation.override('pl'): management.call_command('leave_locale_alone_true', stdout=out) self.assertEqual(out.getvalue(), "pl\n") def test_find_command_without_PATH(self): """ find_command should still work when the PATH environment variable doesn't exist (#22256). """ current_path = os.environ.pop('PATH', None) try: self.assertIsNone(find_command('_missing_')) finally: if current_path is not None: os.environ['PATH'] = current_path def test_discover_commands_in_eggs(self): """ Test that management commands can also be loaded from Python eggs. """ egg_dir = '%s/eggs' % os.path.dirname(upath(__file__)) egg_name = '%s/basic.egg' % egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=['commandegg']): cmds = find_commands(os.path.join(apps.get_app_config('commandegg').path, 'management')) self.assertEqual(cmds, ['eggcommand']) def test_call_command_option_parsing(self): """ When passing the long option name to call_command, the available option key is the option dest name (#22985). """ out = StringIO() management.call_command('dance', stdout=out, opt_3=True) self.assertIn("option3", out.getvalue()) self.assertNotIn("opt_3", out.getvalue()) self.assertNotIn("opt-3", out.getvalue()) @ignore_warnings(category=RemovedInDjango110Warning) def test_optparse_compatibility(self): """ optparse should be supported during Django 1.8/1.9 releases. """ out = StringIO() management.call_command('optparse_cmd', stdout=out) self.assertEqual(out.getvalue(), "All right, let's dance Rock'n'Roll.\n") # Simulate command line execution with captured_stdout() as stdout, captured_stderr(): management.execute_from_command_line(['django-admin', 'optparse_cmd']) self.assertEqual(stdout.getvalue(), "All right, let's dance Rock'n'Roll.\n") def test_calling_a_command_with_only_empty_parameter_should_ends_gracefully(self): out = StringIO() management.call_command('hal', "--empty", stdout=out) self.assertIn("Dave, I can't do that.\n", out.getvalue()) def test_calling_command_with_app_labels_and_parameters_should_be_ok(self): out = StringIO() management.call_command('hal', 'myapp', "--verbosity", "3", stdout=out) self.assertIn("Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue()) def test_calling_command_with_parameters_and_app_labels_at_the_end_should_be_ok(self): out = StringIO() management.call_command('hal', "--verbosity", "3", "myapp", stdout=out) self.assertIn("Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue()) def test_calling_a_command_with_no_app_labels_and_parameters_should_raise_a_command_error(self): out = StringIO() with self.assertRaises(CommandError): management.call_command('hal', stdout=out) def test_output_transaction(self): out = StringIO() management.call_command('transaction', stdout=out, no_color=True) output = out.getvalue().strip() self.assertTrue(output.startswith(connection.ops.start_transaction_sql())) self.assertTrue(output.endswith(connection.ops.end_transaction_sql())) def test_call_command_no_checks(self): """ By default, call_command should not trigger the check framework, unless specifically asked. """ self.counter = 0 def patched_check(self_, **kwargs): self.counter = self.counter + 1 saved_check = BaseCommand.check BaseCommand.check = patched_check try: management.call_command("dance", verbosity=0) self.assertEqual(self.counter, 0) management.call_command("dance", verbosity=0, skip_checks=False) self.assertEqual(self.counter, 1) finally: BaseCommand.check = saved_check class UtilsTests(SimpleTestCase): def test_no_existent_external_program(self): self.assertRaises(CommandError, popen_wrapper, ['a_42_command_that_doesnt_exist_42'])
bsd-3-clause
erikr/django
tests/auth_tests/test_hashers.py
8
22989
# -*- coding: utf-8 -*- from __future__ import unicode_literals from unittest import skipUnless from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH, BasePasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, check_password, get_hasher, identify_hasher, is_password_usable, make_password, ) from django.test import SimpleTestCase, mock from django.test.utils import override_settings from django.utils.encoding import force_bytes try: import crypt except ImportError: crypt = None else: # On some platforms (e.g. OpenBSD), crypt.crypt() always return None. if crypt.crypt('', '') is None: crypt = None try: import bcrypt except ImportError: bcrypt = None try: import argon2 except ImportError: argon2 = None class PBKDF2SingleIterationHasher(PBKDF2PasswordHasher): iterations = 1 @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPass(SimpleTestCase): def test_simple(self): encoded = make_password('lètmein') self.assertTrue(encoded.startswith('pbkdf2_sha256$')) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) # Blank passwords blank_encoded = make_password('') self.assertTrue(blank_encoded.startswith('pbkdf2_sha256$')) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) def test_pbkdf2(self): encoded = make_password('lètmein', 'seasalt', 'pbkdf2_sha256') self.assertEqual(encoded, 'pbkdf2_sha256$36000$seasalt$mEUPPFJkT/xtwDU8rB7Q+puHRZnR07WRjerTkt/3HI0=') self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "pbkdf2_sha256") # Blank passwords blank_encoded = make_password('', 'seasalt', 'pbkdf2_sha256') self.assertTrue(blank_encoded.startswith('pbkdf2_sha256$')) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher']) def test_sha1(self): encoded = make_password('lètmein', 'seasalt', 'sha1') self.assertEqual(encoded, 'sha1$seasalt$cff36ea83f5706ce9aa7454e63e431fc726b2dc8') self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "sha1") # Blank passwords blank_encoded = make_password('', 'seasalt', 'sha1') self.assertTrue(blank_encoded.startswith('sha1$')) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.MD5PasswordHasher']) def test_md5(self): encoded = make_password('lètmein', 'seasalt', 'md5') self.assertEqual(encoded, 'md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3') self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "md5") # Blank passwords blank_encoded = make_password('', 'seasalt', 'md5') self.assertTrue(blank_encoded.startswith('md5$')) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.UnsaltedMD5PasswordHasher']) def test_unsalted_md5(self): encoded = make_password('lètmein', '', 'unsalted_md5') self.assertEqual(encoded, '88a434c88cca4e900f7874cd98123f43') self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_md5") # Alternate unsalted syntax alt_encoded = "md5$$%s" % encoded self.assertTrue(is_password_usable(alt_encoded)) self.assertTrue(check_password('lètmein', alt_encoded)) self.assertFalse(check_password('lètmeinz', alt_encoded)) # Blank passwords blank_encoded = make_password('', '', 'unsalted_md5') self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher']) def test_unsalted_sha1(self): encoded = make_password('lètmein', '', 'unsalted_sha1') self.assertEqual(encoded, 'sha1$$6d138ca3ae545631b3abd71a4f076ce759c5700b') self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_sha1") # Raw SHA1 isn't acceptable alt_encoded = encoded[6:] self.assertFalse(check_password('lètmein', alt_encoded)) # Blank passwords blank_encoded = make_password('', '', 'unsalted_sha1') self.assertTrue(blank_encoded.startswith('sha1$')) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) @skipUnless(crypt, "no crypt module to generate password.") @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.CryptPasswordHasher']) def test_crypt(self): encoded = make_password('lètmei', 'ab', 'crypt') self.assertEqual(encoded, 'crypt$$ab1Hv2Lg7ltQo') self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmei', encoded)) self.assertFalse(check_password('lètmeiz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "crypt") # Blank passwords blank_encoded = make_password('', 'ab', 'crypt') self.assertTrue(blank_encoded.startswith('crypt$')) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_sha256(self): encoded = make_password('lètmein', hasher='bcrypt_sha256') self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith('bcrypt_sha256$')) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt_sha256") # password truncation no longer works password = ( 'VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5' 'JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN' ) encoded = make_password(password, hasher='bcrypt_sha256') self.assertTrue(check_password(password, encoded)) self.assertFalse(check_password(password[:72], encoded)) # Blank passwords blank_encoded = make_password('', hasher='bcrypt_sha256') self.assertTrue(blank_encoded.startswith('bcrypt_sha256$')) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt(self): encoded = make_password('lètmein', hasher='bcrypt') self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith('bcrypt$')) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt") # Blank passwords blank_encoded = make_password('', hasher='bcrypt') self.assertTrue(blank_encoded.startswith('bcrypt$')) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_upgrade(self): hasher = get_hasher('bcrypt') self.assertEqual('bcrypt', hasher.algorithm) self.assertNotEqual(hasher.rounds, 4) old_rounds = hasher.rounds try: # Generate a password with 4 rounds. hasher.rounds = 4 encoded = make_password('letmein', hasher='bcrypt') rounds = hasher.safe_summary(encoded)['work factor'] self.assertEqual(rounds, '04') state = {'upgraded': False} def setter(password): state['upgraded'] = True # No upgrade is triggered. self.assertTrue(check_password('letmein', encoded, setter, 'bcrypt')) self.assertFalse(state['upgraded']) # Revert to the old rounds count and ... hasher.rounds = old_rounds # ... check if the password would get updated to the new count. self.assertTrue(check_password('letmein', encoded, setter, 'bcrypt')) self.assertTrue(state['upgraded']) finally: hasher.rounds = old_rounds @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_harden_runtime(self): hasher = get_hasher('bcrypt') self.assertEqual('bcrypt', hasher.algorithm) with mock.patch.object(hasher, 'rounds', 4): encoded = make_password('letmein', hasher='bcrypt') with mock.patch.object(hasher, 'rounds', 6), \ mock.patch.object(hasher, 'encode', side_effect=hasher.encode): hasher.harden_runtime('wrong_password', encoded) # Increasing rounds from 4 to 6 means an increase of 4 in workload, # therefore hardening should run 3 times to make the timing the # same (the original encode() call already ran once). self.assertEqual(hasher.encode.call_count, 3) # Get the original salt (includes the original workload factor) algorithm, data = encoded.split('$', 1) expected_call = (('wrong_password', force_bytes(data[:29])),) self.assertEqual(hasher.encode.call_args_list, [expected_call] * 3) def test_unusable(self): encoded = make_password(None) self.assertEqual(len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH) self.assertFalse(is_password_usable(encoded)) self.assertFalse(check_password(None, encoded)) self.assertFalse(check_password(encoded, encoded)) self.assertFalse(check_password(UNUSABLE_PASSWORD_PREFIX, encoded)) self.assertFalse(check_password('', encoded)) self.assertFalse(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) with self.assertRaises(ValueError): identify_hasher(encoded) # Assert that the unusable passwords actually contain a random part. # This might fail one day due to a hash collision. self.assertNotEqual(encoded, make_password(None), "Random password collision?") def test_unspecified_password(self): """ Makes sure specifying no plain password with a valid encoded password returns `False`. """ self.assertFalse(check_password(None, make_password('lètmein'))) def test_bad_algorithm(self): with self.assertRaises(ValueError): make_password('lètmein', hasher='lolcat') with self.assertRaises(ValueError): identify_hasher('lolcat$salt$hash') def test_bad_encoded(self): self.assertFalse(is_password_usable('lètmein_badencoded')) self.assertFalse(is_password_usable('')) def test_low_level_pbkdf2(self): hasher = PBKDF2PasswordHasher() encoded = hasher.encode('lètmein', 'seasalt2') self.assertEqual(encoded, 'pbkdf2_sha256$36000$seasalt2$QkIBVCvGmTmyjPJ5yox2y/jQB8isvgUNK98FxOU1UYo=') self.assertTrue(hasher.verify('lètmein', encoded)) def test_low_level_pbkdf2_sha1(self): hasher = PBKDF2SHA1PasswordHasher() encoded = hasher.encode('lètmein', 'seasalt2') self.assertEqual(encoded, 'pbkdf2_sha1$36000$seasalt2$GoU+9AubJ/xRkO0WD1Xf3WPxWfE=') self.assertTrue(hasher.verify('lètmein', encoded)) @override_settings( PASSWORD_HASHERS=[ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.MD5PasswordHasher', ], ) def test_upgrade(self): self.assertEqual('pbkdf2_sha256', get_hasher('default').algorithm) for algo in ('sha1', 'md5'): encoded = make_password('lètmein', hasher=algo) state = {'upgraded': False} def setter(password): state['upgraded'] = True self.assertTrue(check_password('lètmein', encoded, setter)) self.assertTrue(state['upgraded']) def test_no_upgrade(self): encoded = make_password('lètmein') state = {'upgraded': False} def setter(): state['upgraded'] = True self.assertFalse(check_password('WRONG', encoded, setter)) self.assertFalse(state['upgraded']) @override_settings( PASSWORD_HASHERS=[ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.MD5PasswordHasher', ], ) def test_no_upgrade_on_incorrect_pass(self): self.assertEqual('pbkdf2_sha256', get_hasher('default').algorithm) for algo in ('sha1', 'md5'): encoded = make_password('lètmein', hasher=algo) state = {'upgraded': False} def setter(): state['upgraded'] = True self.assertFalse(check_password('WRONG', encoded, setter)) self.assertFalse(state['upgraded']) def test_pbkdf2_upgrade(self): hasher = get_hasher('default') self.assertEqual('pbkdf2_sha256', hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) old_iterations = hasher.iterations try: # Generate a password with 1 iteration. hasher.iterations = 1 encoded = make_password('letmein') algo, iterations, salt, hash = encoded.split('$', 3) self.assertEqual(iterations, '1') state = {'upgraded': False} def setter(password): state['upgraded'] = True # No upgrade is triggered self.assertTrue(check_password('letmein', encoded, setter)) self.assertFalse(state['upgraded']) # Revert to the old iteration count and ... hasher.iterations = old_iterations # ... check if the password would get updated to the new iteration count. self.assertTrue(check_password('letmein', encoded, setter)) self.assertTrue(state['upgraded']) finally: hasher.iterations = old_iterations def test_pbkdf2_harden_runtime(self): hasher = get_hasher('default') self.assertEqual('pbkdf2_sha256', hasher.algorithm) with mock.patch.object(hasher, 'iterations', 1): encoded = make_password('letmein') with mock.patch.object(hasher, 'iterations', 6), \ mock.patch.object(hasher, 'encode', side_effect=hasher.encode): hasher.harden_runtime('wrong_password', encoded) # Encode should get called once ... self.assertEqual(hasher.encode.call_count, 1) # ... with the original salt and 5 iterations. algorithm, iterations, salt, hash = encoded.split('$', 3) expected_call = (('wrong_password', salt, 5),) self.assertEqual(hasher.encode.call_args, expected_call) def test_pbkdf2_upgrade_new_hasher(self): hasher = get_hasher('default') self.assertEqual('pbkdf2_sha256', hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) state = {'upgraded': False} def setter(password): state['upgraded'] = True with self.settings(PASSWORD_HASHERS=[ 'auth_tests.test_hashers.PBKDF2SingleIterationHasher']): encoded = make_password('letmein') algo, iterations, salt, hash = encoded.split('$', 3) self.assertEqual(iterations, '1') # No upgrade is triggered self.assertTrue(check_password('letmein', encoded, setter)) self.assertFalse(state['upgraded']) # Revert to the old iteration count and check if the password would get # updated to the new iteration count. with self.settings(PASSWORD_HASHERS=[ 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'auth_tests.test_hashers.PBKDF2SingleIterationHasher']): self.assertTrue(check_password('letmein', encoded, setter)) self.assertTrue(state['upgraded']) def test_check_password_calls_harden_runtime(self): hasher = get_hasher('default') encoded = make_password('letmein') with mock.patch.object(hasher, 'harden_runtime'), \ mock.patch.object(hasher, 'must_update', return_value=True): # Correct password supplied, no hardening needed check_password('letmein', encoded) self.assertEqual(hasher.harden_runtime.call_count, 0) # Wrong password supplied, hardening needed check_password('wrong_password', encoded) self.assertEqual(hasher.harden_runtime.call_count, 1) def test_load_library_no_algorithm(self): with self.assertRaises(ValueError) as e: BasePasswordHasher()._load_library() self.assertEqual("Hasher 'BasePasswordHasher' doesn't specify a library attribute", str(e.exception)) def test_load_library_importerror(self): PlainHasher = type(str('PlainHasher'), (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'}) # Python 3 adds quotes around module name msg = "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?" with self.assertRaisesRegex(ValueError, msg): PlainHasher()._load_library() @skipUnless(argon2, "argon2-cffi not installed") @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPassArgon2(SimpleTestCase): def test_argon2(self): encoded = make_password('lètmein', hasher='argon2') self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith('argon2$')) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) self.assertEqual(identify_hasher(encoded).algorithm, 'argon2') # Blank passwords blank_encoded = make_password('', hasher='argon2') self.assertTrue(blank_encoded.startswith('argon2$')) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password('', blank_encoded)) self.assertFalse(check_password(' ', blank_encoded)) # Old hashes without version attribute encoded = ( 'argon2$argon2i$m=8,t=1,p=1$c29tZXNhbHQ$gwQOXSNhxiOxPOA0+PY10P9QFO' '4NAYysnqRt1GSQLE55m+2GYDt9FEjPMHhP2Cuf0nOEXXMocVrsJAtNSsKyfg' ) self.assertTrue(check_password('secret', encoded)) self.assertFalse(check_password('wrong', encoded)) def test_argon2_upgrade(self): self._test_argon2_upgrade('time_cost', 'time cost', 1) self._test_argon2_upgrade('memory_cost', 'memory cost', 16) self._test_argon2_upgrade('parallelism', 'parallelism', 1) def test_argon2_version_upgrade(self): hasher = get_hasher('argon2') state = {'upgraded': False} encoded = ( 'argon2$argon2i$m=8,t=1,p=1$c29tZXNhbHQ$gwQOXSNhxiOxPOA0+PY10P9QFO' '4NAYysnqRt1GSQLE55m+2GYDt9FEjPMHhP2Cuf0nOEXXMocVrsJAtNSsKyfg' ) def setter(password): state['upgraded'] = True old_m = hasher.memory_cost old_t = hasher.time_cost old_p = hasher.parallelism try: hasher.memory_cost = 8 hasher.time_cost = 1 hasher.parallelism = 1 self.assertTrue(check_password('secret', encoded, setter, 'argon2')) self.assertTrue(state['upgraded']) finally: hasher.memory_cost = old_m hasher.time_cost = old_t hasher.parallelism = old_p def _test_argon2_upgrade(self, attr, summary_key, new_value): hasher = get_hasher('argon2') self.assertEqual('argon2', hasher.algorithm) self.assertNotEqual(getattr(hasher, attr), new_value) old_value = getattr(hasher, attr) try: # Generate hash with attr set to 1 setattr(hasher, attr, new_value) encoded = make_password('letmein', hasher='argon2') attr_value = hasher.safe_summary(encoded)[summary_key] self.assertEqual(attr_value, new_value) state = {'upgraded': False} def setter(password): state['upgraded'] = True # No upgrade is triggered. self.assertTrue(check_password('letmein', encoded, setter, 'argon2')) self.assertFalse(state['upgraded']) # Revert to the old rounds count and ... setattr(hasher, attr, old_value) # ... check if the password would get updated to the new count. self.assertTrue(check_password('letmein', encoded, setter, 'argon2')) self.assertTrue(state['upgraded']) finally: setattr(hasher, attr, old_value)
bsd-3-clause
queria/my-tempest
tempest/services/volume/json/admin/volume_hosts_client.py
3
1484
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import urllib from tempest.common import rest_client from tempest import config CONF = config.CONF class VolumeHostsClientJSON(rest_client.RestClient): """ Client class to send CRUD Volume Hosts API requests to a Cinder endpoint """ def __init__(self, auth_provider): super(VolumeHostsClientJSON, self).__init__(auth_provider) self.service = CONF.volume.catalog_type self.build_interval = CONF.volume.build_interval self.build_timeout = CONF.volume.build_timeout def list_hosts(self, params=None): """Lists all hosts.""" url = 'os-hosts' if params: url += '?%s' % urllib.urlencode(params) resp, body = self.get(url) body = json.loads(body) self.expected_success(200, resp.status) return resp, body['hosts']
apache-2.0
songfj/scrapy
scrapy/utils/defer.py
61
3554
""" Helper functions for dealing with Twisted deferreds """ from twisted.internet import defer, reactor, task from twisted.python import failure from scrapy.exceptions import IgnoreRequest def defer_fail(_failure): """Same as twisted.internet.defer.fail but delay calling errback until next reactor loop It delays by 100ms so reactor has a chance to go trough readers and writers before attending pending delayed calls, so do not set delay to zero. """ d = defer.Deferred() reactor.callLater(0.1, d.errback, _failure) return d def defer_succeed(result): """Same as twisted.internet.defer.succeed but delay calling callback until next reactor loop It delays by 100ms so reactor has a chance to go trough readers and writers before attending pending delayed calls, so do not set delay to zero. """ d = defer.Deferred() reactor.callLater(0.1, d.callback, result) return d def defer_result(result): if isinstance(result, defer.Deferred): return result elif isinstance(result, failure.Failure): return defer_fail(result) else: return defer_succeed(result) def mustbe_deferred(f, *args, **kw): """Same as twisted.internet.defer.maybeDeferred, but delay calling callback/errback to next reactor loop """ try: result = f(*args, **kw) # FIXME: Hack to avoid introspecting tracebacks. This to speed up # processing of IgnoreRequest errors which are, by far, the most common # exception in Scrapy - see #125 except IgnoreRequest as e: return defer_fail(failure.Failure(e)) except: return defer_fail(failure.Failure()) else: return defer_result(result) def parallel(iterable, count, callable, *args, **named): """Execute a callable over the objects in the given iterable, in parallel, using no more than ``count`` concurrent calls. Taken from: http://jcalderone.livejournal.com/24285.html """ coop = task.Cooperator() work = (callable(elem, *args, **named) for elem in iterable) return defer.DeferredList([coop.coiterate(work) for i in range(count)]) def process_chain(callbacks, input, *a, **kw): """Return a Deferred built by chaining the given callbacks""" d = defer.Deferred() for x in callbacks: d.addCallback(x, *a, **kw) d.callback(input) return d def process_chain_both(callbacks, errbacks, input, *a, **kw): """Return a Deferred built by chaining the given callbacks and errbacks""" d = defer.Deferred() for cb, eb in zip(callbacks, errbacks): d.addCallbacks(cb, eb, callbackArgs=a, callbackKeywords=kw, errbackArgs=a, errbackKeywords=kw) if isinstance(input, failure.Failure): d.errback(input) else: d.callback(input) return d def process_parallel(callbacks, input, *a, **kw): """Return a Deferred with the output of all successful calls to the given callbacks """ dfds = [defer.succeed(input).addCallback(x, *a, **kw) for x in callbacks] d = defer.DeferredList(dfds, fireOnOneErrback=1, consumeErrors=1) d.addCallbacks(lambda r: [x[1] for x in r], lambda f: f.value.subFailure) return d def iter_errback(iterable, errback, *a, **kw): """Wraps an iterable calling an errback if an error is caught while iterating it. """ it = iter(iterable) while True: try: yield next(it) except StopIteration: break except: errback(failure.Failure(), *a, **kw)
bsd-3-clause
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_09_01/aio/operations/_vpn_gateways_operations.py
1
32392
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class VpnGatewaysOperations: """VpnGatewaysOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_09_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def get( self, resource_group_name: str, gateway_name: str, **kwargs ) -> "_models.VpnGateway": """Retrieves the details of a virtual wan vpn gateway. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: VpnGateway, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_09_01.models.VpnGateway :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnGateway"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('VpnGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, gateway_name: str, vpn_gateway_parameters: "_models.VpnGateway", **kwargs ) -> "_models.VpnGateway": cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnGateway"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(vpn_gateway_parameters, 'VpnGateway') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('VpnGateway', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('VpnGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, gateway_name: str, vpn_gateway_parameters: "_models.VpnGateway", **kwargs ) -> AsyncLROPoller["_models.VpnGateway"]: """Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :param vpn_gateway_parameters: Parameters supplied to create or Update a virtual wan vpn gateway. :type vpn_gateway_parameters: ~azure.mgmt.network.v2019_09_01.models.VpnGateway :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either VpnGateway or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2019_09_01.models.VpnGateway] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnGateway"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, gateway_name=gateway_name, vpn_gateway_parameters=vpn_gateway_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('VpnGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'} # type: ignore async def update_tags( self, resource_group_name: str, gateway_name: str, vpn_gateway_parameters: "_models.TagsObject", **kwargs ) -> "_models.VpnGateway": """Updates virtual wan vpn gateway tags. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :param vpn_gateway_parameters: Parameters supplied to update a virtual wan vpn gateway tags. :type vpn_gateway_parameters: ~azure.mgmt.network.v2019_09_01.models.TagsObject :keyword callable cls: A custom type or function that will be passed the direct response :return: VpnGateway, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_09_01.models.VpnGateway :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnGateway"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update_tags.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(vpn_gateway_parameters, 'TagsObject') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('VpnGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, gateway_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'} # type: ignore async def begin_delete( self, resource_group_name: str, gateway_name: str, **kwargs ) -> AsyncLROPoller[None]: """Deletes a virtual wan vpn gateway. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, gateway_name=gateway_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}'} # type: ignore async def _reset_initial( self, resource_group_name: str, gateway_name: str, **kwargs ) -> Optional["_models.VpnGateway"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.VpnGateway"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" accept = "application/json" # Construct URL url = self._reset_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('VpnGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _reset_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/reset'} # type: ignore async def begin_reset( self, resource_group_name: str, gateway_name: str, **kwargs ) -> AsyncLROPoller["_models.VpnGateway"]: """Resets the primary of the vpn gateway in the specified resource group. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either VpnGateway or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2019_09_01.models.VpnGateway] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnGateway"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._reset_initial( resource_group_name=resource_group_name, gateway_name=gateway_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('VpnGateway', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_reset.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/reset'} # type: ignore def list_by_resource_group( self, resource_group_name: str, **kwargs ) -> AsyncIterable["_models.ListVpnGatewaysResult"]: """Lists all the VpnGateways in a resource group. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListVpnGatewaysResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2019_09_01.models.ListVpnGatewaysResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnGatewaysResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListVpnGatewaysResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways'} # type: ignore def list( self, **kwargs ) -> AsyncIterable["_models.ListVpnGatewaysResult"]: """Lists all the VpnGateways in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListVpnGatewaysResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2019_09_01.models.ListVpnGatewaysResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnGatewaysResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-09-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListVpnGatewaysResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnGateways'} # type: ignore
mit
adviti/melange
thirdparty/google_appengine/lib/django_1_2/django/contrib/gis/management/commands/inspectdb.py
311
1553
from optparse import make_option from django.core.management.base import CommandError from django.core.management.commands.inspectdb import Command as InspectDBCommand class Command(InspectDBCommand): db_module = 'django.contrib.gis.db' gis_tables = {} def get_field_type(self, connection, table_name, row): field_type, field_params, field_notes = super(Command, self).get_field_type(connection, table_name, row) if field_type == 'GeometryField': geo_col = row[0] # Getting a more specific field type and any additional parameters # from the `get_geometry_type` routine for the spatial backend. field_type, geo_params = connection.introspection.get_geometry_type(table_name, geo_col) field_params.update(geo_params) # Adding the table name and column to the `gis_tables` dictionary, this # allows us to track which tables need a GeoManager. if table_name in self.gis_tables: self.gis_tables[table_name].append(geo_col) else: self.gis_tables[table_name] = [geo_col] return field_type, field_params, field_notes def get_meta(self, table_name): meta_lines = super(Command, self).get_meta(table_name) if table_name in self.gis_tables: # If the table is a geographic one, then we need make # GeoManager the default manager for the model. meta_lines.insert(0, ' objects = models.GeoManager()') return meta_lines
apache-2.0
hieukypc/ERP
openerp/addons/pos_restaurant/__openerp__.py
46
1152
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Restaurant', 'version': '1.0', 'category': 'Point of Sale', 'sequence': 6, 'summary': 'Restaurant extensions for the Point of Sale ', 'description': """ ======================= This module adds several restaurant features to the Point of Sale: - Bill Printing: Allows you to print a receipt before the order is paid - Bill Splitting: Allows you to split an order into different orders - Kitchen Order Printing: allows you to print orders updates to kitchen or bar printers """, 'depends': ['point_of_sale'], 'website': 'https://www.odoo.com/page/point-of-sale', 'data': [ 'restaurant_view.xml', 'security/ir.model.access.csv', 'views/templates.xml', ], 'qweb':[ 'static/src/xml/multiprint.xml', 'static/src/xml/splitbill.xml', 'static/src/xml/printbill.xml', 'static/src/xml/notes.xml', 'static/src/xml/floors.xml', ], 'demo': [ 'restaurant_demo.xml', ], 'installable': True, 'auto_install': False, }
gpl-3.0
akx/shoop
shoop/admin/modules/users/__init__.py
1
2997
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import six from django.contrib.auth import get_user_model from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from shoop.admin.base import AdminModule, MenuEntry, SearchResult from shoop.admin.utils.urls import admin_url, derive_model_url, get_model_url class UserModule(AdminModule): name = _("Users") category = _("Contacts") breadcrumbs_menu_entry = MenuEntry(name, url="shoop_admin:user.list") def get_urls(self): return [ admin_url( "^users/(?P<pk>\d+)/change-password/$", "shoop.admin.modules.users.views.UserChangePasswordView", name="user.change-password" ), admin_url( "^users/(?P<pk>\d+)/reset-password/$", "shoop.admin.modules.users.views.UserResetPasswordView", name="user.reset-password" ), admin_url( "^users/(?P<pk>\d+)/change-permissions/$", "shoop.admin.modules.users.views.UserChangePermissionsView", name="user.change-permissions" ), admin_url( "^users/(?P<pk>\d+)/$", "shoop.admin.modules.users.views.UserDetailView", name="user.detail" ), admin_url( "^users/new/$", "shoop.admin.modules.users.views.UserDetailView", kwargs={"pk": None}, name="user.new" ), admin_url( "^users/$", "shoop.admin.modules.users.views.UserListView", name="user.list" ), ] def get_menu_category_icons(self): return {self.category: "fa fa-users"} def get_menu_entries(self, request): return [ MenuEntry( text=_("Users"), icon="fa fa-users", url="shoop_admin:user.list", category=self.category ) ] def get_search_results(self, request, query): minimum_query_length = 3 if len(query) >= minimum_query_length: users = get_user_model().objects.filter( Q(username__icontains=query) | Q(email=query) ) for i, user in enumerate(users[:10]): relevance = 100 - i yield SearchResult( text=six.text_type(user), url=get_model_url(user), category=self.category, relevance=relevance ) def get_model_url(self, object, kind): return derive_model_url(get_user_model(), "shoop_admin:user", object, kind)
agpl-3.0
mxrrow/zaicoin
src/deps/boost/tools/regression/xsl_reports/test/test.py
30
1121
import sys sys.path.append( '..' ) import os import boost_wide_report import common import utils import shutil import time tag = "CVS-HEAD" if os.path.exists( "results/incoming/CVS-HEAD/processed/merged" ): shutil.rmtree( "results/incoming/CVS-HEAD/processed/merged" ) boost_wide_report.ftp_task = lambda ftp_site, site_path, incoming_dir: 1 boost_wide_report.unzip_archives_task = lambda incoming_dir, processed_dir, unzip: 1 boost_wide_report.execute_tasks( tag = tag , user = None , run_date = common.format_timestamp( time.gmtime() ) , comment_file = os.path.abspath( "comment.html" ) , results_dir = os.path.abspath( "results" ) , output_dir = os.path.abspath( "output" ) , reports = [ "i", "x", "ds", "dd", "dsr", "ddr", "us", "ud", "usr", "udr" ] , warnings = [ 'Warning text 1', 'Warning text 2' ] , extended_test_results = os.path.abspath( "output/extended_test_results.xml" ) , dont_collect_logs = 1 , expected_results_file = os.path.abspath( "expected_results.xml" ) , failures_markup_file = os.path.abspath( "explicit-failures-markup.xml" ) )
mit
ThomasMiconi/nupic.research
projects/sequence_prediction/discrete_sequences/lstm/lstm_scalar_encoding_capacity.py
12
1880
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import numpy as np from suite import DistributedEncoder num_encodings = 1000 num_nonrandoms = 12 nDim = 25 enc = DistributedEncoder(nDim, minValue=-1.0, maxValue=1.0, classifyWithRandom=True) for i in range(num_encodings): enc.encode(i) symbolList = range(num_nonrandoms) outcome = [] for _ in range(1000): # select two symbols, and decode using the average of the two encodings symbol1 = np.random.choice(symbolList) symbol2 = np.random.choice(symbolList) encoding1 = enc.encode(symbol1) encoding2 = enc.encode(symbol2) closest_symbols = enc.classify((encoding1+encoding2)/2, num=2) correct = symbol1 in closest_symbols and symbol2 in closest_symbols outcome.append(correct) print _, symbol1, symbol2, closest_symbols, correct print " Decode Success Rate: ", np.mean(outcome)
agpl-3.0
jason-vallet/graph-ryder-api
routes/tag/tag_aggregations.py
1
5067
from flask_restful import Resource, reqparse from neo4j.v1 import ResultError from connector import neo4j from routes.utils import addargs, makeResponse parser = reqparse.RequestParser() class CountAllTag(Resource): def get(self): req = "MATCH (:tag) RETURN count(*) AS nb_tags" result = neo4j.query_neo4j(req) try: return makeResponse(result.single()['nb_tags'], 200) except ResultError: return makeResponse("ERROR", 500) class CountTagsByParent(Resource): def get(self, parent_tag_id): req = "MATCH (t:tag {tag_id : %d})<-[:IS_CHILD]-(:tag) RETURN count(*) AS nb_child" % parent_tag_id result = neo4j.query_neo4j(req) try: return makeResponse(result.single()['nb_child'], 200) except ResultError: return makeResponse("ERROR", 500) class TagsByDate(Resource): def get(self, timestamp1, timestamp2, limit): req = "match (n)<-[:ANNOTATES]-(a:annotation)-[:REFERS_TO]->(t:tag) where n.timestamp > %d and n.timestamp < %d and ('post' in labels(n) or 'comment' in labels(n)) return t.tag_id as id, t.label as label, count(t) as count order by count desc limit %d" % (timestamp1, timestamp2, limit) result = neo4j.query_neo4j(req) tags=[] for record in result: tags.append({'id': record['id'], "label": record['label'], "count": record['count']}) try: return makeResponse(tags, 200) except ResultError: return makeResponse("ERROR", 500) class CoocurrencesByTag(Resource): def get(self, tag_id): req = "MATCH (t1: tag {tag_id: %d})--(a1: annotation)-[:ANNOTATES]->(e:post)<-[:ANNOTATES]-(a2:annotation)--(t2: tag) where t1<>t2 return t2, count(e) as count order by count desc" % tag_id result = neo4j.query_neo4j(req) tags = [] for record in result: tag = record['t2'].properties if record['count']: tag['count'] = record['count'] tags.append(tag) try: return makeResponse(tags,200) except ResultError: return makeResponse("ERROR",500) class ContentWithCommonTags(Resource): def get(self, tag_id1, tag_id2): req = "MATCH (find:tag {tag_id: %d}) RETURN find" % tag_id1 result = neo4j.query_neo4j(req) tag1 = result.single()['find'].properties req = "MATCH (find:tag {tag_id: %d}) RETURN find" % tag_id2 result = neo4j.query_neo4j(req) tag2 = result.single()['find'].properties response = {} if tag1['tag_id'] <= tag2['tag_id']: response['tag_src'] = tag1 response['tag_dst'] = tag2 else: response['tag_src'] = tag2 response['tag_dst'] = tag1 req = "match (t1: tag {tag_id: %d})<-[:REFERS_TO]-(a: annotation)-[:ANNOTATES]->(e) " % tag_id1 req += "match (e)<-[:ANNOTATES]-(a2: annotation)-[:REFERS_TO]->(t2: tag {tag_id: %d}) " % tag_id2 req += "match (e)<-[:AUTHORSHIP]-(u: user) " req += "return distinct t1.tag_id, CASE e.post_id when null then e.comment_id else e.post_id end as id, CASE e.post_id WHEN null THEN 'comment' ELSE 'post' END as entity_type, e.timestamp as timestamp, e.label as label, u.user_id as user_id, u.label as user_label, t2.tag_id ORDER BY e.timestamp DESC" result = neo4j.query_neo4j(req) tags = [] for record in result: tags.append({'id': record['id'], "entity_type": record['entity_type'], "timestamp": record['timestamp'], 'label': record['label'], 'user_id': record['user_id'], 'user_label': record['user_label']}) response['list'] = tags try: tags except ResultError: return makeResponse("ERROR",500) return makeResponse(response, 200) class ContentWithCommonTagsByDate(Resource): def get(self, tag_id1, tag_id2, start_date, end_date): req = "match (t1: tag {tag_id: %d})<-[:REFERS_TO]-(a: annotation)-[:ANNOTATES]->(e) " % tag_id1 req += "match (e)<-[:ANNOTATES]-(a2: annotation)-[:REFERS_TO]->(t2: tag {tag_id: %d}) " % tag_id2 req += "match (e)<-[:AUTHORSHIP]-(u: user) " req += "where e.timestamp >= %d and e.timestamp <= %d " % (start_date, end_date) req += "return distinct t1.tag_id, CASE e.post_id when null then e.comment_id else e.post_id end as id, CASE e.post_id when null then 'comment' else 'post' end as entity_type, e.timestamp as timestamp, e.label as label, u.user_id as user_id, u.label as user_label, t2.tag_id ORDER BY e.timestamp DESC" result = neo4j.query_neo4j(req) tags = [] for record in result: tags.append({'id': record['id'], "entity_type": record['entity_type'], "timestamp": record['timestamp'], 'label': record['label'], 'user_id': record['user_id'], 'user_label': record['user_label']}) try: return makeResponse(tags,200) except ResultError: return makeResponse("ERROR",500)
lgpl-3.0
CroissanceCommune/autonomie
autonomie/views/indicators.py
1
1974
# -*- coding: utf-8 -*- # * Authors: # * TJEBBES Gaston <g.t@majerti.fr> # * Arezki Feth <f.a@majerti.fr>; # * Miotte Julien <j.m@majerti.fr>; import logging from pyramid.httpexceptions import HTTPFound from autonomie.events.indicators import IndicatorChanged INDICATOR_ROUTE = "/indicators/{id}" logger = logging.getLogger(__name__) def force_indicator_view(context, request): """ Force an indicator (sets forced to True """ if context.forced: context.unforce() logger.debug( u"+ Setting force=False for the indicator {}".format( context.id, ) ) else: logger.debug( u"+ Setting force=True for the indicator {}".format( context.id, ) ) context.force() request.dbsession.merge(context) request.registry.notify(IndicatorChanged(request, context)) return HTTPFound(request.referrer) def validate_file_view(context, request): """ """ validation_status = request.GET.get('validation_status') if validation_status in context.VALIDATION_STATUS: logger.debug(u"+ Setting the status of the indicator {} to {}".format( context.id, validation_status )) context.set_validation_status(validation_status) request.registry.notify(IndicatorChanged(request, context)) else: request.session.flash(u"Statut invalide : %s" % validation_status) return HTTPFound(request.referrer) def includeme(config): config.add_route(INDICATOR_ROUTE, INDICATOR_ROUTE, traverse=INDICATOR_ROUTE) config.add_view( force_indicator_view, route_name=INDICATOR_ROUTE, permission="force.indicator", request_param="action=force", ) config.add_view( validate_file_view, route_name=INDICATOR_ROUTE, permission="valid.indicator", request_param="action=validation_status", )
gpl-3.0
nitzmahone/ansible
lib/ansible/modules/cloud/cloudstack/cs_disk_offering.py
7
11292
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2018, David Passante <@dpassante> # (c) 2017, René Moser <mail@renemoser.net> # 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: cs_disk_offering description: - Create and delete disk offerings for guest VMs. - Update display_text or display_offering of existing disk offering. short_description: Manages disk offerings on Apache CloudStack based clouds. version_added: "2.7" author: - "David Passante (@dpassante)" - "René Moser (@resmo)" options: disk_size: description: - Size of the disk offering in GB (1GB = 1,073,741,824 bytes). bytes_read_rate: description: - Bytes read rate of the disk offering. bytes_write_rate: description: - Bytes write rate of the disk offering. display_text: description: - Display text of the disk offering. - If not set, C(name) will be used as C(display_text) while creating. domain: description: - Domain the disk offering is related to. - Public for all domains and subdomains if not set. hypervisor_snapshot_reserve: description: - Hypervisor snapshot reserve space as a percent of a volume. - Only for managed storage using Xen or VMware. customized: description: - Whether disk offering iops is custom or not. type: bool default: false iops_read_rate: description: - IO requests read rate of the disk offering. iops_write_rate: description: - IO requests write rate of the disk offering. iops_max: description: - Max. iops of the disk offering. iops_min: description: - Min. iops of the disk offering. name: description: - Name of the disk offering. required: true provisioning_type: description: - Provisioning type used to create volumes. choices: - thin - sparse - fat state: description: - State of the disk offering. choices: - present - absent default: present storage_type: description: - The storage type of the disk offering. choices: - local - shared storage_tags: description: - The storage tags for this disk offering. aliases: - storage_tag display_offering: description: - An optional field, whether to display the offering to the end user or not. type: bool extends_documentation_fragment: cloudstack ''' EXAMPLES = ''' - name: Create a disk offering with local storage local_action: module: cs_disk_offering name: small display_text: Small 10GB disk_size: 10 storage_type: local - name: Create or update a disk offering with shared storage local_action: module: cs_disk_offering name: small display_text: Small 10GB disk_size: 10 storage_type: shared storage_tags: SAN01 - name: Remove a disk offering local_action: module: cs_disk_offering name: small state: absent ''' RETURN = ''' --- id: description: UUID of the disk offering returned: success type: string sample: a6f7a5fc-43f8-11e5-a151-feff819cdc9f disk_size: description: Size of the disk offering in GB returned: success type: int sample: 10 iops_max: description: Max iops of the disk offering returned: success type: int sample: 1000 iops_min: description: Min iops of the disk offering returned: success type: int sample: 500 bytes_read_rate: description: Bytes read rate of the disk offering returned: success type: int sample: 1000 bytes_write_rate: description: Bytes write rate of the disk offering returned: success type: int sample: 1000 iops_read_rate: description: IO requests per second read rate of the disk offering returned: success type: int sample: 1000 iops_write_rate: description: IO requests per second write rate of the disk offering returned: success type: int sample: 1000 created: description: Date the offering was created returned: success type: string sample: 2017-11-19T10:48:59+0000 display_text: description: Display text of the offering returned: success type: string sample: Small 10GB domain: description: Domain the offering is into returned: success type: string sample: ROOT storage_tags: description: List of storage tags returned: success type: list sample: [ 'eco' ] customized: description: Whether the offering uses custom IOPS or not returned: success type: bool sample: false name: description: Name of the system offering returned: success type: string sample: Micro provisioning_type: description: Provisioning type used to create volumes returned: success type: string sample: thin storage_type: description: Storage type used to create volumes returned: success type: string sample: shared display_offering: description: Whether to display the offering to the end user or not. returned: success type: bool sample: false ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, cs_argument_spec, cs_required_together, ) class AnsibleCloudStackDiskOffering(AnsibleCloudStack): def __init__(self, module): super(AnsibleCloudStackDiskOffering, self).__init__(module) self.returns = { 'disksize': 'disk_size', 'diskBytesReadRate': 'bytes_read_rate', 'diskBytesWriteRate': 'bytes_write_rate', 'diskIopsReadRate': 'iops_read_rate', 'diskIopsWriteRate': 'iops_write_rate', 'maxiops': 'iops_max', 'miniops': 'iops_min', 'hypervisorsnapshotreserve': 'hypervisor_snapshot_reserve', 'customized': 'customized', 'provisioningtype': 'provisioning_type', 'storagetype': 'storage_type', 'tags': 'storage_tags', 'displayoffering': 'display_offering', } self.disk_offering = None def get_disk_offering(self): args = { 'name': self.module.params.get('name'), 'domainid': self.get_domain(key='id'), } disk_offerings = self.query_api('listDiskOfferings', **args) if disk_offerings: for disk_offer in disk_offerings['diskoffering']: if args['name'] == disk_offer['name']: self.disk_offering = disk_offer return self.disk_offering def present_disk_offering(self): disk_offering = self.get_disk_offering() if not disk_offering: disk_offering = self._create_offering(disk_offering) else: disk_offering = self._update_offering(disk_offering) return disk_offering def absent_disk_offering(self): disk_offering = self.get_disk_offering() if disk_offering: self.result['changed'] = True if not self.module.check_mode: args = { 'id': disk_offering['id'], } self.query_api('deleteDiskOffering', **args) return disk_offering def _create_offering(self, disk_offering): self.result['changed'] = True args = { 'name': self.module.params.get('name'), 'displaytext': self.get_or_fallback('display_text', 'name'), 'disksize': self.module.params.get('disk_size'), 'bytesreadrate': self.module.params.get('bytes_read_rate'), 'byteswriterate': self.module.params.get('bytes_write_rate'), 'customized': self.module.params.get('customized'), 'domainid': self.get_domain(key='id'), 'hypervisorsnapshotreserve': self.module.params.get('hypervisor_snapshot_reserve'), 'iopsreadrate': self.module.params.get('iops_read_rate'), 'iopswriterate': self.module.params.get('iops_write_rate'), 'maxiops': self.module.params.get('iops_max'), 'miniops': self.module.params.get('iops_min'), 'provisioningtype': self.module.params.get('provisioning_type'), 'diskofferingdetails': self.module.params.get('disk_offering_details'), 'storagetype': self.module.params.get('storage_type'), 'tags': self.module.params.get('storage_tags'), 'displayoffering': self.module.params.get('display_offering'), } if not self.module.check_mode: res = self.query_api('createDiskOffering', **args) disk_offering = res['diskoffering'] return disk_offering def _update_offering(self, disk_offering): args = { 'id': disk_offering['id'], 'name': self.module.params.get('name'), 'displaytext': self.get_or_fallback('display_text', 'name'), 'displayoffering': self.module.params.get('display_offering'), } if self.has_changed(args, disk_offering): self.result['changed'] = True if not self.module.check_mode: res = self.query_api('updateDiskOffering', **args) disk_offering = res['diskoffering'] return disk_offering def get_result(self, disk_offering): super(AnsibleCloudStackDiskOffering, self).get_result(disk_offering) if disk_offering: # Prevent confusion, the api returns a tags key for storage tags. if 'tags' in disk_offering: self.result['storage_tags'] = disk_offering['tags'].split(',') or [disk_offering['tags']] if 'tags' in self.result: del self.result['tags'] return self.result def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name=dict(required=True), display_text=dict(), domain=dict(), disk_size=dict(type='int'), display_offering=dict(type='bool'), hypervisor_snapshot_reserve=dict(type='int'), bytes_read_rate=dict(type='int'), bytes_write_rate=dict(type='int'), customized=dict(type='bool'), iops_read_rate=dict(type='int'), iops_write_rate=dict(type='int'), iops_max=dict(type='int'), iops_min=dict(type='int'), provisioning_type=dict(choices=['thin', 'sparse', 'fat']), storage_type=dict(choices=['local', 'shared']), storage_tags=dict(type='list', aliases=['storage_tag']), state=dict(choices=['present', 'absent'], default='present'), )) module = AnsibleModule( argument_spec=argument_spec, required_together=cs_required_together(), supports_check_mode=True ) acs_do = AnsibleCloudStackDiskOffering(module) state = module.params.get('state') if state == "absent": disk_offering = acs_do.absent_disk_offering() else: disk_offering = acs_do.present_disk_offering() result = acs_do.get_result(disk_offering) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
matsengrp/bioboxpartis
python/event.py
2
11988
""" Container to hold the information for a single recombination event. """ import csv import random import numpy import os from opener import opener import utils #---------------------------------------------------------------------------------------- class RecombinationEvent(object): """ Container to hold the information for a single recombination event. """ def __init__(self, germlines): self.germlines = germlines self.vdj_combo_label = () # A tuple with the names of the chosen versions (v_gene, d_gene, j_gene, cdr3_length, <erosion lengths>) # NOTE I leave the lengths in here as strings self.genes = {} self.original_seqs = {} self.eroded_seqs = {} self.local_cyst_position, self.final_cyst_position = -1, -1 # the 'local' one is without the v left erosion self.local_tryp_position, self.final_tryp_position = -1, -1 # NOTE the first is the position *within* the j gene *only*, while the second is the tryp position in the final recombined sequence self.erosions = {} # erosion lengths for the event self.effective_erosions = {} # v left and j right erosions self.cdr3_length = 0 # NOTE this is the *desired* cdr3_length, i.e. after erosion and insertion self.insertion_lengths = {} self.insertions = {} self.recombined_seq = '' # combined sequence *before* mutations self.final_seqs = [] self.original_cyst_word = '' self.original_tryp_word = '' # ---------------------------------------------------------------------------------------- def set_vdj_combo(self, vdj_combo_label, cyst_positions, tryp_positions, all_seqs, debug=False, mimic_data_read_length=False): """ Set the label which labels the gene/length choice (a tuple of strings) as well as it's constituent parts """ self.vdj_combo_label = vdj_combo_label for region in utils.regions: self.genes[region] = vdj_combo_label[utils.index_keys[region + '_gene']] self.original_seqs[region] = all_seqs[region][self.genes[region]] self.original_seqs[region] = self.original_seqs[region].replace('N', utils.int_to_nucleotide(random.randint(0, 3))) # replace any Ns with a random nuke (a.t.m. use the same nuke for all Ns in a given seq) self.local_cyst_position = cyst_positions[self.genes['v']]['cysteine-position'] # cyst position in uneroded v self.local_tryp_position = int(tryp_positions[self.genes['j']]) # tryp position within j only self.cdr3_length = int(vdj_combo_label[utils.index_keys['cdr3_length']]) for boundary in utils.boundaries: self.insertion_lengths[boundary] = int(vdj_combo_label[utils.index_keys[boundary + '_insertion']]) for erosion in utils.real_erosions: self.erosions[erosion] = int(vdj_combo_label[utils.index_keys[erosion + '_del']]) for erosion in utils.effective_erosions: if mimic_data_read_length: # use v left and j right erosions from data? self.effective_erosions[erosion] = int(vdj_combo_label[utils.index_keys[erosion + '_del']]) else: # otherwise ignore data, and keep the entire v and j genes self.effective_erosions[erosion] = 0 # set the original conserved codon words, so we can revert them if they get mutated self.original_cyst_word = str(self.original_seqs['v'][self.local_cyst_position : self.local_cyst_position + 3 ]) self.original_tryp_word = str(self.original_seqs['j'][self.local_tryp_position : self.local_tryp_position + 3 ]) if debug: self.print_gene_choice() # ---------------------------------------------------------------------------------------- def set_final_cyst_tryp_positions(self, debug=False, total_length_from_right=-1): """ Set tryp position in the final, combined sequence. """ self.final_cyst_position = self.local_cyst_position - self.effective_erosions['v_5p'] self.final_tryp_position = utils.find_tryp_in_joined_seq(self.local_tryp_position, self.eroded_seqs['v'], self.insertions['vd'], self.eroded_seqs['d'], self.insertions['dj'], self.eroded_seqs['j'], self.erosions['j_5p']) if debug: print ' final tryptophan position: %d' % self.final_tryp_position # make sure cdr3 length matches the desired length in vdj_combo_label final_cdr3_length = self.final_tryp_position - self.final_cyst_position + 3 if debug: print ' final_tryp_position - final_cyst_position + 3 = %d - %d + 3 = %d (should be %d)' % (self.final_tryp_position, self.final_cyst_position, final_cdr3_length, self.cdr3_length) utils.check_both_conserved_codons(self.eroded_seqs['v'] + self.insertions['vd'] + self.eroded_seqs['d'] + self.insertions['dj'] + self.eroded_seqs['j'], self.final_cyst_position, self.final_tryp_position) assert final_cdr3_length == int(self.cdr3_length) assert total_length_from_right == -1 # deprecated (I think) now that I'm adding the mimic_data_read_length option # if total_length_from_right >= 0: # self.effective_erosions['v_5p'] = len(self.recombined_seq) - total_length_from_right # ---------------------------------------------------------------------------------------- def write_event(self, outfile, total_length_from_right=0, irandom=None): """ Write out all info to csv file. NOTE/RANT so, in calculating each sequence's unique id, we need to hash more than the information about the rearrangement event and mutation, because if we create identical events and sequences in independent recombinator threads, we *need* them to have different unique ids (otherwise all hell will break loose when you try to analyze them). The easy way to avoid this is to add a random number to the information before you hash it... but then you have no way to reproduce that random number when you want to run again with a set random seed to get identical output. The FIX for this at the moment is to pass in <irandom>, i.e. the calling proc tells write_event() that we're writing the <irandom>th event that that calling event is working on. Which effectively means we (drastically) reduce the period of our random number generator for hashing in exchange for reproducibility. Should be ok... """ columns = ('unique_id', 'reco_id') + utils.index_columns + ('seq', ) mode = '' if os.path.isfile(outfile): mode = 'ab' else: mode = 'wb' with opener(mode)(outfile) as csvfile: writer = csv.DictWriter(csvfile, columns) if mode == 'wb': # write the header if file wasn't there before writer.writeheader() # fill the row with values row = {} # first the stuff that's common to the whole recombination event row['cdr3_length'] = self.cdr3_length for region in utils.regions: row[region + '_gene'] = self.genes[region] for boundary in utils.boundaries: row[boundary + '_insertion'] = self.insertions[boundary] for erosion in utils.real_erosions: row[erosion + '_del'] = self.erosions[erosion] for erosion in utils.effective_erosions: row[erosion + '_del'] = self.effective_erosions[erosion] # hash the information that uniquely identifies each recombination event reco_id = '' for column in row: assert 'unique_id' not in row assert 'seq' not in row reco_id += str(row[column]) row['reco_id'] = hash(reco_id) assert 'fv_insertion' not in row # well, in principle it's ok if they're there, but in that case I'll need to at least think about updating some things assert 'jf_insertion' not in row row['fv_insertion'] = '' row['jf_insertion'] = '' # then the stuff that's particular to each mutant/clone for imute in range(len(self.final_seqs)): row['seq'] = self.final_seqs[imute] if total_length_from_right > 0: row['seq'] = row['seq'][len(row['seq'])-total_length_from_right : ] unique_id = '' # Hash to uniquely identify the sequence. for column in row: unique_id += str(row[column]) if irandom is None: # NOTE see note above unique_id += str(numpy.random.uniform()) else: # print 'ievt',irandom unique_id += str(irandom) row['unique_id'] = hash(unique_id) # print row['unique_id'], unique_id writer.writerow(row) # ---------------------------------------------------------------------------------------- def print_event(self, total_length_from_right=0): line = {} # collect some information into a form that print_reco_event understands line['cdr3_length'] = self.cdr3_length for region in utils.regions: line[region + '_gene'] = self.genes[region] for boundary in utils.boundaries: line[boundary + '_insertion'] = self.insertions[boundary] for erosion in utils.real_erosions: line[erosion + '_del'] = self.erosions[erosion] for erosion in utils.effective_erosions: line[erosion + '_del'] = self.effective_erosions[erosion] line['cyst_position'] = self.final_cyst_position line['tryp_position'] = self.final_tryp_position assert 'fv_insertion' not in line # well, in principle it's ok if they're there, but in that case I'll need to at least think about updating some things assert 'jf_insertion' not in line line['fv_insertion'] = '' line['jf_insertion'] = '' for imute in range(len(self.final_seqs)): line['seq'] = self.final_seqs[imute] if total_length_from_right > 0: line['seq'] = line['seq'][len(line['seq'])-total_length_from_right : ] utils.print_reco_event(self.germlines, line, one_line=(imute!=0)) # ---------------------------------------------------------------------------------------- def print_gene_choice(self): print ' chose: gene length' for region in utils.regions: print ' %s %-18s %-3d' % (region, self.genes[region], len(self.original_seqs[region])), if region == 'v': print ' (cysteine: %d)' % self.local_cyst_position elif region == 'j': print ' (tryptophan: %d)' % self.local_tryp_position else: print '' # ---------------------------------------------------------------------------------------- def revert_conserved_codons(self, seq): """ revert conserved cysteine and tryptophan to their original bases, eg if they were messed up by s.h.m. """ cpos = self.final_cyst_position if seq[cpos : cpos + 3] != self.original_cyst_word: seq = seq[:cpos] + self.original_cyst_word + seq[cpos+3:] tpos = self.final_tryp_position if seq[tpos : tpos + 3] != self.original_tryp_word: seq = seq[:tpos] + self.original_tryp_word + seq[tpos+3:] return seq
gpl-3.0
analogue/mythbox
resources/lib/twisted/twisted/test/test_digestauth.py
59
23470
# Copyright (c) 2008-2009 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.cred._digest} and the associated bits in L{twisted.cred.credentials}. """ from zope.interface.verify import verifyObject from twisted.trial.unittest import TestCase from twisted.python.hashlib import md5, sha1 from twisted.internet.address import IPv4Address from twisted.cred.error import LoginFailed from twisted.cred.credentials import calcHA1, calcHA2, IUsernameDigestHash from twisted.cred.credentials import calcResponse, DigestCredentialFactory def b64encode(s): return s.encode('base64').strip() class FakeDigestCredentialFactory(DigestCredentialFactory): """ A Fake Digest Credential Factory that generates a predictable nonce and opaque """ def __init__(self, *args, **kwargs): super(FakeDigestCredentialFactory, self).__init__(*args, **kwargs) self.privateKey = "0" def _generateNonce(self): """ Generate a static nonce """ return '178288758716122392881254770685' def _getTime(self): """ Return a stable time """ return 0 class DigestAuthTests(TestCase): """ L{TestCase} mixin class which defines a number of tests for L{DigestCredentialFactory}. Because this mixin defines C{setUp}, it must be inherited before L{TestCase}. """ def setUp(self): """ Create a DigestCredentialFactory for testing """ self.username = "foobar" self.password = "bazquux" self.realm = "test realm" self.algorithm = "md5" self.cnonce = "29fc54aa1641c6fa0e151419361c8f23" self.qop = "auth" self.uri = "/write/" self.clientAddress = IPv4Address('TCP', '10.2.3.4', 43125) self.method = 'GET' self.credentialFactory = DigestCredentialFactory( self.algorithm, self.realm) def test_MD5HashA1(self, _algorithm='md5', _hash=md5): """ L{calcHA1} accepts the C{'md5'} algorithm and returns an MD5 hash of its parameters, excluding the nonce and cnonce. """ nonce = 'abc123xyz' hashA1 = calcHA1(_algorithm, self.username, self.realm, self.password, nonce, self.cnonce) a1 = '%s:%s:%s' % (self.username, self.realm, self.password) expected = _hash(a1).hexdigest() self.assertEqual(hashA1, expected) def test_MD5SessionHashA1(self): """ L{calcHA1} accepts the C{'md5-sess'} algorithm and returns an MD5 hash of its parameters, including the nonce and cnonce. """ nonce = 'xyz321abc' hashA1 = calcHA1('md5-sess', self.username, self.realm, self.password, nonce, self.cnonce) a1 = '%s:%s:%s' % (self.username, self.realm, self.password) ha1 = md5(a1).digest() a1 = '%s:%s:%s' % (ha1, nonce, self.cnonce) expected = md5(a1).hexdigest() self.assertEqual(hashA1, expected) def test_SHAHashA1(self): """ L{calcHA1} accepts the C{'sha'} algorithm and returns a SHA hash of its parameters, excluding the nonce and cnonce. """ self.test_MD5HashA1('sha', sha1) def test_MD5HashA2Auth(self, _algorithm='md5', _hash=md5): """ L{calcHA2} accepts the C{'md5'} algorithm and returns an MD5 hash of its arguments, excluding the entity hash for QOP other than C{'auth-int'}. """ method = 'GET' hashA2 = calcHA2(_algorithm, method, self.uri, 'auth', None) a2 = '%s:%s' % (method, self.uri) expected = _hash(a2).hexdigest() self.assertEqual(hashA2, expected) def test_MD5HashA2AuthInt(self, _algorithm='md5', _hash=md5): """ L{calcHA2} accepts the C{'md5'} algorithm and returns an MD5 hash of its arguments, including the entity hash for QOP of C{'auth-int'}. """ method = 'GET' hentity = 'foobarbaz' hashA2 = calcHA2(_algorithm, method, self.uri, 'auth-int', hentity) a2 = '%s:%s:%s' % (method, self.uri, hentity) expected = _hash(a2).hexdigest() self.assertEqual(hashA2, expected) def test_MD5SessHashA2Auth(self): """ L{calcHA2} accepts the C{'md5-sess'} algorithm and QOP of C{'auth'} and returns the same value as it does for the C{'md5'} algorithm. """ self.test_MD5HashA2Auth('md5-sess') def test_MD5SessHashA2AuthInt(self): """ L{calcHA2} accepts the C{'md5-sess'} algorithm and QOP of C{'auth-int'} and returns the same value as it does for the C{'md5'} algorithm. """ self.test_MD5HashA2AuthInt('md5-sess') def test_SHAHashA2Auth(self): """ L{calcHA2} accepts the C{'sha'} algorithm and returns a SHA hash of its arguments, excluding the entity hash for QOP other than C{'auth-int'}. """ self.test_MD5HashA2Auth('sha', sha1) def test_SHAHashA2AuthInt(self): """ L{calcHA2} accepts the C{'sha'} algorithm and returns a SHA hash of its arguments, including the entity hash for QOP of C{'auth-int'}. """ self.test_MD5HashA2AuthInt('sha', sha1) def test_MD5HashResponse(self, _algorithm='md5', _hash=md5): """ L{calcResponse} accepts the C{'md5'} algorithm and returns an MD5 hash of its parameters, excluding the nonce count, client nonce, and QoP value if the nonce count and client nonce are C{None} """ hashA1 = 'abc123' hashA2 = '789xyz' nonce = 'lmnopq' response = '%s:%s:%s' % (hashA1, nonce, hashA2) expected = _hash(response).hexdigest() digest = calcResponse(hashA1, hashA2, _algorithm, nonce, None, None, None) self.assertEqual(expected, digest) def test_MD5SessionHashResponse(self): """ L{calcResponse} accepts the C{'md5-sess'} algorithm and returns an MD5 hash of its parameters, excluding the nonce count, client nonce, and QoP value if the nonce count and client nonce are C{None} """ self.test_MD5HashResponse('md5-sess') def test_SHAHashResponse(self): """ L{calcResponse} accepts the C{'sha'} algorithm and returns a SHA hash of its parameters, excluding the nonce count, client nonce, and QoP value if the nonce count and client nonce are C{None} """ self.test_MD5HashResponse('sha', sha1) def test_MD5HashResponseExtra(self, _algorithm='md5', _hash=md5): """ L{calcResponse} accepts the C{'md5'} algorithm and returns an MD5 hash of its parameters, including the nonce count, client nonce, and QoP value if they are specified. """ hashA1 = 'abc123' hashA2 = '789xyz' nonce = 'lmnopq' nonceCount = '00000004' clientNonce = 'abcxyz123' qop = 'auth' response = '%s:%s:%s:%s:%s:%s' % ( hashA1, nonce, nonceCount, clientNonce, qop, hashA2) expected = _hash(response).hexdigest() digest = calcResponse( hashA1, hashA2, _algorithm, nonce, nonceCount, clientNonce, qop) self.assertEqual(expected, digest) def test_MD5SessionHashResponseExtra(self): """ L{calcResponse} accepts the C{'md5-sess'} algorithm and returns an MD5 hash of its parameters, including the nonce count, client nonce, and QoP value if they are specified. """ self.test_MD5HashResponseExtra('md5-sess') def test_SHAHashResponseExtra(self): """ L{calcResponse} accepts the C{'sha'} algorithm and returns a SHA hash of its parameters, including the nonce count, client nonce, and QoP value if they are specified. """ self.test_MD5HashResponseExtra('sha', sha1) def formatResponse(self, quotes=True, **kw): """ Format all given keyword arguments and their values suitably for use as the value of an HTTP header. @types quotes: C{bool} @param quotes: A flag indicating whether to quote the values of each field in the response. @param **kw: Keywords and C{str} values which will be treated as field name/value pairs to include in the result. @rtype: C{str} @return: The given fields formatted for use as an HTTP header value. """ if 'username' not in kw: kw['username'] = self.username if 'realm' not in kw: kw['realm'] = self.realm if 'algorithm' not in kw: kw['algorithm'] = self.algorithm if 'qop' not in kw: kw['qop'] = self.qop if 'cnonce' not in kw: kw['cnonce'] = self.cnonce if 'uri' not in kw: kw['uri'] = self.uri if quotes: quote = '"' else: quote = '' return ', '.join([ '%s=%s%s%s' % (k, quote, v, quote) for (k, v) in kw.iteritems() if v is not None]) def getDigestResponse(self, challenge, ncount): """ Calculate the response for the given challenge """ nonce = challenge.get('nonce') algo = challenge.get('algorithm').lower() qop = challenge.get('qop') ha1 = calcHA1( algo, self.username, self.realm, self.password, nonce, self.cnonce) ha2 = calcHA2(algo, "GET", self.uri, qop, None) expected = calcResponse(ha1, ha2, algo, nonce, ncount, self.cnonce, qop) return expected def test_response(self, quotes=True): """ L{DigestCredentialFactory.decode} accepts a digest challenge response and parses it into an L{IUsernameHashedPassword} provider. """ challenge = self.credentialFactory.getChallenge(self.clientAddress.host) nc = "00000001" clientResponse = self.formatResponse( quotes=quotes, nonce=challenge['nonce'], response=self.getDigestResponse(challenge, nc), nc=nc, opaque=challenge['opaque']) creds = self.credentialFactory.decode( clientResponse, self.method, self.clientAddress.host) self.assertTrue(creds.checkPassword(self.password)) self.assertFalse(creds.checkPassword(self.password + 'wrong')) def test_responseWithoutQuotes(self): """ L{DigestCredentialFactory.decode} accepts a digest challenge response which does not quote the values of its fields and parses it into an L{IUsernameHashedPassword} provider in the same way it would a response which included quoted field values. """ self.test_response(False) def test_caseInsensitiveAlgorithm(self): """ The case of the algorithm value in the response is ignored when checking the credentials. """ self.algorithm = 'MD5' self.test_response() def test_md5DefaultAlgorithm(self): """ The algorithm defaults to MD5 if it is not supplied in the response. """ self.algorithm = None self.test_response() def test_responseWithoutClientIP(self): """ L{DigestCredentialFactory.decode} accepts a digest challenge response even if the client address it is passed is C{None}. """ challenge = self.credentialFactory.getChallenge(None) nc = "00000001" clientResponse = self.formatResponse( nonce=challenge['nonce'], response=self.getDigestResponse(challenge, nc), nc=nc, opaque=challenge['opaque']) creds = self.credentialFactory.decode(clientResponse, self.method, None) self.assertTrue(creds.checkPassword(self.password)) self.assertFalse(creds.checkPassword(self.password + 'wrong')) def test_multiResponse(self): """ L{DigestCredentialFactory.decode} handles multiple responses to a single challenge. """ challenge = self.credentialFactory.getChallenge(self.clientAddress.host) nc = "00000001" clientResponse = self.formatResponse( nonce=challenge['nonce'], response=self.getDigestResponse(challenge, nc), nc=nc, opaque=challenge['opaque']) creds = self.credentialFactory.decode(clientResponse, self.method, self.clientAddress.host) self.assertTrue(creds.checkPassword(self.password)) self.assertFalse(creds.checkPassword(self.password + 'wrong')) nc = "00000002" clientResponse = self.formatResponse( nonce=challenge['nonce'], response=self.getDigestResponse(challenge, nc), nc=nc, opaque=challenge['opaque']) creds = self.credentialFactory.decode(clientResponse, self.method, self.clientAddress.host) self.assertTrue(creds.checkPassword(self.password)) self.assertFalse(creds.checkPassword(self.password + 'wrong')) def test_failsWithDifferentMethod(self): """ L{DigestCredentialFactory.decode} returns an L{IUsernameHashedPassword} provider which rejects a correct password for the given user if the challenge response request is made using a different HTTP method than was used to request the initial challenge. """ challenge = self.credentialFactory.getChallenge(self.clientAddress.host) nc = "00000001" clientResponse = self.formatResponse( nonce=challenge['nonce'], response=self.getDigestResponse(challenge, nc), nc=nc, opaque=challenge['opaque']) creds = self.credentialFactory.decode(clientResponse, 'POST', self.clientAddress.host) self.assertFalse(creds.checkPassword(self.password)) self.assertFalse(creds.checkPassword(self.password + 'wrong')) def test_noUsername(self): """ L{DigestCredentialFactory.decode} raises L{LoginFailed} if the response has no username field or if the username field is empty. """ # Check for no username e = self.assertRaises( LoginFailed, self.credentialFactory.decode, self.formatResponse(username=None), self.method, self.clientAddress.host) self.assertEqual(str(e), "Invalid response, no username given.") # Check for an empty username e = self.assertRaises( LoginFailed, self.credentialFactory.decode, self.formatResponse(username=""), self.method, self.clientAddress.host) self.assertEqual(str(e), "Invalid response, no username given.") def test_noNonce(self): """ L{DigestCredentialFactory.decode} raises L{LoginFailed} if the response has no nonce. """ e = self.assertRaises( LoginFailed, self.credentialFactory.decode, self.formatResponse(opaque="abc123"), self.method, self.clientAddress.host) self.assertEqual(str(e), "Invalid response, no nonce given.") def test_noOpaque(self): """ L{DigestCredentialFactory.decode} raises L{LoginFailed} if the response has no opaque. """ e = self.assertRaises( LoginFailed, self.credentialFactory.decode, self.formatResponse(), self.method, self.clientAddress.host) self.assertEqual(str(e), "Invalid response, no opaque given.") def test_checkHash(self): """ L{DigestCredentialFactory.decode} returns an L{IUsernameDigestHash} provider which can verify a hash of the form 'username:realm:password'. """ challenge = self.credentialFactory.getChallenge(self.clientAddress.host) nc = "00000001" clientResponse = self.formatResponse( nonce=challenge['nonce'], response=self.getDigestResponse(challenge, nc), nc=nc, opaque=challenge['opaque']) creds = self.credentialFactory.decode(clientResponse, self.method, self.clientAddress.host) self.assertTrue(verifyObject(IUsernameDigestHash, creds)) cleartext = '%s:%s:%s' % (self.username, self.realm, self.password) hash = md5(cleartext) self.assertTrue(creds.checkHash(hash.hexdigest())) hash.update('wrong') self.assertFalse(creds.checkHash(hash.hexdigest())) def test_invalidOpaque(self): """ L{DigestCredentialFactory.decode} raises L{LoginFailed} when the opaque value does not contain all the required parts. """ credentialFactory = FakeDigestCredentialFactory(self.algorithm, self.realm) challenge = credentialFactory.getChallenge(self.clientAddress.host) exc = self.assertRaises( LoginFailed, credentialFactory._verifyOpaque, 'badOpaque', challenge['nonce'], self.clientAddress.host) self.assertEqual(str(exc), 'Invalid response, invalid opaque value') badOpaque = 'foo-' + b64encode('nonce,clientip') exc = self.assertRaises( LoginFailed, credentialFactory._verifyOpaque, badOpaque, challenge['nonce'], self.clientAddress.host) self.assertEqual(str(exc), 'Invalid response, invalid opaque value') exc = self.assertRaises( LoginFailed, credentialFactory._verifyOpaque, '', challenge['nonce'], self.clientAddress.host) self.assertEqual(str(exc), 'Invalid response, invalid opaque value') badOpaque = ( 'foo-' + b64encode('%s,%s,foobar' % ( challenge['nonce'], self.clientAddress.host))) exc = self.assertRaises( LoginFailed, credentialFactory._verifyOpaque, badOpaque, challenge['nonce'], self.clientAddress.host) self.assertEqual( str(exc), 'Invalid response, invalid opaque/time values') def test_incompatibleNonce(self): """ L{DigestCredentialFactory.decode} raises L{LoginFailed} when the given nonce from the response does not match the nonce encoded in the opaque. """ credentialFactory = FakeDigestCredentialFactory(self.algorithm, self.realm) challenge = credentialFactory.getChallenge(self.clientAddress.host) badNonceOpaque = credentialFactory._generateOpaque( '1234567890', self.clientAddress.host) exc = self.assertRaises( LoginFailed, credentialFactory._verifyOpaque, badNonceOpaque, challenge['nonce'], self.clientAddress.host) self.assertEqual( str(exc), 'Invalid response, incompatible opaque/nonce values') exc = self.assertRaises( LoginFailed, credentialFactory._verifyOpaque, badNonceOpaque, '', self.clientAddress.host) self.assertEqual( str(exc), 'Invalid response, incompatible opaque/nonce values') def test_incompatibleClientIP(self): """ L{DigestCredentialFactory.decode} raises L{LoginFailed} when the request comes from a client IP other than what is encoded in the opaque. """ credentialFactory = FakeDigestCredentialFactory(self.algorithm, self.realm) challenge = credentialFactory.getChallenge(self.clientAddress.host) badAddress = '10.0.0.1' # Sanity check self.assertNotEqual(self.clientAddress.host, badAddress) badNonceOpaque = credentialFactory._generateOpaque( challenge['nonce'], badAddress) self.assertRaises( LoginFailed, credentialFactory._verifyOpaque, badNonceOpaque, challenge['nonce'], self.clientAddress.host) def test_oldNonce(self): """ L{DigestCredentialFactory.decode} raises L{LoginFailed} when the given opaque is older than C{DigestCredentialFactory.CHALLENGE_LIFETIME_SECS} """ credentialFactory = FakeDigestCredentialFactory(self.algorithm, self.realm) challenge = credentialFactory.getChallenge(self.clientAddress.host) key = '%s,%s,%s' % (challenge['nonce'], self.clientAddress.host, '-137876876') digest = md5(key + credentialFactory.privateKey).hexdigest() ekey = b64encode(key) oldNonceOpaque = '%s-%s' % (digest, ekey.strip('\n')) self.assertRaises( LoginFailed, credentialFactory._verifyOpaque, oldNonceOpaque, challenge['nonce'], self.clientAddress.host) def test_mismatchedOpaqueChecksum(self): """ L{DigestCredentialFactory.decode} raises L{LoginFailed} when the opaque checksum fails verification. """ credentialFactory = FakeDigestCredentialFactory(self.algorithm, self.realm) challenge = credentialFactory.getChallenge(self.clientAddress.host) key = '%s,%s,%s' % (challenge['nonce'], self.clientAddress.host, '0') digest = md5(key + 'this is not the right pkey').hexdigest() badChecksum = '%s-%s' % (digest, b64encode(key)) self.assertRaises( LoginFailed, credentialFactory._verifyOpaque, badChecksum, challenge['nonce'], self.clientAddress.host) def test_incompatibleCalcHA1Options(self): """ L{calcHA1} raises L{TypeError} when any of the pszUsername, pszRealm, or pszPassword arguments are specified with the preHA1 keyword argument. """ arguments = ( ("user", "realm", "password", "preHA1"), (None, "realm", None, "preHA1"), (None, None, "password", "preHA1"), ) for pszUsername, pszRealm, pszPassword, preHA1 in arguments: self.assertRaises( TypeError, calcHA1, "md5", pszUsername, pszRealm, pszPassword, "nonce", "cnonce", preHA1=preHA1) def test_noNewlineOpaque(self): """ L{DigestCredentialFactory._generateOpaque} returns a value without newlines, regardless of the length of the nonce. """ opaque = self.credentialFactory._generateOpaque( "long nonce " * 10, None) self.assertNotIn('\n', opaque)
gpl-2.0
nlloyd/SubliminalCollaborator
libs/twisted/web/test/test_distrib.py
41
15230
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.web.distrib}. """ from os.path import abspath from xml.dom.minidom import parseString try: import pwd except ImportError: pwd = None from zope.interface.verify import verifyObject from twisted.python import log, filepath from twisted.internet import reactor, defer from twisted.trial import unittest from twisted.spread import pb from twisted.spread.banana import SIZE_LIMIT from twisted.web import http, distrib, client, resource, static, server from twisted.web.test.test_web import DummyRequest from twisted.web.test._util import _render from twisted.test import proto_helpers class MySite(server.Site): pass class PBServerFactory(pb.PBServerFactory): """ A PB server factory which keeps track of the most recent protocol it created. @ivar proto: L{None} or the L{Broker} instance most recently returned from C{buildProtocol}. """ proto = None def buildProtocol(self, addr): self.proto = pb.PBServerFactory.buildProtocol(self, addr) return self.proto class DistribTest(unittest.TestCase): port1 = None port2 = None sub = None f1 = None def tearDown(self): """ Clean up all the event sources left behind by either directly by test methods or indirectly via some distrib API. """ dl = [defer.Deferred(), defer.Deferred()] if self.f1 is not None and self.f1.proto is not None: self.f1.proto.notifyOnDisconnect(lambda: dl[0].callback(None)) else: dl[0].callback(None) if self.sub is not None and self.sub.publisher is not None: self.sub.publisher.broker.notifyOnDisconnect( lambda: dl[1].callback(None)) self.sub.publisher.broker.transport.loseConnection() else: dl[1].callback(None) if self.port1 is not None: dl.append(self.port1.stopListening()) if self.port2 is not None: dl.append(self.port2.stopListening()) return defer.gatherResults(dl) def testDistrib(self): # site1 is the publisher r1 = resource.Resource() r1.putChild("there", static.Data("root", "text/plain")) site1 = server.Site(r1) self.f1 = PBServerFactory(distrib.ResourcePublisher(site1)) self.port1 = reactor.listenTCP(0, self.f1) self.sub = distrib.ResourceSubscription("127.0.0.1", self.port1.getHost().port) r2 = resource.Resource() r2.putChild("here", self.sub) f2 = MySite(r2) self.port2 = reactor.listenTCP(0, f2) d = client.getPage("http://127.0.0.1:%d/here/there" % \ self.port2.getHost().port) d.addCallback(self.assertEqual, 'root') return d def _setupDistribServer(self, child): """ Set up a resource on a distrib site using L{ResourcePublisher}. @param child: The resource to publish using distrib. @return: A tuple consisting of the host and port on which to contact the created site. """ distribRoot = resource.Resource() distribRoot.putChild("child", child) distribSite = server.Site(distribRoot) self.f1 = distribFactory = PBServerFactory( distrib.ResourcePublisher(distribSite)) distribPort = reactor.listenTCP( 0, distribFactory, interface="127.0.0.1") self.addCleanup(distribPort.stopListening) addr = distribPort.getHost() self.sub = mainRoot = distrib.ResourceSubscription( addr.host, addr.port) mainSite = server.Site(mainRoot) mainPort = reactor.listenTCP(0, mainSite, interface="127.0.0.1") self.addCleanup(mainPort.stopListening) mainAddr = mainPort.getHost() return mainPort, mainAddr def _requestTest(self, child, **kwargs): """ Set up a resource on a distrib site using L{ResourcePublisher} and then retrieve it from a L{ResourceSubscription} via an HTTP client. @param child: The resource to publish using distrib. @param **kwargs: Extra keyword arguments to pass to L{getPage} when requesting the resource. @return: A L{Deferred} which fires with the result of the request. """ mainPort, mainAddr = self._setupDistribServer(child) return client.getPage("http://%s:%s/child" % ( mainAddr.host, mainAddr.port), **kwargs) def _requestAgentTest(self, child, **kwargs): """ Set up a resource on a distrib site using L{ResourcePublisher} and then retrieve it from a L{ResourceSubscription} via an HTTP client. @param child: The resource to publish using distrib. @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when requesting the resource. @return: A L{Deferred} which fires with a tuple consisting of a L{twisted.test.proto_helpers.AccumulatingProtocol} containing the body of the response and an L{IResponse} with the response itself. """ mainPort, mainAddr = self._setupDistribServer(child) d = client.Agent(reactor).request("GET", "http://%s:%s/child" % ( mainAddr.host, mainAddr.port), **kwargs) def cbCollectBody(response): protocol = proto_helpers.AccumulatingProtocol() response.deliverBody(protocol) d = protocol.closedDeferred = defer.Deferred() d.addCallback(lambda _: (protocol, response)) return d d.addCallback(cbCollectBody) return d def test_requestHeaders(self): """ The request headers are available on the request object passed to a distributed resource's C{render} method. """ requestHeaders = {} class ReportRequestHeaders(resource.Resource): def render(self, request): requestHeaders.update(dict( request.requestHeaders.getAllRawHeaders())) return "" request = self._requestTest( ReportRequestHeaders(), headers={'foo': 'bar'}) def cbRequested(result): self.assertEqual(requestHeaders['Foo'], ['bar']) request.addCallback(cbRequested) return request def test_requestResponseCode(self): """ The response code can be set by the request object passed to a distributed resource's C{render} method. """ class SetResponseCode(resource.Resource): def render(self, request): request.setResponseCode(200) return "" request = self._requestAgentTest(SetResponseCode()) def cbRequested(result): self.assertEqual(result[0].data, "") self.assertEqual(result[1].code, 200) self.assertEqual(result[1].phrase, "OK") request.addCallback(cbRequested) return request def test_requestResponseCodeMessage(self): """ The response code and message can be set by the request object passed to a distributed resource's C{render} method. """ class SetResponseCode(resource.Resource): def render(self, request): request.setResponseCode(200, "some-message") return "" request = self._requestAgentTest(SetResponseCode()) def cbRequested(result): self.assertEqual(result[0].data, "") self.assertEqual(result[1].code, 200) self.assertEqual(result[1].phrase, "some-message") request.addCallback(cbRequested) return request def test_largeWrite(self): """ If a string longer than the Banana size limit is passed to the L{distrib.Request} passed to the remote resource, it is broken into smaller strings to be transported over the PB connection. """ class LargeWrite(resource.Resource): def render(self, request): request.write('x' * SIZE_LIMIT + 'y') request.finish() return server.NOT_DONE_YET request = self._requestTest(LargeWrite()) request.addCallback(self.assertEqual, 'x' * SIZE_LIMIT + 'y') return request def test_largeReturn(self): """ Like L{test_largeWrite}, but for the case where C{render} returns a long string rather than explicitly passing it to L{Request.write}. """ class LargeReturn(resource.Resource): def render(self, request): return 'x' * SIZE_LIMIT + 'y' request = self._requestTest(LargeReturn()) request.addCallback(self.assertEqual, 'x' * SIZE_LIMIT + 'y') return request def test_connectionLost(self): """ If there is an error issuing the request to the remote publisher, an error response is returned. """ # Using pb.Root as a publisher will cause request calls to fail with an # error every time. Just what we want to test. self.f1 = serverFactory = PBServerFactory(pb.Root()) self.port1 = serverPort = reactor.listenTCP(0, serverFactory) self.sub = subscription = distrib.ResourceSubscription( "127.0.0.1", serverPort.getHost().port) request = DummyRequest(['']) d = _render(subscription, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 500) # This is the error we caused the request to fail with. It should # have been logged. self.assertEqual(len(self.flushLoggedErrors(pb.NoSuchMethod)), 1) d.addCallback(cbRendered) return d class _PasswordDatabase: def __init__(self, users): self._users = users def getpwall(self): return iter(self._users) def getpwnam(self, username): for user in self._users: if user[0] == username: return user raise KeyError() class UserDirectoryTests(unittest.TestCase): """ Tests for L{UserDirectory}, a resource for listing all user resources available on a system. """ def setUp(self): self.alice = ('alice', 'x', 123, 456, 'Alice,,,', self.mktemp(), '/bin/sh') self.bob = ('bob', 'x', 234, 567, 'Bob,,,', self.mktemp(), '/bin/sh') self.database = _PasswordDatabase([self.alice, self.bob]) self.directory = distrib.UserDirectory(self.database) def test_interface(self): """ L{UserDirectory} instances provide L{resource.IResource}. """ self.assertTrue(verifyObject(resource.IResource, self.directory)) def _404Test(self, name): """ Verify that requesting the C{name} child of C{self.directory} results in a 404 response. """ request = DummyRequest([name]) result = self.directory.getChild(name, request) d = _render(result, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 404) d.addCallback(cbRendered) return d def test_getInvalidUser(self): """ L{UserDirectory.getChild} returns a resource which renders a 404 response when passed a string which does not correspond to any known user. """ return self._404Test('carol') def test_getUserWithoutResource(self): """ L{UserDirectory.getChild} returns a resource which renders a 404 response when passed a string which corresponds to a known user who has neither a user directory nor a user distrib socket. """ return self._404Test('alice') def test_getPublicHTMLChild(self): """ L{UserDirectory.getChild} returns a L{static.File} instance when passed the name of a user with a home directory containing a I{public_html} directory. """ home = filepath.FilePath(self.bob[-2]) public_html = home.child('public_html') public_html.makedirs() request = DummyRequest(['bob']) result = self.directory.getChild('bob', request) self.assertIsInstance(result, static.File) self.assertEqual(result.path, public_html.path) def test_getDistribChild(self): """ L{UserDirectory.getChild} returns a L{ResourceSubscription} instance when passed the name of a user suffixed with C{".twistd"} who has a home directory containing a I{.twistd-web-pb} socket. """ home = filepath.FilePath(self.bob[-2]) home.makedirs() web = home.child('.twistd-web-pb') request = DummyRequest(['bob']) result = self.directory.getChild('bob.twistd', request) self.assertIsInstance(result, distrib.ResourceSubscription) self.assertEqual(result.host, 'unix') self.assertEqual(abspath(result.port), web.path) def test_invalidMethod(self): """ L{UserDirectory.render} raises L{UnsupportedMethod} in response to a non-I{GET} request. """ request = DummyRequest(['']) request.method = 'POST' self.assertRaises( server.UnsupportedMethod, self.directory.render, request) def test_render(self): """ L{UserDirectory} renders a list of links to available user content in response to a I{GET} request. """ public_html = filepath.FilePath(self.alice[-2]).child('public_html') public_html.makedirs() web = filepath.FilePath(self.bob[-2]) web.makedirs() # This really only works if it's a unix socket, but the implementation # doesn't currently check for that. It probably should someday, and # then skip users with non-sockets. web.child('.twistd-web-pb').setContent("") request = DummyRequest(['']) result = _render(self.directory, request) def cbRendered(ignored): document = parseString(''.join(request.written)) # Each user should have an li with a link to their page. [alice, bob] = document.getElementsByTagName('li') self.assertEqual(alice.firstChild.tagName, 'a') self.assertEqual(alice.firstChild.getAttribute('href'), 'alice/') self.assertEqual(alice.firstChild.firstChild.data, 'Alice (file)') self.assertEqual(bob.firstChild.tagName, 'a') self.assertEqual(bob.firstChild.getAttribute('href'), 'bob.twistd/') self.assertEqual(bob.firstChild.firstChild.data, 'Bob (twistd)') result.addCallback(cbRendered) return result def test_passwordDatabase(self): """ If L{UserDirectory} is instantiated with no arguments, it uses the L{pwd} module as its password database. """ directory = distrib.UserDirectory() self.assertIdentical(directory._pwd, pwd) if pwd is None: test_passwordDatabase.skip = "pwd module required"
apache-2.0
compiteing/flask-ponypermission
venv/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.py
488
6221
# -*- coding: utf-8 -*- # pidlockfile.py # # Copyright © 2008–2009 Ben Finney <ben+python@benfinney.id.au> # # This is free software: you may copy, modify, and/or distribute this work # under the terms of the Python Software Foundation License, version 2 or # later as published by the Python Software Foundation. # No warranty expressed or implied. See the file LICENSE.PSF-2 for details. """ Lockfile behaviour implemented via Unix PID files. """ from __future__ import absolute_import import os import sys import errno import time from . import (LockBase, AlreadyLocked, LockFailed, NotLocked, NotMyLock, LockTimeout) class PIDLockFile(LockBase): """ Lockfile implemented as a Unix PID file. The lock file is a normal file named by the attribute `path`. A lock's PID file contains a single line of text, containing the process ID (PID) of the process that acquired the lock. >>> lock = PIDLockFile('somefile') >>> lock = PIDLockFile('somefile') """ def __init__(self, path, threaded=False, timeout=None): # pid lockfiles don't support threaded operation, so always force # False as the threaded arg. LockBase.__init__(self, path, False, timeout) dirname = os.path.dirname(self.lock_file) basename = os.path.split(self.path)[-1] self.unique_name = self.path def read_pid(self): """ Get the PID from the lock file. """ return read_pid_from_pidfile(self.path) def is_locked(self): """ Test if the lock is currently held. The lock is held if the PID file for this lock exists. """ return os.path.exists(self.path) def i_am_locking(self): """ Test if the lock is held by the current process. Returns ``True`` if the current process ID matches the number stored in the PID file. """ return self.is_locked() and os.getpid() == self.read_pid() def acquire(self, timeout=None): """ Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired. """ timeout = timeout is not None and timeout or self.timeout end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout while True: try: write_pid_to_pidfile(self.path) except OSError as exc: if exc.errno == errno.EEXIST: # The lock creation failed. Maybe sleep a bit. if timeout is not None and time.time() > end_time: if timeout > 0: raise LockTimeout("Timeout waiting to acquire" " lock for %s" % self.path) else: raise AlreadyLocked("%s is already locked" % self.path) time.sleep(timeout is not None and timeout/10 or 0.1) else: raise LockFailed("failed to create %s" % self.path) else: return def release(self): """ Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not hold the lock. """ if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) if not self.i_am_locking(): raise NotMyLock("%s is locked, but not by me" % self.path) remove_existing_pidfile(self.path) def break_lock(self): """ Break an existing lock. Removes the PID file if it already exists, otherwise does nothing. """ remove_existing_pidfile(self.path) def read_pid_from_pidfile(pidfile_path): """ Read the PID recorded in the named PID file. Read and return the numeric PID recorded as text in the named PID file. If the PID file cannot be read, or if the content is not a valid PID, return ``None``. """ pid = None try: pidfile = open(pidfile_path, 'r') except IOError: pass else: # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. # # Programs that read PID files should be somewhat flexible # in what they accept; i.e., they should ignore extra # whitespace, leading zeroes, absence of the trailing # newline, or additional lines in the PID file. line = pidfile.readline().strip() try: pid = int(line) except ValueError: pass pidfile.close() return pid def write_pid_to_pidfile(pidfile_path): """ Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process and write it to the named file as a line of text. """ open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY) open_mode = 0o644 pidfile_fd = os.open(pidfile_path, open_flags, open_mode) pidfile = os.fdopen(pidfile_fd, 'w') # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. For # example, if crond was process number 25, /var/run/crond.pid # would contain three characters: two, five, and newline. pid = os.getpid() line = "%(pid)d\n" % vars() pidfile.write(line) pidfile.close() def remove_existing_pidfile(pidfile_path): """ Remove the named PID file if it exists. Removing a PID file that doesn't already exist puts us in the desired state, so we ignore the condition if the file does not exist. """ try: os.remove(pidfile_path) except OSError as exc: if exc.errno == errno.ENOENT: pass else: raise
mit
openai/baselines
baselines/common/tests/envs/identity_env.py
1
2444
import numpy as np from abc import abstractmethod from gym import Env from gym.spaces import MultiDiscrete, Discrete, Box from collections import deque class IdentityEnv(Env): def __init__( self, episode_len=None, delay=0, zero_first_rewards=True ): self.observation_space = self.action_space self.episode_len = episode_len self.time = 0 self.delay = delay self.zero_first_rewards = zero_first_rewards self.q = deque(maxlen=delay+1) def reset(self): self.q.clear() for _ in range(self.delay + 1): self.q.append(self.action_space.sample()) self.time = 0 return self.q[-1] def step(self, actions): rew = self._get_reward(self.q.popleft(), actions) if self.zero_first_rewards and self.time < self.delay: rew = 0 self.q.append(self.action_space.sample()) self.time += 1 done = self.episode_len is not None and self.time >= self.episode_len return self.q[-1], rew, done, {} def seed(self, seed=None): self.action_space.seed(seed) @abstractmethod def _get_reward(self, state, actions): raise NotImplementedError class DiscreteIdentityEnv(IdentityEnv): def __init__( self, dim, episode_len=None, delay=0, zero_first_rewards=True ): self.action_space = Discrete(dim) super().__init__(episode_len=episode_len, delay=delay, zero_first_rewards=zero_first_rewards) def _get_reward(self, state, actions): return 1 if state == actions else 0 class MultiDiscreteIdentityEnv(IdentityEnv): def __init__( self, dims, episode_len=None, delay=0, ): self.action_space = MultiDiscrete(dims) super().__init__(episode_len=episode_len, delay=delay) def _get_reward(self, state, actions): return 1 if all(state == actions) else 0 class BoxIdentityEnv(IdentityEnv): def __init__( self, shape, episode_len=None, ): self.action_space = Box(low=-1.0, high=1.0, shape=shape, dtype=np.float32) super().__init__(episode_len=episode_len) def _get_reward(self, state, actions): diff = actions - state diff = diff[:] return -0.5 * np.dot(diff, diff)
mit
byt3bl33d3r/pth-toolkit
lib/python2.7/site-packages/samba/external/testtools/tests/test_content.py
8
8042
# Copyright (c) 2008-2011 testtools developers. See LICENSE for details. import os import tempfile import unittest from testtools import TestCase from testtools.compat import ( _b, _u, StringIO, ) from testtools.content import ( attach_file, Content, content_from_file, content_from_stream, TracebackContent, text_content, ) from testtools.content_type import ( ContentType, UTF8_TEXT, ) from testtools.matchers import ( Equals, MatchesException, Raises, raises, ) from testtools.tests.helpers import an_exc_info raises_value_error = Raises(MatchesException(ValueError)) class TestContent(TestCase): def test___init___None_errors(self): self.assertThat(lambda: Content(None, None), raises_value_error) self.assertThat( lambda: Content(None, lambda: ["traceback"]), raises_value_error) self.assertThat( lambda: Content(ContentType("text", "traceback"), None), raises_value_error) def test___init___sets_ivars(self): content_type = ContentType("foo", "bar") content = Content(content_type, lambda: ["bytes"]) self.assertEqual(content_type, content.content_type) self.assertEqual(["bytes"], list(content.iter_bytes())) def test___eq__(self): content_type = ContentType("foo", "bar") one_chunk = lambda: [_b("bytes")] two_chunk = lambda: [_b("by"), _b("tes")] content1 = Content(content_type, one_chunk) content2 = Content(content_type, one_chunk) content3 = Content(content_type, two_chunk) content4 = Content(content_type, lambda: [_b("by"), _b("te")]) content5 = Content(ContentType("f", "b"), two_chunk) self.assertEqual(content1, content2) self.assertEqual(content1, content3) self.assertNotEqual(content1, content4) self.assertNotEqual(content1, content5) def test___repr__(self): content = Content(ContentType("application", "octet-stream"), lambda: [_b("\x00bin"), _b("ary\xff")]) self.assertIn("\\x00binary\\xff", repr(content)) def test_iter_text_not_text_errors(self): content_type = ContentType("foo", "bar") content = Content(content_type, lambda: ["bytes"]) self.assertThat(content.iter_text, raises_value_error) def test_iter_text_decodes(self): content_type = ContentType("text", "strange", {"charset": "utf8"}) content = Content( content_type, lambda: [_u("bytes\xea").encode("utf8")]) self.assertEqual([_u("bytes\xea")], list(content.iter_text())) def test_iter_text_default_charset_iso_8859_1(self): content_type = ContentType("text", "strange") text = _u("bytes\xea") iso_version = text.encode("ISO-8859-1") content = Content(content_type, lambda: [iso_version]) self.assertEqual([text], list(content.iter_text())) def test_from_file(self): fd, path = tempfile.mkstemp() self.addCleanup(os.remove, path) os.write(fd, _b('some data')) os.close(fd) content = content_from_file(path, UTF8_TEXT, chunk_size=2) self.assertThat( list(content.iter_bytes()), Equals([_b('so'), _b('me'), _b(' d'), _b('at'), _b('a')])) def test_from_nonexistent_file(self): directory = tempfile.mkdtemp() nonexistent = os.path.join(directory, 'nonexistent-file') content = content_from_file(nonexistent) self.assertThat(content.iter_bytes, raises(IOError)) def test_from_file_default_type(self): content = content_from_file('/nonexistent/path') self.assertThat(content.content_type, Equals(UTF8_TEXT)) def test_from_file_eager_loading(self): fd, path = tempfile.mkstemp() os.write(fd, _b('some data')) os.close(fd) content = content_from_file(path, UTF8_TEXT, buffer_now=True) os.remove(path) self.assertThat( ''.join(content.iter_text()), Equals('some data')) def test_from_stream(self): data = StringIO('some data') content = content_from_stream(data, UTF8_TEXT, chunk_size=2) self.assertThat( list(content.iter_bytes()), Equals(['so', 'me', ' d', 'at', 'a'])) def test_from_stream_default_type(self): data = StringIO('some data') content = content_from_stream(data) self.assertThat(content.content_type, Equals(UTF8_TEXT)) def test_from_stream_eager_loading(self): fd, path = tempfile.mkstemp() self.addCleanup(os.remove, path) os.write(fd, _b('some data')) stream = open(path, 'rb') content = content_from_stream(stream, UTF8_TEXT, buffer_now=True) os.write(fd, _b('more data')) os.close(fd) self.assertThat( ''.join(content.iter_text()), Equals('some data')) def test_from_text(self): data = _u("some data") expected = Content(UTF8_TEXT, lambda: [data.encode('utf8')]) self.assertEqual(expected, text_content(data)) class TestTracebackContent(TestCase): def test___init___None_errors(self): self.assertThat( lambda: TracebackContent(None, None), raises_value_error) def test___init___sets_ivars(self): content = TracebackContent(an_exc_info, self) content_type = ContentType("text", "x-traceback", {"language": "python", "charset": "utf8"}) self.assertEqual(content_type, content.content_type) result = unittest.TestResult() expected = result._exc_info_to_string(an_exc_info, self) self.assertEqual(expected, ''.join(list(content.iter_text()))) class TestAttachFile(TestCase): def make_file(self, data): # GZ 2011-04-21: This helper could be useful for methods above trying # to use mkstemp, but should handle write failures and # always close the fd. There must be a better way. fd, path = tempfile.mkstemp() self.addCleanup(os.remove, path) os.write(fd, _b(data)) os.close(fd) return path def test_simple(self): class SomeTest(TestCase): def test_foo(self): pass test = SomeTest('test_foo') data = 'some data' path = self.make_file(data) my_content = text_content(data) attach_file(test, path, name='foo') self.assertEqual({'foo': my_content}, test.getDetails()) def test_optional_name(self): # If no name is provided, attach_file just uses the base name of the # file. class SomeTest(TestCase): def test_foo(self): pass test = SomeTest('test_foo') path = self.make_file('some data') base_path = os.path.basename(path) attach_file(test, path) self.assertEqual([base_path], list(test.getDetails())) def test_lazy_read(self): class SomeTest(TestCase): def test_foo(self): pass test = SomeTest('test_foo') path = self.make_file('some data') attach_file(test, path, name='foo', buffer_now=False) content = test.getDetails()['foo'] content_file = open(path, 'w') content_file.write('new data') content_file.close() self.assertEqual(''.join(content.iter_text()), 'new data') def test_eager_read_by_default(self): class SomeTest(TestCase): def test_foo(self): pass test = SomeTest('test_foo') path = self.make_file('some data') attach_file(test, path, name='foo') content = test.getDetails()['foo'] content_file = open(path, 'w') content_file.write('new data') content_file.close() self.assertEqual(''.join(content.iter_text()), 'some data') def test_suite(): from unittest import TestLoader return TestLoader().loadTestsFromName(__name__)
bsd-2-clause
saurabh6790/frappe
frappe/patches/v8_0/set_user_permission_for_page_and_report.py
19
1687
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe def execute(): if not frappe.db.exists('DocType', 'Custom Role'): frappe.reload_doc("core", 'doctype', "custom_role") set_user_permission_for_page_and_report() update_ref_doctype_in_custom_role() def update_ref_doctype_in_custom_role(): frappe.reload_doc("core", 'doctype', "custom_role") frappe.db.sql("""update `tabCustom Role` set ref_doctype = (select ref_doctype from tabReport where name = `tabCustom Role`.report) where report is not null""") def set_user_permission_for_page_and_report(): make_custom_roles_for_page_and_report() def make_custom_roles_for_page_and_report(): for doctype in ['Page', 'Report']: for data in get_data(doctype): doc = frappe.get_doc(doctype, data.name) roles = get_roles(doctype, data, doc) make_custom_roles(doctype, doc.name, roles) def get_data(doctype): fields = ["name"] if doctype == 'Page' else ["name", "ref_doctype"] return frappe.get_all(doctype, fields = fields) def get_roles(doctype, data, doc): roles = [] if doctype == 'Page': for d in doc.roles: if frappe.db.exists('Role', d.role): roles.append({'role': d.role}) else: out = frappe.get_all('Custom DocPerm', fields='distinct role', filters=dict(parent = data.ref_doctype)) for d in out: roles.append({'role': d.role}) return roles def make_custom_roles(doctype, name, roles): field = doctype.lower() if roles: custom_permission = frappe.get_doc({ 'doctype': 'Custom Role', field : name, 'roles' : roles }).insert()
mit
toastedcornflakes/scikit-learn
sklearn/externals/joblib/_memory_helpers.py
52
3606
try: # Available in Python 3 from tokenize import open as open_py_source except ImportError: # Copied from python3 tokenize from codecs import lookup, BOM_UTF8 import re from io import TextIOWrapper, open cookie_re = re.compile("coding[:=]\s*([-\w.]+)") def _get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): return "iso-8859-1" return orig_enc def _detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argment, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned. If no encoding is specified, then the default of 'utf-8' will be returned. """ bom_found = False encoding = None default = 'utf-8' def read_or_stop(): try: return readline() except StopIteration: return b'' def find_cookie(line): try: line_string = line.decode('ascii') except UnicodeDecodeError: return None matches = cookie_re.findall(line_string) if not matches: return None encoding = _get_normal_name(matches[0]) try: codec = lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter raise SyntaxError("unknown encoding: " + encoding) if bom_found: if codec.name != 'utf-8': # This behaviour mimics the Python interpreter raise SyntaxError('encoding problem: utf-8') encoding += '-sig' return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = 'utf-8-sig' if not first: return default, [] encoding = find_cookie(first) if encoding: return encoding, [first] second = read_or_stop() if not second: return default, [first] encoding = find_cookie(second) if encoding: return encoding, [first, second] return default, [first, second] def open_py_source(filename): """Open a file in read only mode using the encoding detected by detect_encoding(). """ buffer = open(filename, 'rb') encoding, lines = _detect_encoding(buffer.readline) buffer.seek(0) text = TextIOWrapper(buffer, encoding, line_buffering=True) text.mode = 'r' return text
bsd-3-clause
BorisJeremic/Real-ESSI-Examples
parallel/compare_function/mycomparator.py
2
7118
#!/usr/bin/python import h5py import sys import numpy as np import os import re import random # find the path to my own python function: cur_dir=os.getcwd() sep='test_cases' test_DIR=cur_dir.split(sep,1)[0] scriptDIR=test_DIR+'compare_function' sys.path.append(scriptDIR) # import my own function for color and comparator from mycomparator import * from mycolor_fun import * epsilon = 1e-10 def h5diff_disp(h5in_ori_filename,h5in_new_filename): # h5in_ori_filename = "imposed_000.h5.feioutput" # h5in_new_filename = "imposed_111.h5.feioutput" h5_ori_file=h5py.File(h5in_ori_filename,"r") h5_new_file=h5py.File(h5in_new_filename,"r") # [()] is a must. Otherwise, result will be a dataset, not an array. disp_all_ori_c=h5_ori_file['/Model/Nodes/Generalized_Displacements'][()] disp_all_new_c=h5_new_file['/Model/Nodes/Generalized_Displacements'][()] # delete the last column disp_all_ori=disp_all_ori_c[:,:] disp_all_new=disp_all_new_c[:,:] # tolerance setting for the overflow and underflow. max_rel_tolerance=1e-03 max_tolerance=1e-03 print_header_flag=0 pass_fail_flag=1 for index, x in np.ndenumerate(disp_all_ori): if abs(( np.float32(x) - np.float32(disp_all_new[index]) ) / (np.float32(x) + epsilon) )> max_rel_tolerance or abs( np.float32(x) - np.float32(disp_all_new[index]) ) > max_tolerance: pass_fail_flag=0 if print_header_flag==0: print_header_flag=1 print headwrongstep(), "================================================" print headwrongstep(), "| Generalized_Displacements have mismatches: | " print headwrongstep(), "================================================" print headwrongstep(), "| Location |Original_value | New_value | " print headwrongstep(), "|",'{:12s}'.format(index) ,"|", '{:+e}'.format(x) ,"|",'{:+e}'.format(disp_all_new[index]) ,"|" # print "================================================" return pass_fail_flag def h5diff_Gauss_output(h5in_ori_filename,h5in_new_filename): h5_ori_file=h5py.File(h5in_ori_filename,"r") h5_new_file=h5py.File(h5in_new_filename,"r") outputs_all_ori_c=h5_ori_file['/Model/Elements/Gauss_Outputs'][()] outputs_all_new_c=h5_new_file['/Model/Elements/Gauss_Outputs'][()] # delete the last column outputs_all_ori=outputs_all_ori_c[:,:] outputs_all_new=outputs_all_new_c[:,:] # tolerance setting for the overflow and underflow. max_rel_tolerance=1e-03 max_tolerance=1e-03 print_header_flag=0 pass_fail_flag=1 for index, x in np.ndenumerate(outputs_all_ori): if abs(( np.float32(x) - np.float32(outputs_all_new[index]) ) / (np.float32(x) + epsilon) )> max_rel_tolerance or abs( np.float32(x) - np.float32(outputs_all_new[index]) ) > max_tolerance: pass_fail_flag=0 if print_header_flag==0: print_header_flag=1 print headwrongstep(),"================================================" print headwrongstep(),"|Gauss outputs (stress strain) have mismatches: " print headwrongstep(),"================================================" print headwrongstep(),"| Location |Original_value | New_value | " # print "|",index,"|", x ,"|", outputs_all_new[index],"|" print headwrongstep(), "|",'{:12s}'.format(index) ,"|", '{:+e}'.format(x) ,"|",'{:+e}'.format(outputs_all_new[index]) ,"|" return pass_fail_flag def h5diff_Element_output(h5in_ori_filename,h5in_new_filename): h5_ori_file=h5py.File(h5in_ori_filename,"r") h5_new_file=h5py.File(h5in_new_filename,"r") outputs_all_ori_c=h5_ori_file['/Model/Elements/Element_Outputs'][()] outputs_all_new_c=h5_new_file['/Model/Elements/Element_Outputs'][()] # delete the last column outputs_all_ori=outputs_all_ori_c[:,:] outputs_all_new=outputs_all_new_c[:,:] # tolerance setting for the overflow and underflow. max_rel_tolerance=1e-03 max_tolerance=1e-03 print_header_flag=0 pass_fail_flag=1 for index, x in np.ndenumerate(outputs_all_ori): if abs(( np.float32(x) - np.float32(outputs_all_new[index]) ) / (np.float32(x) + epsilon) )> max_rel_tolerance or abs( np.float32(x) - np.float32(outputs_all_new[index]) ) > max_tolerance: pass_fail_flag=0 if print_header_flag==0: print_header_flag=1 print headwrongstep(),"================================================" print headwrongstep(),"|Element outputs have mismatches: " print headwrongstep(),"================================================" print headwrongstep(),"| Location |Original_value | New_value | " # print "|",index,"|", x ,"|", outputs_all_new[index],"|" print headwrongstep(), "|",'{:12s}'.format(index) ,"|", '{:+e}'.format(x) ,"|",'{:+e}'.format(outputs_all_new[index]) ,"|" return pass_fail_flag def find_max_disp(h5in_file_name,_step): h5file_in=h5py.File(h5in_file_name,"r") # [()] is a must. Otherwise, disp will be a dataset, not an array. dispall=h5file_in['/Model/Nodes/Generalized_Displacements'][()] # Select the step. disp=dispall[:,_step] # axis =0 is a must. Otherwise, disp will be sorted along the first axis. disp=np.sort(disp,axis=0) # If disp[0] is negative, disp[0] will become the positive value. # Elseif disp[0] is positive, disp[0] will be the smaller positive value # in the sorted array. disp[0]=-disp[0] # disp[-1] is the last (biggest) element in the sorted array. max_disp=max(disp[0],disp[-1]) return max_disp def find_disp_Nstep(h5in_file_name): h5file_in=h5py.File(h5in_file_name,"r") # [()] is a must. Otherwise, disp will be a dataset, not an array. dispall=h5file_in['/Model/Nodes/Generalized_Displacements'][()] return dispall.shape[1] def h5diff_eigen_frequency(h5in_ori_filename, h5in_new_filename): # h5in_ori_filename = "imposed_000.h5.feioutput" # h5in_new_filename = "imposed_111.h5.feioutput" h5_ori_file=h5py.File(h5in_ori_filename,"r") h5_new_file=h5py.File(h5in_new_filename,"r") # [()] is a must. Otherwise, result will be a dataset, not an array. eigen_all_ori=h5_ori_file['/Eigen_Mode_Analysis/frequencies'][()] eigen_all_new=h5_new_file['/Eigen_Mode_Analysis/frequencies'][()] # tolerance setting for the overflow and underflow. max_rel_tolerance=1e-03 max_tolerance=1e-03 print_header_flag=0 pass_fail_flag=1 for index, x in np.ndenumerate(eigen_all_ori): if abs(( np.float32(x) - np.float32(eigen_all_new[index]) ) / (np.float32(x) + epsilon) )> max_rel_tolerance or abs( np.float32(x) - np.float32(eigen_all_new[index]) ) > max_tolerance: pass_fail_flag=0 if print_header_flag==0: print_header_flag=1 print headwrongstep(), "================================================" print headwrongstep(), "| Eigen_Analysis Frequencies have mismatches: |" print headwrongstep(), "================================================" print headwrongstep(), "| Location |Original_value | New_value | " print headwrongstep(), "|",'{:12s}'.format(index) ,"|", '{:+e}'.format(x) ,"|",'{:+e}'.format(eigen_all_new[index]) ,"|" # print "================================================" return pass_fail_flag # legacy backup # h5in_file_name=sys.argv[1] # h5in_file_name="t_1.h5.feioutput" # h5in_file_name="0_Fz.h5.feioutput"
cc0-1.0
zhengyongbo/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/common/editdistance.py
138
2351
# Copyright (c) 2011 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. from array import array def edit_distance(str1, str2): unsignedShort = 'h' distances = [array(unsignedShort, (0,) * (len(str2) + 1)) for i in range(0, len(str1) + 1)] # distances[0][0] = 0 since distance between str1[:0] and str2[:0] is 0 for i in range(1, len(str1) + 1): distances[i][0] = i # Distance between str1[:i] and str2[:0] is i for j in range(1, len(str2) + 1): distances[0][j] = j # Distance between str1[:0] and str2[:j] is j for i in range(0, len(str1)): for j in range(0, len(str2)): diff = 0 if str1[i] == str2[j] else 1 # Deletion, Insertion, Identical / Replacement distances[i + 1][j + 1] = min(distances[i + 1][j] + 1, distances[i][j + 1] + 1, distances[i][j] + diff) return distances[len(str1)][len(str2)]
bsd-3-clause
jamespcole/home-assistant
homeassistant/components/template/cover.py
4
15965
""" Support for covers which integrate with other components. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/cover.template/ """ import logging import voluptuous as vol from homeassistant.core import callback from homeassistant.components.cover import ( ENTITY_ID_FORMAT, CoverDevice, PLATFORM_SCHEMA, SUPPORT_OPEN_TILT, SUPPORT_CLOSE_TILT, SUPPORT_STOP_TILT, SUPPORT_SET_TILT_POSITION, SUPPORT_OPEN, SUPPORT_CLOSE, SUPPORT_STOP, SUPPORT_SET_POSITION, ATTR_POSITION, ATTR_TILT_POSITION) from homeassistant.const import ( CONF_FRIENDLY_NAME, CONF_ENTITY_ID, EVENT_HOMEASSISTANT_START, MATCH_ALL, CONF_VALUE_TEMPLATE, CONF_ICON_TEMPLATE, CONF_ENTITY_PICTURE_TEMPLATE, CONF_OPTIMISTIC, STATE_OPEN, STATE_CLOSED) from homeassistant.exceptions import TemplateError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.event import async_track_state_change from homeassistant.helpers.script import Script _LOGGER = logging.getLogger(__name__) _VALID_STATES = [STATE_OPEN, STATE_CLOSED, 'true', 'false'] CONF_COVERS = 'covers' CONF_POSITION_TEMPLATE = 'position_template' CONF_TILT_TEMPLATE = 'tilt_template' OPEN_ACTION = 'open_cover' CLOSE_ACTION = 'close_cover' STOP_ACTION = 'stop_cover' POSITION_ACTION = 'set_cover_position' TILT_ACTION = 'set_cover_tilt_position' CONF_TILT_OPTIMISTIC = 'tilt_optimistic' CONF_VALUE_OR_POSITION_TEMPLATE = 'value_or_position' CONF_OPEN_OR_CLOSE = 'open_or_close' TILT_FEATURES = (SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_STOP_TILT | SUPPORT_SET_TILT_POSITION) COVER_SCHEMA = vol.Schema({ vol.Inclusive(OPEN_ACTION, CONF_OPEN_OR_CLOSE): cv.SCRIPT_SCHEMA, vol.Inclusive(CLOSE_ACTION, CONF_OPEN_OR_CLOSE): cv.SCRIPT_SCHEMA, vol.Optional(STOP_ACTION): cv.SCRIPT_SCHEMA, vol.Exclusive(CONF_POSITION_TEMPLATE, CONF_VALUE_OR_POSITION_TEMPLATE): cv.template, vol.Exclusive(CONF_VALUE_TEMPLATE, CONF_VALUE_OR_POSITION_TEMPLATE): cv.template, vol.Optional(CONF_POSITION_TEMPLATE): cv.template, vol.Optional(CONF_TILT_TEMPLATE): cv.template, vol.Optional(CONF_ICON_TEMPLATE): cv.template, vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template, vol.Optional(CONF_OPTIMISTIC): cv.boolean, vol.Optional(CONF_TILT_OPTIMISTIC): cv.boolean, vol.Optional(POSITION_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(TILT_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(CONF_FRIENDLY_NAME): cv.string, vol.Optional(CONF_ENTITY_ID): cv.entity_ids }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_COVERS): cv.schema_with_slug_keys(COVER_SCHEMA), }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Template cover.""" covers = [] for device, device_config in config[CONF_COVERS].items(): friendly_name = device_config.get(CONF_FRIENDLY_NAME, device) state_template = device_config.get(CONF_VALUE_TEMPLATE) position_template = device_config.get(CONF_POSITION_TEMPLATE) tilt_template = device_config.get(CONF_TILT_TEMPLATE) icon_template = device_config.get(CONF_ICON_TEMPLATE) entity_picture_template = device_config.get( CONF_ENTITY_PICTURE_TEMPLATE) open_action = device_config.get(OPEN_ACTION) close_action = device_config.get(CLOSE_ACTION) stop_action = device_config.get(STOP_ACTION) position_action = device_config.get(POSITION_ACTION) tilt_action = device_config.get(TILT_ACTION) optimistic = device_config.get(CONF_OPTIMISTIC) tilt_optimistic = device_config.get(CONF_TILT_OPTIMISTIC) if position_action is None and open_action is None: _LOGGER.error('Must specify at least one of %s' or '%s', OPEN_ACTION, POSITION_ACTION) continue template_entity_ids = set() if state_template is not None: temp_ids = state_template.extract_entities() if str(temp_ids) != MATCH_ALL: template_entity_ids |= set(temp_ids) if position_template is not None: temp_ids = position_template.extract_entities() if str(temp_ids) != MATCH_ALL: template_entity_ids |= set(temp_ids) if tilt_template is not None: temp_ids = tilt_template.extract_entities() if str(temp_ids) != MATCH_ALL: template_entity_ids |= set(temp_ids) if icon_template is not None: temp_ids = icon_template.extract_entities() if str(temp_ids) != MATCH_ALL: template_entity_ids |= set(temp_ids) if entity_picture_template is not None: temp_ids = entity_picture_template.extract_entities() if str(temp_ids) != MATCH_ALL: template_entity_ids |= set(temp_ids) if not template_entity_ids: template_entity_ids = MATCH_ALL entity_ids = device_config.get(CONF_ENTITY_ID, template_entity_ids) covers.append( CoverTemplate( hass, device, friendly_name, state_template, position_template, tilt_template, icon_template, entity_picture_template, open_action, close_action, stop_action, position_action, tilt_action, optimistic, tilt_optimistic, entity_ids ) ) if not covers: _LOGGER.error("No covers added") return False async_add_entities(covers) return True class CoverTemplate(CoverDevice): """Representation of a Template cover.""" def __init__(self, hass, device_id, friendly_name, state_template, position_template, tilt_template, icon_template, entity_picture_template, open_action, close_action, stop_action, position_action, tilt_action, optimistic, tilt_optimistic, entity_ids): """Initialize the Template cover.""" self.hass = hass self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass) self._name = friendly_name self._template = state_template self._position_template = position_template self._tilt_template = tilt_template self._icon_template = icon_template self._entity_picture_template = entity_picture_template self._open_script = None if open_action is not None: self._open_script = Script(hass, open_action) self._close_script = None if close_action is not None: self._close_script = Script(hass, close_action) self._stop_script = None if stop_action is not None: self._stop_script = Script(hass, stop_action) self._position_script = None if position_action is not None: self._position_script = Script(hass, position_action) self._tilt_script = None if tilt_action is not None: self._tilt_script = Script(hass, tilt_action) self._optimistic = (optimistic or (not state_template and not position_template)) self._tilt_optimistic = tilt_optimistic or not tilt_template self._icon = None self._entity_picture = None self._position = None self._tilt_value = None self._entities = entity_ids if self._template is not None: self._template.hass = self.hass if self._position_template is not None: self._position_template.hass = self.hass if self._tilt_template is not None: self._tilt_template.hass = self.hass if self._icon_template is not None: self._icon_template.hass = self.hass if self._entity_picture_template is not None: self._entity_picture_template.hass = self.hass async def async_added_to_hass(self): """Register callbacks.""" @callback def template_cover_state_listener(entity, old_state, new_state): """Handle target device state changes.""" self.async_schedule_update_ha_state(True) @callback def template_cover_startup(event): """Update template on startup.""" async_track_state_change( self.hass, self._entities, template_cover_state_listener) self.async_schedule_update_ha_state(True) self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_START, template_cover_startup) @property def name(self): """Return the name of the cover.""" return self._name @property def is_closed(self): """Return if the cover is closed.""" return self._position == 0 @property def current_cover_position(self): """Return current position of cover. None is unknown, 0 is closed, 100 is fully open. """ if self._position_template or self._position_script: return self._position return None @property def current_cover_tilt_position(self): """Return current position of cover tilt. None is unknown, 0 is closed, 100 is fully open. """ return self._tilt_value @property def icon(self): """Return the icon to use in the frontend, if any.""" return self._icon @property def entity_picture(self): """Return the entity picture to use in the frontend, if any.""" return self._entity_picture @property def supported_features(self): """Flag supported features.""" supported_features = SUPPORT_OPEN | SUPPORT_CLOSE if self._stop_script is not None: supported_features |= SUPPORT_STOP if self._position_script is not None: supported_features |= SUPPORT_SET_POSITION if self.current_cover_tilt_position is not None: supported_features |= TILT_FEATURES return supported_features @property def should_poll(self): """Return the polling state.""" return False async def async_open_cover(self, **kwargs): """Move the cover up.""" if self._open_script: await self._open_script.async_run(context=self._context) elif self._position_script: await self._position_script.async_run( {"position": 100}, context=self._context) if self._optimistic: self._position = 100 self.async_schedule_update_ha_state() async def async_close_cover(self, **kwargs): """Move the cover down.""" if self._close_script: await self._close_script.async_run(context=self._context) elif self._position_script: await self._position_script.async_run( {"position": 0}, context=self._context) if self._optimistic: self._position = 0 self.async_schedule_update_ha_state() async def async_stop_cover(self, **kwargs): """Fire the stop action.""" if self._stop_script: await self._stop_script.async_run(context=self._context) async def async_set_cover_position(self, **kwargs): """Set cover position.""" self._position = kwargs[ATTR_POSITION] await self._position_script.async_run( {"position": self._position}, context=self._context) if self._optimistic: self.async_schedule_update_ha_state() async def async_open_cover_tilt(self, **kwargs): """Tilt the cover open.""" self._tilt_value = 100 await self._tilt_script.async_run( {"tilt": self._tilt_value}, context=self._context) if self._tilt_optimistic: self.async_schedule_update_ha_state() async def async_close_cover_tilt(self, **kwargs): """Tilt the cover closed.""" self._tilt_value = 0 await self._tilt_script.async_run( {"tilt": self._tilt_value}, context=self._context) if self._tilt_optimistic: self.async_schedule_update_ha_state() async def async_set_cover_tilt_position(self, **kwargs): """Move the cover tilt to a specific position.""" self._tilt_value = kwargs[ATTR_TILT_POSITION] await self._tilt_script.async_run( {"tilt": self._tilt_value}, context=self._context) if self._tilt_optimistic: self.async_schedule_update_ha_state() async def async_update(self): """Update the state from the template.""" if self._template is not None: try: state = self._template.async_render().lower() if state in _VALID_STATES: if state in ('true', STATE_OPEN): self._position = 100 else: self._position = 0 else: _LOGGER.error( 'Received invalid cover is_on state: %s. Expected: %s', state, ', '.join(_VALID_STATES)) self._position = None except TemplateError as ex: _LOGGER.error(ex) self._position = None if self._position_template is not None: try: state = float(self._position_template.async_render()) if state < 0 or state > 100: self._position = None _LOGGER.error("Cover position value must be" " between 0 and 100." " Value was: %.2f", state) else: self._position = state except TemplateError as ex: _LOGGER.error(ex) self._position = None except ValueError as ex: _LOGGER.error(ex) self._position = None if self._tilt_template is not None: try: state = float(self._tilt_template.async_render()) if state < 0 or state > 100: self._tilt_value = None _LOGGER.error("Tilt value must be between 0 and 100." " Value was: %.2f", state) else: self._tilt_value = state except TemplateError as ex: _LOGGER.error(ex) self._tilt_value = None except ValueError as ex: _LOGGER.error(ex) self._tilt_value = None for property_name, template in ( ('_icon', self._icon_template), ('_entity_picture', self._entity_picture_template)): if template is None: continue try: setattr(self, property_name, template.async_render()) except TemplateError as ex: friendly_property_name = property_name[1:].replace('_', ' ') if ex.args and ex.args[0].startswith( "UndefinedError: 'None' has no attribute"): # Common during HA startup - so just a warning _LOGGER.warning('Could not render %s template %s,' ' the state is unknown.', friendly_property_name, self._name) return try: setattr(self, property_name, getattr(super(), property_name)) except AttributeError: _LOGGER.error('Could not render %s template %s: %s', friendly_property_name, self._name, ex)
apache-2.0
jamespcole/home-assistant
homeassistant/components/ps4/media_player.py
1
12386
""" Support for PlayStation 4 consoles. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/ps4/ """ import logging import socket import voluptuous as vol from homeassistant.components.media_player import ( ENTITY_IMAGE_URL, MediaPlayerDevice) from homeassistant.components.media_player.const import ( MEDIA_TYPE_GAME, SUPPORT_SELECT_SOURCE, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON) from homeassistant.const import ( ATTR_COMMAND, ATTR_ENTITY_ID, CONF_HOST, CONF_NAME, CONF_REGION, CONF_TOKEN, STATE_IDLE, STATE_OFF, STATE_PLAYING) import homeassistant.helpers.config_validation as cv from homeassistant.util.json import load_json, save_json from .const import DOMAIN as PS4_DOMAIN, REGIONS as deprecated_regions DEPENDENCIES = ['ps4'] _LOGGER = logging.getLogger(__name__) SUPPORT_PS4 = SUPPORT_TURN_OFF | SUPPORT_TURN_ON | \ SUPPORT_STOP | SUPPORT_SELECT_SOURCE PS4_DATA = 'ps4_data' ICON = 'mdi:playstation' GAMES_FILE = '.ps4-games.json' MEDIA_IMAGE_DEFAULT = None COMMANDS = ( 'up', 'down', 'right', 'left', 'enter', 'back', 'option', 'ps', ) SERVICE_COMMAND = 'send_command' PS4_COMMAND_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_COMMAND): vol.In(list(COMMANDS)) }) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up PS4 from a config entry.""" config = config_entry def add_entities(entities, update_before_add=False): """Sync version of async add devices.""" hass.add_job(async_add_entities, entities, update_before_add) await hass.async_add_executor_job( setup_platform, hass, config, add_entities, None) async def async_service_handle(hass): """Handle for services.""" def service_command(call): entity_ids = call.data[ATTR_ENTITY_ID] command = call.data[ATTR_COMMAND] for device in hass.data[PS4_DATA].devices: if device.entity_id in entity_ids: device.send_command(command) hass.services.async_register( PS4_DOMAIN, SERVICE_COMMAND, service_command, schema=PS4_COMMAND_SCHEMA) await async_service_handle(hass) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up PS4 Platform.""" import pyps4_homeassistant as pyps4 hass.data[PS4_DATA] = PS4Data() games_file = hass.config.path(GAMES_FILE) creds = config.data[CONF_TOKEN] device_list = [] for device in config.data['devices']: host = device[CONF_HOST] region = device[CONF_REGION] name = device[CONF_NAME] ps4 = pyps4.Ps4(host, creds) device_list.append(PS4Device( name, host, region, ps4, games_file)) add_entities(device_list, True) class PS4Data(): """Init Data Class.""" def __init__(self): """Init Class.""" self.devices = [] class PS4Device(MediaPlayerDevice): """Representation of a PS4.""" def __init__(self, name, host, region, ps4, games_file): """Initialize the ps4 device.""" self._ps4 = ps4 self._host = host self._name = name self._region = region self._state = None self._games_filename = games_file self._media_content_id = None self._media_title = None self._media_image = None self._source = None self._games = {} self._source_list = [] self._retry = 0 self._info = None self._unique_id = None self._power_on = False async def async_added_to_hass(self): """Subscribe PS4 events.""" self.hass.data[PS4_DATA].devices.append(self) def update(self): """Retrieve the latest data.""" try: status = self._ps4.get_status() if self._info is None: # Add entity to registry self.get_device_info(status) self._games = self.load_games() if self._games is not None: self._source_list = list(sorted(self._games.values())) # Non-Breaking although data returned may be inaccurate. if self._region in deprecated_regions: _LOGGER.info("""Region: %s has been deprecated. Please remove PS4 integration and Re-configure again to utilize current regions""", self._region) except socket.timeout: status = None if status is not None: self._retry = 0 if status.get('status') == 'Ok': # Check if only 1 device in Hass. if len(self.hass.data[PS4_DATA].devices) == 1: # Enable keep alive feature for PS4 Connection. # Only 1 device is supported, Since have to use port 997. self._ps4.keep_alive = True else: self._ps4.keep_alive = False if self._power_on: # Auto Login after Turn On. self._ps4.open() self._power_on = False title_id = status.get('running-app-titleid') name = status.get('running-app-name') if title_id and name is not None: self._state = STATE_PLAYING if self._media_content_id != title_id: self._media_content_id = title_id self.get_title_data(title_id, name) else: self.idle() else: self.state_off() elif self._retry > 5: self.state_unknown() else: self._retry += 1 def idle(self): """Set states for state idle.""" self.reset_title() self._state = STATE_IDLE def state_off(self): """Set states for state off.""" self.reset_title() self._state = STATE_OFF def state_unknown(self): """Set states for state unknown.""" self.reset_title() self._state = None _LOGGER.warning("PS4 could not be reached") self._retry = 0 def reset_title(self): """Update if there is no title.""" self._media_title = None self._media_content_id = None self._source = None def get_title_data(self, title_id, name): """Get PS Store Data.""" app_name = None art = None try: app_name, art = self._ps4.get_ps_store_data( name, title_id, self._region) except TypeError: _LOGGER.error( "Could not find data in region: %s for PS ID: %s", self._region, title_id) finally: self._media_title = app_name or name self._source = self._media_title self._media_image = art self.update_list() def update_list(self): """Update Game List, Correct data if different.""" if self._media_content_id in self._games: store = self._games[self._media_content_id] if store != self._media_title: self._games.pop(self._media_content_id) if self._media_content_id not in self._games: self.add_games(self._media_content_id, self._media_title) self._games = self.load_games() self._source_list = list(sorted(self._games.values())) def load_games(self): """Load games for sources.""" g_file = self._games_filename try: games = load_json(g_file) # If file does not exist, create empty file. except FileNotFoundError: games = {} self.save_games(games) return games def save_games(self, games): """Save games to file.""" g_file = self._games_filename try: save_json(g_file, games) except OSError as error: _LOGGER.error("Could not save game list, %s", error) # Retry loading file if games is None: self.load_games() def add_games(self, title_id, app_name): """Add games to list.""" games = self._games if title_id is not None and title_id not in games: game = {title_id: app_name} games.update(game) self.save_games(games) def get_device_info(self, status): """Return device info for registry.""" _sw_version = status['system-version'] _sw_version = _sw_version[1:4] sw_version = "{}.{}".format(_sw_version[0], _sw_version[1:]) self._info = { 'name': status['host-name'], 'model': 'PlayStation 4', 'identifiers': { (PS4_DOMAIN, status['host-id']) }, 'manufacturer': 'Sony Interactive Entertainment Inc.', 'sw_version': sw_version } self._unique_id = status['host-id'] async def async_will_remove_from_hass(self): """Remove Entity from Hass.""" # Close TCP Socket await self.hass.async_add_executor_job(self._ps4.close) self.hass.data[PS4_DATA].devices.remove(self) @property def device_info(self): """Return information about the device.""" return self._info @property def unique_id(self): """Return Unique ID for entity.""" return self._unique_id @property def entity_picture(self): """Return picture.""" if self._state == STATE_PLAYING and self._media_content_id is not None: image_hash = self.media_image_hash if image_hash is not None: return ENTITY_IMAGE_URL.format( self.entity_id, self.access_token, image_hash) return MEDIA_IMAGE_DEFAULT @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def icon(self): """Icon.""" return ICON @property def media_content_id(self): """Content ID of current playing media.""" return self._media_content_id @property def media_content_type(self): """Content type of current playing media.""" return MEDIA_TYPE_GAME @property def media_image_url(self): """Image url of current playing media.""" if self._media_content_id is None: return MEDIA_IMAGE_DEFAULT return self._media_image @property def media_title(self): """Title of current playing media.""" return self._media_title @property def supported_features(self): """Media player features that are supported.""" return SUPPORT_PS4 @property def source(self): """Return the current input source.""" return self._source @property def source_list(self): """List of available input sources.""" return self._source_list def turn_off(self): """Turn off media player.""" self._ps4.standby() def turn_on(self): """Turn on the media player.""" self._power_on = True self._ps4.wakeup() def media_pause(self): """Send keypress ps to return to menu.""" self.send_remote_control('ps') def media_stop(self): """Send keypress ps to return to menu.""" self.send_remote_control('ps') def select_source(self, source): """Select input source.""" for title_id, game in self._games.items(): if source == game: _LOGGER.debug( "Starting PS4 game %s (%s) using source %s", game, title_id, source) self._ps4.start_title( title_id, running_id=self._media_content_id) return def send_command(self, command): """Send Button Command.""" self.send_remote_control(command) def send_remote_control(self, command): """Send RC command.""" self._ps4.remote_control(command)
apache-2.0
odooindia/odoo
addons/crm/__openerp__.py
40
4506
# -*- 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/>. # ############################################################################## { 'name': 'CRM', 'version': '1.0', 'category': 'Customer Relationship Management', 'sequence': 2, 'summary': 'Leads, Opportunities, Phone Calls', 'description': """ The generic OpenERP Customer Relationship Management ==================================================== This application enables a group of people to intelligently and efficiently manage leads, opportunities, meetings and phone calls. It manages key tasks such as communication, identification, prioritization, assignment, resolution and notification. OpenERP ensures that all cases are successfully tracked by users, customers and suppliers. It can automatically send reminders, escalate the request, trigger specific methods and many other actions based on your own enterprise rules. The greatest thing about this system is that users don't need to do anything special. The CRM module has an email gateway for the synchronization interface between mails and OpenERP. That way, users can just send emails to the request tracker. OpenERP will take care of thanking them for their message, automatically routing it to the appropriate staff and make sure all future correspondence gets to the right place. Dashboard for CRM will include: ------------------------------- * Planned Revenue by Stage and User (graph) * Opportunities by Stage (graph) """, 'author': 'OpenERP SA', 'website': 'http://www.openerp.com', 'depends': [ 'base_action_rule', 'base_setup', 'sales_team', 'mail', 'email_template', 'calendar', 'resource', 'board', 'fetchmail', ], 'data': [ 'crm_data.xml', 'crm_lead_data.xml', 'crm_phonecall_data.xml', 'security/crm_security.xml', 'security/ir.model.access.csv', 'wizard/crm_lead_to_opportunity_view.xml', 'wizard/crm_phonecall_to_phonecall_view.xml', 'wizard/crm_merge_opportunities_view.xml', 'crm_view.xml', 'crm_phonecall_view.xml', 'crm_phonecall_menu.xml', 'crm_lead_view.xml', 'crm_lead_menu.xml', 'calendar_event_menu.xml', 'report/crm_lead_report_view.xml', 'report/crm_phonecall_report_view.xml', 'res_partner_view.xml', 'res_config_view.xml', 'base_partner_merge_view.xml', 'sales_team_view.xml', ], 'demo': [ 'crm_demo.xml', 'crm_lead_demo.xml', 'crm_phonecall_demo.xml', 'crm_action_rule_demo.xml', ], 'test': [ 'test/crm_access_group_users.yml', 'test/crm_lead_message.yml', 'test/lead2opportunity2win.yml', 'test/lead2opportunity_assign_salesmen.yml', 'test/crm_lead_merge.yml', 'test/crm_lead_cancel.yml', 'test/segmentation.yml', 'test/phonecalls.yml', 'test/crm_lead_onchange.yml', 'test/crm_lead_copy.yml', 'test/crm_lead_unlink.yml', 'test/crm_lead_find_stage.yml', ], 'installable': True, 'application': True, 'auto_install': False, 'images': [ 'images/customers.png', 'images/leads.png', 'images/opportunities_kanban.png', 'images/opportunities_form.png', 'images/opportunities_calendar.png', 'images/opportunities_graph.png', 'images/logged_calls.png', 'images/scheduled_calls.png', 'images/stages.png', ], } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
paulfantom/AGH-weather-mqtt
weather.py
1
2385
#!/usr/bin/env python3 from urllib.request import urlopen from lxml import etree import re from utils.xmlhelper import etree2dict class Weather(object): def __init__(self,url=None): if url is None: self.url = "http://meteo.ftj.agh.edu.pl/meteo/meteo.xml" else: self.url = url self.data = None self.refresh() def refresh(self): with urlopen(self.url) as response: msg = response.read() tree = etree.fromstring(msg) self.data = etree2dict(tree)['meteo'] # def _format(self,data): unit = None try: val = re.match('(-|\d|\.)+',data).group(0) unit = data[len(val)+1:] val = float(val) except AttributeError: val = data return {'value' : val, 'unit' : unit } def basics(self): return {'temperature' : self.temperature(), 'humidity' : self.humidity(), 'pressure' : self.pressure(), 'windspeed' : self.windspeed()} def temperature(self): return self._format(self.data['dane_aktualne']['ta']) def humidity(self): return self._format(self.data['dane_aktualne']['ua']) def windchill(self): return self._format(self.data['dane_aktualne']['owindchill']) def dewpoint(self): return self._format(self.data['dane_aktualne']['odew']) def heatindex(self): return self._format(self.data['dane_aktualne']['oheatindex']) def windspeed(self): return self.windspeedavg() def windspeedavg(self): return self._format(self.data['dane_aktualne']['sm']) def windspeedmax(self): return self._format(self.data['dane_aktualne']['sx']) def winddirection(self): return self._format(self.data['dane_aktualne']['dm']) def pressure(self): return self.pressuresea() def pressuresea(self): return self._format(self.data['dane_aktualne']['barosealevel']) def pressurealt(self): return self._format(self.data['dane_aktualne']['pa']) def precipitation(self): return self._format(self.data['dane_aktualne']['rc']) def tendency(self): return self.data['dane_aktualne']['tendency'] if __name__ == '__main__': #print(Weather().data) print(Weather().basics())
mit
anakinsolo/backend
Lib/encodings/cp1258.py
593
13620
""" Python Character Mapping Codec cp1258 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1258.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='cp1258', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( u'\x00' # 0x00 -> NULL u'\x01' # 0x01 -> START OF HEADING u'\x02' # 0x02 -> START OF TEXT u'\x03' # 0x03 -> END OF TEXT u'\x04' # 0x04 -> END OF TRANSMISSION u'\x05' # 0x05 -> ENQUIRY u'\x06' # 0x06 -> ACKNOWLEDGE u'\x07' # 0x07 -> BELL u'\x08' # 0x08 -> BACKSPACE u'\t' # 0x09 -> HORIZONTAL TABULATION u'\n' # 0x0A -> LINE FEED u'\x0b' # 0x0B -> VERTICAL TABULATION u'\x0c' # 0x0C -> FORM FEED u'\r' # 0x0D -> CARRIAGE RETURN u'\x0e' # 0x0E -> SHIFT OUT u'\x0f' # 0x0F -> SHIFT IN u'\x10' # 0x10 -> DATA LINK ESCAPE u'\x11' # 0x11 -> DEVICE CONTROL ONE u'\x12' # 0x12 -> DEVICE CONTROL TWO u'\x13' # 0x13 -> DEVICE CONTROL THREE u'\x14' # 0x14 -> DEVICE CONTROL FOUR u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE u'\x16' # 0x16 -> SYNCHRONOUS IDLE u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK u'\x18' # 0x18 -> CANCEL u'\x19' # 0x19 -> END OF MEDIUM u'\x1a' # 0x1A -> SUBSTITUTE u'\x1b' # 0x1B -> ESCAPE u'\x1c' # 0x1C -> FILE SEPARATOR u'\x1d' # 0x1D -> GROUP SEPARATOR u'\x1e' # 0x1E -> RECORD SEPARATOR u'\x1f' # 0x1F -> UNIT SEPARATOR u' ' # 0x20 -> SPACE u'!' # 0x21 -> EXCLAMATION MARK u'"' # 0x22 -> QUOTATION MARK u'#' # 0x23 -> NUMBER SIGN u'$' # 0x24 -> DOLLAR SIGN u'%' # 0x25 -> PERCENT SIGN u'&' # 0x26 -> AMPERSAND u"'" # 0x27 -> APOSTROPHE u'(' # 0x28 -> LEFT PARENTHESIS u')' # 0x29 -> RIGHT PARENTHESIS u'*' # 0x2A -> ASTERISK u'+' # 0x2B -> PLUS SIGN u',' # 0x2C -> COMMA u'-' # 0x2D -> HYPHEN-MINUS u'.' # 0x2E -> FULL STOP u'/' # 0x2F -> SOLIDUS u'0' # 0x30 -> DIGIT ZERO u'1' # 0x31 -> DIGIT ONE u'2' # 0x32 -> DIGIT TWO u'3' # 0x33 -> DIGIT THREE u'4' # 0x34 -> DIGIT FOUR u'5' # 0x35 -> DIGIT FIVE u'6' # 0x36 -> DIGIT SIX u'7' # 0x37 -> DIGIT SEVEN u'8' # 0x38 -> DIGIT EIGHT u'9' # 0x39 -> DIGIT NINE u':' # 0x3A -> COLON u';' # 0x3B -> SEMICOLON u'<' # 0x3C -> LESS-THAN SIGN u'=' # 0x3D -> EQUALS SIGN u'>' # 0x3E -> GREATER-THAN SIGN u'?' # 0x3F -> QUESTION MARK u'@' # 0x40 -> COMMERCIAL AT u'A' # 0x41 -> LATIN CAPITAL LETTER A u'B' # 0x42 -> LATIN CAPITAL LETTER B u'C' # 0x43 -> LATIN CAPITAL LETTER C u'D' # 0x44 -> LATIN CAPITAL LETTER D u'E' # 0x45 -> LATIN CAPITAL LETTER E u'F' # 0x46 -> LATIN CAPITAL LETTER F u'G' # 0x47 -> LATIN CAPITAL LETTER G u'H' # 0x48 -> LATIN CAPITAL LETTER H u'I' # 0x49 -> LATIN CAPITAL LETTER I u'J' # 0x4A -> LATIN CAPITAL LETTER J u'K' # 0x4B -> LATIN CAPITAL LETTER K u'L' # 0x4C -> LATIN CAPITAL LETTER L u'M' # 0x4D -> LATIN CAPITAL LETTER M u'N' # 0x4E -> LATIN CAPITAL LETTER N u'O' # 0x4F -> LATIN CAPITAL LETTER O u'P' # 0x50 -> LATIN CAPITAL LETTER P u'Q' # 0x51 -> LATIN CAPITAL LETTER Q u'R' # 0x52 -> LATIN CAPITAL LETTER R u'S' # 0x53 -> LATIN CAPITAL LETTER S u'T' # 0x54 -> LATIN CAPITAL LETTER T u'U' # 0x55 -> LATIN CAPITAL LETTER U u'V' # 0x56 -> LATIN CAPITAL LETTER V u'W' # 0x57 -> LATIN CAPITAL LETTER W u'X' # 0x58 -> LATIN CAPITAL LETTER X u'Y' # 0x59 -> LATIN CAPITAL LETTER Y u'Z' # 0x5A -> LATIN CAPITAL LETTER Z u'[' # 0x5B -> LEFT SQUARE BRACKET u'\\' # 0x5C -> REVERSE SOLIDUS u']' # 0x5D -> RIGHT SQUARE BRACKET u'^' # 0x5E -> CIRCUMFLEX ACCENT u'_' # 0x5F -> LOW LINE u'`' # 0x60 -> GRAVE ACCENT u'a' # 0x61 -> LATIN SMALL LETTER A u'b' # 0x62 -> LATIN SMALL LETTER B u'c' # 0x63 -> LATIN SMALL LETTER C u'd' # 0x64 -> LATIN SMALL LETTER D u'e' # 0x65 -> LATIN SMALL LETTER E u'f' # 0x66 -> LATIN SMALL LETTER F u'g' # 0x67 -> LATIN SMALL LETTER G u'h' # 0x68 -> LATIN SMALL LETTER H u'i' # 0x69 -> LATIN SMALL LETTER I u'j' # 0x6A -> LATIN SMALL LETTER J u'k' # 0x6B -> LATIN SMALL LETTER K u'l' # 0x6C -> LATIN SMALL LETTER L u'm' # 0x6D -> LATIN SMALL LETTER M u'n' # 0x6E -> LATIN SMALL LETTER N u'o' # 0x6F -> LATIN SMALL LETTER O u'p' # 0x70 -> LATIN SMALL LETTER P u'q' # 0x71 -> LATIN SMALL LETTER Q u'r' # 0x72 -> LATIN SMALL LETTER R u's' # 0x73 -> LATIN SMALL LETTER S u't' # 0x74 -> LATIN SMALL LETTER T u'u' # 0x75 -> LATIN SMALL LETTER U u'v' # 0x76 -> LATIN SMALL LETTER V u'w' # 0x77 -> LATIN SMALL LETTER W u'x' # 0x78 -> LATIN SMALL LETTER X u'y' # 0x79 -> LATIN SMALL LETTER Y u'z' # 0x7A -> LATIN SMALL LETTER Z u'{' # 0x7B -> LEFT CURLY BRACKET u'|' # 0x7C -> VERTICAL LINE u'}' # 0x7D -> RIGHT CURLY BRACKET u'~' # 0x7E -> TILDE u'\x7f' # 0x7F -> DELETE u'\u20ac' # 0x80 -> EURO SIGN u'\ufffe' # 0x81 -> UNDEFINED u'\u201a' # 0x82 -> SINGLE LOW-9 QUOTATION MARK u'\u0192' # 0x83 -> LATIN SMALL LETTER F WITH HOOK u'\u201e' # 0x84 -> DOUBLE LOW-9 QUOTATION MARK u'\u2026' # 0x85 -> HORIZONTAL ELLIPSIS u'\u2020' # 0x86 -> DAGGER u'\u2021' # 0x87 -> DOUBLE DAGGER u'\u02c6' # 0x88 -> MODIFIER LETTER CIRCUMFLEX ACCENT u'\u2030' # 0x89 -> PER MILLE SIGN u'\ufffe' # 0x8A -> UNDEFINED u'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK u'\u0152' # 0x8C -> LATIN CAPITAL LIGATURE OE u'\ufffe' # 0x8D -> UNDEFINED u'\ufffe' # 0x8E -> UNDEFINED u'\ufffe' # 0x8F -> UNDEFINED u'\ufffe' # 0x90 -> UNDEFINED u'\u2018' # 0x91 -> LEFT SINGLE QUOTATION MARK u'\u2019' # 0x92 -> RIGHT SINGLE QUOTATION MARK u'\u201c' # 0x93 -> LEFT DOUBLE QUOTATION MARK u'\u201d' # 0x94 -> RIGHT DOUBLE QUOTATION MARK u'\u2022' # 0x95 -> BULLET u'\u2013' # 0x96 -> EN DASH u'\u2014' # 0x97 -> EM DASH u'\u02dc' # 0x98 -> SMALL TILDE u'\u2122' # 0x99 -> TRADE MARK SIGN u'\ufffe' # 0x9A -> UNDEFINED u'\u203a' # 0x9B -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK u'\u0153' # 0x9C -> LATIN SMALL LIGATURE OE u'\ufffe' # 0x9D -> UNDEFINED u'\ufffe' # 0x9E -> UNDEFINED u'\u0178' # 0x9F -> LATIN CAPITAL LETTER Y WITH DIAERESIS u'\xa0' # 0xA0 -> NO-BREAK SPACE u'\xa1' # 0xA1 -> INVERTED EXCLAMATION MARK u'\xa2' # 0xA2 -> CENT SIGN u'\xa3' # 0xA3 -> POUND SIGN u'\xa4' # 0xA4 -> CURRENCY SIGN u'\xa5' # 0xA5 -> YEN SIGN u'\xa6' # 0xA6 -> BROKEN BAR u'\xa7' # 0xA7 -> SECTION SIGN u'\xa8' # 0xA8 -> DIAERESIS u'\xa9' # 0xA9 -> COPYRIGHT SIGN u'\xaa' # 0xAA -> FEMININE ORDINAL INDICATOR u'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xac' # 0xAC -> NOT SIGN u'\xad' # 0xAD -> SOFT HYPHEN u'\xae' # 0xAE -> REGISTERED SIGN u'\xaf' # 0xAF -> MACRON u'\xb0' # 0xB0 -> DEGREE SIGN u'\xb1' # 0xB1 -> PLUS-MINUS SIGN u'\xb2' # 0xB2 -> SUPERSCRIPT TWO u'\xb3' # 0xB3 -> SUPERSCRIPT THREE u'\xb4' # 0xB4 -> ACUTE ACCENT u'\xb5' # 0xB5 -> MICRO SIGN u'\xb6' # 0xB6 -> PILCROW SIGN u'\xb7' # 0xB7 -> MIDDLE DOT u'\xb8' # 0xB8 -> CEDILLA u'\xb9' # 0xB9 -> SUPERSCRIPT ONE u'\xba' # 0xBA -> MASCULINE ORDINAL INDICATOR u'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK u'\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER u'\xbd' # 0xBD -> VULGAR FRACTION ONE HALF u'\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS u'\xbf' # 0xBF -> INVERTED QUESTION MARK u'\xc0' # 0xC0 -> LATIN CAPITAL LETTER A WITH GRAVE u'\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE u'\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX u'\u0102' # 0xC3 -> LATIN CAPITAL LETTER A WITH BREVE u'\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS u'\xc5' # 0xC5 -> LATIN CAPITAL LETTER A WITH RING ABOVE u'\xc6' # 0xC6 -> LATIN CAPITAL LETTER AE u'\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA u'\xc8' # 0xC8 -> LATIN CAPITAL LETTER E WITH GRAVE u'\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE u'\xca' # 0xCA -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX u'\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS u'\u0300' # 0xCC -> COMBINING GRAVE ACCENT u'\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE u'\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX u'\xcf' # 0xCF -> LATIN CAPITAL LETTER I WITH DIAERESIS u'\u0110' # 0xD0 -> LATIN CAPITAL LETTER D WITH STROKE u'\xd1' # 0xD1 -> LATIN CAPITAL LETTER N WITH TILDE u'\u0309' # 0xD2 -> COMBINING HOOK ABOVE u'\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE u'\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX u'\u01a0' # 0xD5 -> LATIN CAPITAL LETTER O WITH HORN u'\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS u'\xd7' # 0xD7 -> MULTIPLICATION SIGN u'\xd8' # 0xD8 -> LATIN CAPITAL LETTER O WITH STROKE u'\xd9' # 0xD9 -> LATIN CAPITAL LETTER U WITH GRAVE u'\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE u'\xdb' # 0xDB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX u'\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS u'\u01af' # 0xDD -> LATIN CAPITAL LETTER U WITH HORN u'\u0303' # 0xDE -> COMBINING TILDE u'\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S u'\xe0' # 0xE0 -> LATIN SMALL LETTER A WITH GRAVE u'\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE u'\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX u'\u0103' # 0xE3 -> LATIN SMALL LETTER A WITH BREVE u'\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS u'\xe5' # 0xE5 -> LATIN SMALL LETTER A WITH RING ABOVE u'\xe6' # 0xE6 -> LATIN SMALL LETTER AE u'\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA u'\xe8' # 0xE8 -> LATIN SMALL LETTER E WITH GRAVE u'\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE u'\xea' # 0xEA -> LATIN SMALL LETTER E WITH CIRCUMFLEX u'\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS u'\u0301' # 0xEC -> COMBINING ACUTE ACCENT u'\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE u'\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX u'\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS u'\u0111' # 0xF0 -> LATIN SMALL LETTER D WITH STROKE u'\xf1' # 0xF1 -> LATIN SMALL LETTER N WITH TILDE u'\u0323' # 0xF2 -> COMBINING DOT BELOW u'\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE u'\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX u'\u01a1' # 0xF5 -> LATIN SMALL LETTER O WITH HORN u'\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS u'\xf7' # 0xF7 -> DIVISION SIGN u'\xf8' # 0xF8 -> LATIN SMALL LETTER O WITH STROKE u'\xf9' # 0xF9 -> LATIN SMALL LETTER U WITH GRAVE u'\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE u'\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX u'\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS u'\u01b0' # 0xFD -> LATIN SMALL LETTER U WITH HORN u'\u20ab' # 0xFE -> DONG SIGN u'\xff' # 0xFF -> LATIN SMALL LETTER Y WITH DIAERESIS ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
mit
noelbk/neutron-juniper
neutron/agent/linux/ovsdb_monitor.py
5
4106
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet from neutron.agent.linux import async_process from neutron.openstack.common import log as logging LOG = logging.getLogger(__name__) class OvsdbMonitor(async_process.AsyncProcess): """Manages an invocation of 'ovsdb-client monitor'.""" def __init__(self, table_name, columns=None, format=None, root_helper=None, respawn_interval=None): cmd = ['ovsdb-client', 'monitor', table_name] if columns: cmd.append(','.join(columns)) if format: cmd.append('--format=%s' % format) super(OvsdbMonitor, self).__init__(cmd, root_helper=root_helper, respawn_interval=respawn_interval) def _read_stdout(self): data = self._process.stdout.readline() if not data: return #TODO(marun) The default root helper outputs exit errors to # stdout due to bug #1219530. This check can be moved to # _read_stderr once the error is correctly output to stderr. if self.root_helper and self.root_helper in data: self._stderr_lines.put(data) LOG.error(_('Error received from ovsdb monitor: %s') % data) else: self._stdout_lines.put(data) LOG.debug(_('Output received from ovsdb monitor: %s') % data) return data def _read_stderr(self): data = super(OvsdbMonitor, self)._read_stderr() if data: LOG.error(_('Error received from ovsdb monitor: %s') % data) # Do not return value to ensure that stderr output will # stop the monitor. class SimpleInterfaceMonitor(OvsdbMonitor): """Monitors the Interface table of the local host's ovsdb for changes. The has_updates() method indicates whether changes to the ovsdb Interface table have been detected since the monitor started or since the previous access. """ def __init__(self, root_helper=None, respawn_interval=None): super(SimpleInterfaceMonitor, self).__init__( 'Interface', columns=['name'], format='json', root_helper=root_helper, respawn_interval=respawn_interval, ) self.data_received = False @property def is_active(self): return (self.data_received and self._kill_event and not self._kill_event.ready()) @property def has_updates(self): """Indicate whether the ovsdb Interface table has been updated. True will be returned if the monitor process is not active. This 'failing open' minimizes the risk of falsely indicating the absence of updates at the expense of potential false positives. """ return bool(list(self.iter_stdout())) or not self.is_active def start(self, block=False, timeout=5): super(SimpleInterfaceMonitor, self).start() if block: eventlet.timeout.Timeout(timeout) while not self.is_active: eventlet.sleep() def _kill(self, *args, **kwargs): self.data_received = False super(SimpleInterfaceMonitor, self)._kill(*args, **kwargs) def _read_stdout(self): data = super(SimpleInterfaceMonitor, self)._read_stdout() if data and not self.data_received: self.data_received = True return data
apache-2.0
fuselock/odoo
addons/google_drive/google_drive.py
74
14765
############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2012 OpenERP SA (<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/>. # ############################################################################## import logging from openerp import SUPERUSER_ID from openerp.addons.google_account import TIMEOUT from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.tools.safe_eval import safe_eval as eval import werkzeug.urls import urllib2 import json import re import openerp _logger = logging.getLogger(__name__) class config(osv.Model): _name = 'google.drive.config' _description = "Google Drive templates config" def get_google_drive_url(self, cr, uid, config_id, res_id, template_id, context=None): config = self.browse(cr, SUPERUSER_ID, config_id, context=context) model = config.model_id filter_name = config.filter_id and config.filter_id.name or False record = self.pool.get(model.model).read(cr, uid, [res_id], context=context)[0] record.update({'model': model.name, 'filter': filter_name}) name_gdocs = config.name_template try: name_gdocs = name_gdocs % record except: raise osv.except_osv(_('Key Error!'), _("At least one key cannot be found in your Google Drive name pattern")) attach_pool = self.pool.get("ir.attachment") attach_ids = attach_pool.search(cr, uid, [('res_model', '=', model.model), ('name', '=', name_gdocs), ('res_id', '=', res_id)]) url = False if attach_ids: attachment = attach_pool.browse(cr, uid, attach_ids[0], context) url = attachment.url else: url = self.copy_doc(cr, uid, res_id, template_id, name_gdocs, model.model, context).get('url') return url def get_access_token(self, cr, uid, scope=None, context=None): ir_config = self.pool['ir.config_parameter'] google_drive_refresh_token = ir_config.get_param(cr, SUPERUSER_ID, 'google_drive_refresh_token') user_is_admin = self.pool['res.users'].has_group(cr, uid, 'base.group_erp_manager') if not google_drive_refresh_token: if user_is_admin: model, action_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'base_setup', 'action_general_configuration') msg = _("You haven't configured 'Authorization Code' generated from google, Please generate and configure it .") raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel')) else: raise osv.except_osv(_('Error!'), _("Google Drive is not yet configured. Please contact your administrator.")) google_drive_client_id = ir_config.get_param(cr, SUPERUSER_ID, 'google_drive_client_id') google_drive_client_secret = ir_config.get_param(cr, SUPERUSER_ID, 'google_drive_client_secret') #For Getting New Access Token With help of old Refresh Token data = werkzeug.url_encode(dict(client_id=google_drive_client_id, refresh_token=google_drive_refresh_token, client_secret=google_drive_client_secret, grant_type="refresh_token", scope=scope or 'https://www.googleapis.com/auth/drive')) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept-Encoding": "gzip, deflate"} try: req = urllib2.Request('https://accounts.google.com/o/oauth2/token', data, headers) content = urllib2.urlopen(req, timeout=TIMEOUT).read() except urllib2.HTTPError: if user_is_admin: model, action_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'base_setup', 'action_general_configuration') msg = _("Something went wrong during the token generation. Please request again an authorization code .") raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel')) else: raise osv.except_osv(_('Error!'), _("Google Drive is not yet configured. Please contact your administrator.")) content = json.loads(content) return content.get('access_token') def copy_doc(self, cr, uid, res_id, template_id, name_gdocs, res_model, context=None): ir_config = self.pool['ir.config_parameter'] google_web_base_url = ir_config.get_param(cr, SUPERUSER_ID, 'web.base.url') access_token = self.get_access_token(cr, uid, context=context) # Copy template in to drive with help of new access token request_url = "https://www.googleapis.com/drive/v2/files/%s?fields=parents/id&access_token=%s" % (template_id, access_token) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept-Encoding": "gzip, deflate"} try: req = urllib2.Request(request_url, None, headers) parents = urllib2.urlopen(req, timeout=TIMEOUT).read() except urllib2.HTTPError: raise osv.except_osv(_('Warning!'), _("The Google Template cannot be found. Maybe it has been deleted.")) parents_dict = json.loads(parents) record_url = "Click on link to open Record in Odoo\n %s/?db=%s#id=%s&model=%s" % (google_web_base_url, cr.dbname, res_id, res_model) data = {"title": name_gdocs, "description": record_url, "parents": parents_dict['parents']} request_url = "https://www.googleapis.com/drive/v2/files/%s/copy?access_token=%s" % (template_id, access_token) headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} data_json = json.dumps(data) # resp, content = Http().request(request_url, "POST", data_json, headers) req = urllib2.Request(request_url, data_json, headers) content = urllib2.urlopen(req, timeout=TIMEOUT).read() content = json.loads(content) res = {} if content.get('alternateLink'): attach_pool = self.pool.get("ir.attachment") attach_vals = {'res_model': res_model, 'name': name_gdocs, 'res_id': res_id, 'type': 'url', 'url': content['alternateLink']} res['id'] = attach_pool.create(cr, uid, attach_vals) # Commit in order to attach the document to the current object instance, even if the permissions has not been written. cr.commit() res['url'] = content['alternateLink'] key = self._get_key_from_url(res['url']) request_url = "https://www.googleapis.com/drive/v2/files/%s/permissions?emailMessage=This+is+a+drive+file+created+by+Odoo&sendNotificationEmails=false&access_token=%s" % (key, access_token) data = {'role': 'writer', 'type': 'anyone', 'value': '', 'withLink': True} try: req = urllib2.Request(request_url, json.dumps(data), headers) urllib2.urlopen(req, timeout=TIMEOUT) except urllib2.HTTPError: raise self.pool.get('res.config.settings').get_config_warning(cr, _("The permission 'reader' for 'anyone with the link' has not been written on the document"), context=context) user = self.pool['res.users'].browse(cr, uid, uid, context=context) if user.email: data = {'role': 'writer', 'type': 'user', 'value': user.email} try: req = urllib2.Request(request_url, json.dumps(data), headers) urllib2.urlopen(req, timeout=TIMEOUT) except urllib2.HTTPError: pass return res def get_google_drive_config(self, cr, uid, res_model, res_id, context=None): ''' Function called by the js, when no google doc are yet associated with a record, with the aim to create one. It will first seek for a google.docs.config associated with the model `res_model` to find out what's the template of google doc to copy (this is usefull if you want to start with a non-empty document, a type or a name different than the default values). If no config is associated with the `res_model`, then a blank text document with a default name is created. :param res_model: the object for which the google doc is created :param ids: the list of ids of the objects for which the google doc is created. This list is supposed to have a length of 1 element only (batch processing is not supported in the code, though nothing really prevent it) :return: the config id and config name ''' if not res_id: raise osv.except_osv(_('Google Drive Error!'), _("Creating google drive may only be done by one at a time.")) # check if a model is configured with a template config_ids = self.search(cr, uid, [('model_id', '=', res_model)], context=context) configs = [] for config in self.browse(cr, uid, config_ids, context=context): if config.filter_id: if (config.filter_id.user_id and config.filter_id.user_id.id != uid): #Private continue domain = [('id', 'in', [res_id])] + eval(config.filter_id.domain) local_context = context and context.copy() or {} local_context.update(eval(config.filter_id.context)) google_doc_configs = self.pool.get(config.filter_id.model_id).search(cr, uid, domain, context=local_context) if google_doc_configs: configs.append({'id': config.id, 'name': config.name}) else: configs.append({'id': config.id, 'name': config.name}) return configs def _get_key_from_url(self, url): mo = re.search("(key=|/d/)([A-Za-z0-9-_]+)", url) if mo: return mo.group(2) return None def _resource_get(self, cr, uid, ids, name, arg, context=None): result = {} for data in self.browse(cr, uid, ids, context): mo = self._get_key_from_url(data.google_drive_template_url) if mo: result[data.id] = mo else: raise osv.except_osv(_('Incorrect URL!'), _("Please enter a valid Google Document URL.")) return result def _client_id_get(self, cr, uid, ids, name, arg, context=None): result = {} client_id = self.pool['ir.config_parameter'].get_param(cr, SUPERUSER_ID, 'google_drive_client_id') for config_id in ids: result[config_id] = client_id return result _columns = { 'name': fields.char('Template Name', required=True), 'model_id': fields.many2one('ir.model', 'Model', ondelete='set null', required=True), 'model': fields.related('model_id', 'model', type='char', string='Model', readonly=True), 'filter_id': fields.many2one('ir.filters', 'Filter', domain="[('model_id', '=', model)]"), 'google_drive_template_url': fields.char('Template URL', required=True, size=1024), 'google_drive_resource_id': fields.function(_resource_get, type="char", string='Resource Id'), 'google_drive_client_id': fields.function(_client_id_get, type="char", string='Google Client '), 'name_template': fields.char('Google Drive Name Pattern', help='Choose how the new google drive will be named, on google side. Eg. gdoc_%(field_name)s', required=True), 'active': fields.boolean('Active'), } def onchange_model_id(self, cr, uid, ids, model_id, context=None): res = {} if model_id: model = self.pool['ir.model'].browse(cr, uid, model_id, context=context) res['value'] = {'model': model.model} else: res['value'] = {'filter_id': False, 'model': False} return res _defaults = { 'name_template': 'Document %(name)s', 'active': True, } def _check_model_id(self, cr, uid, ids, context=None): config_id = self.browse(cr, uid, ids[0], context=context) if config_id.filter_id and config_id.model_id.model != config_id.filter_id.model_id: return False return True _constraints = [ (_check_model_id, 'Model of selected filter is not matching with model of current template.', ['model_id', 'filter_id']), ] def get_google_scope(self): return 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file' class base_config_settings(osv.TransientModel): _inherit = "base.config.settings" _columns = { 'google_drive_authorization_code': fields.char('Authorization Code'), 'google_drive_uri': fields.char('URI', readonly=True, help="The URL to generate the authorization code from Google"), } _defaults = { 'google_drive_uri': lambda s, cr, uid, c: s.pool['google.service']._get_google_token_uri(cr, uid, 'drive', scope=s.pool['google.drive.config'].get_google_scope(), context=c), 'google_drive_authorization_code': lambda s, cr, uid, c: s.pool['ir.config_parameter'].get_param(cr, SUPERUSER_ID, 'google_drive_authorization_code', context=c), } def set_google_authorization_code(self, cr, uid, ids, context=None): ir_config_param = self.pool['ir.config_parameter'] config = self.browse(cr, uid, ids[0], context) auth_code = config.google_drive_authorization_code if auth_code and auth_code != ir_config_param.get_param(cr, uid, 'google_drive_authorization_code', context=context): refresh_token = self.pool['google.service'].generate_refresh_token(cr, uid, 'drive', config.google_drive_authorization_code, context=context) ir_config_param.set_param(cr, uid, 'google_drive_authorization_code', auth_code, groups=['base.group_system']) ir_config_param.set_param(cr, uid, 'google_drive_refresh_token', refresh_token, groups=['base.group_system'])
agpl-3.0
CuriousLearner/kivy
examples/widgets/carousel_buttons.py
40
1031
''' Carousel example with button inside. This is a tiny test for testing the scroll distance/timeout And ensure the down/up are dispatched if no gesture is done. ''' from kivy.uix.carousel import Carousel from kivy.uix.gridlayout import GridLayout from kivy.app import App from kivy.lang import Builder Builder.load_string(''' <Page>: cols: 3 Label: text: str(id(root)) Button Button Button Button text: 'load(page 3)' on_release: carousel = root.parent.parent carousel.load_slide(carousel.slides[2]) Button Button text: 'prev' on_release: root.parent.parent.load_previous() Button Button text: 'next' on_release: root.parent.parent.load_next() ''') class Page(GridLayout): pass class TestApp(App): def build(self): root = Carousel() for x in range(10): root.add_widget(Page()) return root if __name__ == '__main__': TestApp().run()
mit
gloaec/trifle
src/rdflib/plugins/serializers/trig.py
6
2718
""" Trig RDF graph serializer for RDFLib. See <http://www.w3.org/TR/trig/> for syntax specification. """ from collections import defaultdict from rdflib.plugins.serializers.turtle import TurtleSerializer, _GEN_QNAME_FOR_DT, VERB from rdflib.term import BNode, Literal __all__ = ['TrigSerializer'] class TrigSerializer(TurtleSerializer): short_name = "trig" indentString = 4 * u' ' def __init__(self, store): if store.context_aware: self.contexts = store.contexts() else: self.contexts = [store] super(TrigSerializer, self).__init__(store) def preprocess(self): for context in self.contexts: self.store = context self._references = defaultdict(int) self._subjects = {} for triple in context: self.preprocessTriple(triple) self._contexts[context]=(self.orderSubjects(), self._subjects, self._references) def preprocessTriple(self, triple): s, p, o = triple self._references[o]+=1 self._subjects[s] = True for i, node in enumerate(triple): if node in self.keywords: continue # Don't use generated prefixes for subjects and objects self.getQName(node, gen_prefix=(i == VERB)) if isinstance(node, Literal) and node.datatype: self.getQName(node.datatype, gen_prefix=_GEN_QNAME_FOR_DT) p = triple[1] if isinstance(p, BNode): self._references[p]+=1 def reset(self): super(TrigSerializer, self).reset() self._contexts = {} def serialize(self, stream, base=None, encoding=None, spacious=None, **args): self.reset() self.stream = stream self.base = base if spacious is not None: self._spacious = spacious self.preprocess() self.startDocument() firstTime = True for store, (ordered_subjects, subjects, ref) in self._contexts.items(): self._references = ref self._serialized = {} self.store = store self._subjects = subjects self.write(self.indent() + '\n<%s> = {' % self.getQName(store.identifier)) self.depth += 1 for subject in ordered_subjects: if self.isDone(subject): continue if firstTime: firstTime = False if self.statement(subject) and not firstTime: self.write('\n') self.depth -= 1 self.write('}\n') self.endDocument() stream.write(u"\n".encode('ascii'))
gpl-3.0
googleapis/python-spanner
tests/unit/spanner_dbapi/test_connection.py
1
27749
# Copyright 2020 Google LLC 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. """Cloud Spanner DB-API Connection class unit tests.""" import mock import unittest import warnings def _make_credentials(): from google.auth import credentials class _CredentialsWithScopes(credentials.Credentials, credentials.Scoped): pass return mock.Mock(spec=_CredentialsWithScopes) class TestConnection(unittest.TestCase): PROJECT = "test-project" INSTANCE = "test-instance" DATABASE = "test-database" USER_AGENT = "user-agent" CREDENTIALS = _make_credentials() def _get_client_info(self): from google.api_core.gapic_v1.client_info import ClientInfo return ClientInfo(user_agent=self.USER_AGENT) def _make_connection(self): from google.cloud.spanner_dbapi import Connection from google.cloud.spanner_v1.instance import Instance # We don't need a real Client object to test the constructor instance = Instance(self.INSTANCE, client=None) database = instance.database(self.DATABASE) return Connection(instance, database) def test_autocommit_setter_transaction_not_started(self): connection = self._make_connection() with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.commit" ) as mock_commit: connection.autocommit = True mock_commit.assert_not_called() self.assertTrue(connection._autocommit) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.commit" ) as mock_commit: connection.autocommit = False mock_commit.assert_not_called() self.assertFalse(connection._autocommit) def test_autocommit_setter_transaction_started(self): connection = self._make_connection() with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.commit" ) as mock_commit: connection._transaction = mock.Mock(committed=False, rolled_back=False) connection.autocommit = True mock_commit.assert_called_once() self.assertTrue(connection._autocommit) def test_autocommit_setter_transaction_started_commited_rolled_back(self): connection = self._make_connection() with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.commit" ) as mock_commit: connection._transaction = mock.Mock(committed=True, rolled_back=False) connection.autocommit = True mock_commit.assert_not_called() self.assertTrue(connection._autocommit) connection.autocommit = False with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.commit" ) as mock_commit: connection._transaction = mock.Mock(committed=False, rolled_back=True) connection.autocommit = True mock_commit.assert_not_called() self.assertTrue(connection._autocommit) def test_property_database(self): from google.cloud.spanner_v1.database import Database connection = self._make_connection() self.assertIsInstance(connection.database, Database) self.assertEqual(connection.database, connection._database) def test_property_instance(self): from google.cloud.spanner_v1.instance import Instance connection = self._make_connection() self.assertIsInstance(connection.instance, Instance) self.assertEqual(connection.instance, connection._instance) def test__session_checkout(self): from google.cloud.spanner_dbapi import Connection with mock.patch("google.cloud.spanner_v1.database.Database") as mock_database: mock_database._pool = mock.MagicMock() mock_database._pool.get = mock.MagicMock(return_value="db_session_pool") connection = Connection(self.INSTANCE, mock_database) connection._session_checkout() mock_database._pool.get.assert_called_once_with() self.assertEqual(connection._session, "db_session_pool") connection._session = "db_session" connection._session_checkout() self.assertEqual(connection._session, "db_session") def test__release_session(self): from google.cloud.spanner_dbapi import Connection with mock.patch("google.cloud.spanner_v1.database.Database") as mock_database: mock_database._pool = mock.MagicMock() mock_database._pool.put = mock.MagicMock() connection = Connection(self.INSTANCE, mock_database) connection._session = "session" connection._release_session() mock_database._pool.put.assert_called_once_with("session") self.assertIsNone(connection._session) def test_transaction_checkout(self): from google.cloud.spanner_dbapi import Connection connection = Connection(self.INSTANCE, self.DATABASE) connection._session_checkout = mock_checkout = mock.MagicMock(autospec=True) connection.transaction_checkout() mock_checkout.assert_called_once_with() connection._transaction = mock_transaction = mock.MagicMock() mock_transaction.committed = mock_transaction.rolled_back = False self.assertEqual(connection.transaction_checkout(), mock_transaction) connection._autocommit = True self.assertIsNone(connection.transaction_checkout()) def test_close(self): from google.cloud.spanner_dbapi import connect, InterfaceError with mock.patch( "google.cloud.spanner_v1.instance.Instance.exists", return_value=True ): with mock.patch( "google.cloud.spanner_v1.database.Database.exists", return_value=True ): connection = connect("test-instance", "test-database") self.assertFalse(connection.is_closed) connection.close() self.assertTrue(connection.is_closed) with self.assertRaises(InterfaceError): connection.cursor() connection._transaction = mock_transaction = mock.MagicMock() mock_transaction.committed = mock_transaction.rolled_back = False mock_transaction.rollback = mock_rollback = mock.MagicMock() connection.close() mock_rollback.assert_called_once_with() connection._transaction = mock.MagicMock() connection._own_pool = False connection.close() self.assertTrue(connection.is_closed) @mock.patch.object(warnings, "warn") def test_commit(self, mock_warn): from google.cloud.spanner_dbapi import Connection from google.cloud.spanner_dbapi.connection import AUTOCOMMIT_MODE_WARNING connection = Connection(self.INSTANCE, self.DATABASE) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection._release_session" ) as mock_release: connection.commit() mock_release.assert_not_called() connection._transaction = mock_transaction = mock.MagicMock( rolled_back=False, committed=False ) mock_transaction.commit = mock_commit = mock.MagicMock() with mock.patch( "google.cloud.spanner_dbapi.connection.Connection._release_session" ) as mock_release: connection.commit() mock_commit.assert_called_once_with() mock_release.assert_called_once_with() connection._autocommit = True connection.commit() mock_warn.assert_called_once_with( AUTOCOMMIT_MODE_WARNING, UserWarning, stacklevel=2 ) @mock.patch.object(warnings, "warn") def test_rollback(self, mock_warn): from google.cloud.spanner_dbapi import Connection from google.cloud.spanner_dbapi.connection import AUTOCOMMIT_MODE_WARNING connection = Connection(self.INSTANCE, self.DATABASE) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection._release_session" ) as mock_release: connection.rollback() mock_release.assert_not_called() connection._transaction = mock_transaction = mock.MagicMock() mock_transaction.rollback = mock_rollback = mock.MagicMock() with mock.patch( "google.cloud.spanner_dbapi.connection.Connection._release_session" ) as mock_release: connection.rollback() mock_rollback.assert_called_once_with() mock_release.assert_called_once_with() connection._autocommit = True connection.rollback() mock_warn.assert_called_once_with( AUTOCOMMIT_MODE_WARNING, UserWarning, stacklevel=2 ) def test_run_prior_DDL_statements(self): from google.cloud.spanner_dbapi import Connection, InterfaceError with mock.patch( "google.cloud.spanner_v1.database.Database", autospec=True ) as mock_database: connection = Connection(self.INSTANCE, mock_database) connection.run_prior_DDL_statements() mock_database.update_ddl.assert_not_called() ddl = ["ddl"] connection._ddl_statements = ddl connection.run_prior_DDL_statements() mock_database.update_ddl.assert_called_once_with(ddl) connection.is_closed = True with self.assertRaises(InterfaceError): connection.run_prior_DDL_statements() def test_context(self): connection = self._make_connection() with connection as conn: self.assertEqual(conn, connection) self.assertTrue(connection.is_closed) def test_connect(self): from google.cloud.spanner_dbapi import Connection, connect with mock.patch("google.cloud.spanner_v1.Client"): with mock.patch( "google.api_core.gapic_v1.client_info.ClientInfo", return_value=self._get_client_info(), ): connection = connect( self.INSTANCE, self.DATABASE, self.PROJECT, self.CREDENTIALS, self.USER_AGENT, ) self.assertIsInstance(connection, Connection) def test_connect_instance_not_found(self): from google.cloud.spanner_dbapi import connect with mock.patch( "google.cloud.spanner_v1.instance.Instance.exists", return_value=False ): with self.assertRaises(ValueError): connect("test-instance", "test-database") def test_connect_database_not_found(self): from google.cloud.spanner_dbapi import connect with mock.patch( "google.cloud.spanner_v1.database.Database.exists", return_value=False ): with mock.patch( "google.cloud.spanner_v1.instance.Instance.exists", return_value=True ): with self.assertRaises(ValueError): connect("test-instance", "test-database") def test_default_sessions_pool(self): from google.cloud.spanner_dbapi import connect with mock.patch("google.cloud.spanner_v1.instance.Instance.database"): with mock.patch( "google.cloud.spanner_v1.instance.Instance.exists", return_value=True ): connection = connect("test-instance", "test-database") self.assertIsNotNone(connection.database._pool) def test_sessions_pool(self): from google.cloud.spanner_dbapi import connect from google.cloud.spanner_v1.pool import FixedSizePool database_id = "test-database" pool = FixedSizePool() with mock.patch( "google.cloud.spanner_v1.instance.Instance.database" ) as database_mock: with mock.patch( "google.cloud.spanner_v1.instance.Instance.exists", return_value=True ): connect("test-instance", database_id, pool=pool) database_mock.assert_called_once_with(database_id, pool=pool) def test_run_statement_remember_statements(self): """Check that Connection remembers executed statements.""" from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.cursor import Statement sql = """SELECT 23 FROM table WHERE id = @a1""" params = {"a1": "value"} param_types = {"a1": str} connection = self._make_connection() statement = Statement(sql, params, param_types, ResultsChecksum(), False) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.transaction_checkout" ): connection.run_statement(statement) self.assertEqual(connection._statements[0].sql, sql) self.assertEqual(connection._statements[0].params, params) self.assertEqual(connection._statements[0].param_types, param_types) self.assertIsInstance(connection._statements[0].checksum, ResultsChecksum) def test_run_statement_dont_remember_retried_statements(self): """Check that Connection doesn't remember re-executed statements.""" from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.cursor import Statement sql = """SELECT 23 FROM table WHERE id = @a1""" params = {"a1": "value"} param_types = {"a1": str} connection = self._make_connection() statement = Statement(sql, params, param_types, ResultsChecksum(), False) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.transaction_checkout" ): connection.run_statement(statement, retried=True) self.assertEqual(len(connection._statements), 0) def test_run_statement_w_heterogenous_insert_statements(self): """Check that Connection executed heterogenous insert statements.""" from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.cursor import Statement sql = "INSERT INTO T (f1, f2) VALUES (1, 2)" params = None param_types = None connection = self._make_connection() statement = Statement(sql, params, param_types, ResultsChecksum(), True) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.transaction_checkout" ): connection.run_statement(statement, retried=True) self.assertEqual(len(connection._statements), 0) def test_run_statement_w_homogeneous_insert_statements(self): """Check that Connection executed homogeneous insert statements.""" from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.cursor import Statement sql = "INSERT INTO T (f1, f2) VALUES (%s, %s), (%s, %s)" params = ["a", "b", "c", "d"] param_types = {"f1": str, "f2": str} connection = self._make_connection() statement = Statement(sql, params, param_types, ResultsChecksum(), True) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.transaction_checkout" ): connection.run_statement(statement, retried=True) self.assertEqual(len(connection._statements), 0) def test_clear_statements_on_commit(self): """ Check that all the saved statements are cleared, when the transaction is commited. """ connection = self._make_connection() connection._transaction = mock.Mock(rolled_back=False, committed=False) connection._statements = [{}, {}] self.assertEqual(len(connection._statements), 2) with mock.patch("google.cloud.spanner_v1.transaction.Transaction.commit"): connection.commit() self.assertEqual(len(connection._statements), 0) def test_clear_statements_on_rollback(self): """ Check that all the saved statements are cleared, when the transaction is roll backed. """ connection = self._make_connection() connection._transaction = mock.Mock() connection._statements = [{}, {}] self.assertEqual(len(connection._statements), 2) with mock.patch("google.cloud.spanner_v1.transaction.Transaction.commit"): connection.rollback() self.assertEqual(len(connection._statements), 0) def test_retry_transaction(self): """Check retrying an aborted transaction.""" from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.cursor import Statement row = ["field1", "field2"] connection = self._make_connection() checksum = ResultsChecksum() checksum.consume_result(row) retried_checkum = ResultsChecksum() statement = Statement("SELECT 1", [], {}, checksum, False) connection._statements.append(statement) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.run_statement", return_value=([row], retried_checkum), ) as run_mock: with mock.patch( "google.cloud.spanner_dbapi.connection._compare_checksums" ) as compare_mock: connection.retry_transaction() compare_mock.assert_called_with(checksum, retried_checkum) run_mock.assert_called_with(statement, retried=True) def test_retry_transaction_checksum_mismatch(self): """ Check retrying an aborted transaction with results checksums mismatch. """ from google.cloud.spanner_dbapi.exceptions import RetryAborted from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.cursor import Statement row = ["field1", "field2"] retried_row = ["field3", "field4"] connection = self._make_connection() checksum = ResultsChecksum() checksum.consume_result(row) retried_checkum = ResultsChecksum() statement = Statement("SELECT 1", [], {}, checksum, False) connection._statements.append(statement) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.run_statement", return_value=([retried_row], retried_checkum), ): with self.assertRaises(RetryAborted): connection.retry_transaction() def test_commit_retry_aborted_statements(self): """Check that retried transaction executing the same statements.""" from google.api_core.exceptions import Aborted from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.connection import connect from google.cloud.spanner_dbapi.cursor import Statement row = ["field1", "field2"] with mock.patch( "google.cloud.spanner_v1.instance.Instance.exists", return_value=True, ): with mock.patch( "google.cloud.spanner_v1.database.Database.exists", return_value=True, ): connection = connect("test-instance", "test-database") cursor = connection.cursor() cursor._checksum = ResultsChecksum() cursor._checksum.consume_result(row) statement = Statement("SELECT 1", [], {}, cursor._checksum, False) connection._statements.append(statement) connection._transaction = mock.Mock(rolled_back=False, committed=False) with mock.patch.object( connection._transaction, "commit", side_effect=(Aborted("Aborted"), None), ): with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.run_statement", return_value=([row], ResultsChecksum()), ) as run_mock: connection.commit() run_mock.assert_called_with(statement, retried=True) def test_retry_transaction_drop_transaction(self): """ Check that before retrying an aborted transaction connection drops the original aborted transaction. """ connection = self._make_connection() transaction_mock = mock.Mock() connection._transaction = transaction_mock # as we didn't set any statements, the method # will only drop the transaction object connection.retry_transaction() self.assertIsNone(connection._transaction) def test_retry_aborted_retry(self): """ Check that in case of a retried transaction failed, the connection will retry it once again. """ from google.api_core.exceptions import Aborted from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.connection import connect from google.cloud.spanner_dbapi.cursor import Statement row = ["field1", "field2"] with mock.patch( "google.cloud.spanner_v1.instance.Instance.exists", return_value=True, ): with mock.patch( "google.cloud.spanner_v1.database.Database.exists", return_value=True, ): connection = connect("test-instance", "test-database") cursor = connection.cursor() cursor._checksum = ResultsChecksum() cursor._checksum.consume_result(row) statement = Statement("SELECT 1", [], {}, cursor._checksum, False) connection._statements.append(statement) metadata_mock = mock.Mock() metadata_mock.trailing_metadata.return_value = {} with mock.patch.object( connection, "run_statement", side_effect=( Aborted("Aborted", errors=[metadata_mock]), ([row], ResultsChecksum()), ), ) as retry_mock: connection.retry_transaction() retry_mock.assert_has_calls( ( mock.call(statement, retried=True), mock.call(statement, retried=True), ) ) def test_retry_transaction_raise_max_internal_retries(self): """Check retrying raise an error of max internal retries.""" from google.cloud.spanner_dbapi import connection as conn from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.cursor import Statement conn.MAX_INTERNAL_RETRIES = 0 row = ["field1", "field2"] connection = self._make_connection() checksum = ResultsChecksum() checksum.consume_result(row) statement = Statement("SELECT 1", [], {}, checksum, False) connection._statements.append(statement) with self.assertRaises(Exception): connection.retry_transaction() conn.MAX_INTERNAL_RETRIES = 50 def test_retry_aborted_retry_without_delay(self): """ Check that in case of a retried transaction failed, the connection will retry it once again. """ from google.api_core.exceptions import Aborted from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.connection import connect from google.cloud.spanner_dbapi.cursor import Statement row = ["field1", "field2"] with mock.patch( "google.cloud.spanner_v1.instance.Instance.exists", return_value=True, ): with mock.patch( "google.cloud.spanner_v1.database.Database.exists", return_value=True, ): connection = connect("test-instance", "test-database") cursor = connection.cursor() cursor._checksum = ResultsChecksum() cursor._checksum.consume_result(row) statement = Statement("SELECT 1", [], {}, cursor._checksum, False) connection._statements.append(statement) metadata_mock = mock.Mock() metadata_mock.trailing_metadata.return_value = {} with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.run_statement", side_effect=( Aborted("Aborted", errors=[metadata_mock]), ([row], ResultsChecksum()), ), ) as retry_mock: with mock.patch( "google.cloud.spanner_dbapi.connection._get_retry_delay", return_value=False, ): connection.retry_transaction() retry_mock.assert_has_calls( ( mock.call(statement, retried=True), mock.call(statement, retried=True), ) ) def test_retry_transaction_w_multiple_statement(self): """Check retrying an aborted transaction.""" from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.cursor import Statement row = ["field1", "field2"] connection = self._make_connection() checksum = ResultsChecksum() checksum.consume_result(row) retried_checkum = ResultsChecksum() statement = Statement("SELECT 1", [], {}, checksum, False) statement1 = Statement("SELECT 2", [], {}, checksum, False) connection._statements.append(statement) connection._statements.append(statement1) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.run_statement", return_value=([row], retried_checkum), ) as run_mock: with mock.patch( "google.cloud.spanner_dbapi.connection._compare_checksums" ) as compare_mock: connection.retry_transaction() compare_mock.assert_called_with(checksum, retried_checkum) run_mock.assert_called_with(statement1, retried=True) def test_retry_transaction_w_empty_response(self): """Check retrying an aborted transaction.""" from google.cloud.spanner_dbapi.checksum import ResultsChecksum from google.cloud.spanner_dbapi.cursor import Statement row = [] connection = self._make_connection() checksum = ResultsChecksum() checksum.count = 1 retried_checkum = ResultsChecksum() statement = Statement("SELECT 1", [], {}, checksum, False) connection._statements.append(statement) with mock.patch( "google.cloud.spanner_dbapi.connection.Connection.run_statement", return_value=(row, retried_checkum), ) as run_mock: with mock.patch( "google.cloud.spanner_dbapi.connection._compare_checksums" ) as compare_mock: connection.retry_transaction() compare_mock.assert_called_with(checksum, retried_checkum) run_mock.assert_called_with(statement, retried=True)
apache-2.0
CalthorpeAnalytics/urbanfootprint
footprint/main/resources/mixins/feature_resource_mixin.py
1
3922
# UrbanFootprint v1.5 # Copyright (C) 2017 Calthorpe Analytics # # This file is part of UrbanFootprint version 1.5 # # UrbanFootprint is distributed under the terms of the GNU General # Public License version 3, as published by the Free Software Foundation. This # code is distributed WITHOUT ANY WARRANTY, without implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License v3 for more details; see <http://www.gnu.org/licenses/>. from tastypie.resources import ModelResource from footprint.main.lib.functions import one_or_none from footprint.main.models import DbEntity, ConfigEntity from footprint.main.models.presentation.layer.layer import Layer from footprint.main.models.presentation.layer_selection import get_or_create_layer_selection_class_for_layer from footprint.main.publishing.layer_initialization import LayerLibraryKey from footprint.main.publishing.layer_publishing import update_or_create_layer_selections_for_layer __author__ = 'calthorpe_analytics' class FeatureResourceMixin(ModelResource): def search_params(self, params): """ The user may optionally specify a layer_selection__id instead of feature ids when querying for features. This prevents huge feature id lists in the URL. :param params :return: """ return params def resolve_layer_selection(self, params): """ Used to get that actual selected features, which is a short cut querying, so we don't have to query for potentially thousands of ids. If No layer exists then there is also no LayerSelection, in which case we return None """ layer = self.resolve_layer(params) config_entity = self.resolve_config_entity(params) if not layer: return None update_or_create_layer_selections_for_layer(layer, users=[self.resolve_user(params)]) layer_selection_class = get_or_create_layer_selection_class_for_layer(layer, config_entity, False) return layer_selection_class.objects.get(user=self.resolve_user(params)) def remove_params(self, params): """ Remove params that are used to identity the Feature subclass, but not for filtering instances :param params: :return: """ return ['layer_selection__id', 'config_entity__id', 'layer__id', 'db_entity__id', 'id', 'file_dataset__id'] def resolve_config_entity(self, params): if params.get('config_entity__id'): return ConfigEntity.objects.get_subclass(id=params['config_entity__id']) else: return self.resolve_db_entity(params).config_entity def resolve_db_entity(self, params): if params.get('db_entity__id'): return DbEntity.objects.get(id=params['db_entity__id']) else: return self.resolve_layer(params).db_entity def resolve_layer(self, params): """ Resolve the Layer if one exists. We don't resolve a Layer from a DbEntity, only from a layer__id. It's assumed that if a Layer id doesn't come from the request params that the user doesn't doesn't need Features related to LayerSelection, thus no Layer is needed :param params: :return: """ if params.get('layer__id'): return Layer.objects.get(id=params['layer__id']) return None def resolve_instance(self, params, dynamic_model_class): return dynamic_model_class.objects.get(id=params['id']) def resolve_model_class(self, config_entity=None, db_entity=None): """ Resolves the model class of the dynamic resource class. In this case it's a Feature subclass """ return db_entity.feature_class if \ db_entity else \ config_entity.feature_class_of_base_class(self._meta.queryset.model)
gpl-3.0
udayankumar/anomaly-detection
strangeness.py
1
2196
import math class Strangeness(object): def __init__(self,threshold, minQueue, epsilon): self.M = 1.0 self.threshold = threshold self.minQueue = minQueue self.epsilon = epsilon self.listTuple = [] def __clusterMean (self, listTuple, singleTuple): if len(listTuple) == 0: return singleTuple dimensions = len(singleTuple) numTuples = len(listTuple) + 1 sumArray = [0] * dimensions #sum of the listTuple for aTuple in listTuple: #TODO: add a try except for the error case when dimensions do not match for i in xrange(0,dimensions): sumArray[i] += aTuple[i] #adding the singleTuple for i in xrange(0,dimensions): sumArray[i] += singleTuple[i] meanArray = [value/numTuples for value in sumArray] return meanArray def __euclideanDistance(self,p1,p2): return sum((x-y)**2 for (x,y) in zip(p1,p2))**(0.5) def __calStrangeness(self, listTuple, singleTuple): clusterPoint = self.__clusterMean(listTuple, singleTuple) strangeness = [self.__euclideanDistance(point, clusterPoint) for point in listTuple] #adding Z_n ZnStrangeness = self.__euclideanDistance(singleTuple, clusterPoint) return [strangeness, ZnStrangeness] def __calPValue(self,listTuple, singleTuple, theta): [strangenessTuple, ZnStrangeness] = self.__calStrangeness(listTuple, singleTuple) siGreater = sum([int(point > ZnStrangeness) for point in strangenessTuple]) #adding 1 for the case Zn = Zn siEqual = sum([int(point == ZnStrangeness) for point in strangenessTuple]) + 1 return (float(siGreater) + theta * float(siEqual))/(len(listTuple) + 1) def getMValue(self,singleVal): if len(self.listTuple) > self.minQueue and self.M < self.threshold: p = self.__calPValue(self.listTuple, singleVal, 0.82) self.M *= self.epsilon * p**(self.epsilon - 1) elif self.M >= self.threshold: self.listTuple = [] self.M = 1.0 self.listTuple.append(singleVal) return self.M
mit
stephrdev/brigitte
brigitte/repositories/forms.py
1
1077
# -*- coding: utf-8 -*- from django import forms from django.forms.models import modelformset_factory from django.template.defaultfilters import slugify from brigitte.repositories.models import Repository, RepositoryUser class RepositoryForm(forms.ModelForm): class Meta: model = Repository exclude = ('user', 'slug', 'last_commit_date', 'repo_type') def __init__(self, user, *args, **kwargs): super(RepositoryForm, self).__init__(*args, **kwargs) self.user = user def clean(self): slug = slugify(self.cleaned_data.get('title', '')) instance_pk = 0 if self.instance: instance_pk = self.instance.pk if Repository.objects.filter( user=self.user, slug=slug ).exclude( pk=instance_pk ).count() > 0: raise forms.ValidationError('Repository name already in use.') return self.cleaned_data RepositoryUserFormSet = modelformset_factory( RepositoryUser, extra=1, exclude=('repo',), can_delete=True )
bsd-3-clause
mehdidc/scikit-learn
examples/linear_model/plot_sgd_weighted_samples.py
344
1458
""" ===================== SGD: Weighted samples ===================== Plot decision function of a weighted dataset, where the size of points is proportional to its weight. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model # we create 20 points np.random.seed(0) X = np.r_[np.random.randn(10, 2) + [1, 1], np.random.randn(10, 2)] y = [1] * 10 + [-1] * 10 sample_weight = 100 * np.abs(np.random.randn(20)) # and assign a bigger weight to the last 10 samples sample_weight[:10] *= 10 # plot the weighted data points xx, yy = np.meshgrid(np.linspace(-4, 5, 500), np.linspace(-4, 5, 500)) plt.figure() plt.scatter(X[:, 0], X[:, 1], c=y, s=sample_weight, alpha=0.9, cmap=plt.cm.bone) ## fit the unweighted model clf = linear_model.SGDClassifier(alpha=0.01, n_iter=100) clf.fit(X, y) Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) no_weights = plt.contour(xx, yy, Z, levels=[0], linestyles=['solid']) ## fit the weighted model clf = linear_model.SGDClassifier(alpha=0.01, n_iter=100) clf.fit(X, y, sample_weight=sample_weight) Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) samples_weights = plt.contour(xx, yy, Z, levels=[0], linestyles=['dashed']) plt.legend([no_weights.collections[0], samples_weights.collections[0]], ["no weights", "with weights"], loc="lower left") plt.xticks(()) plt.yticks(()) plt.show()
bsd-3-clause
aleksandar-mitrevski/ai
Simulated-Annealing-and-Constraint-Satisfaction/Simulated-Annealing/search.py
1
7711
import random import math import matplotlib.pyplot as pyplot import time class CitySearchLibrary(object): """Defines a search library for finding minimum cost paths between cities. Author: Aleksandar Mitrevski """ def __init__(self, cities): """Initializes a library. Keyword arguments: cities -- A list of 'CityData' objects. """ self.cities = cities self.number_of_cities = len(self.cities) def search(self, maximum_runtime_allowed): """Looks for a shortest cost cycle that connects all cities (i.e. looks for a solution to the traveling salesman problem) using simulated annealing. Returns: - The minimum cost found. - The number of moves (ascends and descends) made by the algorithm. Keyword arguments: maximum_runtime_allowed -- Maximum time (in seconds) allowed for the search. """ print 'Running simulated annealing...' #we start with a random initial state current_state = self._get_initial_state() #we find the total cost of the initial configuration #because we will need to use it for comparing with the costs #of the neighbour states cost = self._calculate_cost(current_state) current_cost = cost #used for visualization purposes cost_at_each_move = [current_cost] #used for counting the number of moves made by the algorithm number_of_moves = 0 start_time = time.clock() time_elapsed = 0. #as long as the descends are optimistic, the algorithm looks for neighbour states #and chooses the one that offers the biggest cost improvement while time_elapsed < maximum_runtime_allowed: temperature = self._schedule(number_of_moves) if temperature < 1e-200: break #we generate a random neighbour of the current state neighbour = self._generate_neighbour(current_state) neighbour_cost = self._calculate_cost(neighbour) delta_cost = neighbour_cost - current_cost #if the neighbour improves the cost, we definitely make a move to it if delta_cost < 0: current_state = list(neighbour) current_cost = neighbour_cost #if the neighbour doesn't offer an improvement, we only select it with a certain probability else: change_state = self._change_state(delta_cost, temperature) if change_state: current_state = list(neighbour) current_cost = neighbour_cost cost_at_each_move.append(current_cost) number_of_moves += 1 time_elapsed = time.clock() - start_time #we visualize the results of the algorithm self.visualize_iterations(number_of_moves, cost_at_each_move) return current_cost, number_of_moves def _get_initial_state(self): """Generates a random city configuration that contains each city once. Assumes that the cities form a complete graph. Returns a list of indices corresponding to cities in 'self.cities'. """ indices = [i for i in xrange(self.number_of_cities)] city_arrangement = [] for i in xrange(self.number_of_cities): city_index = random.randint(0, len(indices)-1) city_arrangement.append(indices[city_index]) del indices[city_index] city_arrangement.append(city_arrangement[0]) return city_arrangement def _calculate_cost(self, city_arrangement): """Calculates costs between all cities in a given city configuration, given the longitude and latitude coordinates of the cities. Returns the total cost between the cities. Keyword arguments: city_arrangement -- A list of city indices. """ total_cost = 0. number_of_cities = len(self.cities) #we calculate the distance between two consecutive #cities in the list; uses the Haversine formula for calculating distance #(source http://www.movable-type.co.uk/scripts/latlong.html) for i in xrange(number_of_cities): current_city = self.cities[city_arrangement[i]] neighbour = self.cities[city_arrangement[i+1]] radius_of_earth = 6371. longitude_distance = (current_city.longitude - neighbour.longitude) * math.pi / 180. latitude_distance = (current_city.latitude - neighbour.latitude) * math.pi / 180. current_city_latitude_radians = current_city.latitude * math.pi / 180.0 neighbour_latitude_radians = neighbour.latitude * math.pi / 180.0 a = math.sin(latitude_distance / 2.)**2 + math.sin(longitude_distance / 2.)**2 * math.cos(current_city_latitude_radians) * math.cos(neighbour_latitude_radians) c = 2. * math.atan2(math.sqrt(a), math.sqrt(1.-a)) distance = radius_of_earth * c total_cost += distance return total_cost def _schedule(self, iteration_counter): """Returns temperature as a function of 'iteration_counter'. Keyword arguments: iteration_counter -- Iteration counter of the simulated annealing algorithm. """ temperature = 1e10 * 0.999**iteration_counter return temperature def _generate_neighbour(self, city_arrangement): """Generates neighbour states for the given city arrangement by choosing a random list position and swapping the element in that position with all the other elements. Once the neighbours have been generated, randomly picks one neighbour and returns it. Keyword arguments: city_arrangement -- A list of city indices. """ city_to_swap = random.randint(0, self.number_of_cities-1) neighbours = [] for i in xrange(self.number_of_cities): if i == city_to_swap: continue neighbour = list(city_arrangement) temp = neighbour[i] neighbour[i] = neighbour[city_to_swap] neighbour[city_to_swap] = temp if city_to_swap == 0: neighbour[len(neighbour)-1] = neighbour[i] neighbours.append(neighbour) neighbour_index = random.randint(0, len(neighbours)-1) return neighbours[neighbour_index] def _change_state(self, delta_cost, temperature): """Returns 'True' if we want to accept the state change and 'False' otherwise. The acceptance probability is exp(-delta_cost/temperature). Keyword arguments: delta_cost -- Difference between the cost of a neighbour state and the cost of the current state. temperature -- A temperature that determines the acceptance probability. """ probability_of_changing = math.exp(-delta_cost/temperature) random_number = random.random() if random_number < probability_of_changing: return True return False def visualize_iterations(self, number_of_moves, cost_at_each_move): """Visualizes the results of the simulated annealing algorithm. Keyword arguments: number_of_moves -- The number of moves in the simulated annealing algorithm. cost_at_each_move -- A list containing costs at each move of the algorithm. """ moves = [x+1 for x in xrange(number_of_moves + 1)] pyplot.xlabel('Number of moves') pyplot.ylabel('Total cost') pyplot.plot(moves, cost_at_each_move, 'b-') pyplot.show()
mit
hojel/calibre
src/calibre/utils/imghdr.py
14
4333
"""Recognize image file formats based on their first few bytes.""" __all__ = ["what"] # -------------------------# # Recognize image headers # # -------------------------# def what(file, h=None): if h is None: if isinstance(file, basestring): f = open(file, 'rb') h = f.read(150) else: location = file.tell() h = file.read(150) file.seek(location) f = None else: f = None try: for tf in tests: res = tf(h, f) if res: return res finally: if f: f.close() # There exist some jpeg files with no headers, only the starting two bits # If we cannot identify as anything else, identify as jpeg. if h[:2] == b'\xff\xd8': return 'jpeg' return None # ---------------------------------# # Subroutines per image file type # # ---------------------------------# tests = [] def test_jpeg(h, f): """JPEG data in JFIF format (Changed by Kovid to mimic the file utility, the original code was failing with some jpegs that included ICC_PROFILE data, for example: http://nationalpostnews.files.wordpress.com/2013/03/budget.jpeg?w=300&h=1571)""" if (h[6:10] in (b'JFIF', b'Exif')) or (h[:2] == b'\xff\xd8' and (b'JFIF' in h[:32] or b'8BIM' in h[:32])): return 'jpeg' tests.append(test_jpeg) def test_png(h, f): if h[:8] == "\211PNG\r\n\032\n": return 'png' tests.append(test_png) def test_gif(h, f): """GIF ('87 and '89 variants)""" if h[:6] in ('GIF87a', 'GIF89a'): return 'gif' tests.append(test_gif) def test_tiff(h, f): """TIFF (can be in Motorola or Intel byte order)""" if h[:2] in ('MM', 'II'): return 'tiff' tests.append(test_tiff) def test_webp(h, f): if h[:4] == b'RIFF' and h[8:12] == b'WEBP': return 'webp' tests.append(test_webp) def test_rgb(h, f): """SGI image library""" if h[:2] == '\001\332': return 'rgb' tests.append(test_rgb) def test_pbm(h, f): """PBM (portable bitmap)""" if len(h) >= 3 and \ h[0] == 'P' and h[1] in '14' and h[2] in ' \t\n\r': return 'pbm' tests.append(test_pbm) def test_pgm(h, f): """PGM (portable graymap)""" if len(h) >= 3 and \ h[0] == 'P' and h[1] in '25' and h[2] in ' \t\n\r': return 'pgm' tests.append(test_pgm) def test_ppm(h, f): """PPM (portable pixmap)""" if len(h) >= 3 and \ h[0] == 'P' and h[1] in '36' and h[2] in ' \t\n\r': return 'ppm' tests.append(test_ppm) def test_rast(h, f): """Sun raster file""" if h[:4] == '\x59\xA6\x6A\x95': return 'rast' tests.append(test_rast) def test_xbm(h, f): """X bitmap (X10 or X11)""" s = '#define ' if h[:len(s)] == s: return 'xbm' tests.append(test_xbm) def test_bmp(h, f): if h[:2] == 'BM': return 'bmp' tests.append(test_bmp) def test_emf(h, f): if h[:4] == b'\x01\0\0\0' and h[40:44] == b' EMF': return 'emf' tests.append(test_emf) def test_svg(h, f): if (h[:2] == b'<?' and h[2:5].lower() == 'xml' and b'<svg' in h) or h.startswith(b'<svg'): return 'svg' tests.append(test_svg) # --------------------# # Small test program # # --------------------# def test(): import sys recursive = 0 if sys.argv[1:] and sys.argv[1] == '-r': del sys.argv[1:2] recursive = 1 try: if sys.argv[1:]: testall(sys.argv[1:], recursive, 1) else: testall(['.'], recursive, 1) except KeyboardInterrupt: sys.stderr.write('\n[Interrupted]\n') sys.exit(1) def testall(list, recursive, toplevel): import sys import os for filename in list: if os.path.isdir(filename): print filename + '/:', if recursive or toplevel: print 'recursing down:' import glob names = glob.glob(os.path.join(filename, '*')) testall(names, recursive, 0) else: print '*** directory (use -r) ***' else: print filename + ':', sys.stdout.flush() try: print what(filename) except IOError: print '*** not found ***'
gpl-3.0
lyft/incubator-airflow
airflow/api/common/experimental/get_code.py
4
1454
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Get code APIs.""" from airflow.api.common.experimental import check_and_get_dag from airflow.exceptions import AirflowException from airflow.www import utils as wwwutils def get_code(dag_id: str) -> str: """Return python code of a given dag_id. :param dag_id: DAG id :return: code of the DAG """ dag = check_and_get_dag(dag_id=dag_id) try: with wwwutils.open_maybe_zipped(dag.fileloc, 'r') as file: code = file.read() return code except OSError as exception: error_message = "Error {} while reading Dag id {} Code".format(str(exception), dag_id) raise AirflowException(error_message)
apache-2.0
prutseltje/ansible
lib/ansible/modules/files/template.py
8
6449
# this is a virtual module that is entirely implemented server side # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'core'} DOCUMENTATION = r''' --- module: template version_added: historical short_description: Templates a file out to a remote server description: - Templates are processed by the Jinja2 templating language (U(http://jinja.pocoo.org/docs/)) - documentation on the template formatting can be found in the Template Designer Documentation (U(http://jinja.pocoo.org/docs/templates/)). - "Six additional variables can be used in templates: C(ansible_managed) (configurable via the C(defaults) section of C(ansible.cfg)) contains a string which can be used to describe the template name, host, modification time of the template file and the owner uid. C(template_host) contains the node name of the template's machine. C(template_uid) is the numeric user id of the owner. C(template_path) is the path of the template. C(template_fullpath) is the absolute path of the template. C(template_run_date) is the date that the template was rendered." options: src: description: - Path of a Jinja2 formatted template on the Ansible controller. This can be a relative or absolute path. required: true dest: description: - Location to render the template to on the remote machine. required: true backup: description: - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. type: bool default: 'no' newline_sequence: description: - Specify the newline sequence to use for templating files. choices: [ '\n', '\r', '\r\n' ] default: '\n' version_added: '2.4' block_start_string: description: - The string marking the beginning of a block. default: '{%' version_added: '2.4' block_end_string: description: - The string marking the end of a block. default: '%}' version_added: '2.4' variable_start_string: description: - The string marking the beginning of a print statement. default: '{{' version_added: '2.4' variable_end_string: description: - The string marking the end of a print statement. default: '}}' version_added: '2.4' trim_blocks: description: - If this is set to True the first newline after a block is removed (block, not variable tag!). type: bool default: 'no' version_added: '2.4' lstrip_blocks: description: - If this is set to True leading spaces and tabs are stripped from the start of a line to a block. Setting this option to True requires Jinja2 version >=2.7. type: bool default: 'no' version_added: '2.6' force: description: - the default is C(yes), which will replace the remote file when contents are different than the source. If C(no), the file will only be transferred if the destination does not exist. type: bool default: 'yes' follow: description: - This flag indicates that filesystem links in the destination, if they exist, should be followed. - Previous to Ansible 2.4, this was hardcoded as C(yes). type: bool default: 'no' version_added: "2.4" mode: description: - "Mode the file or directory should be. For those used to I(/usr/bin/chmod) remember that modes are actually octal numbers. You must either specify the leading zero so that Ansible's YAML parser knows it is an octal number (like C(0644) or C(01777)) or quote it (like C('644') or C('0644') so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for example, C(u+rwx) or C(u=rw,g=r,o=r)). As of version 2.6, the mode may also be the special string C(preserve). C(preserve) means that the file will be given the same permissions as the source file." notes: - For Windows you can use M(win_template) which uses '\\r\\n' as C(newline_sequence). - Including a string that uses a date in the template will result in the template being marked 'changed' each time - "Since Ansible version 0.9, templates are loaded with C(trim_blocks=True)." - "Also, you can override jinja2 settings by adding a special header to template file. i.e. C(#jinja2:variable_start_string:'[%', variable_end_string:'%]', trim_blocks: False) which changes the variable interpolation markers to [% var %] instead of {{ var }}. This is the best way to prevent evaluation of things that look like, but should not be Jinja2. raw/endraw in Jinja2 will not work as you expect because templates in Ansible are recursively evaluated." - You can use the C(copy) module with the C(content:) option if you prefer the template inline, as part of the playbook. author: - Ansible Core Team - Michael DeHaan extends_documentation_fragment: - files - validate ''' EXAMPLES = r''' # Example from Ansible Playbooks - template: src: /mytemplates/foo.j2 dest: /etc/file.conf owner: bin group: wheel mode: 0644 # The same example, but using symbolic modes equivalent to 0644 - template: src: /mytemplates/foo.j2 dest: /etc/file.conf owner: bin group: wheel mode: "u=rw,g=r,o=r" # Create a DOS-style text file from a template - template: src: config.ini.j2 dest: /share/windows/config.ini newline_sequence: '\r\n' # Copy a new "sudoers" file into place, after passing validation with visudo - template: src: /mine/sudoers dest: /etc/sudoers validate: '/usr/sbin/visudo -cf %s' # Update sshd configuration safely, avoid locking yourself out - template: src: etc/ssh/sshd_config.j2 dest: /etc/ssh/sshd_config owner: root group: root mode: '0600' validate: /usr/sbin/sshd -t -f %s backup: yes '''
gpl-3.0
mrquim/repository.mrquim
repo/script.module.exodus/lib/resources/lib/modules/proxy.py
5
5052
# -*- coding: utf-8 -*- """ Exodus Add-on This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import random import re import urllib import urlparse from resources.lib.modules import client from resources.lib.modules import utils def request(url, check, close=True, redirect=True, error=False, proxy=None, post=None, headers=None, mobile=False, XHR=False, limit=None, referer=None, cookie=None, compression=True, output='', timeout='30'): try: r = client.request(url, close=close, redirect=redirect, proxy=proxy, post=post, headers=headers, mobile=mobile, XHR=XHR, limit=limit, referer=referer, cookie=cookie, compression=compression, output=output, timeout=timeout) if r is not None and error is not False: return r if check in str(r) or str(r) == '': return r proxies = sorted(get(), key=lambda x: random.random()) proxies = sorted(proxies, key=lambda x: random.random()) proxies = proxies[:3] for p in proxies: p += urllib.quote_plus(url) if post is not None: if isinstance(post, dict): post = utils.byteify(post) post = urllib.urlencode(post) p += urllib.quote_plus('?%s' % post) r = client.request(p, close=close, redirect=redirect, proxy=proxy, headers=headers, mobile=mobile, XHR=XHR, limit=limit, referer=referer, cookie=cookie, compression=compression, output=output, timeout='20') if check in str(r) or str(r) == '': return r except: pass def geturl(url): try: r = client.request(url, output='geturl') if r is None: return r host1 = re.findall('([\w]+)[.][\w]+$', urlparse.urlparse(url.strip().lower()).netloc)[0] host2 = re.findall('([\w]+)[.][\w]+$', urlparse.urlparse(r.strip().lower()).netloc)[0] if host1 == host2: return r proxies = sorted(get(), key=lambda x: random.random()) proxies = sorted(proxies, key=lambda x: random.random()) proxies = proxies[:3] for p in proxies: p += urllib.quote_plus(url) r = client.request(p, output='geturl') if r is not None: return parse(r) except: pass def parse(url): try: url = client.replaceHTMLCodes(url) except: pass try: url = urlparse.parse_qs(urlparse.urlparse(url).query)['u'][0] except: pass try: url = urlparse.parse_qs(urlparse.urlparse(url).query)['q'][0] except: pass return url def get(): return [ 'https://www.3proxy.us/index.php?hl=2e5&q=', 'https://www.4proxy.us/index.php?hl=2e5&q=', 'http://www.xxlproxy.com/index.php?hl=3e4&q=', 'http://free-proxyserver.com/browse.php?b=20&u=', 'http://proxite.net/browse.php?b=20&u=', 'http://proxydash.com/browse.php?b=20&u=', 'http://webproxy.stealthy.co/browse.php?b=20&u=', 'http://sslpro.eu/browse.php?b=20&u=', 'http://webtunnel.org/browse.php?b=20&u=', 'http://proxycloud.net/browse.php?b=20&u=', 'http://sno9.com/browse.php?b=20&u=', 'http://www.onlineipchanger.com/browse.php?b=20&u=', 'http://www.pingproxy.com/browse.php?b=20&u=', 'https://www.ip123a.com/browse.php?b=20&u=', 'http://buka.link/browse.php?b=20&u=', 'https://zend2.com/open18.php?b=20&u=', 'http://proxy.deals/browse.php?b=20&u=', 'http://freehollandproxy.com/browse.php?b=20&u=', 'http://proxy.rocks/browse.php?b=20&u=', 'http://proxy.discount/browse.php?b=20&u=', 'http://proxy.lgbt/browse.php?b=20&u=', 'http://proxy.vet/browse.php?b=20&u=', 'http://www.unblockmyweb.com/browse.php?b=20&u=', 'http://onewebproxy.com/browse.php?b=20&u=', 'http://pr0xii.com/browse.php?b=20&u=', 'http://mlproxy.science/surf.php?b=20&u=', 'https://www.prontoproxy.com/browse.php?b=20&u=', 'http://fproxy.net/browse.php?b=20&u=', #'http://www.ruby-group.xyz/browse.php?b=20&u=', #'http://securefor.com/browse.php?b=20&u=', #'http://www.singleclick.info/browse.php?b=20&u=', #'http://www.socialcommunication.xyz/browse.php?b=20&u=', #'http://www.theprotected.xyz/browse.php?b=20&u=', #'http://www.highlytrustedgroup.xyz/browse.php?b=20&u=', #'http://www.medicalawaregroup.xyz/browse.php?b=20&u=', #'http://www.proxywebsite.us/browse.php?b=20&u=', 'http://www.mybriefonline.xyz/browse.php?b=20&u=', 'http://www.navigate-online.xyz/browse.php?b=20&u=' ]
gpl-2.0
sjperkins/tensorflow
tensorflow/contrib/session_bundle/gc.py
47
6397
# 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. # ============================================================================== r"""System for specifying garbage collection (GC) of path based data. This framework allows for GC of data specified by path names, for example files on disk. gc.Path objects each represent a single item stored at a path and may be a base directory, /tmp/exports/0/... /tmp/exports/1/... ... or a fully qualified file, /tmp/train-1.ckpt /tmp/train-2.ckpt ... A gc filter function takes and returns a list of gc.Path items. Filter functions are responsible for selecting Path items for preservation or deletion. Note that functions should always return a sorted list. For example, base_dir = "/tmp" # create the directories for e in xrange(10): os.mkdir("%s/%d" % (base_dir, e), 0o755) # create a simple parser that pulls the export_version from the directory def parser(path): match = re.match("^" + base_dir + "/(\\d+)$", path.path) if not match: return None return path._replace(export_version=int(match.group(1))) path_list = gc.get_paths("/tmp", parser) # contains all ten Paths every_fifth = gc.mod_export_version(5) print every_fifth(path_list) # shows ["/tmp/0", "/tmp/5"] largest_three = gc.largest_export_versions(3) print largest_three(all_paths) # shows ["/tmp/7", "/tmp/8", "/tmp/9"] both = gc.union(every_fifth, largest_three) print both(all_paths) # shows ["/tmp/0", "/tmp/5", # "/tmp/7", "/tmp/8", "/tmp/9"] # delete everything not in 'both' to_delete = gc.negation(both) for p in to_delete(all_paths): gfile.DeleteRecursively(p.path) # deletes: "/tmp/1", "/tmp/2", # "/tmp/3", "/tmp/4", "/tmp/6", """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import heapq import math import os from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated Path = collections.namedtuple('Path', 'path export_version') @deprecated('2017-06-30', 'Please use SavedModel instead.') def largest_export_versions(n): """Creates a filter that keeps the largest n export versions. Args: n: number of versions to keep. Returns: A filter function that keeps the n largest paths. """ def keep(paths): heap = [] for idx, path in enumerate(paths): if path.export_version is not None: heapq.heappush(heap, (path.export_version, idx)) keepers = [paths[i] for _, i in heapq.nlargest(n, heap)] return sorted(keepers) return keep @deprecated('2017-06-30', 'Please use SavedModel instead.') def one_of_every_n_export_versions(n): r"""Creates a filter that keeps one of every n export versions. Args: n: interval size. Returns: A filter function that keeps exactly one path from each interval [0, n], (n, 2n], (2n, 3n], etc... If more than one path exists in an interval the largest is kept. """ def keep(paths): keeper_map = {} # map from interval to largest path seen in that interval for p in paths: if p.export_version is None: # Skip missing export_versions. continue # Find the interval (with a special case to map export_version = 0 to # interval 0. interval = math.floor( (p.export_version - 1) / n) if p.export_version else 0 existing = keeper_map.get(interval, None) if (not existing) or (existing.export_version < p.export_version): keeper_map[interval] = p return sorted(keeper_map.values()) return keep @deprecated('2017-06-30', 'Please use SavedModel instead.') def mod_export_version(n): """Creates a filter that keeps every export that is a multiple of n. Args: n: step size. Returns: A filter function that keeps paths where export_version % n == 0. """ def keep(paths): keepers = [] for p in paths: if p.export_version % n == 0: keepers.append(p) return sorted(keepers) return keep @deprecated('2017-06-30', 'Please use SavedModel instead.') def union(lf, rf): """Creates a filter that keeps the union of two filters. Args: lf: first filter rf: second filter Returns: A filter function that keeps the n largest paths. """ def keep(paths): l = set(lf(paths)) r = set(rf(paths)) return sorted(list(l|r)) return keep @deprecated('2017-06-30', 'Please use SavedModel instead.') def negation(f): """Negate a filter. Args: f: filter function to invert Returns: A filter function that returns the negation of f. """ def keep(paths): l = set(paths) r = set(f(paths)) return sorted(list(l-r)) return keep @deprecated('2017-06-30', 'Please use SavedModel instead.') def get_paths(base_dir, parser): """Gets a list of Paths in a given directory. Args: base_dir: directory. parser: a function which gets the raw Path and can augment it with information such as the export_version, or ignore the path by returning None. An example parser may extract the export version from a path such as "/tmp/exports/100" an another may extract from a full file name such as "/tmp/checkpoint-99.out". Returns: A list of Paths contained in the base directory with the parsing function applied. By default the following fields are populated, - Path.path The parsing function is responsible for populating, - Path.export_version """ raw_paths = gfile.ListDirectory(base_dir) paths = [] for r in raw_paths: p = parser(Path(os.path.join(base_dir, r), None)) if p: paths.append(p) return sorted(paths)
apache-2.0
sgubianpm/HyGSA
sdaopt/benchmark/go_benchmark_functions/go_funcs_W.py
47
9855
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import from numpy import atleast_2d, arange, sum, cos, exp, pi from .go_benchmark import Benchmark class Watson(Benchmark): r""" Watson objective function. This class defines the Watson [1]_ global optimization problem. This is a unimodal minimization problem defined as follows: .. math:: f_{\text{Watson}}(x) = \sum_{i=0}^{29} \left\{ \sum_{j=0}^4 ((j + 1)a_i^j x_{j+1}) - \left[ \sum_{j=0}^5 a_i^j x_{j+1} \right ]^2 - 1 \right\}^2 + x_1^2 Where, in this exercise, :math:`a_i = i/29`. with :math:`x_i \in [-5, 5]` for :math:`i = 1, ..., 6`. *Global optimum*: :math:`f(x) = 0.002288` for :math:`x = [-0.0158, 1.012, -0.2329, 1.260, -1.513, 0.9928]` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. TODO Jamil #161 writes equation using (j - 1). According to code in Adorio and Gavana it should be (j+1). However the equations in those papers contain (j - 1) as well. However, I've got the right global minimum!!! """ def __init__(self, dimensions=6): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-5.0] * self.N, [5.0] * self.N)) self.global_optimum = [[-0.0158, 1.012, -0.2329, 1.260, -1.513, 0.9928]] self.fglob = 0.002288 def fun(self, x, *args): self.nfev += 1 i = atleast_2d(arange(30.)).T a = i / 29. j = arange(5.) k = arange(6.) t1 = sum((j + 1) * a ** j * x[1:], axis=1) t2 = sum(a ** k * x, axis=1) inner = (t1 - t2 ** 2 - 1) ** 2 return sum(inner) + x[0] ** 2 class Wavy(Benchmark): r""" Wavy objective function. This class defines the W / Wavy [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Wavy}}(x) = 1 - \frac{1}{n} \sum_{i=1}^{n} \cos(kx_i)e^{-\frac{x_i^2}{2}} Where, in this exercise, :math:`k = 10`. The number of local minima is :math:`kn` and :math:`(k + 1)n` for odd and even :math:`k` respectively. Here, :math:`x_i \in [-\pi, \pi]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = 0` for :math:`x = [0, 0]` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-pi] * self.N, [pi] * self.N)) self.global_optimum = [[0.0 for _ in range(self.N)]] self.fglob = 0.0 self.change_dimensionality = True def fun(self, x, *args): self.nfev += 1 return 1.0 - (1.0 / self.N) * sum(cos(10 * x) * exp(-x ** 2.0 / 2.0)) class WayburnSeader01(Benchmark): r""" Wayburn and Seader 1 objective function. This class defines the Wayburn and Seader 1 [1]_ global optimization problem. This is a unimodal minimization problem defined as follows: .. math:: f_{\text{WayburnSeader01}}(x) = (x_1^6 + x_2^4 - 17)^2 + (2x_1 + x_2 - 4)^2 with :math:`x_i \in [-5, 5]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = 0` for :math:`x = [1, 2]` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-5.0] * self.N, [5.0] * self.N)) self.custom_bounds = ([-2, 2], [-2, 2]) self.global_optimum = [[1.0, 2.0]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 return (x[0] ** 6 + x[1] ** 4 - 17) ** 2 + (2 * x[0] + x[1] - 4) ** 2 class WayburnSeader02(Benchmark): r""" Wayburn and Seader 2 objective function. This class defines the Wayburn and Seader 2 [1]_ global optimization problem. This is a unimodal minimization problem defined as follows: .. math:: f_{\text{WayburnSeader02}}(x) = \left[ 1.613 - 4(x_1 - 0.3125)^2 - 4(x_2 - 1.625)^2 \right]^2 + (x_2 - 1)^2 with :math:`x_i \in [-500, 500]` for :math:`i = 1, 2`. *Global optimum*: :math:`f(x) = 0` for :math:`x = [0.2, 1]` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-500.0] * self.N, [500.0] * self.N)) self.custom_bounds = ([-1, 2], [-1, 2]) self.global_optimum = [[0.2, 1.0]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 u = (1.613 - 4 * (x[0] - 0.3125) ** 2 - 4 * (x[1] - 1.625) ** 2) ** 2 v = (x[1] - 1) ** 2 return u + v class Weierstrass(Benchmark): r""" Weierstrass objective function. This class defines the Weierstrass [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Weierstrass}}(x) = \sum_{i=1}^{n} \left [ \sum_{k=0}^{kmax} a^k \cos \left( 2 \pi b^k (x_i + 0.5) \right) - n \sum_{k=0}^{kmax} a^k \cos(\pi b^k) \right ] Where, in this exercise, :math:`kmax = 20`, :math:`a = 0.5` and :math:`b = 3`. Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-0.5, 0.5]` for :math:`i = 1, ..., n`. *Global optimum*: :math:`f(x) = 4` for :math:`x_i = 0` for :math:`i = 1, ..., n` .. [1] Mishra, S. Global Optimization by Differential Evolution and Particle Swarm Methods: Evaluation on Some Benchmark Functions. Munich Personal RePEc Archive, 2006, 1005 TODO line 1591. TODO Jamil, Gavana have got it wrong. The second term is not supposed to be included in the outer sum. Mishra code has it right as does the reference referred to in Jamil#166. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-0.5] * self.N, [0.5] * self.N)) self.global_optimum = [[0.0 for _ in range(self.N)]] self.fglob = 0 self.change_dimensionality = True def fun(self, x, *args): self.nfev += 1 kmax = 20 a, b = 0.5, 3.0 k = atleast_2d(arange(kmax + 1.)).T t1 = a ** k * cos(2 * pi * b ** k * (x + 0.5)) t2 = self.N * sum(a ** k.T * cos(pi * b ** k.T)) return sum(sum(t1, axis=0)) - t2 class Whitley(Benchmark): r""" Whitley objective function. This class defines the Whitley [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Whitley}}(x) = \sum_{i=1}^n \sum_{j=1}^n \left[\frac{(100(x_i^2-x_j)^2 + (1-x_j)^2)^2}{4000} - \cos(100(x_i^2-x_j)^2 + (1-x_j)^2)+1 \right] Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-10.24, 10.24]` for :math:`i = 1, ..., n`. *Global optimum*: :math:`f(x) = 0` for :math:`x_i = 1` for :math:`i = 1, ..., n` .. [1] Gavana, A. Global Optimization Benchmarks and AMPGO retrieved 2015 TODO Jamil#167 has '+ 1' inside the cos term, when it should be outside it. """ def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-10.24] * self.N, [10.24] * self.N)) self.custom_bounds = ([-1, 2], [-1, 2]) self.global_optimum = [[1.0 for _ in range(self.N)]] self.fglob = 0.0 self.change_dimensionality = True def fun(self, x, *args): self.nfev += 1 XI = x XJ = atleast_2d(x).T temp = 100.0 * ((XI ** 2.0) - XJ) + (1.0 - XJ) ** 2.0 inner = (temp ** 2.0 / 4000.0) - cos(temp) + 1.0 return sum(sum(inner, axis=0)) class Wolfe(Benchmark): r""" Wolfe objective function. This class defines the Wolfe [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Wolfe}}(x) = \frac{4}{3}(x_1^2 + x_2^2 - x_1x_2)^{0.75} + x_3 with :math:`x_i \in [0, 2]` for :math:`i = 1, 2, 3`. *Global optimum*: :math:`f(x) = 0` for :math:`x = [0, 0, 0]` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ def __init__(self, dimensions=3): Benchmark.__init__(self, dimensions) self._bounds = list(zip([0.0] * self.N, [2.0] * self.N)) self.global_optimum = [[0.0 for _ in range(self.N)]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 return 4 / 3 * (x[0] ** 2 + x[1] ** 2 - x[0] * x[1]) ** 0.75 + x[2]
bsd-2-clause
CERNatschool/particle-rate-plotter
timestuff/constants.py
1
1111
#!/usr/bin/env python # -*- coding: utf-8 -*- """ CERN@school: Data Profiling - Time Stuff - Constants. See http://cernatschool.web.cern.ch for more information. """ SECONDS_IN_A_MINUTE = 60 MINUTES_IN_AN_HOUR = 60 HOURS_IN_A_DAY = 24 ## Dictionary for the month start times in seconds since epoch. month_start_times = {} month_start_times["2012-01-01-000000"] = 1325376000 month_start_times["2012-02-01-000000"] = 1328054400 month_start_times["2012-03-01-000000"] = 1330560000 month_start_times["2012-04-01-000000"] = 1333238400 month_start_times["2012-05-01-000000"] = 1335830400 month_start_times["2012-06-01-000000"] = 1338508800 month_start_times["2012-07-01-000000"] = 1341100800 month_start_times["2012-08-01-000000"] = 1343779200 month_start_times["2012-09-01-000000"] = 1346457600 month_start_times["2012-10-01-000000"] = 1349049600 month_start_times["2012-11-01-000000"] = 1351728000 month_start_times["2012-12-01-000000"] = 1354320000 month_start_times["2013-01-01-000000"] = 1356998400 month_start_times["2013-02-01-000000"] = 1359676800 month_start_times["2013-03-01-000000"] = 1362096000
mit
Sweetgrassbuffalo/ReactionSweeGrass-v2
.meteor/local/dev_bundle/python/Lib/distutils/command/sdist.py
84
18557
"""distutils.command.sdist Implements the Distutils 'sdist' command (create a source distribution).""" __revision__ = "$Id$" import os import string import sys from glob import glob from warnings import warn from distutils.core import Command from distutils import dir_util, dep_util, file_util, archive_util from distutils.text_file import TextFile from distutils.errors import (DistutilsPlatformError, DistutilsOptionError, DistutilsTemplateError) from distutils.filelist import FileList from distutils import log from distutils.util import convert_path def show_formats(): """Print all possible values for the 'formats' option (used by the "--help-formats" command-line option). """ from distutils.fancy_getopt import FancyGetopt from distutils.archive_util import ARCHIVE_FORMATS formats = [] for format in ARCHIVE_FORMATS.keys(): formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2])) formats.sort() FancyGetopt(formats).print_help( "List of available source distribution formats:") class sdist(Command): description = "create a source distribution (tarball, zip file, etc.)" def checking_metadata(self): """Callable used for the check sub-command. Placed here so user_options can view it""" return self.metadata_check user_options = [ ('template=', 't', "name of manifest template file [default: MANIFEST.in]"), ('manifest=', 'm', "name of manifest file [default: MANIFEST]"), ('use-defaults', None, "include the default file set in the manifest " "[default; disable with --no-defaults]"), ('no-defaults', None, "don't include the default file set"), ('prune', None, "specifically exclude files/directories that should not be " "distributed (build tree, RCS/CVS dirs, etc.) " "[default; disable with --no-prune]"), ('no-prune', None, "don't automatically exclude anything"), ('manifest-only', 'o', "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', "forcibly regenerate the manifest and carry on as usual. " "Deprecated: now the manifest is always regenerated."), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', "keep the distribution tree around after creating " + "archive file(s)"), ('dist-dir=', 'd', "directory to put the source distribution archive(s) in " "[default: dist]"), ('metadata-check', None, "Ensure that all required elements of meta-data " "are supplied. Warn if any missing. [default]"), ('owner=', 'u', "Owner name used when creating a tar file [default: current user]"), ('group=', 'g', "Group name used when creating a tar file [default: current group]"), ] boolean_options = ['use-defaults', 'prune', 'manifest-only', 'force-manifest', 'keep-temp', 'metadata-check'] help_options = [ ('help-formats', None, "list available distribution formats", show_formats), ] negative_opt = {'no-defaults': 'use-defaults', 'no-prune': 'prune' } default_format = {'posix': 'gztar', 'nt': 'zip' } sub_commands = [('check', checking_metadata)] def initialize_options(self): # 'template' and 'manifest' are, respectively, the names of # the manifest template and manifest file. self.template = None self.manifest = None # 'use_defaults': if true, we will include the default file set # in the manifest self.use_defaults = 1 self.prune = 1 self.manifest_only = 0 self.force_manifest = 0 self.formats = None self.keep_temp = 0 self.dist_dir = None self.archive_files = None self.metadata_check = 1 self.owner = None self.group = None def finalize_options(self): if self.manifest is None: self.manifest = "MANIFEST" if self.template is None: self.template = "MANIFEST.in" self.ensure_string_list('formats') if self.formats is None: try: self.formats = [self.default_format[os.name]] except KeyError: raise DistutilsPlatformError, \ "don't know how to create source distributions " + \ "on platform %s" % os.name bad_format = archive_util.check_archive_formats(self.formats) if bad_format: raise DistutilsOptionError, \ "unknown archive format '%s'" % bad_format if self.dist_dir is None: self.dist_dir = "dist" def run(self): # 'filelist' contains the list of files that will make up the # manifest self.filelist = FileList() # Run sub commands for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) # Do whatever it takes to get the list of files to process # (process the manifest template, read an existing manifest, # whatever). File list is accumulated in 'self.filelist'. self.get_file_list() # If user just wanted us to regenerate the manifest, stop now. if self.manifest_only: return # Otherwise, go ahead and create the source distribution tarball, # or zipfile, or whatever. self.make_distribution() def check_metadata(self): """Deprecated API.""" warn("distutils.command.sdist.check_metadata is deprecated, \ use the check command instead", PendingDeprecationWarning) check = self.distribution.get_command_obj('check') check.ensure_finalized() check.run() def get_file_list(self): """Figure out the list of files to include in the source distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options. """ # new behavior when using a template: # the file list is recalculated every time because # even if MANIFEST.in or setup.py are not changed # the user might have added some files in the tree that # need to be included. # # This makes --force the default and only behavior with templates. template_exists = os.path.isfile(self.template) if not template_exists and self._manifest_is_not_generated(): self.read_manifest() self.filelist.sort() self.filelist.remove_duplicates() return if not template_exists: self.warn(("manifest template '%s' does not exist " + "(using default file list)") % self.template) self.filelist.findall() if self.use_defaults: self.add_defaults() if template_exists: self.read_template() if self.prune: self.prune_file_list() self.filelist.sort() self.filelist.remove_duplicates() self.write_manifest() def add_defaults(self): """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional. """ standards = [('README', 'README.txt'), self.distribution.script_name] for fn in standards: if isinstance(fn, tuple): alts = fn got_it = 0 for fn in alts: if os.path.exists(fn): got_it = 1 self.filelist.append(fn) break if not got_it: self.warn("standard file not found: should have one of " + string.join(alts, ', ')) else: if os.path.exists(fn): self.filelist.append(fn) else: self.warn("standard file '%s' not found" % fn) optional = ['test/test*.py', 'setup.cfg'] for pattern in optional: files = filter(os.path.isfile, glob(pattern)) if files: self.filelist.extend(files) # build_py is used to get: # - python modules # - files defined in package_data build_py = self.get_finalized_command('build_py') # getting python files if self.distribution.has_pure_modules(): self.filelist.extend(build_py.get_source_files()) # getting package_data files # (computed in build_py.data_files by build_py.finalize_options) for pkg, src_dir, build_dir, filenames in build_py.data_files: for filename in filenames: self.filelist.append(os.path.join(src_dir, filename)) # getting distribution.data_files if self.distribution.has_data_files(): for item in self.distribution.data_files: if isinstance(item, str): # plain file item = convert_path(item) if os.path.isfile(item): self.filelist.append(item) else: # a (dirname, filenames) tuple dirname, filenames = item for f in filenames: f = convert_path(f) if os.path.isfile(f): self.filelist.append(f) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') self.filelist.extend(build_ext.get_source_files()) if self.distribution.has_c_libraries(): build_clib = self.get_finalized_command('build_clib') self.filelist.extend(build_clib.get_source_files()) if self.distribution.has_scripts(): build_scripts = self.get_finalized_command('build_scripts') self.filelist.extend(build_scripts.get_source_files()) def read_template(self): """Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by 'self.filelist', which updates itself accordingly. """ log.info("reading manifest template '%s'", self.template) template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1) try: while 1: line = template.readline() if line is None: # end of file break try: self.filelist.process_template_line(line) # the call above can raise a DistutilsTemplateError for # malformed lines, or a ValueError from the lower-level # convert_path function except (DistutilsTemplateError, ValueError) as msg: self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg)) finally: template.close() def prune_file_list(self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.exclude_pattern(None, prefix=build.build_base) self.filelist.exclude_pattern(None, prefix=base_dir) # pruning out vcs directories # both separators are used under win32 if sys.platform == 'win32': seps = r'/|\\' else: seps = '/' vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs'] vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1) def write_manifest(self): """Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'. """ if self._manifest_is_not_generated(): log.info("not writing to manually maintained " "manifest file '%s'" % self.manifest) return content = self.filelist.files[:] content.insert(0, '# file GENERATED by distutils, do NOT edit') self.execute(file_util.write_file, (self.manifest, content), "writing manifest file '%s'" % self.manifest) def _manifest_is_not_generated(self): # check for special comment used in 2.7.1 and higher if not os.path.isfile(self.manifest): return False fp = open(self.manifest, 'rU') try: first_line = fp.readline() finally: fp.close() return first_line != '# file GENERATED by distutils, do NOT edit\n' def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest) for line in manifest: # ignore comments and blank lines line = line.strip() if line.startswith('#') or not line: continue self.filelist.append(line) manifest.close() def make_release_tree(self, base_dir, files): """Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer's source tree, but in a directory named after the distribution, containing only the files to be distributed. """ # Create all the directories under 'base_dir' necessary to # put 'files' there; the 'mkpath()' is just so we don't die # if the manifest happens to be empty. self.mkpath(base_dir) dir_util.create_tree(base_dir, files, dry_run=self.dry_run) # And walk over the list of files, either making a hard link (if # os.link exists) to each one that doesn't already exist in its # corresponding location under 'base_dir', or copying each file # that's out-of-date in 'base_dir'. (Usually, all files will be # out-of-date, because by default we blow away 'base_dir' when # we're done making the distribution archives.) if hasattr(os, 'link'): # can make hard links on this system link = 'hard' msg = "making hard links in %s..." % base_dir else: # nope, have to copy link = None msg = "copying files to %s..." % base_dir if not files: log.warn("no files to distribute -- empty manifest?") else: log.info(msg) for file in files: if not os.path.isfile(file): log.warn("'%s' not a regular file -- skipping" % file) else: dest = os.path.join(base_dir, file) self.copy_file(file, dest, link=link) self.distribution.metadata.write_pkg_info(base_dir) def make_distribution(self): """Create the source distribution(s). First, we create the release tree with 'make_release_tree()'; then, we create all required archive files (according to 'self.formats') from the release tree. Finally, we clean up by blowing away the release tree (unless 'self.keep_temp' is true). The list of archive files created is stored so it can be retrieved later by 'get_archive_files()'. """ # Don't warn about missing meta-data here -- should be (and is!) # done elsewhere. base_dir = self.distribution.get_fullname() base_name = os.path.join(self.dist_dir, base_dir) self.make_release_tree(base_dir, self.filelist.files) archive_files = [] # remember names of files we create # tar archive must be created last to avoid overwrite and remove if 'tar' in self.formats: self.formats.append(self.formats.pop(self.formats.index('tar'))) for fmt in self.formats: file = self.make_archive(base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group) archive_files.append(file) self.distribution.dist_files.append(('sdist', '', file)) self.archive_files = archive_files if not self.keep_temp: dir_util.remove_tree(base_dir, dry_run=self.dry_run) def get_archive_files(self): """Return the list of archive files created when the command was run, or None if the command hasn't run yet. """ return self.archive_files
gpl-3.0
caktus/rapidsms-nutrition
nutrition/forms.py
1
6598
from __future__ import unicode_literals from decimal import Decimal from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from healthcare.api import client from healthcare.exceptions import PatientDoesNotExist, ProviderDoesNotExist from nutrition.models import Report from nutrition.fields import NullDecimalField, NullYesNoField, PlainErrorList class NutritionFormBase(object): def __init__(self, *args, **kwargs): # The connection is used to retrieve the reporter. self.connection = kwargs.pop('connection') self.raw_text = kwargs.pop('raw_text') super(NutritionFormBase, self).__init__(*args, **kwargs) def clean(self): self.clean_connection() # Do this before attempting further cleaning. return super(NutritionFormBase, self).clean() def clean_connection(self): """Validate that the reporter is registered and active.""" self.reporter = None # TODO def clean_patient_id(self): """Validate that the patient is registered and active.""" patient_id = self.cleaned_data['patient_id'] source = getattr(settings, 'NUTRITION_PATIENT_HEALTHCARE_SOURCE', None) try: patient = client.patients.get(patient_id, source=source) except PatientDoesNotExist: msg = self.fields['patient_id'].error_messages['invalid'] raise forms.ValidationError(msg) if patient['status'] != 'A': msg = self.fields['patient_id'].error_messages['invalid'] raise forms.ValidationError(msg) self.patient = patient return patient_id @property def error(self): """Condense form errors into a single error message.""" for field in self.fields: # Return the first field error based on field order. if field in self.errors: return self.errors[field].as_text() if forms.forms.NON_FIELD_ERRORS in self.errors: return self.errors[forms.forms.NON_FIELD_ERRORS].as_text() return None class CancelReportForm(NutritionFormBase, forms.Form): """Cancels a patient's most recently created report.""" patient_id = forms.CharField() def __init__(self, *args, **kwargs): # Descriptive error messages. self.messages = { 'patient_id': _('Nutrition reports must be for a patient who is ' 'registered and active.'), } self.messages.update(kwargs.pop('messages', {})) if 'error_class' not in kwargs: kwargs['error_class'] = PlainErrorList super(CancelReportForm, self).__init__(*args, **kwargs) # Set the error messages. for field_name in self.messages: for msg_type in self.fields[field_name].error_messages: field = self.fields[field_name] field.error_messages[msg_type] = self.messages[field_name] def cancel(self): """Cancels the patient's most recently created report. Raises Report.DoesNotExist if the patient has no reports. """ # TODO: filter to only reports created by our connection, to # prevent a text-message race condition. # We do not filter on report status. It is possible that the most # recent report is already cancelled, but that's okay for now because # this feature is not intended to allow reporters to cancel all # reports to the beginning of time. patient_id = self.cleaned_data['patient_id'] # Report.DoesNotExist should be handled by the caller. report = Report.objects.filter(patient_id=patient_id)\ .latest('created') report.cancel() return report class CreateReportForm(NutritionFormBase, forms.ModelForm): """ Report form which can validate input from an SMS message. To send a null or unknown value, send 'x' in its place. """ oedema = NullYesNoField(required=False) weight = NullDecimalField(min_value=Decimal('0'), max_digits=4, required=False) height = NullDecimalField(min_value=Decimal('0'), max_digits=4, required=False) muac = NullDecimalField(min_value=Decimal('0'), max_digits=4, required=False) class Meta: model = Report fields = ('patient_id', 'weight', 'height', 'muac', 'oedema') def __init__(self, *args, **kwargs): # Descriptive field error messages. self.messages = { 'patient_id': _('Nutrition reports must be for a patient who ' 'is registered and active.'), 'weight': _('Please send a positive value (in kg) for weight.'), 'height': _('Please send a positive value (in cm) for height.'), 'muac': _('Please send a positive value (in cm) for mid-upper ' 'arm circumference.'), 'oedema': _('Please send Y or N to indicate whether the patient ' 'has oedema.'), } self.messages.update(kwargs.pop('messages', {})) if 'error_class' not in kwargs: kwargs['error_class'] = PlainErrorList super(CreateReportForm, self).__init__(*args, **kwargs) # Set the error messages. for field_name in self.messages: for msg_type in self.fields[field_name].error_messages: field = self.fields[field_name] field.error_messages[msg_type] = self.messages[field_name] # Add more specific sizing messages. for field_name in ('weight', 'height', 'muac'): field = self.fields[field_name] field.error_messages['max_digits'] = _('Nutrition report ' 'measurements should be no more than %s digits in length.') def save(self, *args, **kwargs): self.instance.raw_text = self.raw_text self.instance.global_patient_id = self.patient['id'] return super(CreateReportForm, self).save(*args, **kwargs) class ReportFilterForm(forms.Form): patient_id = forms.CharField(label='Patient ID', required=False) reporter_id = forms.CharField(label='Reporter ID', required=False) status = forms.ChoiceField(choices=[('', '')] + Report.STATUSES, required=False) def get_items(self): if self.is_valid(): filters = dict([(k, v) for k, v in self.cleaned_data.iteritems() if v]) return Report.objects.filter(**filters) return Report.objects.none()
bsd-3-clause
Spinmob/spinmob
_plotting_mess.py
1
40481
import os as _os import pylab as _pylab import numpy as _n import itertools as _itertools import time as _time import spinmob as _s try: from . import _functions as _fun except: import _functions as _fun try: from . import _pylab_tweaks as _pt except: import _pylab_tweaks as _pt from . import _data as _data try: from . import _data as _data except: import _data as _data # expose all the eval statements to all the functions in numpy from numpy import * from scipy.special import * # handle for the colormap so it doesn't immediately close _colormap = None def _get_standard_title(): """ Gets the standard title. """ title = 'Plot created ' + _time.asctime() # Try to add the last command to the title. try: command = list(get_ipython().history_manager.get_range())[-1][2] # Get the path of the runfile() if command[0:8] == 'runfile(': def f(*a, **kw): return a[0] command = eval('f'+command[7:], dict(f=f)) # Just the last line command = command.replace('\n', '; ') title = title + '\n' + command except: pass return title def _draw(): """ Method for interactive drawing used by all plotters at the end.""" _pylab.ion() _pylab.draw() _pylab.show() # This command always raises the figure, unfortunately, and is needed to see it on the first plot. def complex_data(data, edata=None, draw=True, **kwargs): """ Plots the imaginary vs real for complex data. Parameters ---------- data Array of complex data edata=None Array of complex error bars draw=True Draw the plot after it's assembled? See spinmob.plot.xy.data() for additional optional keyword arguments. """ _pylab.ioff() # generate the data the easy way try: rdata = _n.real(data) idata = _n.imag(data) if edata is None: erdata = None eidata = None else: erdata = _n.real(edata) eidata = _n.imag(edata) # generate the data the hard way. except: rdata = [] idata = [] if edata is None: erdata = None eidata = None else: erdata = [] eidata = [] for n in range(len(data)): rdata.append(_n.real(data[n])) idata.append(_n.imag(data[n])) if not edata is None: erdata.append(_n.real(edata[n])) eidata.append(_n.imag(edata[n])) if 'xlabel' not in kwargs: kwargs['xlabel'] = 'Real' if 'ylabel' not in kwargs: kwargs['ylabel'] = 'Imaginary' xy_data(rdata, idata, eidata, erdata, draw=False, **kwargs) if draw: _draw() def complex_databoxes(ds, script='d[1]+1j*d[2]', escript=None, **kwargs): """ Uses databoxes and specified script to generate data and send to spinmob.plot.complex_data() Parameters ---------- ds List of databoxes script='d[1]+1j*d[2]' Complex-valued script for data array. escript=None Complex-valued script for error bars See spinmob.plot.complex.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ datas = [] labels = [] if escript is None: errors = None else: errors = [] for d in ds: datas.append(d(script)) labels.append(_os.path.split(d.path)[-1]) if not escript is None: errors.append(d(escript)) complex_data(datas, errors, label=labels, **kwargs) if "draw" in kwargs and not kwargs["draw"]: return _pylab.ion() _pylab.draw() _pylab.show() return ds def complex_files(script='d[1]+1j*d[2]', escript=None, paths=None, **kwargs): """ Loads files and plots complex data in the real-imaginary plane. Parameters ---------- script='d[1]+1j*d[2]' Complex-valued script for data array. escript=None Complex-valued script for error bars paths=None List of paths to open. None means use a dialog See spinmob.plot.complex.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ ds = _data.load_multiple(paths=paths) if len(ds) == 0: return if 'title' not in kwargs: kwargs['title'] = _os.path.split(ds[0].path)[0] return complex_databoxes(ds, script=script, **kwargs) def complex_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs): """ Plots function(s) in the complex plane over the specified range. Parameters ---------- f='1.0/(1+1j*x)' Complex-valued function or list of functions to plot. These can be string functions or single-argument python functions; additional globals can be supplied by g. xmin=-1, xmax=1, steps=200 Range over which to plot and how many points to plot p='x' If using strings for functions, p is the independent parameter name. g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the x data? See spinmob.plot.xy.data() for additional optional keyword arguments. """ kwargs2 = dict(xlabel='Real', ylabel='Imaginary') kwargs2.update(kwargs) function(f, xmin, xmax, steps, p, g, erange, plotter=xy_data, complex_plane=True, draw=True, **kwargs2) def magphase_data(xdata, ydata, eydata=None, exdata=None, xscale='linear', mscale='linear', pscale='linear', mlabel='Magnitude', plabel='Phase', phase='degrees', figure='gcf', clear=1, draw=True, **kwargs): """ Plots the magnitude and phase of complex ydata vs xdata. Parameters ---------- xdata Real-valued x-axis data ydata Complex-valued y-axis data eydata=None Complex-valued y-error exdata=None Real-valued x-error xscale='linear' 'log' or 'linear' scale of the x axis mscale='linear' 'log' or 'linear' scale of the magnitude axis pscale='linear' 'log' or 'linear' scale of the phase axis mlabel='Magnitude' y-axis label for magnitude plot plabel='Phase' y-axis label for phase plot phase='degrees' 'degrees' or 'radians' for the phase axis figure='gcf' Plot on the specified figure instance or 'gcf' for current figure. clear=1 Clear the figure? draw=True Draw the figure when complete? See spinmob.plot.xy.data() for additional optional keyword arguments. """ _pylab.ioff() # set up the figure and axes if figure == 'gcf': f = _pylab.gcf() if clear: f.clear() axes1 = _pylab.subplot(211) axes2 = _pylab.subplot(212,sharex=axes1) # Make sure the dimensionality of the data sets matches xdata, ydata = _fun._match_data_sets(xdata, ydata) exdata = _fun._match_error_to_data_set(xdata, exdata) eydata = _fun._match_error_to_data_set(ydata, eydata) # convert to magnitude and phase m = [] p = [] em = [] ep = [] # Note this is a loop over data sets, not points. for l in range(len(ydata)): m.append(_n.abs(ydata[l])) p.append(_n.angle(ydata[l])) # get the mag - phase errors if eydata[l] is None: em.append(None) ep.append(None) else: er = _n.real(eydata[l]) ei = _n.imag(eydata[l]) em.append(0.5*((er+ei) + (er-ei)*_n.cos(p[l])) ) ep.append(0.5*((er+ei) - (er-ei)*_n.cos(p[l]))/m[l] ) # convert to degrees if phase=='degrees': p[-1] = p[-1]*180.0/_n.pi if not ep[l] is None: ep[l] = ep[l]*180.0/_n.pi if phase=='degrees': plabel = plabel + " (degrees)" else: plabel = plabel + " (radians)" if 'xlabel' in kwargs: xlabel=kwargs.pop('xlabel') else: xlabel='' if 'ylabel' in kwargs: kwargs.pop('ylabel') if 'autoformat' not in kwargs: kwargs['autoformat'] = True autoformat = kwargs['autoformat'] kwargs['autoformat'] = False kwargs['xlabel'] = '' xy_data(xdata, m, em, exdata, ylabel=mlabel, axes=axes1, clear=0, xscale=xscale, yscale=mscale, draw=False, **kwargs) kwargs['autoformat'] = autoformat kwargs['xlabel'] = xlabel xy_data(xdata, p, ep, exdata, ylabel=plabel, axes=axes2, clear=0, xscale=xscale, yscale=pscale, draw=False, **kwargs) axes2.set_title('') if draw: _draw() def magphase_databoxes(ds, xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, g=None, **kwargs): """ Use databoxes and scripts to generate data and plot the complex magnitude and phase versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ databoxes(ds, xscript, yscript, eyscript, exscript, plotter=magphase_data, g=g, **kwargs) def magphase_files(xscript=0, yscript='d[1]+1j*d[2]', eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's magnitude and phase versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.magphase.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ return files(xscript, yscript, eyscript, exscript, plotter=magphase_databoxes, paths=paths, g=g, **kwargs) def magphase_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs): """ Plots function(s) magnitude and phase over the specified range. Parameters ---------- f='1.0/(1+1j*x)' Complex-valued function or list of functions to plot. These can be string functions or single-argument python functions; additional globals can be supplied by g. xmin=-1, xmax=1, steps=200 Range over which to plot and how many points to plot p='x' If using strings for functions, p is the independent parameter name. g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the x data? See spinmob.plot.xy.data() for additional optional keyword arguments. """ function(f, xmin, xmax, steps, p, g, erange, plotter=magphase_data, **kwargs) def realimag_data(xdata, ydata, eydata=None, exdata=None, xscale='linear', rscale='linear', iscale='linear', rlabel='Real', ilabel='Imaginary', figure='gcf', clear=1, draw=True, **kwargs): """ Plots the real and imaginary parts of complex ydata vs xdata. Parameters ---------- xdata Real-valued x-axis data ydata Complex-valued y-axis data eydata=None Complex-valued y-error exdata=None Real-valued x-error xscale='linear' 'log' or 'linear' scale of the x axis rscale='linear' 'log' or 'linear' scale of the real axis iscale='linear' 'log' or 'linear' scale of the imaginary axis rlabel='Magnitude' y-axis label for real value plot ilabel='Phase' y-axis label for imaginary value plot figure='gcf' Plot on the specified figure instance or 'gcf' for current figure. clear=1 Clear the figure? draw=True Draw the figure when completed? See spinmob.plot.xy.data() for additional optional keyword arguments. """ _pylab.ioff() # Make sure the dimensionality of the data sets matches xdata, ydata = _fun._match_data_sets(xdata, ydata) exdata = _fun._match_error_to_data_set(xdata, exdata) eydata = _fun._match_error_to_data_set(ydata, eydata) # convert to real imag, and get error bars rdata = [] idata = [] erdata = [] eidata = [] for l in range(len(ydata)): rdata.append(_n.real(ydata[l])) idata.append(_n.imag(ydata[l])) if eydata[l] is None: erdata.append(None) eidata.append(None) else: erdata.append(_n.real(eydata[l])) eidata.append(_n.imag(eydata[l])) # set up the figure and axes if figure == 'gcf': f = _pylab.gcf() if clear: f.clear() axes1 = _pylab.subplot(211) axes2 = _pylab.subplot(212,sharex=axes1) if 'xlabel' in kwargs : xlabel=kwargs.pop('xlabel') else: xlabel='' if 'ylabel' in kwargs : kwargs.pop('ylabel') if 'tall' not in kwargs: kwargs['tall'] = False if 'autoformat' not in kwargs: kwargs['autoformat'] = True autoformat = kwargs['autoformat'] kwargs['autoformat'] = False kwargs['xlabel'] = '' xy_data(xdata, rdata, eydata=erdata, exdata=exdata, ylabel=rlabel, axes=axes1, clear=0, xscale=xscale, yscale=rscale, draw=False, **kwargs) kwargs['autoformat'] = autoformat kwargs['xlabel'] = xlabel xy_data(xdata, idata, eydata=eidata, exdata=exdata, ylabel=ilabel, axes=axes2, clear=0, xscale=xscale, yscale=iscale, draw=False, **kwargs) axes2.set_title('') if draw: _draw() def realimag_databoxes(ds, xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, g=None, **kwargs): """ Use databoxes and scripts to generate data and plot the real and imaginary ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ databoxes(ds, xscript, yscript, eyscript, exscript, plotter=realimag_data, g=g, **kwargs) def realimag_files(xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's real and imaginary parts versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]+1j*d[2]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.realimag.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ return files(xscript, yscript, eyscript, exscript, plotter=realimag_databoxes, paths=paths, g=g, **kwargs) def realimag_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs): """ Plots function(s) real and imaginary parts over the specified range. Parameters ---------- f='1.0/(1+1j*x)' Complex-valued function or list of functions to plot. These can be string functions or single-argument python functions; additional globals can be supplied by g. xmin=-1, xmax=1, steps=200 Range over which to plot and how many points to plot p='x' If using strings for functions, p is the independent parameter name. g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the x data? See spinmob.plot.xy.data() for additional optional keyword arguments. """ function(f, xmin, xmax, steps, p, g, erange, plotter=realimag_data, **kwargs) def xy_data(xdata, ydata, eydata=None, exdata=None, label=None, xlabel='', ylabel='', \ title='', shell_history=0, xshift=0, yshift=0, xshift_every=1, yshift_every=1, \ coarsen=0, style=None, clear=True, axes=None, xscale='linear', yscale='linear', grid=False, \ legend='best', legend_max=20, autoformat=True, autoformat_window=True, tall=False, draw=True, **kwargs): """ Plots specified data. Parameters ---------- xdata, ydata Arrays (or arrays of arrays) of data to plot. You can also specify None for one of these, which will result in a plot versus the data point number (starting from zero). Or you can specify a number (alone, generally not in a list) to set the scale of the auto-generated data. eydata=None, exdata=None Arrays of x and y errorbar values label=None String or array of strings for the line labels xlabel='' Label for the x-axis ylabel='' Label for the y-axis title='' Title for the axes; set to None to have nothing. shell_history=0 How many commands from the pyshell history to include with the title xshift=0, yshift=0 Progressive shifts on the data, to make waterfall plots xshift_every=1 Perform the progressive shift every 1 or n'th line. Set to 0 or False to shift all the curves by the same amount. yshift_every=1 perform the progressive shift every 1 or n'th line. Set to 0 or False to shift all the curves by the same amount. style=None style cycle object. clear=True If no axes are specified (see below), clear the figure, otherwise clear just the axes. axes=None Which matplotlib axes to use, or "gca" for the current axes xscale='linear', yscale='linear' 'linear' or 'log' x and y axis scales. grid=False Should we draw a grid on the axes? legend='best' Where to place the legend (see pylab.legend() for options) Set this to None to ignore the legend. legend_max=20 Number of legend entries before it's truncated with '...' autoformat=True Should we format the figure for printing? autoformat_window=True Should we resize and reposition the window when autoformatting? tall=False Should the format be tall? draw=True Whether or not to draw the plot and raise the figure after plotting. See matplotlib's errorbar() function for additional optional keyword arguments. """ _pylab.ioff() # Make sure the dimensionality of the data sets matches xdata, ydata = _fun._match_data_sets(xdata, ydata) exdata = _fun._match_error_to_data_set(xdata, exdata) eydata = _fun._match_error_to_data_set(ydata, eydata) # check that the labels is a list of strings of the same length if not _fun.is_iterable(label): label = [label]*len(xdata) while len(label) < len(ydata): label.append(label[0]) # concatenate if necessary if len(label) > legend_max: label[legend_max-2] = '...' for n in range(legend_max-1,len(label)-1): label[n] = "_nolegend_" # clear the figure? if clear and not axes: _pylab.gcf().clear() # axes cleared later # setup axes if axes=="gca" or not axes: axes = _pylab.gca() # if we're clearing the axes if clear: axes.clear() # set the current axes _pylab.axes(axes) # now loop over the list of data in xdata and ydata for n in range(0,len(xdata)): # get the label if label[n]=='_nolegend_': l = '_nolegend_' elif len(xdata) > 1: l = str(n)+": "+str(label[n]) else: l = str(label[n]) # calculate the x an y progressive shifts if xshift_every: dx = xshift*(n/xshift_every) else: dx = xshift if yshift_every: dy = yshift*(n/yshift_every) else: dy = yshift # if we're supposed to coarsen the data, do so. x = _fun.coarsen_array(xdata[n], coarsen) y = _fun.coarsen_array(ydata[n], coarsen) ey = _fun.coarsen_array(eydata[n], coarsen, 'quadrature') ex = _fun.coarsen_array(exdata[n], coarsen, 'quadrature') # update the style if not style is None: kwargs.update(next(style)) axes.errorbar(x+dx, y+dy, label=l, yerr=ey, xerr=ex, **kwargs) _pylab.xscale(xscale) _pylab.yscale(yscale) if legend: axes.legend(loc=legend) axes.set_xlabel(xlabel) axes.set_ylabel(ylabel) # for some arguments there should be no title. if title in [None, False, 0]: axes.set_title('') # add the commands to the title else: title = str(title) history = _fun.get_shell_history() for n in range(0, min(shell_history, len(history))): title = title + "\n" + history[n].split('\n')[0].strip() title = title + '\n' + _get_standard_title() axes.set_title(title) if grid: _pylab.grid(True) if autoformat: _pt.format_figure(draw=False, modify_geometry=autoformat_window) _pt.auto_zoom(axes=axes, draw=False) # update the canvas if draw: _draw() return axes def xy_databoxes(ds, xscript=0, yscript='d[1]', eyscript=None, exscript=None, g=None, **kwargs): """ Use databoxes and scripts to generate and plot ydata versus xdata. Parameters ---------- ds List of databoxes xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ databoxes(ds, xscript, yscript, eyscript, exscript, plotter=xy_data, g=g, **kwargs) def xy_files(xscript=0, yscript='d[1]', eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata versus xdata. Parameters ---------- xscript=0 Script for x data yscript='d[1]' Script for y data eyscript=None Script for y error exscript=None Script for x error paths=None List of paths to open. g=None Optional dictionary of globals for the scripts See spinmob.plot.xy.data() for additional optional arguments. See spinmob.data.databox.execute_script() for more information about scripts. Common additional parameters ---------------------------- filters="*.*" Set the file filters for the dialog. """ return files(xscript, yscript, eyscript, exscript, plotter=xy_databoxes, paths=paths, g=g, **kwargs) def xy_function(f='sin(x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs): """ Plots function(s) over the specified range. Parameters ---------- f='sin(x)' Function or list of functions to plot. These can be string functions or single-argument python functions; additional globals can be supplied by g. xmin=-1, xmax=1, steps=200 Range over which to plot and how many points to plot p='x' If using strings for functions, p is the independent parameter name. g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the x data? See spinmob.plot.xy.data() for additional optional keyword arguments. """ function(f, xmin, xmax, steps, p, g, erange, plotter=xy_data, **kwargs) def databoxes(ds, xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_data, transpose=False, **kwargs): """ Plots the listed databox objects with the specified scripts. ds list of databoxes xscript script for x data yscript script for y data eyscript script for y error exscript script for x error plotter function used to do the plotting transpose applies databox.transpose() prior to plotting g optional dictionary of globals for the supplied scripts **kwargs are sent to plotter() """ if not _fun.is_iterable(ds): ds = [ds] if 'xlabel' not in kwargs: kwargs['xlabel'] = str(xscript) if 'ylabel' not in kwargs: kwargs['ylabel'] = str(yscript) # First make sure everything is a list of scripts (or None's) if not _fun.is_iterable(xscript): xscript = [xscript] if not _fun.is_iterable(yscript): yscript = [yscript] if not _fun.is_iterable(exscript): exscript = [exscript] if not _fun.is_iterable(eyscript): eyscript = [eyscript] # make sure exscript matches shape with xscript (and the same for y) if len(exscript) < len(xscript): for n in range(len(xscript)-1): exscript.append(exscript[0]) if len(eyscript) < len(yscript): for n in range(len(yscript)-1): eyscript.append(eyscript[0]) # Make xscript and exscript match in shape with yscript and eyscript if len(xscript) < len(yscript): for n in range(len(yscript)-1): xscript.append(xscript[0]) exscript.append(exscript[0]) # check for the reverse possibility if len(yscript) < len(xscript): for n in range(len(xscript)-1): yscript.append(yscript[0]) eyscript.append(eyscript[0]) # now check for None's (counting scripts) for n in range(len(xscript)): if xscript[n] is None and yscript[n] is None: print("Two None scripts? But... why?") return if xscript[n] is None: if type(yscript[n])==str: xscript[n] = 'range(len('+yscript[n]+'))' else: xscript[n] = 'range(len(c('+str(yscript[n])+')))' if yscript[n] is None: if type(xscript[n])==str: yscript[n] = 'range(len('+xscript[n]+'))' else: yscript[n] = 'range(len(c('+str(xscript[n])+')))' xdatas = [] ydatas = [] exdatas = [] eydatas = [] labels = [] # Loop over all the data boxes for i in range(len(ds)): # Reset the default globals all_globals = dict(n=i,m=len(ds)-1-i) # Update them with the user-specified globals if not g==None: all_globals.update(g) # For ease of coding d = ds[i] # Take the transpose if necessary if transpose: d = d.transpose() # Generate the x-data; returns a list of outputs, one for each xscript xdata = d(xscript, all_globals) # Loop over each xdata, appending to the master list, and generating a label for n in range(len(xdata)): xdatas.append(xdata[n]) # Normal data set is a 1d array labels.append(_os.path.split(d.path)[-1]) # Special case: single-point per file if _fun.is_a_number(xdata[0]) == 1 and len(ds) > 1: labels = [_os.path.split(ds[0].path)[-1] + ' - ' + _os.path.split(ds[-1].path)[-1]] # Append the other data sets to their master lists for y in d( yscript, all_globals): ydatas.append(y) for x in d(exscript, all_globals): exdatas.append(x) for y in d(eyscript, all_globals): eydatas.append(y) if "label" in kwargs: labels = kwargs.pop("label") plotter(xdatas, ydatas, eydatas, exdatas, label=labels, **kwargs) def files(xscript=0, yscript=1, eyscript=None, exscript=None, g=None, plotter=xy_databoxes, paths=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot this data using the specified databox plotter. xscript, yscript, eyscript, exscript scripts to generate x, y, and errors g optional dictionary of globals optional: filters="*.*" to set the file filters for the dialog. **kwargs are sent to plotter() """ if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter') else: delimiter = None if 'filters' in kwargs: filters = kwargs.pop('filters') else: filters = '*.*' ds = _data.load_multiple(paths=paths, delimiter=delimiter, filters=filters) if ds is None or len(ds) == 0: return # generate a default title (the directory) if 'title' not in kwargs: kwargs['title']=_os.path.split(ds[0].path)[0] # run the databox plotter plotter(ds, xscript=xscript, yscript=yscript, eyscript=eyscript, exscript=exscript, g=g, **kwargs) return ds def function(f='sin(x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, plotter=xy_data, complex_plane=False, **kwargs): """ Plots the function over the specified range f function or list of functions to plot; can be string functions xmin, xmax, steps range over which to plot, and how many points to plot p if using strings for functions, p is the parameter name g optional dictionary of extra globals. Try g=globals() erange Use exponential spacing of the x data? plotter function used to plot the generated data complex_plane plot imag versus real of f? **kwargs are sent to spinmob.plot.real_imag.data() """ if not g: g = {} # do the opposite kind of update() for k in list(globals().keys()): if k not in g: g[k] = globals()[k] # if the x-axis is a log scale, use erange steps = int(steps) if erange: x = _fun.erange(xmin, xmax, steps) else: x = _n.linspace(xmin, xmax, steps) # make sure it's a list so we can loop over it if not type(f) in [type([]), type(())]: f = [f] # loop over the list of functions xdatas = [] ydatas = [] labels = [] for fs in f: if type(fs) == str: a = eval('lambda ' + p + ': ' + fs, g) a.__name__ = fs else: a = fs # try directly evaluating try: y = a(x) # do it the slow way. except: y = [] for z in x: y.append(a(z)) xdatas.append(x) ydatas.append(y) labels.append(a.__name__) if 'xlabel' not in kwargs: kwargs['xlabel'] = p if 'label' not in kwargs: kwargs['label'] = labels # plot! if complex_plane: plotter(_n.real(ydatas),_n.imag(ydatas), **kwargs) else: plotter(xdatas, ydatas, **kwargs) def image_data(Z, X=[0,1.0], Y=[0,1.0], aspect=1.0, zmin=None, zmax=None, clear=1, clabel='z', autoformat=True, colormap="Last Used", shell_history=0, **kwargs): """ Generates an image plot. Parameters ---------- Z 2-d array of z-values X=[0,1.0], Y=[0,1.0] 1-d array of x-values (only the first and last element are used) See matplotlib's imshow() for additional optional arguments. """ global _colormap # Set interpolation to something more relevant for every day science if not 'interpolation' in kwargs.keys(): kwargs['interpolation'] = 'nearest' _pylab.ioff() fig = _pylab.gcf() if clear: fig.clear() _pylab.axes() # generate the 3d axes X = _n.array(X) Y = _n.array(Y) Z = _n.array(Z) # assume X and Y are the bin centers and figure out the bin widths x_width = abs(float(X[-1] - X[0])/(len(Z[0])-1)) y_width = abs(float(Y[-1] - Y[0])/(len(Z)-1)) # reverse the Z's # Transpose and reverse Z = Z.transpose() Z = Z[-1::-1] # get rid of the label and title kwargs xlabel='' ylabel='' title ='' if 'xlabel' in kwargs: xlabel = kwargs.pop('xlabel') if 'ylabel' in kwargs: ylabel = kwargs.pop('ylabel') if 'title' in kwargs: title = kwargs.pop('title') _pylab.imshow(Z, extent=[X[0]-x_width/2.0, X[-1]+x_width/2.0, Y[0]-y_width/2.0, Y[-1]+y_width/2.0], **kwargs) cb = _pylab.colorbar() _pt.image_set_clim(zmin,zmax) _pt.image_set_aspect(aspect) cb.set_label(clabel) a = _pylab.gca() a.set_xlabel(xlabel) a.set_ylabel(ylabel) #_pt.close_sliders() #_pt.image_sliders() # title history = _fun.get_shell_history() for n in range(0, min(shell_history, len(history))): title = title + "\n" + history[n].split('\n')[0].strip() title = title + '\n' + _get_standard_title() a.set_title(title.strip()) if autoformat: _pt.image_format_figure(fig) _draw() # add the color sliders if colormap: if _colormap: _colormap.close() _colormap = _pt.image_colormap(colormap, image=a.images[0]) def image_function(f='sin(5*x)*cos(5*y)', xmin=-1, xmax=1, ymin=-1, ymax=1, xsteps=100, ysteps=100, p='x,y', g=None, **kwargs): """ Plots a 2-d function over the specified range Parameters ---------- f='sin(5*x)*cos(5*y)' Takes two inputs and returns one value. Can also be a string function such as sin(x*y) xmin=-1, xmax=1, ymin=-1, ymax=1 Range over which to generate/plot the data xsteps=100, ysteps=100 How many points to plot on the specified range p='x,y' If using strings for functions, this is a string of parameters. g=None Optional additional globals. Try g=globals()! See spinmob.plot.image.data() for additional optional keyword arguments. """ default_kwargs = dict(clabel=str(f), xlabel='x', ylabel='y') default_kwargs.update(kwargs) # aggregate globals if not g: g = {} for k in list(globals().keys()): if k not in g: g[k] = globals()[k] if type(f) == str: f = eval('lambda ' + p + ': ' + f, g) # generate the grid x and y coordinates xones = _n.linspace(1,1,ysteps) x = _n.linspace(xmin, xmax, xsteps) xgrid = _n.outer(xones, x) yones = _n.linspace(1,1,xsteps) y = _n.linspace(ymin, ymax, ysteps) ygrid = _n.outer(y, yones) # now get the z-grid try: # try it the fast numpy way. Add 0 to assure dimensions zgrid = f(xgrid, ygrid) + xgrid*0.0 except: print("Notice: function is not rocking hardcore. Generating grid the slow way...") # manually loop over the data to generate the z-grid zgrid = [] for ny in range(0, len(y)): zgrid.append([]) for nx in range(0, len(x)): zgrid[ny].append(f(x[nx], y[ny])) zgrid = _n.array(zgrid) # now plot! image_data(zgrid.transpose(), x, y, **default_kwargs) def image_file(path=None, zscript='self[1:]', xscript='[0,1]', yscript='d[0]', g=None, **kwargs): """ Loads an data file and plots it with color. Data file must have columns of the same length! Parameters ---------- path=None Path to data file. zscript='self[1:]' Determines how to get data from the columns xscript='[0,1]', yscript='d[0]' Determine the x and y arrays used for setting the axes bounds g=None Optional dictionary of globals for the scripts See spinmob.plot.image.data() for additional optional keyword arguments. See spinmob.data.databox.execute_script() for more information about scripts. """ if 'delimiter' in kwargs: delimiter = kwargs.pop('delimiter') else: delimiter = None d = _data.load(paths=path, delimiter = delimiter) if d is None or len(d) == 0: return # allows the user to overwrite the defaults default_kwargs = dict(xlabel = str(xscript), ylabel = str(yscript), title = d.path, clabel = str(zscript)) default_kwargs.update(kwargs) # get the data X = d(xscript, g) Y = d(yscript, g) Z = _n.array(d(zscript, g)) # Z = Z.transpose() # plot! image_data(Z, X, Y, **default_kwargs) def parametric_function(fx='sin(t)', fy='cos(t)', tmin=-1, tmax=1, steps=200, p='t', g=None, erange=False, **kwargs): """ Plots the parametric function over the specified range Parameters ---------- fx='sin(t)', fy='cos(t)' Functions or (matching) lists of functions to plot; can be string functions or python functions taking one argument tmin=-1, tmax=1, steps=200 Range over which to plot, and how many points to plot p='t' If using strings for functions, p is the parameter name g=None Optional dictionary of extra globals. Try g=globals()! erange=False Use exponential spacing of the t data? See spinmob.plot.xy.data() for additional optional keyword arguments. """ if not g: g = {} for k in list(globals().keys()): if k not in g: g[k] = globals()[k] # if the x-axis is a log scale, use erange if erange: r = _fun.erange(tmin, tmax, steps) else: r = _n.linspace(tmin, tmax, steps) # make sure it's a list so we can loop over it if not type(fy) in [type([]), type(())]: fy = [fy] if not type(fx) in [type([]), type(())]: fx = [fx] # loop over the list of functions xdatas = [] ydatas = [] labels = [] for fs in fx: if type(fs) == str: a = eval('lambda ' + p + ': ' + fs, g) a.__name__ = fs else: a = fs x = [] for z in r: x.append(a(z)) xdatas.append(x) labels.append(a.__name__) for n in range(len(fy)): fs = fy[n] if type(fs) == str: a = eval('lambda ' + p + ': ' + fs, g) a.__name__ = fs else: a = fs y = [] for z in r: y.append(a(z)) ydatas.append(y) labels[n] = labels[n]+', '+a.__name__ # plot! xy_data(xdatas, ydatas, label=labels, **kwargs) class plot_style_cycle(dict): iterators = {} def __init__(self, **kwargs): """ Supply keyword arguments that would be sent to pylab.plot(), except as a list so there is some order to follow. For example: style = plot_style_cycle(color=['k','r','b'], marker='o') """ self.iterators = {} # make sure everything is iterable for key in kwargs: if not getattr(kwargs[key],'__iter__',False): kwargs[key] = [kwargs[key]] # The base class is a dictionary, so update our own elements! self.update(kwargs) # create the auxiliary iterator dictionary self.reset() def __repr__(self): return '{style}' def __next__(self): """ Returns the next dictionary of styles to send to plot as kwargs. For example: pylab.plot([1,2,3],[1,2,1], **style.next()) """ s = {} for key in list(self.iterators.keys()): s[key] = next(self.iterators[key]) return s def reset(self): """ Resets the style cycle. """ for key in list(self.keys()): self.iterators[key] = _itertools.cycle(self[key]) return self if __name__ == '__main__': xy_files(0, 'd[1]*2**n', yscale='log')
gpl-3.0
AdoHe/kubernetes
cluster/juju/layers/kubernetes-worker/reactive/kubernetes_worker.py
1
36897
#!/usr/bin/env python # Copyright 2015 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os import random import shutil import subprocess import time from shlex import split from subprocess import check_call, check_output from subprocess import CalledProcessError from socket import gethostname from charms import layer from charms.layer import snap from charms.reactive import hook from charms.reactive import set_state, remove_state, is_state from charms.reactive import when, when_any, when_not from charms.kubernetes.common import get_version from charms.reactive.helpers import data_changed, any_file_changed from charms.templating.jinja2 import render from charmhelpers.core import hookenv, unitdata from charmhelpers.core.host import service_stop, service_restart from charmhelpers.contrib.charmsupport import nrpe # Override the default nagios shortname regex to allow periods, which we # need because our bin names contain them (e.g. 'snap.foo.daemon'). The # default regex in charmhelpers doesn't allow periods, but nagios itself does. nrpe.Check.shortname_re = '[\.A-Za-z0-9-_]+$' kubeconfig_path = '/root/cdk/kubeconfig' kubeproxyconfig_path = '/root/cdk/kubeproxyconfig' kubeclientconfig_path = '/root/.kube/config' os.environ['PATH'] += os.pathsep + os.path.join(os.sep, 'snap', 'bin') db = unitdata.kv() @hook('upgrade-charm') def upgrade_charm(): # Trigger removal of PPA docker installation if it was previously set. set_state('config.changed.install_from_upstream') hookenv.atexit(remove_state, 'config.changed.install_from_upstream') cleanup_pre_snap_services() check_resources_for_upgrade_needed() # Remove the RC for nginx ingress if it exists if hookenv.config().get('ingress'): kubectl_success('delete', 'rc', 'nginx-ingress-controller') # Remove gpu.enabled state so we can reconfigure gpu-related kubelet flags, # since they can differ between k8s versions remove_state('kubernetes-worker.gpu.enabled') remove_state('kubernetes-worker.cni-plugins.installed') remove_state('kubernetes-worker.config.created') remove_state('kubernetes-worker.ingress.available') set_state('kubernetes-worker.restart-needed') def check_resources_for_upgrade_needed(): hookenv.status_set('maintenance', 'Checking resources') resources = ['kubectl', 'kubelet', 'kube-proxy'] paths = [hookenv.resource_get(resource) for resource in resources] if any_file_changed(paths): set_upgrade_needed() def set_upgrade_needed(): set_state('kubernetes-worker.snaps.upgrade-needed') config = hookenv.config() previous_channel = config.previous('channel') require_manual = config.get('require-manual-upgrade') if previous_channel is None or not require_manual: set_state('kubernetes-worker.snaps.upgrade-specified') def cleanup_pre_snap_services(): # remove old states remove_state('kubernetes-worker.components.installed') # disable old services services = ['kubelet', 'kube-proxy'] for service in services: hookenv.log('Stopping {0} service.'.format(service)) service_stop(service) # cleanup old files files = [ "/lib/systemd/system/kubelet.service", "/lib/systemd/system/kube-proxy.service", "/etc/default/kube-default", "/etc/default/kubelet", "/etc/default/kube-proxy", "/srv/kubernetes", "/usr/local/bin/kubectl", "/usr/local/bin/kubelet", "/usr/local/bin/kube-proxy", "/etc/kubernetes" ] for file in files: if os.path.isdir(file): hookenv.log("Removing directory: " + file) shutil.rmtree(file) elif os.path.isfile(file): hookenv.log("Removing file: " + file) os.remove(file) @when('config.changed.channel') def channel_changed(): set_upgrade_needed() @when('kubernetes-worker.snaps.upgrade-needed') @when_not('kubernetes-worker.snaps.upgrade-specified') def upgrade_needed_status(): msg = 'Needs manual upgrade, run the upgrade action' hookenv.status_set('blocked', msg) @when('kubernetes-worker.snaps.upgrade-specified') def install_snaps(): check_resources_for_upgrade_needed() channel = hookenv.config('channel') hookenv.status_set('maintenance', 'Installing kubectl snap') snap.install('kubectl', channel=channel, classic=True) hookenv.status_set('maintenance', 'Installing kubelet snap') snap.install('kubelet', channel=channel, classic=True) hookenv.status_set('maintenance', 'Installing kube-proxy snap') snap.install('kube-proxy', channel=channel, classic=True) set_state('kubernetes-worker.snaps.installed') set_state('kubernetes-worker.restart-needed') remove_state('kubernetes-worker.snaps.upgrade-needed') remove_state('kubernetes-worker.snaps.upgrade-specified') @hook('stop') def shutdown(): ''' When this unit is destroyed: - delete the current node - stop the worker services ''' try: if os.path.isfile(kubeconfig_path): kubectl('delete', 'node', gethostname().lower()) except CalledProcessError: hookenv.log('Failed to unregister node.') service_stop('snap.kubelet.daemon') service_stop('snap.kube-proxy.daemon') @when('docker.available') @when_not('kubernetes-worker.cni-plugins.installed') def install_cni_plugins(): ''' Unpack the cni-plugins resource ''' charm_dir = os.getenv('CHARM_DIR') # Get the resource via resource_get try: resource_name = 'cni-{}'.format(arch()) archive = hookenv.resource_get(resource_name) except Exception: message = 'Error fetching the cni resource.' hookenv.log(message) hookenv.status_set('blocked', message) return if not archive: hookenv.log('Missing cni resource.') hookenv.status_set('blocked', 'Missing cni resource.') return # Handle null resource publication, we check if filesize < 1mb filesize = os.stat(archive).st_size if filesize < 1000000: hookenv.status_set('blocked', 'Incomplete cni resource.') return hookenv.status_set('maintenance', 'Unpacking cni resource.') unpack_path = '{}/files/cni'.format(charm_dir) os.makedirs(unpack_path, exist_ok=True) cmd = ['tar', 'xfvz', archive, '-C', unpack_path] hookenv.log(cmd) check_call(cmd) apps = [ {'name': 'loopback', 'path': '/opt/cni/bin'} ] for app in apps: unpacked = '{}/{}'.format(unpack_path, app['name']) app_path = os.path.join(app['path'], app['name']) install = ['install', '-v', '-D', unpacked, app_path] hookenv.log(install) check_call(install) # Used by the "registry" action. The action is run on a single worker, but # the registry pod can end up on any worker, so we need this directory on # all the workers. os.makedirs('/srv/registry', exist_ok=True) set_state('kubernetes-worker.cni-plugins.installed') @when('kubernetes-worker.snaps.installed') def set_app_version(): ''' Declare the application version to juju ''' cmd = ['kubelet', '--version'] version = check_output(cmd) hookenv.application_version_set(version.split(b' v')[-1].rstrip()) @when('kubernetes-worker.snaps.installed') @when_not('kube-control.dns.available') def notify_user_transient_status(): ''' Notify to the user we are in a transient state and the application is still converging. Potentially remotely, or we may be in a detached loop wait state ''' # During deployment the worker has to start kubelet without cluster dns # configured. If this is the first unit online in a service pool waiting # to self host the dns pod, and configure itself to query the dns service # declared in the kube-system namespace hookenv.status_set('waiting', 'Waiting for cluster DNS.') @when('kubernetes-worker.snaps.installed', 'kube-control.dns.available') @when_not('kubernetes-worker.snaps.upgrade-needed') def charm_status(kube_control): '''Update the status message with the current status of kubelet.''' update_kubelet_status() def update_kubelet_status(): ''' There are different states that the kubelet can be in, where we are waiting for dns, waiting for cluster turnup, or ready to serve applications.''' services = [ 'kubelet', 'kube-proxy' ] failing_services = [] for service in services: daemon = 'snap.{}.daemon'.format(service) if not _systemctl_is_active(daemon): failing_services.append(service) if len(failing_services) == 0: hookenv.status_set('active', 'Kubernetes worker running.') else: msg = 'Waiting for {} to start.'.format(','.join(failing_services)) hookenv.status_set('waiting', msg) @when('certificates.available') def send_data(tls): '''Send the data that is required to create a server certificate for this server.''' # Use the public ip of this unit as the Common Name for the certificate. common_name = hookenv.unit_public_ip() # Create SANs that the tls layer will add to the server cert. sans = [ hookenv.unit_public_ip(), hookenv.unit_private_ip(), gethostname() ] # Create a path safe name by removing path characters from the unit name. certificate_name = hookenv.local_unit().replace('/', '_') # Request a server cert with this information. tls.request_server_cert(common_name, sans, certificate_name) @when('kube-api-endpoint.available', 'kube-control.dns.available', 'cni.available') def watch_for_changes(kube_api, kube_control, cni): ''' Watch for configuration changes and signal if we need to restart the worker services ''' servers = get_kube_api_servers(kube_api) dns = kube_control.get_dns() cluster_cidr = cni.get_config()['cidr'] if (data_changed('kube-api-servers', servers) or data_changed('kube-dns', dns) or data_changed('cluster-cidr', cluster_cidr)): set_state('kubernetes-worker.restart-needed') @when('kubernetes-worker.snaps.installed', 'kube-api-endpoint.available', 'tls_client.ca.saved', 'tls_client.client.certificate.saved', 'tls_client.client.key.saved', 'tls_client.server.certificate.saved', 'tls_client.server.key.saved', 'kube-control.dns.available', 'kube-control.auth.available', 'cni.available', 'kubernetes-worker.restart-needed', 'worker.auth.bootstrapped') def start_worker(kube_api, kube_control, auth_control, cni): ''' Start kubelet using the provided API and DNS info.''' servers = get_kube_api_servers(kube_api) # Note that the DNS server doesn't necessarily exist at this point. We know # what its IP will eventually be, though, so we can go ahead and configure # kubelet with that info. This ensures that early pods are configured with # the correct DNS even though the server isn't ready yet. dns = kube_control.get_dns() cluster_cidr = cni.get_config()['cidr'] if cluster_cidr is None: hookenv.log('Waiting for cluster cidr.') return creds = db.get('credentials') data_changed('kube-control.creds', creds) # set --allow-privileged flag for kubelet set_privileged() create_config(random.choice(servers), creds) configure_kubelet(dns) configure_kube_proxy(servers, cluster_cidr) set_state('kubernetes-worker.config.created') restart_unit_services() update_kubelet_status() apply_node_labels() remove_state('kubernetes-worker.restart-needed') @when('cni.connected') @when_not('cni.configured') def configure_cni(cni): ''' Set worker configuration on the CNI relation. This lets the CNI subordinate know that we're the worker so it can respond accordingly. ''' cni.set_config(is_master=False, kubeconfig_path=kubeconfig_path) @when('config.changed.ingress') def toggle_ingress_state(): ''' Ingress is a toggled state. Remove ingress.available if set when toggled ''' remove_state('kubernetes-worker.ingress.available') @when('docker.sdn.configured') def sdn_changed(): '''The Software Defined Network changed on the container so restart the kubernetes services.''' restart_unit_services() update_kubelet_status() remove_state('docker.sdn.configured') @when('kubernetes-worker.config.created') @when_not('kubernetes-worker.ingress.available') def render_and_launch_ingress(): ''' If configuration has ingress daemon set enabled, launch the ingress load balancer and default http backend. Otherwise attempt deletion. ''' config = hookenv.config() # If ingress is enabled, launch the ingress controller if config.get('ingress'): launch_default_ingress_controller() else: hookenv.log('Deleting the http backend and ingress.') kubectl_manifest('delete', '/root/cdk/addons/default-http-backend.yaml') kubectl_manifest('delete', '/root/cdk/addons/ingress-daemon-set.yaml') # noqa hookenv.close_port(80) hookenv.close_port(443) @when('config.changed.labels', 'kubernetes-worker.config.created') def apply_node_labels(): ''' Parse the labels configuration option and apply the labels to the node. ''' # scrub and try to format an array from the configuration option config = hookenv.config() user_labels = _parse_labels(config.get('labels')) # For diffing sake, iterate the previous label set if config.previous('labels'): previous_labels = _parse_labels(config.previous('labels')) hookenv.log('previous labels: {}'.format(previous_labels)) else: # this handles first time run if there is no previous labels config previous_labels = _parse_labels("") # Calculate label removal for label in previous_labels: if label not in user_labels: hookenv.log('Deleting node label {}'.format(label)) _apply_node_label(label, delete=True) # if the label is in user labels we do nothing here, it will get set # during the atomic update below. # Atomically set a label for label in user_labels: _apply_node_label(label, overwrite=True) # Set label for application name _apply_node_label('juju-application={}'.format(hookenv.service_name()), overwrite=True) @when_any('config.changed.kubelet-extra-args', 'config.changed.proxy-extra-args') def extra_args_changed(): set_state('kubernetes-worker.restart-needed') @when('config.changed.docker-logins') def docker_logins_changed(): config = hookenv.config() previous_logins = config.previous('docker-logins') logins = config['docker-logins'] logins = json.loads(logins) if previous_logins: previous_logins = json.loads(previous_logins) next_servers = {login['server'] for login in logins} previous_servers = {login['server'] for login in previous_logins} servers_to_logout = previous_servers - next_servers for server in servers_to_logout: cmd = ['docker', 'logout', server] subprocess.check_call(cmd) for login in logins: server = login['server'] username = login['username'] password = login['password'] cmd = ['docker', 'login', server, '-u', username, '-p', password] subprocess.check_call(cmd) set_state('kubernetes-worker.restart-needed') def arch(): '''Return the package architecture as a string. Raise an exception if the architecture is not supported by kubernetes.''' # Get the package architecture for this system. architecture = check_output(['dpkg', '--print-architecture']).rstrip() # Convert the binary result into a string. architecture = architecture.decode('utf-8') return architecture def create_config(server, creds): '''Create a kubernetes configuration for the worker unit.''' # Get the options from the tls-client layer. layer_options = layer.options('tls-client') # Get all the paths to the tls information required for kubeconfig. ca = layer_options.get('ca_certificate_path') # Create kubernetes configuration in the default location for ubuntu. create_kubeconfig('/home/ubuntu/.kube/config', server, ca, token=creds['client_token'], user='ubuntu') # Make the config dir readable by the ubuntu users so juju scp works. cmd = ['chown', '-R', 'ubuntu:ubuntu', '/home/ubuntu/.kube'] check_call(cmd) # Create kubernetes configuration in the default location for root. create_kubeconfig(kubeclientconfig_path, server, ca, token=creds['client_token'], user='root') # Create kubernetes configuration for kubelet, and kube-proxy services. create_kubeconfig(kubeconfig_path, server, ca, token=creds['kubelet_token'], user='kubelet') create_kubeconfig(kubeproxyconfig_path, server, ca, token=creds['proxy_token'], user='kube-proxy') def parse_extra_args(config_key): elements = hookenv.config().get(config_key, '').split() args = {} for element in elements: if '=' in element: key, _, value = element.partition('=') args[key] = value else: args[element] = 'true' return args def configure_kubernetes_service(service, base_args, extra_args_key): db = unitdata.kv() prev_args_key = 'kubernetes-worker.prev_args.' + service prev_args = db.get(prev_args_key) or {} extra_args = parse_extra_args(extra_args_key) args = {} for arg in prev_args: # remove previous args by setting to null args[arg] = 'null' for k, v in base_args.items(): args[k] = v for k, v in extra_args.items(): args[k] = v cmd = ['snap', 'set', service] + ['%s=%s' % item for item in args.items()] check_call(cmd) db.set(prev_args_key, args) def configure_kubelet(dns): layer_options = layer.options('tls-client') ca_cert_path = layer_options.get('ca_certificate_path') server_cert_path = layer_options.get('server_certificate_path') server_key_path = layer_options.get('server_key_path') kubelet_opts = {} kubelet_opts['require-kubeconfig'] = 'true' kubelet_opts['kubeconfig'] = kubeconfig_path kubelet_opts['network-plugin'] = 'cni' kubelet_opts['v'] = '0' kubelet_opts['address'] = '0.0.0.0' kubelet_opts['port'] = '10250' kubelet_opts['cluster-domain'] = dns['domain'] kubelet_opts['anonymous-auth'] = 'false' kubelet_opts['client-ca-file'] = ca_cert_path kubelet_opts['tls-cert-file'] = server_cert_path kubelet_opts['tls-private-key-file'] = server_key_path kubelet_opts['logtostderr'] = 'true' kubelet_opts['fail-swap-on'] = 'false' if (dns['enable-kube-dns']): kubelet_opts['cluster-dns'] = dns['sdn-ip'] privileged = is_state('kubernetes-worker.privileged') kubelet_opts['allow-privileged'] = 'true' if privileged else 'false' if is_state('kubernetes-worker.gpu.enabled'): if get_version('kubelet') < (1, 6): hookenv.log('Adding --experimental-nvidia-gpus=1 to kubelet') kubelet_opts['experimental-nvidia-gpus'] = '1' else: hookenv.log('Adding --feature-gates=Accelerators=true to kubelet') kubelet_opts['feature-gates'] = 'Accelerators=true' configure_kubernetes_service('kubelet', kubelet_opts, 'kubelet-extra-args') def configure_kube_proxy(api_servers, cluster_cidr): kube_proxy_opts = {} kube_proxy_opts['cluster-cidr'] = cluster_cidr kube_proxy_opts['kubeconfig'] = kubeproxyconfig_path kube_proxy_opts['logtostderr'] = 'true' kube_proxy_opts['v'] = '0' kube_proxy_opts['master'] = random.choice(api_servers) if b'lxc' in check_output('virt-what', shell=True): kube_proxy_opts['conntrack-max-per-core'] = '0' configure_kubernetes_service('kube-proxy', kube_proxy_opts, 'proxy-extra-args') def create_kubeconfig(kubeconfig, server, ca, key=None, certificate=None, user='ubuntu', context='juju-context', cluster='juju-cluster', password=None, token=None): '''Create a configuration for Kubernetes based on path using the supplied arguments for values of the Kubernetes server, CA, key, certificate, user context and cluster.''' if not key and not certificate and not password and not token: raise ValueError('Missing authentication mechanism.') # token and password are mutually exclusive. Error early if both are # present. The developer has requested an impossible situation. # see: kubectl config set-credentials --help if token and password: raise ValueError('Token and Password are mutually exclusive.') # Create the config file with the address of the master server. cmd = 'kubectl config --kubeconfig={0} set-cluster {1} ' \ '--server={2} --certificate-authority={3} --embed-certs=true' check_call(split(cmd.format(kubeconfig, cluster, server, ca))) # Delete old users cmd = 'kubectl config --kubeconfig={0} unset users' check_call(split(cmd.format(kubeconfig))) # Create the credentials using the client flags. cmd = 'kubectl config --kubeconfig={0} ' \ 'set-credentials {1} '.format(kubeconfig, user) if key and certificate: cmd = '{0} --client-key={1} --client-certificate={2} '\ '--embed-certs=true'.format(cmd, key, certificate) if password: cmd = "{0} --username={1} --password={2}".format(cmd, user, password) # This is mutually exclusive from password. They will not work together. if token: cmd = "{0} --token={1}".format(cmd, token) check_call(split(cmd)) # Create a default context with the cluster. cmd = 'kubectl config --kubeconfig={0} set-context {1} ' \ '--cluster={2} --user={3}' check_call(split(cmd.format(kubeconfig, context, cluster, user))) # Make the config use this new context. cmd = 'kubectl config --kubeconfig={0} use-context {1}' check_call(split(cmd.format(kubeconfig, context))) @when_any('config.changed.default-backend-image', 'config.changed.nginx-image') def launch_default_ingress_controller(): ''' Launch the Kubernetes ingress controller & default backend (404) ''' config = hookenv.config() # need to test this in case we get in # here from a config change to the image if not config.get('ingress'): return context = {} context['arch'] = arch() addon_path = '/root/cdk/addons/{}' context['defaultbackend_image'] = config.get('default-backend-image') if (context['defaultbackend_image'] == "" or context['defaultbackend_image'] == "auto"): if context['arch'] == 's390x': context['defaultbackend_image'] = \ "gcr.io/google_containers/defaultbackend-s390x:1.4" else: context['defaultbackend_image'] = \ "gcr.io/google_containers/defaultbackend:1.4" # Render the default http backend (404) replicationcontroller manifest manifest = addon_path.format('default-http-backend.yaml') render('default-http-backend.yaml', manifest, context) hookenv.log('Creating the default http backend.') try: kubectl('apply', '-f', manifest) except CalledProcessError as e: hookenv.log(e) hookenv.log('Failed to create default-http-backend. Will attempt again next update.') # noqa hookenv.close_port(80) hookenv.close_port(443) return # Render the ingress daemon set controller manifest context['ingress_image'] = config.get('nginx-image') if context['ingress_image'] == "" or context['ingress_image'] == "auto": if context['arch'] == 's390x': context['ingress_image'] = \ "docker.io/cdkbot/nginx-ingress-controller-s390x:0.9.0-beta.13" else: context['ingress_image'] = \ "gcr.io/google_containers/nginx-ingress-controller:0.9.0-beta.15" # noqa context['juju_application'] = hookenv.service_name() manifest = addon_path.format('ingress-daemon-set.yaml') render('ingress-daemon-set.yaml', manifest, context) hookenv.log('Creating the ingress daemon set.') try: kubectl('apply', '-f', manifest) except CalledProcessError as e: hookenv.log(e) hookenv.log('Failed to create ingress controller. Will attempt again next update.') # noqa hookenv.close_port(80) hookenv.close_port(443) return set_state('kubernetes-worker.ingress.available') hookenv.open_port(80) hookenv.open_port(443) def restart_unit_services(): '''Restart worker services.''' hookenv.log('Restarting kubelet and kube-proxy.') services = ['kube-proxy', 'kubelet'] for service in services: service_restart('snap.%s.daemon' % service) def get_kube_api_servers(kube_api): '''Return the kubernetes api server address and port for this relationship.''' hosts = [] # Iterate over every service from the relation object. for service in kube_api.services(): for unit in service['hosts']: hosts.append('https://{0}:{1}'.format(unit['hostname'], unit['port'])) return hosts def kubectl(*args): ''' Run a kubectl cli command with a config file. Returns stdout and throws an error if the command fails. ''' command = ['kubectl', '--kubeconfig=' + kubeclientconfig_path] + list(args) hookenv.log('Executing {}'.format(command)) return check_output(command) def kubectl_success(*args): ''' Runs kubectl with the given args. Returns True if succesful, False if not. ''' try: kubectl(*args) return True except CalledProcessError: return False def kubectl_manifest(operation, manifest): ''' Wrap the kubectl creation command when using filepath resources :param operation - one of get, create, delete, replace :param manifest - filepath to the manifest ''' # Deletions are a special case if operation == 'delete': # Ensure we immediately remove requested resources with --now return kubectl_success(operation, '-f', manifest, '--now') else: # Guard against an error re-creating the same manifest multiple times if operation == 'create': # If we already have the definition, its probably safe to assume # creation was true. if kubectl_success('get', '-f', manifest): hookenv.log('Skipping definition for {}'.format(manifest)) return True # Execute the requested command that did not match any of the special # cases above return kubectl_success(operation, '-f', manifest) @when('nrpe-external-master.available') @when_not('nrpe-external-master.initial-config') def initial_nrpe_config(nagios=None): set_state('nrpe-external-master.initial-config') update_nrpe_config(nagios) @when('kubernetes-worker.config.created') @when('nrpe-external-master.available') @when_any('config.changed.nagios_context', 'config.changed.nagios_servicegroups') def update_nrpe_config(unused=None): services = ('snap.kubelet.daemon', 'snap.kube-proxy.daemon') hostname = nrpe.get_nagios_hostname() current_unit = nrpe.get_nagios_unit_name() nrpe_setup = nrpe.NRPE(hostname=hostname) nrpe.add_init_service_checks(nrpe_setup, services, current_unit) nrpe_setup.write() @when_not('nrpe-external-master.available') @when('nrpe-external-master.initial-config') def remove_nrpe_config(nagios=None): remove_state('nrpe-external-master.initial-config') # List of systemd services for which the checks will be removed services = ('snap.kubelet.daemon', 'snap.kube-proxy.daemon') # The current nrpe-external-master interface doesn't handle a lot of logic, # use the charm-helpers code for now. hostname = nrpe.get_nagios_hostname() nrpe_setup = nrpe.NRPE(hostname=hostname) for service in services: nrpe_setup.remove_check(shortname=service) def set_privileged(): """Update the allow-privileged flag for kubelet. """ privileged = hookenv.config('allow-privileged') if privileged == 'auto': gpu_enabled = is_state('kubernetes-worker.gpu.enabled') privileged = 'true' if gpu_enabled else 'false' if privileged == 'true': set_state('kubernetes-worker.privileged') else: remove_state('kubernetes-worker.privileged') @when('config.changed.allow-privileged') @when('kubernetes-worker.config.created') def on_config_allow_privileged_change(): """React to changed 'allow-privileged' config value. """ set_state('kubernetes-worker.restart-needed') remove_state('config.changed.allow-privileged') @when('cuda.installed') @when('kubernetes-worker.config.created') @when_not('kubernetes-worker.gpu.enabled') def enable_gpu(): """Enable GPU usage on this node. """ config = hookenv.config() if config['allow-privileged'] == "false": hookenv.status_set( 'active', 'GPUs available. Set allow-privileged="auto" to enable.' ) return hookenv.log('Enabling gpu mode') try: # Not sure why this is necessary, but if you don't run this, k8s will # think that the node has 0 gpus (as shown by the output of # `kubectl get nodes -o yaml` check_call(['nvidia-smi']) except CalledProcessError as cpe: hookenv.log('Unable to communicate with the NVIDIA driver.') hookenv.log(cpe) return # Apply node labels _apply_node_label('gpu=true', overwrite=True) _apply_node_label('cuda=true', overwrite=True) set_state('kubernetes-worker.gpu.enabled') set_state('kubernetes-worker.restart-needed') @when('kubernetes-worker.gpu.enabled') @when_not('kubernetes-worker.privileged') @when_not('kubernetes-worker.restart-needed') def disable_gpu(): """Disable GPU usage on this node. This handler fires when we're running in gpu mode, and then the operator sets allow-privileged="false". Since we can no longer run privileged containers, we need to disable gpu mode. """ hookenv.log('Disabling gpu mode') # Remove node labels _apply_node_label('gpu', delete=True) _apply_node_label('cuda', delete=True) remove_state('kubernetes-worker.gpu.enabled') set_state('kubernetes-worker.restart-needed') @when('kubernetes-worker.gpu.enabled') @when('kube-control.connected') def notify_master_gpu_enabled(kube_control): """Notify kubernetes-master that we're gpu-enabled. """ kube_control.set_gpu(True) @when_not('kubernetes-worker.gpu.enabled') @when('kube-control.connected') def notify_master_gpu_not_enabled(kube_control): """Notify kubernetes-master that we're not gpu-enabled. """ kube_control.set_gpu(False) @when('kube-control.connected') def request_kubelet_and_proxy_credentials(kube_control): """ Request kubelet node authorization with a well formed kubelet user. This also implies that we are requesting kube-proxy auth. """ # The kube-cotrol interface is created to support RBAC. # At this point we might as well do the right thing and return the hostname # even if it will only be used when we enable RBAC nodeuser = 'system:node:{}'.format(gethostname().lower()) kube_control.set_auth_request(nodeuser) @when('kube-control.connected') def catch_change_in_creds(kube_control): """Request a service restart in case credential updates were detected.""" nodeuser = 'system:node:{}'.format(gethostname().lower()) creds = kube_control.get_auth_credentials(nodeuser) if creds \ and data_changed('kube-control.creds', creds) \ and creds['user'] == nodeuser: # We need to cache the credentials here because if the # master changes (master leader dies and replaced by a new one) # the new master will have no recollection of our certs. db.set('credentials', creds) set_state('worker.auth.bootstrapped') set_state('kubernetes-worker.restart-needed') @when_not('kube-control.connected') def missing_kube_control(): """Inform the operator they need to add the kube-control relation. If deploying via bundle this won't happen, but if operator is upgrading a a charm in a deployment that pre-dates the kube-control relation, it'll be missing. """ hookenv.status_set( 'blocked', 'Relate {}:kube-control kubernetes-master:kube-control'.format( hookenv.service_name())) @when('docker.ready') def fix_iptables_for_docker_1_13(): """ Fix iptables FORWARD policy for Docker >=1.13 https://github.com/kubernetes/kubernetes/issues/40182 https://github.com/kubernetes/kubernetes/issues/39823 """ cmd = ['iptables', '-w', '300', '-P', 'FORWARD', 'ACCEPT'] check_call(cmd) def _systemctl_is_active(application): ''' Poll systemctl to determine if the application is running ''' cmd = ['systemctl', 'is-active', application] try: raw = check_output(cmd) return b'active' in raw except Exception: return False class GetNodeNameFailed(Exception): pass def get_node_name(): # Get all the nodes in the cluster cmd = 'kubectl --kubeconfig={} get no -o=json'.format(kubeconfig_path) cmd = cmd.split() deadline = time.time() + 60 while time.time() < deadline: try: raw = check_output(cmd) break except CalledProcessError: hookenv.log('Failed to get node name for node %s.' ' Will retry.' % (gethostname())) time.sleep(1) else: msg = 'Failed to get node name for node %s' % gethostname() raise GetNodeNameFailed(msg) result = json.loads(raw.decode('utf-8')) if 'items' in result: for node in result['items']: if 'status' not in node: continue if 'addresses' not in node['status']: continue # find the hostname for address in node['status']['addresses']: if address['type'] == 'Hostname': if address['address'] == gethostname(): return node['metadata']['name'] # if we didn't match, just bail to the next node break msg = 'Failed to get node name for node %s' % gethostname() raise GetNodeNameFailed(msg) class ApplyNodeLabelFailed(Exception): pass def _apply_node_label(label, delete=False, overwrite=False): ''' Invoke kubectl to apply node label changes ''' nodename = get_node_name() # TODO: Make this part of the kubectl calls instead of a special string cmd_base = 'kubectl --kubeconfig={0} label node {1} {2}' if delete is True: label_key = label.split('=')[0] cmd = cmd_base.format(kubeconfig_path, nodename, label_key) cmd = cmd + '-' else: cmd = cmd_base.format(kubeconfig_path, nodename, label) if overwrite: cmd = '{} --overwrite'.format(cmd) cmd = cmd.split() deadline = time.time() + 60 while time.time() < deadline: code = subprocess.call(cmd) if code == 0: break hookenv.log('Failed to apply label %s, exit code %d. Will retry.' % ( label, code)) time.sleep(1) else: msg = 'Failed to apply label %s' % label raise ApplyNodeLabelFailed(msg) def _parse_labels(labels): ''' Parse labels from a key=value string separated by space.''' label_array = labels.split(' ') sanitized_labels = [] for item in label_array: if '=' in item: sanitized_labels.append(item) else: hookenv.log('Skipping malformed option: {}'.format(item)) return sanitized_labels
apache-2.0
damdam-s/OCB
addons/calendar/__openerp__.py
269
1999
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2011 OpenERP S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Calendar', 'version': '1.0', 'depends': ['base', 'mail', 'base_action_rule', 'web_calendar'], 'summary': 'Personal & Shared Calendar', 'description': """ This is a full-featured calendar system. ======================================== It supports: ------------ - Calendar of events - Recurring events If you need to manage your meetings, you should install the CRM module. """, 'author': 'OpenERP SA', 'category': 'Hidden/Dependency', 'website': 'https://www.odoo.com/page/crm', 'demo': ['calendar_demo.xml'], 'data': [ 'calendar_cron.xml', 'security/ir.model.access.csv', 'security/calendar_security.xml', 'calendar_view.xml', 'calendar_data.xml', 'views/calendar.xml', ], 'qweb': ['static/src/xml/*.xml'], 'test': [ 'test/calendar_test.yml', 'test/test_calendar_recurrent_event_case2.yml' ], 'installable': True, 'application': True, 'auto_install': False, }
agpl-3.0
croneter/PlexKodiConnect
resources/lib/skip_plex_intro.py
2
1366
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals from .windows.skip_intro import SkipIntroDialog from . import app, variables as v def skip_intro(intros): try: progress = app.APP.player.getTime() except RuntimeError: # XBMC is not playing any media file yet return in_intro = False for start, end in intros: if start <= progress < end: in_intro = True if in_intro and app.APP.skip_intro_dialog is None: app.APP.skip_intro_dialog = SkipIntroDialog('script-plex-skip_intro.xml', v.ADDON_PATH, 'default', '1080i', intro_end=end) app.APP.skip_intro_dialog.show() elif not in_intro and app.APP.skip_intro_dialog is not None: app.APP.skip_intro_dialog.close() app.APP.skip_intro_dialog = None def check(): with app.APP.lock_playqueues: if len(app.PLAYSTATE.active_players) != 1: return playerid = list(app.PLAYSTATE.active_players)[0] intros = app.PLAYSTATE.player_states[playerid]['intro_markers'] if not intros: return skip_intro(intros)
gpl-2.0
ktdreyer/ceph-deploy
ceph_deploy/util/log.py
14
1974
import logging import sys BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) COLORS = { 'WARNING': YELLOW, 'INFO': WHITE, 'DEBUG': BLUE, 'CRITICAL': RED, 'ERROR': RED, 'FATAL': RED, } RESET_SEQ = "\033[0m" COLOR_SEQ = "\033[1;%dm" BOLD_SEQ = "\033[1m" BASE_COLOR_FORMAT = "[$BOLD%(name)s$RESET][%(color_levelname)-17s] %(message)s" BASE_FORMAT = "[%(name)s][%(levelname)-6s] %(message)s" def supports_color(): """ Returns True if the running system's terminal supports color, and False otherwise. """ unsupported_platform = (sys.platform in ('win32', 'Pocket PC')) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() if unsupported_platform or not is_a_tty: return False return True def color_message(message): message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ) return message class ColoredFormatter(logging.Formatter): """ A very basic logging formatter that not only applies color to the levels of the ouput but will also truncate the level names so that they do not alter the visuals of logging when presented on the terminal. """ def __init__(self, msg): logging.Formatter.__init__(self, msg) def format(self, record): levelname = record.levelname truncated_level = record.levelname[:6] levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + truncated_level + RESET_SEQ record.color_levelname = levelname_color return logging.Formatter.format(self, record) def color_format(): """ Main entry point to get a colored formatter, it will use the BASE_FORMAT by default and fall back to no colors if the system does not support it """ str_format = BASE_COLOR_FORMAT if supports_color() else BASE_FORMAT color_format = color_message(str_format) return ColoredFormatter(color_format)
mit
cchamberlain/gyp
PRESUBMIT.py
88
3685
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Top-level presubmit script for GYP. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into gcl. """ PYLINT_BLACKLIST = [ # TODO: fix me. # From SCons, not done in google style. 'test/lib/TestCmd.py', 'test/lib/TestCommon.py', 'test/lib/TestGyp.py', ] PYLINT_DISABLED_WARNINGS = [ # TODO: fix me. # Many tests include modules they don't use. 'W0611', # Possible unbalanced tuple unpacking with sequence. 'W0632', # Attempting to unpack a non-sequence. 'W0633', # Include order doesn't properly include local files? 'F0401', # Some use of built-in names. 'W0622', # Some unused variables. 'W0612', # Operator not preceded/followed by space. 'C0323', 'C0322', # Unnecessary semicolon. 'W0301', # Unused argument. 'W0613', # String has no effect (docstring in wrong place). 'W0105', # map/filter on lambda could be replaced by comprehension. 'W0110', # Use of eval. 'W0123', # Comma not followed by space. 'C0324', # Access to a protected member. 'W0212', # Bad indent. 'W0311', # Line too long. 'C0301', # Undefined variable. 'E0602', # Not exception type specified. 'W0702', # No member of that name. 'E1101', # Dangerous default {}. 'W0102', # Cyclic import. 'R0401', # Others, too many to sort. 'W0201', 'W0232', 'E1103', 'W0621', 'W0108', 'W0223', 'W0231', 'R0201', 'E0101', 'C0321', # ************* Module copy # W0104:427,12:_test.odict.__setitem__: Statement seems to have no effect 'W0104', ] def CheckChangeOnUpload(input_api, output_api): report = [] report.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api)) return report def CheckChangeOnCommit(input_api, output_api): report = [] # Accept any year number from 2009 to the current year. current_year = int(input_api.time.strftime('%Y')) allowed_years = (str(s) for s in reversed(xrange(2009, current_year + 1))) years_re = '(' + '|'.join(allowed_years) + ')' # The (c) is deprecated, but tolerate it until it's removed from all files. license = ( r'.*? Copyright (\(c\) )?%(year)s Google Inc\. All rights reserved\.\n' r'.*? Use of this source code is governed by a BSD-style license that ' r'can be\n' r'.*? found in the LICENSE file\.\n' ) % { 'year': years_re, } report.extend(input_api.canned_checks.PanProjectChecks( input_api, output_api, license_header=license)) report.extend(input_api.canned_checks.CheckTreeIsOpen( input_api, output_api, 'http://gyp-status.appspot.com/status', 'http://gyp-status.appspot.com/current')) import os import sys old_sys_path = sys.path try: sys.path = ['pylib', 'test/lib'] + sys.path blacklist = PYLINT_BLACKLIST if sys.platform == 'win32': blacklist = [os.path.normpath(x).replace('\\', '\\\\') for x in PYLINT_BLACKLIST] report.extend(input_api.canned_checks.RunPylint( input_api, output_api, black_list=blacklist, disabled_warnings=PYLINT_DISABLED_WARNINGS)) finally: sys.path = old_sys_path return report TRYBOTS = [ 'gyp-win32', 'gyp-win64', 'gyp-linux', 'gyp-mac', ] def GetPreferredTryMasters(_, change): return { 'tryserver.nacl': { t: set(['defaulttests']) for t in TRYBOTS }, }
bsd-3-clause
mrquim/mrquimrepo
script.module.schism.common/lib/js2py/legecy_translators/constants.py
31
10955
from string import ascii_lowercase, digits ################################## StringName = u'PyJsConstantString%d_' NumberName = u'PyJsConstantNumber%d_' RegExpName = u'PyJsConstantRegExp%d_' ################################## ALPHAS = set(ascii_lowercase+ ascii_lowercase.upper()) NUMS = set(digits) IDENTIFIER_START = ALPHAS.union(NUMS) ESCAPE_CHARS = {'n', '0', 'b', 'f', 'r', 't', 'v', '"', "'", '\\'} OCTAL = {'0', '1', '2', '3', '4', '5', '6', '7'} HEX = set('0123456789abcdefABCDEF') from utils import * IDENTIFIER_PART = IDENTIFIER_PART.union({'.'}) def _is_cancelled(source, n): cancelled = False k = 0 while True: k+=1 if source[n-k]!='\\': break cancelled = not cancelled return cancelled def _ensure_regexp(source, n): #<- this function has to be improved '''returns True if regexp starts at n else returns False checks whether it is not a division ''' markers = '(+~"\'=[%:?!*^|&-,;/\\' k = 0 while True: k+=1 if n-k<0: return True char = source[n-k] if char in markers: return True if char!=' ' and char!='\n': break return False def parse_num(source, start, charset): """Returns a first index>=start of chat not in charset""" while start<len(source) and source[start] in charset: start+=1 return start def parse_exponent(source, start): """returns end of exponential, raises SyntaxError if failed""" if not source[start] in ['e', 'E']: if source[start] in IDENTIFIER_PART: raise SyntaxError('Invalid number literal!') return start start += 1 if source[start] in ['-', '+']: start += 1 FOUND = False # we need at least one dig after exponent while source[start] in NUMS: FOUND = True start+=1 if not FOUND or source[start] in IDENTIFIER_PART: raise SyntaxError('Invalid number literal!') return start def remove_constants(source): '''Replaces Strings and Regexp literals in the source code with identifiers and *removes comments*. Identifier is of the format: PyJsStringConst(String const number)_ - for Strings PyJsRegExpConst(RegExp const number)_ - for RegExps Returns dict which relates identifier and replaced constant. Removes single line and multiline comments from JavaScript source code Pseudo comments (inside strings) will not be removed. For example this line: var x = "/*PSEUDO COMMENT*/ TEXT //ANOTHER PSEUDO COMMENT" will be unaltered''' source=' '+source+'\n' comments = [] inside_comment, single_comment = False, False inside_single, inside_double = False, False inside_regexp = False regexp_class_count = 0 n = 0 while n < len(source): char = source[n] if char=='"' and not (inside_comment or inside_single or inside_regexp): if not _is_cancelled(source, n): if inside_double: inside_double[1] = n+1 comments.append(inside_double) inside_double = False else: inside_double = [n, None, 0] elif char=="'" and not (inside_comment or inside_double or inside_regexp): if not _is_cancelled(source, n): if inside_single: inside_single[1] = n+1 comments.append(inside_single) inside_single = False else: inside_single = [n, None, 0] elif (inside_single or inside_double): if char in LINE_TERMINATOR: if _is_cancelled(source, n): if char==CR and source[n+1]==LF: n+=1 n+=1 continue else: raise SyntaxError('Invalid string literal. Line terminators must be escaped!') else: if inside_comment: if single_comment: if char in LINE_TERMINATOR: inside_comment[1] = n comments.append(inside_comment) inside_comment = False single_comment = False else: # Multiline if char=='/' and source[n-1]=='*': inside_comment[1] = n+1 comments.append(inside_comment) inside_comment = False elif inside_regexp: if not quiting_regexp: if char in LINE_TERMINATOR: raise SyntaxError('Invalid regexp literal. Line terminators cant appear!') if _is_cancelled(source, n): n+=1 continue if char=='[': regexp_class_count += 1 elif char==']': regexp_class_count = max(regexp_class_count-1, 0) elif char=='/' and not regexp_class_count: quiting_regexp = True else: if char not in IDENTIFIER_START: inside_regexp[1] = n comments.append(inside_regexp) inside_regexp = False elif char=='/' and source[n-1]=='/': single_comment = True inside_comment = [n-1, None, 1] elif char=='*' and source[n-1]=='/': inside_comment = [n-1, None, 1] elif char=='/' and source[n+1] not in ('/', '*'): if not _ensure_regexp(source, n): #<- improve this one n+=1 continue #Probably just a division quiting_regexp = False inside_regexp = [n, None, 2] elif not (inside_comment or inside_regexp): if (char in NUMS and source[n-1] not in IDENTIFIER_PART) or char=='.': if char=='.': k = parse_num(source,n+1, NUMS) if k==n+1: # just a stupid dot... n+=1 continue k = parse_exponent(source, k) elif char=='0' and source[n+1] in ['x', 'X']: #Hex number probably k = parse_num(source, n+2, HEX) if k==n+2 or source[k] in IDENTIFIER_PART: raise SyntaxError('Invalid hex literal!') else: #int or exp or flot or exp flot k = parse_num(source, n+1, NUMS) if source[k]=='.': k = parse_num(source, k+1, NUMS) k = parse_exponent(source, k) comments.append((n, k, 3)) n = k continue n+=1 res = '' start = 0 count = 0 constants = {} for end, next_start, typ in comments: res += source[start:end] start = next_start if typ==0: # String name = StringName elif typ==1: # comment continue elif typ==2: # regexp name = RegExpName elif typ==3: # number name = NumberName else: raise RuntimeError() res += ' '+name % count+' ' constants[name % count] = source[end: next_start] count += 1 res+=source[start:] # remove this stupid white space for e in WHITE: res = res.replace(e, ' ') res = res.replace(CR+LF, '\n') for e in LINE_TERMINATOR: res = res.replace(e, '\n') return res.strip(), constants def recover_constants(py_source, replacements): #now has n^2 complexity. improve to n '''Converts identifiers representing Js constants to the PyJs constants PyJsNumberConst_1_ which has the true value of 5 will be converted to PyJsNumber(5)''' for identifier, value in replacements.iteritems(): if identifier.startswith('PyJsConstantRegExp'): py_source = py_source.replace(identifier, 'JsRegExp(%s)'%repr(value)) elif identifier.startswith('PyJsConstantString'): py_source = py_source.replace(identifier, 'Js(u%s)' % unify_string_literals(value)) else: py_source = py_source.replace(identifier, 'Js(%s)'%value) return py_source def unify_string_literals(js_string): """this function parses the string just like javascript for example literal '\d' in JavaScript would be interpreted as 'd' - backslash would be ignored and in Pyhon this would be interpreted as '\\d' This function fixes this problem.""" n = 0 res = '' limit = len(js_string) while n < limit: char = js_string[n] if char=='\\': new, n = do_escape(js_string, n) res += new else: res += char n += 1 return res def unify_regexp_literals(js): pass def do_escape(source, n): """Its actually quite complicated to cover every case :) http://www.javascriptkit.com/jsref/escapesequence.shtml""" if not n+1 < len(source): return '' # not possible here but can be possible in general case. if source[n+1] in LINE_TERMINATOR: if source[n+1]==CR and n+2<len(source) and source[n+2]==LF: return source[n:n+3], n+3 return source[n:n+2], n+2 if source[n+1] in ESCAPE_CHARS: return source[n:n+2], n+2 if source[n+1]in ['x', 'u']: char, length = ('u', 4) if source[n+1]=='u' else ('x', 2) n+=2 end = parse_num(source, n, HEX) if end-n < length: raise SyntaxError('Invalid escape sequence!') #if length==4: # return unichr(int(source[n:n+4], 16)), n+4 # <- this was a very bad way of solving this problem :) return source[n-2:n+length], n+length if source[n+1] in OCTAL: n += 1 end = parse_num(source, n, OCTAL) end = min(end, n+3) # cant be longer than 3 # now the max allowed is 377 ( in octal) and 255 in decimal max_num = 255 num = 0 len_parsed = 0 for e in source[n:end]: cand = 8*num + int(e) if cand > max_num: break num = cand len_parsed += 1 # we have to return in a different form because python may want to parse more... # for example '\777' will be parsed by python as a whole while js will use only \77 return '\\' + hex(num)[1:], n + len_parsed return source[n+1], n+2 #####TEST###### if __name__=='__main__': test = (''' ''') t, d = remove_constants(test) print t, d
gpl-2.0
ArcherSys/ArcherSys
Lib/site-packages/django/core/mail/backends/smtp.py
477
5239
"""SMTP email backend class.""" import smtplib import ssl import threading from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.message import sanitize_address from django.core.mail.utils import DNS_NAME class EmailBackend(BaseEmailBackend): """ A wrapper that manages the SMTP network connection. """ def __init__(self, host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs): super(EmailBackend, self).__init__(fail_silently=fail_silently) self.host = host or settings.EMAIL_HOST self.port = port or settings.EMAIL_PORT self.username = settings.EMAIL_HOST_USER if username is None else username self.password = settings.EMAIL_HOST_PASSWORD if password is None else password self.use_tls = settings.EMAIL_USE_TLS if use_tls is None else use_tls self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout self.ssl_keyfile = settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile self.ssl_certfile = settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile if self.use_ssl and self.use_tls: raise ValueError( "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set " "one of those settings to True.") self.connection = None self._lock = threading.RLock() def open(self): """ Ensures we have a connection to the email server. Returns whether or not a new connection was required (True or False). """ if self.connection: # Nothing to do if the connection is already open. return False connection_class = smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP # If local_hostname is not specified, socket.getfqdn() gets used. # For performance, we use the cached FQDN for local_hostname. connection_params = {'local_hostname': DNS_NAME.get_fqdn()} if self.timeout is not None: connection_params['timeout'] = self.timeout if self.use_ssl: connection_params.update({ 'keyfile': self.ssl_keyfile, 'certfile': self.ssl_certfile, }) try: self.connection = connection_class(self.host, self.port, **connection_params) # TLS/SSL are mutually exclusive, so only attempt TLS over # non-secure connections. if not self.use_ssl and self.use_tls: self.connection.ehlo() self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) self.connection.ehlo() if self.username and self.password: self.connection.login(self.username, self.password) return True except smtplib.SMTPException: if not self.fail_silently: raise def close(self): """Closes the connection to the email server.""" if self.connection is None: return try: try: self.connection.quit() except (ssl.SSLError, smtplib.SMTPServerDisconnected): # This happens when calling quit() on a TLS connection # sometimes, or when the connection was already disconnected # by the server. self.connection.close() except smtplib.SMTPException: if self.fail_silently: return raise finally: self.connection = None def send_messages(self, email_messages): """ Sends one or more EmailMessage objects and returns the number of email messages sent. """ if not email_messages: return with self._lock: new_conn_created = self.open() if not self.connection: # We failed silently on open(). # Trying to send would be pointless. return num_sent = 0 for message in email_messages: sent = self._send(message) if sent: num_sent += 1 if new_conn_created: self.close() return num_sent def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False from_email = sanitize_address(email_message.from_email, email_message.encoding) recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.recipients()] message = email_message.message() try: self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) except smtplib.SMTPException: if not self.fail_silently: raise return False return True
mit
Chiru/NVE_Simulation
NS3/src/applications/bindings/modulegen__gcc_ILP32.py
12
632959
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.applications', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## packetbb.h (module 'network'): ns3::PbbAddressLength [enumeration] module.add_enum('PbbAddressLength', ['IPV4', 'IPV6'], import_from_module='ns.network') ## ethernet-header.h (module 'network'): ns3::ethernet_header_t [enumeration] module.add_enum('ethernet_header_t', ['LENGTH', 'VLAN', 'QINQ'], import_from_module='ns.network') ## 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') ## application-container.h (module 'network'): ns3::ApplicationContainer [class] module.add_class('ApplicationContainer', import_from_module='ns.network') ## ascii-file.h (module 'network'): ns3::AsciiFile [class] module.add_class('AsciiFile', 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') ## 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']) ## average.h (module 'tools'): ns3::Average<double> [class] module.add_class('Average', import_from_module='ns.tools', template_parameters=['double']) ## 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']) ## bulk-send-helper.h (module 'applications'): ns3::BulkSendHelper [class] module.add_class('BulkSendHelper') ## 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') ## channel-list.h (module 'network'): ns3::ChannelList [class] module.add_class('ChannelList', import_from_module='ns.network') ## data-output-interface.h (module 'stats'): ns3::DataOutputCallback [class] module.add_class('DataOutputCallback', allow_subclassing=True, import_from_module='ns.stats') ## data-rate.h (module 'network'): ns3::DataRate [class] module.add_class('DataRate', import_from_module='ns.network') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## 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']) ## mac64-address.h (module 'network'): ns3::Mac64Address [class] module.add_class('Mac64Address', import_from_module='ns.network') ## mac64-address.h (module 'network'): ns3::Mac64Address [class] root_module['ns3::Mac64Address'].implicitly_converts_to(root_module['ns3::Address']) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## node-list.h (module 'network'): ns3::NodeList [class] module.add_class('NodeList', 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') ## on-off-helper.h (module 'applications'): ns3::OnOffHelper [class] module.add_class('OnOffHelper') ## packet-loss-counter.h (module 'applications'): ns3::PacketLossCounter [class] module.add_class('PacketLossCounter') ## 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-sink-helper.h (module 'applications'): ns3::PacketSinkHelper [class] module.add_class('PacketSinkHelper') ## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class] module.add_class('PacketSocketAddress', import_from_module='ns.network') ## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class] root_module['ns3::PacketSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper [class] module.add_class('PacketSocketHelper', import_from_module='ns.network') ## 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']) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock [class] module.add_class('PbbAddressTlvBlock', import_from_module='ns.network') ## packetbb.h (module 'network'): ns3::PbbTlvBlock [class] module.add_class('PbbTlvBlock', import_from_module='ns.network') ## 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') ## ping6-helper.h (module 'applications'): ns3::Ping6Helper [class] module.add_class('Ping6Helper') ## 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') ## data-calculator.h (module 'stats'): ns3::StatisticalSummary [class] module.add_class('StatisticalSummary', allow_subclassing=True, import_from_module='ns.stats') ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class] module.add_class('SystemWallClockMs', import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## 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']) ## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper [class] module.add_class('UdpClientHelper') ## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper [class] module.add_class('UdpEchoClientHelper') ## udp-echo-helper.h (module 'applications'): ns3::UdpEchoServerHelper [class] module.add_class('UdpEchoServerHelper') ## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper [class] module.add_class('UdpServerHelper') ## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper [class] module.add_class('UdpTraceClientHelper') ## v4ping-helper.h (module 'applications'): ns3::V4PingHelper [class] module.add_class('V4PingHelper') ## 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']) ## packet-socket.h (module 'network'): ns3::DeviceNameTag [class] module.add_class('DeviceNameTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## flow-id-tag.h (module 'network'): ns3::FlowIdTag [class] module.add_class('FlowIdTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader [class] module.add_class('LlcSnapHeader', import_from_module='ns.network', parent=root_module['ns3::Header']) ## 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']) ## packet-burst.h (module 'network'): ns3::PacketBurst [class] module.add_class('PacketBurst', import_from_module='ns.network', parent=root_module['ns3::Object']) ## packet-socket.h (module 'network'): ns3::PacketSocketTag [class] module.add_class('PacketSocketTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class] module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=root_module['ns3::Object']) ## queue.h (module 'network'): ns3::Queue [class] module.add_class('Queue', import_from_module='ns.network', parent=root_module['ns3::Object']) ## queue.h (module 'network'): ns3::Queue::QueueMode [enumeration] module.add_enum('QueueMode', ['QUEUE_MODE_PACKETS', 'QUEUE_MODE_BYTES'], outer_class=root_module['ns3::Queue'], import_from_module='ns.network') ## radiotap-header.h (module 'network'): ns3::RadiotapHeader [class] module.add_class('RadiotapHeader', import_from_module='ns.network', parent=root_module['ns3::Header']) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader [enumeration] module.add_enum('', ['FRAME_FLAG_NONE', 'FRAME_FLAG_CFP', 'FRAME_FLAG_SHORT_PREAMBLE', 'FRAME_FLAG_WEP', 'FRAME_FLAG_FRAGMENTED', 'FRAME_FLAG_FCS_INCLUDED', 'FRAME_FLAG_DATA_PADDING', 'FRAME_FLAG_BAD_FCS', 'FRAME_FLAG_SHORT_GUARD'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network') ## radiotap-header.h (module 'network'): ns3::RadiotapHeader [enumeration] module.add_enum('', ['CHANNEL_FLAG_NONE', 'CHANNEL_FLAG_TURBO', 'CHANNEL_FLAG_CCK', 'CHANNEL_FLAG_OFDM', 'CHANNEL_FLAG_SPECTRUM_2GHZ', 'CHANNEL_FLAG_SPECTRUM_5GHZ', 'CHANNEL_FLAG_PASSIVE', 'CHANNEL_FLAG_DYNAMIC', 'CHANNEL_FLAG_GFSK'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network') ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## red-queue.h (module 'network'): ns3::RedQueue [class] module.add_class('RedQueue', import_from_module='ns.network', parent=root_module['ns3::Queue']) ## red-queue.h (module 'network'): ns3::RedQueue [enumeration] module.add_enum('', ['DTYPE_NONE', 'DTYPE_FORCED', 'DTYPE_UNFORCED'], outer_class=root_module['ns3::RedQueue'], import_from_module='ns.network') ## red-queue.h (module 'network'): ns3::RedQueue::Stats [struct] module.add_class('Stats', import_from_module='ns.network', outer_class=root_module['ns3::RedQueue']) ## seq-ts-header.h (module 'applications'): ns3::SeqTsHeader [class] module.add_class('SeqTsHeader', parent=root_module['ns3::Header']) ## 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::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::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbAddressBlock', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbAddressBlock>'], 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::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbMessage', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbMessage>'], 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::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbPacket', 'ns3::Header', 'ns3::DefaultDeleter<ns3::PbbPacket>'], parent=root_module['ns3::Header'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbTlv', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbTlv>'], 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::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::RadvdInterface', 'ns3::empty', 'ns3::DefaultDeleter<ns3::RadvdInterface>'], 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::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::RadvdPrefix', 'ns3::empty', 'ns3::DefaultDeleter<ns3::RadvdPrefix>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketAddressTag [class] module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket-factory.h (module 'network'): ns3::SocketFactory [class] module.add_class('SocketFactory', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['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']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## application.h (module 'network'): ns3::Application [class] module.add_class('Application', import_from_module='ns.network', 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> >']) ## boolean.h (module 'core'): ns3::BooleanChecker [class] module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## boolean.h (module 'core'): ns3::BooleanValue [class] module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## bulk-send-application.h (module 'applications'): ns3::BulkSendApplication [class] module.add_class('BulkSendApplication', parent=root_module['ns3::Application']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## data-calculator.h (module 'stats'): ns3::DataCalculator [class] module.add_class('DataCalculator', import_from_module='ns.stats', parent=root_module['ns3::Object']) ## data-output-interface.h (module 'stats'): ns3::DataOutputInterface [class] module.add_class('DataOutputInterface', import_from_module='ns.stats', parent=root_module['ns3::Object']) ## data-rate.h (module 'network'): ns3::DataRateChecker [class] module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## data-rate.h (module 'network'): ns3::DataRateValue [class] module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue [class] module.add_class('DropTailQueue', import_from_module='ns.network', parent=root_module['ns3::Queue']) ## 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-model.h (module 'network'): ns3::ErrorModel [class] module.add_class('ErrorModel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## ethernet-header.h (module 'network'): ns3::EthernetHeader [class] module.add_class('EthernetHeader', import_from_module='ns.network', parent=root_module['ns3::Header']) ## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer [class] module.add_class('EthernetTrailer', import_from_module='ns.network', parent=root_module['ns3::Trailer']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class] module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## ipv4-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']) ## error-model.h (module 'network'): ns3::ListErrorModel [class] module.add_class('ListErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel']) ## 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']) ## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<double> [class] module.add_class('MinMaxAvgTotalCalculator', import_from_module='ns.stats', template_parameters=['double'], parent=[root_module['ns3::DataCalculator'], root_module['ns3::StatisticalSummary']]) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## 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']) ## onoff-application.h (module 'applications'): ns3::OnOffApplication [class] module.add_class('OnOffApplication', parent=root_module['ns3::Application']) ## 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> >']) ## packet-sink.h (module 'applications'): ns3::PacketSink [class] module.add_class('PacketSink', parent=root_module['ns3::Application']) ## packet-socket.h (module 'network'): ns3::PacketSocket [class] module.add_class('PacketSocket', import_from_module='ns.network', parent=root_module['ns3::Socket']) ## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory [class] module.add_class('PacketSocketFactory', import_from_module='ns.network', parent=root_module['ns3::SocketFactory']) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## packetbb.h (module 'network'): ns3::PbbAddressBlock [class] module.add_class('PbbAddressBlock', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >']) ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4 [class] module.add_class('PbbAddressBlockIpv4', import_from_module='ns.network', parent=root_module['ns3::PbbAddressBlock']) ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6 [class] module.add_class('PbbAddressBlockIpv6', import_from_module='ns.network', parent=root_module['ns3::PbbAddressBlock']) ## packetbb.h (module 'network'): ns3::PbbMessage [class] module.add_class('PbbMessage', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >']) ## packetbb.h (module 'network'): ns3::PbbMessageIpv4 [class] module.add_class('PbbMessageIpv4', import_from_module='ns.network', parent=root_module['ns3::PbbMessage']) ## packetbb.h (module 'network'): ns3::PbbMessageIpv6 [class] module.add_class('PbbMessageIpv6', import_from_module='ns.network', parent=root_module['ns3::PbbMessage']) ## packetbb.h (module 'network'): ns3::PbbPacket [class] module.add_class('PbbPacket', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >']) ## packetbb.h (module 'network'): ns3::PbbTlv [class] module.add_class('PbbTlv', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >']) ## ping6.h (module 'applications'): ns3::Ping6 [class] module.add_class('Ping6', parent=root_module['ns3::Application']) ## radvd.h (module 'applications'): ns3::Radvd [class] module.add_class('Radvd', parent=root_module['ns3::Application']) ## radvd-interface.h (module 'applications'): ns3::RadvdInterface [class] module.add_class('RadvdInterface', parent=root_module['ns3::SimpleRefCount< ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >']) ## radvd-prefix.h (module 'applications'): ns3::RadvdPrefix [class] module.add_class('RadvdPrefix', parent=root_module['ns3::SimpleRefCount< ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >']) ## error-model.h (module 'network'): ns3::RateErrorModel [class] module.add_class('RateErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel']) ## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit [enumeration] module.add_enum('ErrorUnit', ['ERROR_UNIT_BIT', 'ERROR_UNIT_BYTE', 'ERROR_UNIT_PACKET'], outer_class=root_module['ns3::RateErrorModel'], import_from_module='ns.network') ## error-model.h (module 'network'): ns3::ReceiveListErrorModel [class] module.add_class('ReceiveListErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel']) ## simple-channel.h (module 'network'): ns3::SimpleChannel [class] module.add_class('SimpleChannel', import_from_module='ns.network', parent=root_module['ns3::Channel']) ## simple-net-device.h (module 'network'): ns3::SimpleNetDevice [class] module.add_class('SimpleNetDevice', import_from_module='ns.network', parent=root_module['ns3::NetDevice']) ## 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']) ## udp-client.h (module 'applications'): ns3::UdpClient [class] module.add_class('UdpClient', parent=root_module['ns3::Application']) ## udp-echo-client.h (module 'applications'): ns3::UdpEchoClient [class] module.add_class('UdpEchoClient', parent=root_module['ns3::Application']) ## udp-echo-server.h (module 'applications'): ns3::UdpEchoServer [class] module.add_class('UdpEchoServer', parent=root_module['ns3::Application']) ## udp-server.h (module 'applications'): ns3::UdpServer [class] module.add_class('UdpServer', parent=root_module['ns3::Application']) ## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient [class] module.add_class('UdpTraceClient', parent=root_module['ns3::Application']) ## v4ping.h (module 'applications'): ns3::V4Ping [class] module.add_class('V4Ping', parent=root_module['ns3::Application']) ## 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']) ## error-model.h (module 'network'): ns3::BurstErrorModel [class] module.add_class('BurstErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel']) ## packetbb.h (module 'network'): ns3::PbbAddressTlv [class] module.add_class('PbbAddressTlv', import_from_module='ns.network', parent=root_module['ns3::PbbTlv']) module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type='vector') module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type='list') module.add_container('std::list< unsigned int >', 'unsigned int', container_type='list') module.add_container('std::list< ns3::Ptr< ns3::Socket > >', 'ns3::Ptr< ns3::Socket >', container_type='list') module.add_container('std::list< ns3::Ptr< ns3::RadvdPrefix > >', 'ns3::Ptr< ns3::RadvdPrefix >', container_type='list') typehandlers.add_type_alias('ns3::SequenceNumber< short unsigned int, short int >', 'ns3::SequenceNumber16') typehandlers.add_type_alias('ns3::SequenceNumber< short unsigned int, short int >*', 'ns3::SequenceNumber16*') typehandlers.add_type_alias('ns3::SequenceNumber< short unsigned int, short int >&', 'ns3::SequenceNumber16&') typehandlers.add_type_alias('ns3::SequenceNumber< unsigned int, int >', 'ns3::SequenceNumber32') typehandlers.add_type_alias('ns3::SequenceNumber< unsigned int, int >*', 'ns3::SequenceNumber32*') typehandlers.add_type_alias('ns3::SequenceNumber< unsigned int, int >&', 'ns3::SequenceNumber32&') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyRxStartCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyRxStartCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyRxStartCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyRxEndErrorCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyRxEndErrorCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyRxEndErrorCallback&') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyTxStartCallback') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyTxStartCallback*') typehandlers.add_type_alias('ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyTxStartCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyTxEndCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyTxEndCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyTxEndCallback&') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ns3::GenericPhyRxEndOkCallback') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', 'ns3::GenericPhyRxEndOkCallback*') typehandlers.add_type_alias('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', 'ns3::GenericPhyRxEndOkCallback&') ## 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 addressUtils nested_module = module.add_cpp_namespace('addressUtils') register_types_ns3_addressUtils(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_addressUtils(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3ApplicationContainer_methods(root_module, root_module['ns3::ApplicationContainer']) register_Ns3AsciiFile_methods(root_module, root_module['ns3::AsciiFile']) register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper']) register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Average__Double_methods(root_module, root_module['ns3::Average< double >']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3BulkSendHelper_methods(root_module, root_module['ns3::BulkSendHelper']) 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_Ns3ChannelList_methods(root_module, root_module['ns3::ChannelList']) register_Ns3DataOutputCallback_methods(root_module, root_module['ns3::DataOutputCallback']) register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) 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_Ns3Mac64Address_methods(root_module, root_module['ns3::Mac64Address']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3NodeList_methods(root_module, root_module['ns3::NodeList']) 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_Ns3OnOffHelper_methods(root_module, root_module['ns3::OnOffHelper']) register_Ns3PacketLossCounter_methods(root_module, root_module['ns3::PacketLossCounter']) 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_Ns3PacketSinkHelper_methods(root_module, root_module['ns3::PacketSinkHelper']) register_Ns3PacketSocketAddress_methods(root_module, root_module['ns3::PacketSocketAddress']) register_Ns3PacketSocketHelper_methods(root_module, root_module['ns3::PacketSocketHelper']) 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_Ns3PbbAddressTlvBlock_methods(root_module, root_module['ns3::PbbAddressTlvBlock']) register_Ns3PbbTlvBlock_methods(root_module, root_module['ns3::PbbTlvBlock']) 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_Ns3Ping6Helper_methods(root_module, root_module['ns3::Ping6Helper']) 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_Ns3StatisticalSummary_methods(root_module, root_module['ns3::StatisticalSummary']) register_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_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_Ns3UdpClientHelper_methods(root_module, root_module['ns3::UdpClientHelper']) register_Ns3UdpEchoClientHelper_methods(root_module, root_module['ns3::UdpEchoClientHelper']) register_Ns3UdpEchoServerHelper_methods(root_module, root_module['ns3::UdpEchoServerHelper']) register_Ns3UdpServerHelper_methods(root_module, root_module['ns3::UdpServerHelper']) register_Ns3UdpTraceClientHelper_methods(root_module, root_module['ns3::UdpTraceClientHelper']) register_Ns3V4PingHelper_methods(root_module, root_module['ns3::V4PingHelper']) 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_Ns3DeviceNameTag_methods(root_module, root_module['ns3::DeviceNameTag']) register_Ns3FlowIdTag_methods(root_module, root_module['ns3::FlowIdTag']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3LlcSnapHeader_methods(root_module, root_module['ns3::LlcSnapHeader']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PacketBurst_methods(root_module, root_module['ns3::PacketBurst']) register_Ns3PacketSocketTag_methods(root_module, root_module['ns3::PacketSocketTag']) register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper']) register_Ns3Queue_methods(root_module, root_module['ns3::Queue']) register_Ns3RadiotapHeader_methods(root_module, root_module['ns3::RadiotapHeader']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3RedQueue_methods(root_module, root_module['ns3::RedQueue']) register_Ns3RedQueueStats_methods(root_module, root_module['ns3::RedQueue::Stats']) register_Ns3SeqTsHeader_methods(root_module, root_module['ns3::SeqTsHeader']) 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__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__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >']) register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >']) register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >']) register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >']) register_Ns3SimpleRefCount__Ns3RadvdInterface_Ns3Empty_Ns3DefaultDeleter__lt__ns3RadvdInterface__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >']) register_Ns3SimpleRefCount__Ns3RadvdPrefix_Ns3Empty_Ns3DefaultDeleter__lt__ns3RadvdPrefix__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag']) register_Ns3SocketFactory_methods(root_module, root_module['ns3::SocketFactory']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_Ns3Application_methods(root_module, root_module['ns3::Application']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker']) register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue']) register_Ns3BulkSendApplication_methods(root_module, root_module['ns3::BulkSendApplication']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DataCalculator_methods(root_module, root_module['ns3::DataCalculator']) register_Ns3DataOutputInterface_methods(root_module, root_module['ns3::DataOutputInterface']) register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker']) register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3DropTailQueue_methods(root_module, root_module['ns3::DropTailQueue']) 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_Ns3ErrorModel_methods(root_module, root_module['ns3::ErrorModel']) register_Ns3EthernetHeader_methods(root_module, root_module['ns3::EthernetHeader']) register_Ns3EthernetTrailer_methods(root_module, root_module['ns3::EthernetTrailer']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_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_Ns3ListErrorModel_methods(root_module, root_module['ns3::ListErrorModel']) 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_Ns3MinMaxAvgTotalCalculator__Double_methods(root_module, root_module['ns3::MinMaxAvgTotalCalculator< double >']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OnOffApplication_methods(root_module, root_module['ns3::OnOffApplication']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3PacketSink_methods(root_module, root_module['ns3::PacketSink']) register_Ns3PacketSocket_methods(root_module, root_module['ns3::PacketSocket']) register_Ns3PacketSocketFactory_methods(root_module, root_module['ns3::PacketSocketFactory']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3PbbAddressBlock_methods(root_module, root_module['ns3::PbbAddressBlock']) register_Ns3PbbAddressBlockIpv4_methods(root_module, root_module['ns3::PbbAddressBlockIpv4']) register_Ns3PbbAddressBlockIpv6_methods(root_module, root_module['ns3::PbbAddressBlockIpv6']) register_Ns3PbbMessage_methods(root_module, root_module['ns3::PbbMessage']) register_Ns3PbbMessageIpv4_methods(root_module, root_module['ns3::PbbMessageIpv4']) register_Ns3PbbMessageIpv6_methods(root_module, root_module['ns3::PbbMessageIpv6']) register_Ns3PbbPacket_methods(root_module, root_module['ns3::PbbPacket']) register_Ns3PbbTlv_methods(root_module, root_module['ns3::PbbTlv']) register_Ns3Ping6_methods(root_module, root_module['ns3::Ping6']) register_Ns3Radvd_methods(root_module, root_module['ns3::Radvd']) register_Ns3RadvdInterface_methods(root_module, root_module['ns3::RadvdInterface']) register_Ns3RadvdPrefix_methods(root_module, root_module['ns3::RadvdPrefix']) register_Ns3RateErrorModel_methods(root_module, root_module['ns3::RateErrorModel']) register_Ns3ReceiveListErrorModel_methods(root_module, root_module['ns3::ReceiveListErrorModel']) register_Ns3SimpleChannel_methods(root_module, root_module['ns3::SimpleChannel']) register_Ns3SimpleNetDevice_methods(root_module, root_module['ns3::SimpleNetDevice']) 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_Ns3UdpClient_methods(root_module, root_module['ns3::UdpClient']) register_Ns3UdpEchoClient_methods(root_module, root_module['ns3::UdpEchoClient']) register_Ns3UdpEchoServer_methods(root_module, root_module['ns3::UdpEchoServer']) register_Ns3UdpServer_methods(root_module, root_module['ns3::UdpServer']) register_Ns3UdpTraceClient_methods(root_module, root_module['ns3::UdpTraceClient']) register_Ns3V4Ping_methods(root_module, root_module['ns3::V4Ping']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3BurstErrorModel_methods(root_module, root_module['ns3::BurstErrorModel']) register_Ns3PbbAddressTlv_methods(root_module, root_module['ns3::PbbAddressTlv']) 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_Ns3ApplicationContainer_methods(root_module, cls): ## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::ApplicationContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::ApplicationContainer const &', 'arg0')]) ## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer() [constructor] cls.add_constructor([]) ## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::Ptr<ns3::Application> application) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Application >', 'application')]) ## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(std::string name) [constructor] cls.add_constructor([param('std::string', 'name')]) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::ApplicationContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::ApplicationContainer', 'other')]) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Application >', 'application')]) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(std::string name) [member function] cls.add_method('Add', 'void', [param('std::string', 'name')]) ## application-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Application>*,std::vector<ns3::Ptr<ns3::Application>, std::allocator<ns3::Ptr<ns3::Application> > > > ns3::ApplicationContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Application > const, std::vector< ns3::Ptr< ns3::Application > > >', [], is_const=True) ## application-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Application>*,std::vector<ns3::Ptr<ns3::Application>, std::allocator<ns3::Ptr<ns3::Application> > > > ns3::ApplicationContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Application > const, std::vector< ns3::Ptr< ns3::Application > > >', [], is_const=True) ## application-container.h (module 'network'): ns3::Ptr<ns3::Application> ns3::ApplicationContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'i')], is_const=True) ## application-container.h (module 'network'): uint32_t ns3::ApplicationContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Start(ns3::Time start) [member function] cls.add_method('Start', 'void', [param('ns3::Time', 'start')]) ## application-container.h (module 'network'): void ns3::ApplicationContainer::Stop(ns3::Time stop) [member function] cls.add_method('Stop', 'void', [param('ns3::Time', 'stop')]) return def register_Ns3AsciiFile_methods(root_module, cls): ## ascii-file.h (module 'network'): ns3::AsciiFile::AsciiFile() [constructor] cls.add_constructor([]) ## ascii-file.h (module 'network'): bool ns3::AsciiFile::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## ascii-file.h (module 'network'): bool ns3::AsciiFile::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## ascii-file.h (module 'network'): void ns3::AsciiFile::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')]) ## ascii-file.h (module 'network'): void ns3::AsciiFile::Close() [member function] cls.add_method('Close', 'void', []) ## ascii-file.h (module 'network'): void ns3::AsciiFile::Read(std::string & line) [member function] cls.add_method('Read', 'void', [param('std::string &', 'line')]) ## ascii-file.h (module 'network'): static bool ns3::AsciiFile::Diff(std::string const & f1, std::string const & f2, uint64_t & lineNumber) [member function] cls.add_method('Diff', 'bool', [param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint64_t &', 'lineNumber')], is_static=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<const ns3::Packet> 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<const ns3::Packet> 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<const ns3::Packet> 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<const ns3::Packet> 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<const ns3::Packet> 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<const ns3::Packet> 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<const ns3::Packet> 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<const ns3::Packet> 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_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_Ns3Average__Double_methods(root_module, cls): ## average.h (module 'tools'): ns3::Average<double>::Average(ns3::Average<double> const & arg0) [copy constructor] cls.add_constructor([param('ns3::Average< double > const &', 'arg0')]) ## average.h (module 'tools'): ns3::Average<double>::Average() [constructor] cls.add_constructor([]) ## average.h (module 'tools'): double ns3::Average<double>::Avg() const [member function] cls.add_method('Avg', 'double', [], is_const=True) ## average.h (module 'tools'): uint32_t ns3::Average<double>::Count() const [member function] cls.add_method('Count', 'uint32_t', [], is_const=True) ## average.h (module 'tools'): double ns3::Average<double>::Error90() const [member function] cls.add_method('Error90', 'double', [], is_const=True) ## average.h (module 'tools'): double ns3::Average<double>::Error95() const [member function] cls.add_method('Error95', 'double', [], is_const=True) ## average.h (module 'tools'): double ns3::Average<double>::Error99() const [member function] cls.add_method('Error99', 'double', [], is_const=True) ## average.h (module 'tools'): double ns3::Average<double>::Max() const [member function] cls.add_method('Max', 'double', [], is_const=True) ## average.h (module 'tools'): double ns3::Average<double>::Mean() const [member function] cls.add_method('Mean', 'double', [], is_const=True) ## average.h (module 'tools'): double ns3::Average<double>::Min() const [member function] cls.add_method('Min', 'double', [], is_const=True) ## average.h (module 'tools'): void ns3::Average<double>::Reset() [member function] cls.add_method('Reset', 'void', []) ## average.h (module 'tools'): double ns3::Average<double>::Stddev() const [member function] cls.add_method('Stddev', 'double', [], is_const=True) ## average.h (module 'tools'): void ns3::Average<double>::Update(double const & x) [member function] cls.add_method('Update', 'void', [param('double const &', 'x')]) ## average.h (module 'tools'): double ns3::Average<double>::Var() const [member function] cls.add_method('Var', 'double', [], is_const=True) 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_Ns3BulkSendHelper_methods(root_module, cls): ## bulk-send-helper.h (module 'applications'): ns3::BulkSendHelper::BulkSendHelper(ns3::BulkSendHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::BulkSendHelper const &', 'arg0')]) ## bulk-send-helper.h (module 'applications'): ns3::BulkSendHelper::BulkSendHelper(std::string protocol, ns3::Address address) [constructor] cls.add_constructor([param('std::string', 'protocol'), param('ns3::Address', 'address')]) ## bulk-send-helper.h (module 'applications'): ns3::ApplicationContainer ns3::BulkSendHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## bulk-send-helper.h (module 'applications'): ns3::ApplicationContainer ns3::BulkSendHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## bulk-send-helper.h (module 'applications'): ns3::ApplicationContainer ns3::BulkSendHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('std::string', 'nodeName')], is_const=True) ## bulk-send-helper.h (module 'applications'): void ns3::BulkSendHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) 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_Ns3ChannelList_methods(root_module, cls): ## channel-list.h (module 'network'): ns3::ChannelList::ChannelList() [constructor] cls.add_constructor([]) ## channel-list.h (module 'network'): ns3::ChannelList::ChannelList(ns3::ChannelList const & arg0) [copy constructor] cls.add_constructor([param('ns3::ChannelList const &', 'arg0')]) ## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::Add(ns3::Ptr<ns3::Channel> channel) [member function] cls.add_method('Add', 'uint32_t', [param('ns3::Ptr< ns3::Channel >', 'channel')], is_static=True) ## channel-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::Begin() [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >', [], is_static=True) ## channel-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::End() [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >', [], is_static=True) ## channel-list.h (module 'network'): static ns3::Ptr<ns3::Channel> ns3::ChannelList::GetChannel(uint32_t n) [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [param('uint32_t', 'n')], is_static=True) ## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::GetNChannels() [member function] cls.add_method('GetNChannels', 'uint32_t', [], is_static=True) return def register_Ns3DataOutputCallback_methods(root_module, cls): ## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback() [constructor] cls.add_constructor([]) ## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback(ns3::DataOutputCallback const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataOutputCallback const &', 'arg0')]) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, int val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('int', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, uint32_t val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('uint32_t', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, double val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('double', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, std::string val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('std::string', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, ns3::Time val) [member function] cls.add_method('OutputSingleton', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('ns3::Time', 'val')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputStatistic(std::string key, std::string variable, ns3::StatisticalSummary const * statSum) [member function] cls.add_method('OutputStatistic', 'void', [param('std::string', 'key'), param('std::string', 'variable'), param('ns3::StatisticalSummary const *', 'statSum')], is_pure_virtual=True, is_virtual=True) return def register_Ns3DataRate_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('>=') ## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRate const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor] cls.add_constructor([param('uint64_t', 'bps')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor] cls.add_constructor([param('std::string', 'rate')]) ## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateTxTime', 'double', [param('uint32_t', 'bytes')], is_const=True) ## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function] cls.add_method('GetBitRate', 'uint64_t', [], is_const=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_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) 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_Ns3Mac64Address_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(ns3::Mac64Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac64Address const &', 'arg0')]) ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address() [constructor] cls.add_constructor([]) ## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac64Address', [], is_static=True) ## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac64Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac64-address.h (module 'network'): static bool ns3::Mac64Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeList_methods(root_module, cls): ## node-list.h (module 'network'): ns3::NodeList::NodeList() [constructor] cls.add_constructor([]) ## node-list.h (module 'network'): ns3::NodeList::NodeList(ns3::NodeList const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeList const &', 'arg0')]) ## node-list.h (module 'network'): static uint32_t ns3::NodeList::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'uint32_t', [param('ns3::Ptr< ns3::Node >', 'node')], is_static=True) ## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::Begin() [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_static=True) ## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::End() [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_static=True) ## node-list.h (module 'network'): static uint32_t ns3::NodeList::GetNNodes() [member function] cls.add_method('GetNNodes', 'uint32_t', [], is_static=True) ## node-list.h (module 'network'): static ns3::Ptr<ns3::Node> ns3::NodeList::GetNode(uint32_t n) [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'n')], is_static=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_Ns3OnOffHelper_methods(root_module, cls): ## on-off-helper.h (module 'applications'): ns3::OnOffHelper::OnOffHelper(ns3::OnOffHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OnOffHelper const &', 'arg0')]) ## on-off-helper.h (module 'applications'): ns3::OnOffHelper::OnOffHelper(std::string protocol, ns3::Address address) [constructor] cls.add_constructor([param('std::string', 'protocol'), param('ns3::Address', 'address')]) ## on-off-helper.h (module 'applications'): int64_t ns3::OnOffHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')]) ## on-off-helper.h (module 'applications'): ns3::ApplicationContainer ns3::OnOffHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## on-off-helper.h (module 'applications'): ns3::ApplicationContainer ns3::OnOffHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## on-off-helper.h (module 'applications'): ns3::ApplicationContainer ns3::OnOffHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('std::string', 'nodeName')], is_const=True) ## on-off-helper.h (module 'applications'): void ns3::OnOffHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## on-off-helper.h (module 'applications'): void ns3::OnOffHelper::SetConstantRate(ns3::DataRate dataRate, uint32_t packetSize=512) [member function] cls.add_method('SetConstantRate', 'void', [param('ns3::DataRate', 'dataRate'), param('uint32_t', 'packetSize', default_value='512')]) return def register_Ns3PacketLossCounter_methods(root_module, cls): ## packet-loss-counter.h (module 'applications'): ns3::PacketLossCounter::PacketLossCounter(ns3::PacketLossCounter const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketLossCounter const &', 'arg0')]) ## packet-loss-counter.h (module 'applications'): ns3::PacketLossCounter::PacketLossCounter(uint8_t bitmapSize) [constructor] cls.add_constructor([param('uint8_t', 'bitmapSize')]) ## packet-loss-counter.h (module 'applications'): uint16_t ns3::PacketLossCounter::GetBitMapSize() const [member function] cls.add_method('GetBitMapSize', 'uint16_t', [], is_const=True) ## packet-loss-counter.h (module 'applications'): uint32_t ns3::PacketLossCounter::GetLost() const [member function] cls.add_method('GetLost', 'uint32_t', [], is_const=True) ## packet-loss-counter.h (module 'applications'): void ns3::PacketLossCounter::NotifyReceived(uint32_t seq) [member function] cls.add_method('NotifyReceived', 'void', [param('uint32_t', 'seq')]) ## packet-loss-counter.h (module 'applications'): void ns3::PacketLossCounter::SetBitMapSize(uint16_t size) [member function] cls.add_method('SetBitMapSize', 'void', [param('uint16_t', 'size')]) 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_Ns3PacketSinkHelper_methods(root_module, cls): ## packet-sink-helper.h (module 'applications'): ns3::PacketSinkHelper::PacketSinkHelper(ns3::PacketSinkHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketSinkHelper const &', 'arg0')]) ## packet-sink-helper.h (module 'applications'): ns3::PacketSinkHelper::PacketSinkHelper(std::string protocol, ns3::Address address) [constructor] cls.add_constructor([param('std::string', 'protocol'), param('ns3::Address', 'address')]) ## packet-sink-helper.h (module 'applications'): ns3::ApplicationContainer ns3::PacketSinkHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## packet-sink-helper.h (module 'applications'): ns3::ApplicationContainer ns3::PacketSinkHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## packet-sink-helper.h (module 'applications'): ns3::ApplicationContainer ns3::PacketSinkHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('std::string', 'nodeName')], is_const=True) ## packet-sink-helper.h (module 'applications'): void ns3::PacketSinkHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_Ns3PacketSocketAddress_methods(root_module, cls): ## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress(ns3::PacketSocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketSocketAddress const &', 'arg0')]) ## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress() [constructor] cls.add_constructor([]) ## packet-socket-address.h (module 'network'): static ns3::PacketSocketAddress ns3::PacketSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::PacketSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## packet-socket-address.h (module 'network'): ns3::Address ns3::PacketSocketAddress::GetPhysicalAddress() const [member function] cls.add_method('GetPhysicalAddress', 'ns3::Address', [], is_const=True) ## packet-socket-address.h (module 'network'): uint16_t ns3::PacketSocketAddress::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint16_t', [], is_const=True) ## packet-socket-address.h (module 'network'): uint32_t ns3::PacketSocketAddress::GetSingleDevice() const [member function] cls.add_method('GetSingleDevice', 'uint32_t', [], is_const=True) ## packet-socket-address.h (module 'network'): static bool ns3::PacketSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## packet-socket-address.h (module 'network'): bool ns3::PacketSocketAddress::IsSingleDevice() const [member function] cls.add_method('IsSingleDevice', 'bool', [], is_const=True) ## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetAllDevices() [member function] cls.add_method('SetAllDevices', 'void', []) ## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetPhysicalAddress(ns3::Address const address) [member function] cls.add_method('SetPhysicalAddress', 'void', [param('ns3::Address const', 'address')]) ## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetProtocol(uint16_t protocol) [member function] cls.add_method('SetProtocol', 'void', [param('uint16_t', 'protocol')]) ## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetSingleDevice(uint32_t device) [member function] cls.add_method('SetSingleDevice', 'void', [param('uint32_t', 'device')]) return def register_Ns3PacketSocketHelper_methods(root_module, cls): ## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper() [constructor] cls.add_constructor([]) ## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper(ns3::PacketSocketHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketSocketHelper const &', 'arg0')]) ## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'void', [param('std::string', 'nodeName')], is_const=True) ## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'void', [param('ns3::NodeContainer', 'c')], is_const=True) 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_Ns3PbbAddressTlvBlock_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock(ns3::PbbAddressTlvBlock const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressTlvBlock const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Back() const [member function] cls.add_method('Back', 'ns3::Ptr< ns3::PbbAddressTlv >', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() [member function] cls.add_method('Begin', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Clear() [member function] cls.add_method('Clear', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): bool ns3::PbbAddressTlvBlock::Empty() const [member function] cls.add_method('Empty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() [member function] cls.add_method('End', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')]) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Front() const [member function] cls.add_method('Front', 'ns3::Ptr< ns3::PbbAddressTlv >', [], is_const=True) ## packetbb.h (module 'network'): uint32_t ns3::PbbAddressTlvBlock::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbAddressTlv> const tlv) [member function] cls.add_method('Insert', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbAddressTlv > const', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopBack() [member function] cls.add_method('PopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopFront() [member function] cls.add_method('PopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushBack(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function] cls.add_method('PushBack', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushFront(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function] cls.add_method('PushFront', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): int ns3::PbbAddressTlvBlock::Size() const [member function] cls.add_method('Size', 'int', [], is_const=True) return def register_Ns3PbbTlvBlock_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock(ns3::PbbTlvBlock const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbTlvBlock const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Back() const [member function] cls.add_method('Back', 'ns3::Ptr< ns3::PbbTlv >', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() [member function] cls.add_method('Begin', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Clear() [member function] cls.add_method('Clear', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): bool ns3::PbbTlvBlock::Empty() const [member function] cls.add_method('Empty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() [member function] cls.add_method('End', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')]) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Front() const [member function] cls.add_method('Front', 'ns3::Ptr< ns3::PbbTlv >', [], is_const=True) ## packetbb.h (module 'network'): uint32_t ns3::PbbTlvBlock::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position, ns3::Ptr<ns3::PbbTlv> const tlv) [member function] cls.add_method('Insert', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopBack() [member function] cls.add_method('PopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopFront() [member function] cls.add_method('PopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('PushBack', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('PushFront', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): int ns3::PbbTlvBlock::Size() const [member function] cls.add_method('Size', 'int', [], is_const=True) 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<const ns3::Packet> 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<const ns3::Packet> 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_Ns3Ping6Helper_methods(root_module, cls): ## ping6-helper.h (module 'applications'): ns3::Ping6Helper::Ping6Helper(ns3::Ping6Helper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ping6Helper const &', 'arg0')]) ## ping6-helper.h (module 'applications'): ns3::Ping6Helper::Ping6Helper() [constructor] cls.add_constructor([]) ## ping6-helper.h (module 'applications'): ns3::ApplicationContainer ns3::Ping6Helper::Install(ns3::NodeContainer c) [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')]) ## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetIfIndex(uint32_t ifIndex) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t', 'ifIndex')]) ## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetLocal(ns3::Ipv6Address ip) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv6Address', 'ip')]) ## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetRemote(ns3::Ipv6Address ip) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Ipv6Address', 'ip')]) ## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetRoutersAddress(std::vector<ns3::Ipv6Address, std::allocator<ns3::Ipv6Address> > routers) [member function] cls.add_method('SetRoutersAddress', 'void', [param('std::vector< ns3::Ipv6Address >', 'routers')]) 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_Ns3StatisticalSummary_methods(root_module, cls): ## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary() [constructor] cls.add_constructor([]) ## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary(ns3::StatisticalSummary const & arg0) [copy constructor] cls.add_constructor([param('ns3::StatisticalSummary const &', 'arg0')]) ## data-calculator.h (module 'stats'): long int ns3::StatisticalSummary::getCount() const [member function] cls.add_method('getCount', 'long int', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMax() const [member function] cls.add_method('getMax', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMean() const [member function] cls.add_method('getMean', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMin() const [member function] cls.add_method('getMin', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSqrSum() const [member function] cls.add_method('getSqrSum', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getStddev() const [member function] cls.add_method('getStddev', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSum() const [member function] cls.add_method('getSum', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getVariance() const [member function] cls.add_method('getVariance', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3SystemWallClockMs_methods(root_module, cls): ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [copy constructor] cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')]) ## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor] cls.add_constructor([]) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function] cls.add_method('End', 'int64_t', []) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function] cls.add_method('GetElapsedReal', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function] cls.add_method('GetElapsedSystem', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function] cls.add_method('GetElapsedUser', 'int64_t', [], is_const=True) ## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function] cls.add_method('Start', 'void', []) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [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_Ns3UdpClientHelper_methods(root_module, cls): ## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::UdpClientHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpClientHelper const &', 'arg0')]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper() [constructor] cls.add_constructor([]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::Ipv4Address ip, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::Ipv6Address ip, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::Address ip, uint16_t port) [constructor] cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port')]) ## udp-client-server-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpClientHelper::Install(ns3::NodeContainer c) [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')]) ## udp-client-server-helper.h (module 'applications'): void ns3::UdpClientHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_Ns3UdpEchoClientHelper_methods(root_module, cls): ## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::UdpEchoClientHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpEchoClientHelper const &', 'arg0')]) ## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::Address ip, uint16_t port) [constructor] cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port')]) ## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::Ipv4Address ip, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')]) ## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::Ipv6Address ip, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')]) ## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoClientHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoClientHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('std::string', 'nodeName')], is_const=True) ## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoClientHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetFill(ns3::Ptr<ns3::Application> app, std::string fill) [member function] cls.add_method('SetFill', 'void', [param('ns3::Ptr< ns3::Application >', 'app'), param('std::string', 'fill')]) ## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetFill(ns3::Ptr<ns3::Application> app, uint8_t fill, uint32_t dataLength) [member function] cls.add_method('SetFill', 'void', [param('ns3::Ptr< ns3::Application >', 'app'), param('uint8_t', 'fill'), param('uint32_t', 'dataLength')]) ## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetFill(ns3::Ptr<ns3::Application> app, uint8_t * fill, uint32_t fillLength, uint32_t dataLength) [member function] cls.add_method('SetFill', 'void', [param('ns3::Ptr< ns3::Application >', 'app'), param('uint8_t *', 'fill'), param('uint32_t', 'fillLength'), param('uint32_t', 'dataLength')]) return def register_Ns3UdpEchoServerHelper_methods(root_module, cls): ## udp-echo-helper.h (module 'applications'): ns3::UdpEchoServerHelper::UdpEchoServerHelper(ns3::UdpEchoServerHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpEchoServerHelper const &', 'arg0')]) ## udp-echo-helper.h (module 'applications'): ns3::UdpEchoServerHelper::UdpEchoServerHelper(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoServerHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoServerHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('std::string', 'nodeName')], is_const=True) ## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoServerHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoServerHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_Ns3UdpServerHelper_methods(root_module, cls): ## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper::UdpServerHelper(ns3::UdpServerHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpServerHelper const &', 'arg0')]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper::UdpServerHelper() [constructor] cls.add_constructor([]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper::UdpServerHelper(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## udp-client-server-helper.h (module 'applications'): ns3::Ptr<ns3::UdpServer> ns3::UdpServerHelper::GetServer() [member function] cls.add_method('GetServer', 'ns3::Ptr< ns3::UdpServer >', []) ## udp-client-server-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpServerHelper::Install(ns3::NodeContainer c) [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')]) ## udp-client-server-helper.h (module 'applications'): void ns3::UdpServerHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_Ns3UdpTraceClientHelper_methods(root_module, cls): ## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::UdpTraceClientHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpTraceClientHelper const &', 'arg0')]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper() [constructor] cls.add_constructor([]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::Address ip, uint16_t port, std::string filename) [constructor] cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port'), param('std::string', 'filename')]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::Ipv4Address ip, uint16_t port, std::string filename) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port'), param('std::string', 'filename')]) ## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::Ipv6Address ip, uint16_t port, std::string filename) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port'), param('std::string', 'filename')]) ## udp-client-server-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpTraceClientHelper::Install(ns3::NodeContainer c) [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'c')]) ## udp-client-server-helper.h (module 'applications'): void ns3::UdpTraceClientHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_Ns3V4PingHelper_methods(root_module, cls): ## v4ping-helper.h (module 'applications'): ns3::V4PingHelper::V4PingHelper(ns3::V4PingHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::V4PingHelper const &', 'arg0')]) ## v4ping-helper.h (module 'applications'): ns3::V4PingHelper::V4PingHelper(ns3::Ipv4Address remote) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'remote')]) ## v4ping-helper.h (module 'applications'): ns3::ApplicationContainer ns3::V4PingHelper::Install(ns3::NodeContainer nodes) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::NodeContainer', 'nodes')], is_const=True) ## v4ping-helper.h (module 'applications'): ns3::ApplicationContainer ns3::V4PingHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## v4ping-helper.h (module 'applications'): ns3::ApplicationContainer ns3::V4PingHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::ApplicationContainer', [param('std::string', 'nodeName')], is_const=True) ## v4ping-helper.h (module 'applications'): void ns3::V4PingHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', 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_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_Ns3DeviceNameTag_methods(root_module, cls): ## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag(ns3::DeviceNameTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeviceNameTag const &', 'arg0')]) ## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag() [constructor] cls.add_constructor([]) ## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## packet-socket.h (module 'network'): std::string ns3::DeviceNameTag::GetDeviceName() const [member function] cls.add_method('GetDeviceName', 'std::string', [], is_const=True) ## packet-socket.h (module 'network'): ns3::TypeId ns3::DeviceNameTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): uint32_t ns3::DeviceNameTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): static ns3::TypeId ns3::DeviceNameTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): void ns3::DeviceNameTag::SetDeviceName(std::string n) [member function] cls.add_method('SetDeviceName', 'void', [param('std::string', 'n')]) return def register_Ns3FlowIdTag_methods(root_module, cls): ## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(ns3::FlowIdTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::FlowIdTag const &', 'arg0')]) ## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag() [constructor] cls.add_constructor([]) ## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(uint32_t flowId) [constructor] cls.add_constructor([param('uint32_t', 'flowId')]) ## flow-id-tag.h (module 'network'): static uint32_t ns3::FlowIdTag::AllocateFlowId() [member function] cls.add_method('AllocateFlowId', 'uint32_t', [], is_static=True) ## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Deserialize(ns3::TagBuffer buf) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buf')], is_virtual=True) ## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetFlowId() const [member function] cls.add_method('GetFlowId', 'uint32_t', [], is_const=True) ## flow-id-tag.h (module 'network'): ns3::TypeId ns3::FlowIdTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## flow-id-tag.h (module 'network'): static ns3::TypeId ns3::FlowIdTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Serialize(ns3::TagBuffer buf) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buf')], is_const=True, is_virtual=True) ## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::SetFlowId(uint32_t flowId) [member function] cls.add_method('SetFlowId', 'void', [param('uint32_t', 'flowId')]) 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_Ns3LlcSnapHeader_methods(root_module, cls): ## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader(ns3::LlcSnapHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::LlcSnapHeader const &', 'arg0')]) ## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader() [constructor] cls.add_constructor([]) ## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## llc-snap-header.h (module 'network'): ns3::TypeId ns3::LlcSnapHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## llc-snap-header.h (module 'network'): uint16_t ns3::LlcSnapHeader::GetType() [member function] cls.add_method('GetType', 'uint16_t', []) ## llc-snap-header.h (module 'network'): static ns3::TypeId ns3::LlcSnapHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::SetType(uint16_t type) [member function] cls.add_method('SetType', 'void', [param('uint16_t', 'type')]) 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_Ns3PacketBurst_methods(root_module, cls): ## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst(ns3::PacketBurst const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketBurst const &', 'arg0')]) ## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst() [constructor] cls.add_constructor([]) ## packet-burst.h (module 'network'): void ns3::PacketBurst::AddPacket(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('AddPacket', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')]) ## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', [], is_const=True) ## packet-burst.h (module 'network'): ns3::Ptr<ns3::PacketBurst> ns3::PacketBurst::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::PacketBurst >', [], is_const=True) ## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', [], is_const=True) ## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## packet-burst.h (module 'network'): std::list<ns3::Ptr<ns3::Packet>, std::allocator<ns3::Ptr<ns3::Packet> > > ns3::PacketBurst::GetPackets() const [member function] cls.add_method('GetPackets', 'std::list< ns3::Ptr< ns3::Packet > >', [], is_const=True) ## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet-burst.h (module 'network'): static ns3::TypeId ns3::PacketBurst::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-burst.h (module 'network'): void ns3::PacketBurst::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3PacketSocketTag_methods(root_module, cls): ## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag(ns3::PacketSocketTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketSocketTag const &', 'arg0')]) ## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag() [constructor] cls.add_constructor([]) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## packet-socket.h (module 'network'): ns3::Address ns3::PacketSocketTag::GetDestAddress() const [member function] cls.add_method('GetDestAddress', 'ns3::Address', [], is_const=True) ## packet-socket.h (module 'network'): ns3::TypeId ns3::PacketSocketTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): ns3::NetDevice::PacketType ns3::PacketSocketTag::GetPacketType() const [member function] cls.add_method('GetPacketType', 'ns3::NetDevice::PacketType', [], is_const=True) ## packet-socket.h (module 'network'): uint32_t ns3::PacketSocketTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocketTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetDestAddress(ns3::Address a) [member function] cls.add_method('SetDestAddress', 'void', [param('ns3::Address', 'a')]) ## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetPacketType(ns3::NetDevice::PacketType t) [member function] cls.add_method('SetPacketType', 'void', [param('ns3::NetDevice::PacketType', 't')]) 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<const ns3::Packet> 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<const ns3::Packet> 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_Ns3Queue_methods(root_module, cls): ## queue.h (module 'network'): ns3::Queue::Queue(ns3::Queue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Queue const &', 'arg0')]) ## queue.h (module 'network'): ns3::Queue::Queue() [constructor] cls.add_constructor([]) ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', []) ## queue.h (module 'network'): void ns3::Queue::DequeueAll() [member function] cls.add_method('DequeueAll', 'void', []) ## queue.h (module 'network'): bool ns3::Queue::Enqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## queue.h (module 'network'): uint32_t ns3::Queue::GetNBytes() const [member function] cls.add_method('GetNBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedBytes() const [member function] cls.add_method('GetTotalDroppedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedPackets() const [member function] cls.add_method('GetTotalDroppedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedBytes() const [member function] cls.add_method('GetTotalReceivedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedPackets() const [member function] cls.add_method('GetTotalReceivedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): static ns3::TypeId ns3::Queue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue.h (module 'network'): bool ns3::Queue::IsEmpty() const [member function] cls.add_method('IsEmpty', 'bool', [], is_const=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::Queue::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet const >', [], is_const=True) ## queue.h (module 'network'): void ns3::Queue::ResetStatistics() [member function] cls.add_method('ResetStatistics', 'void', []) ## queue.h (module 'network'): void ns3::Queue::Drop(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('Drop', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue::DoDequeue() [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::Packet >', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h (module 'network'): bool ns3::Queue::DoEnqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::Queue::DoPeek() const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::Packet const >', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3RadiotapHeader_methods(root_module, cls): ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader(ns3::RadiotapHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::RadiotapHeader const &', 'arg0')]) ## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader() [constructor] cls.add_constructor([]) ## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetAntennaNoisePower() const [member function] cls.add_method('GetAntennaNoisePower', 'uint8_t', [], is_const=True) ## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetAntennaSignalPower() const [member function] cls.add_method('GetAntennaSignalPower', 'uint8_t', [], is_const=True) ## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetChannelFlags() const [member function] cls.add_method('GetChannelFlags', 'uint16_t', [], is_const=True) ## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetChannelFrequency() const [member function] cls.add_method('GetChannelFrequency', 'uint16_t', [], is_const=True) ## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetFrameFlags() const [member function] cls.add_method('GetFrameFlags', 'uint8_t', [], is_const=True) ## radiotap-header.h (module 'network'): ns3::TypeId ns3::RadiotapHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetRate() const [member function] cls.add_method('GetRate', 'uint8_t', [], is_const=True) ## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## radiotap-header.h (module 'network'): uint64_t ns3::RadiotapHeader::GetTsft() const [member function] cls.add_method('GetTsft', 'uint64_t', [], is_const=True) ## radiotap-header.h (module 'network'): static ns3::TypeId ns3::RadiotapHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaNoisePower(double noise) [member function] cls.add_method('SetAntennaNoisePower', 'void', [param('double', 'noise')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaSignalPower(double signal) [member function] cls.add_method('SetAntennaSignalPower', 'void', [param('double', 'signal')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetChannelFrequencyAndFlags(uint16_t frequency, uint16_t flags) [member function] cls.add_method('SetChannelFrequencyAndFlags', 'void', [param('uint16_t', 'frequency'), param('uint16_t', 'flags')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetFrameFlags(uint8_t flags) [member function] cls.add_method('SetFrameFlags', 'void', [param('uint8_t', 'flags')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetRate(uint8_t rate) [member function] cls.add_method('SetRate', 'void', [param('uint8_t', 'rate')]) ## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetTsft(uint64_t tsft) [member function] cls.add_method('SetTsft', 'void', [param('uint64_t', 'tsft')]) 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_Ns3RedQueue_methods(root_module, cls): ## red-queue.h (module 'network'): ns3::RedQueue::RedQueue(ns3::RedQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::RedQueue const &', 'arg0')]) ## red-queue.h (module 'network'): ns3::RedQueue::RedQueue() [constructor] cls.add_constructor([]) ## red-queue.h (module 'network'): int64_t ns3::RedQueue::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## red-queue.h (module 'network'): ns3::Queue::QueueMode ns3::RedQueue::GetMode() [member function] cls.add_method('GetMode', 'ns3::Queue::QueueMode', []) ## red-queue.h (module 'network'): uint32_t ns3::RedQueue::GetQueueSize() [member function] cls.add_method('GetQueueSize', 'uint32_t', []) ## red-queue.h (module 'network'): ns3::RedQueue::Stats ns3::RedQueue::GetStats() [member function] cls.add_method('GetStats', 'ns3::RedQueue::Stats', []) ## red-queue.h (module 'network'): static ns3::TypeId ns3::RedQueue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## red-queue.h (module 'network'): void ns3::RedQueue::SetMode(ns3::Queue::QueueMode mode) [member function] cls.add_method('SetMode', 'void', [param('ns3::Queue::QueueMode', 'mode')]) ## red-queue.h (module 'network'): void ns3::RedQueue::SetQueueLimit(uint32_t lim) [member function] cls.add_method('SetQueueLimit', 'void', [param('uint32_t', 'lim')]) ## red-queue.h (module 'network'): void ns3::RedQueue::SetTh(double minTh, double maxTh) [member function] cls.add_method('SetTh', 'void', [param('double', 'minTh'), param('double', 'maxTh')]) ## red-queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::RedQueue::DoDequeue() [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::Packet >', [], visibility='private', is_virtual=True) ## red-queue.h (module 'network'): bool ns3::RedQueue::DoEnqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## red-queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::RedQueue::DoPeek() const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::Packet const >', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3RedQueueStats_methods(root_module, cls): ## red-queue.h (module 'network'): ns3::RedQueue::Stats::Stats() [constructor] cls.add_constructor([]) ## red-queue.h (module 'network'): ns3::RedQueue::Stats::Stats(ns3::RedQueue::Stats const & arg0) [copy constructor] cls.add_constructor([param('ns3::RedQueue::Stats const &', 'arg0')]) ## red-queue.h (module 'network'): ns3::RedQueue::Stats::forcedDrop [variable] cls.add_instance_attribute('forcedDrop', 'uint32_t', is_const=False) ## red-queue.h (module 'network'): ns3::RedQueue::Stats::qLimDrop [variable] cls.add_instance_attribute('qLimDrop', 'uint32_t', is_const=False) ## red-queue.h (module 'network'): ns3::RedQueue::Stats::unforcedDrop [variable] cls.add_instance_attribute('unforcedDrop', 'uint32_t', is_const=False) return def register_Ns3SeqTsHeader_methods(root_module, cls): ## seq-ts-header.h (module 'applications'): ns3::SeqTsHeader::SeqTsHeader(ns3::SeqTsHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::SeqTsHeader const &', 'arg0')]) ## seq-ts-header.h (module 'applications'): ns3::SeqTsHeader::SeqTsHeader() [constructor] cls.add_constructor([]) ## seq-ts-header.h (module 'applications'): uint32_t ns3::SeqTsHeader::GetSeq() const [member function] cls.add_method('GetSeq', 'uint32_t', [], is_const=True) ## seq-ts-header.h (module 'applications'): ns3::Time ns3::SeqTsHeader::GetTs() const [member function] cls.add_method('GetTs', 'ns3::Time', [], is_const=True) ## seq-ts-header.h (module 'applications'): static ns3::TypeId ns3::SeqTsHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## seq-ts-header.h (module 'applications'): void ns3::SeqTsHeader::SetSeq(uint32_t seq) [member function] cls.add_method('SetSeq', 'void', [param('uint32_t', 'seq')]) ## seq-ts-header.h (module 'applications'): uint32_t ns3::SeqTsHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], visibility='private', is_virtual=True) ## seq-ts-header.h (module 'applications'): ns3::TypeId ns3::SeqTsHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, visibility='private', is_virtual=True) ## seq-ts-header.h (module 'applications'): uint32_t ns3::SeqTsHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, visibility='private', is_virtual=True) ## seq-ts-header.h (module 'applications'): void ns3::SeqTsHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, visibility='private', is_virtual=True) ## seq-ts-header.h (module 'applications'): void ns3::SeqTsHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, 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__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__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter< ns3::PbbAddressBlock > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter< ns3::PbbMessage > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter< ns3::PbbPacket > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter< ns3::PbbTlv > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3RadvdInterface_Ns3Empty_Ns3DefaultDeleter__lt__ns3RadvdInterface__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >::SimpleRefCount(ns3::SimpleRefCount<ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter< ns3::RadvdInterface > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3RadvdPrefix_Ns3Empty_Ns3DefaultDeleter__lt__ns3RadvdPrefix__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >::SimpleRefCount(ns3::SimpleRefCount<ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter< ns3::RadvdPrefix > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >::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_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTos() const [member function] cls.add_method('IsManualIpTos', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketAddressTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::Address ns3::SocketAddressTag::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::SetAddress(ns3::Address addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'addr')]) return def register_Ns3SocketFactory_methods(root_module, cls): ## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory(ns3::SocketFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketFactory const &', 'arg0')]) ## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory() [constructor] cls.add_constructor([]) ## socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::SocketFactory::CreateSocket() [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## socket-factory.h (module 'network'): static ns3::TypeId ns3::SocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', 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_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_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3Application_methods(root_module, cls): ## application.h (module 'network'): ns3::Application::Application(ns3::Application const & arg0) [copy constructor] cls.add_constructor([param('ns3::Application const &', 'arg0')]) ## application.h (module 'network'): ns3::Application::Application() [constructor] cls.add_constructor([]) ## application.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Application::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## application.h (module 'network'): static ns3::TypeId ns3::Application::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## application.h (module 'network'): void ns3::Application::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## application.h (module 'network'): void ns3::Application::SetStartTime(ns3::Time start) [member function] cls.add_method('SetStartTime', 'void', [param('ns3::Time', 'start')]) ## application.h (module 'network'): void ns3::Application::SetStopTime(ns3::Time stop) [member function] cls.add_method('SetStopTime', 'void', [param('ns3::Time', 'stop')]) ## application.h (module 'network'): void ns3::Application::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## application.h (module 'network'): void ns3::Application::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## application.h (module 'network'): void ns3::Application::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## application.h (module 'network'): void ns3::Application::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3BooleanChecker_methods(root_module, cls): ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')]) return def register_Ns3BooleanValue_methods(root_module, cls): cls.add_output_stream_operator() ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor] cls.add_constructor([param('bool', 'value')]) ## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function] cls.add_method('Get', 'bool', [], is_const=True) ## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function] cls.add_method('Set', 'void', [param('bool', 'value')]) return def register_Ns3BulkSendApplication_methods(root_module, cls): ## bulk-send-application.h (module 'applications'): ns3::BulkSendApplication::BulkSendApplication(ns3::BulkSendApplication const & arg0) [copy constructor] cls.add_constructor([param('ns3::BulkSendApplication const &', 'arg0')]) ## bulk-send-application.h (module 'applications'): ns3::BulkSendApplication::BulkSendApplication() [constructor] cls.add_constructor([]) ## bulk-send-application.h (module 'applications'): ns3::Ptr<ns3::Socket> ns3::BulkSendApplication::GetSocket() const [member function] cls.add_method('GetSocket', 'ns3::Ptr< ns3::Socket >', [], is_const=True) ## bulk-send-application.h (module 'applications'): static ns3::TypeId ns3::BulkSendApplication::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::SetMaxBytes(uint32_t maxBytes) [member function] cls.add_method('SetMaxBytes', 'void', [param('uint32_t', 'maxBytes')]) ## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', 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_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_Ns3DataCalculator_methods(root_module, cls): ## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator(ns3::DataCalculator const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataCalculator const &', 'arg0')]) ## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator() [constructor] cls.add_constructor([]) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Disable() [member function] cls.add_method('Disable', 'void', []) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Enable() [member function] cls.add_method('Enable', 'void', []) ## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetContext() const [member function] cls.add_method('GetContext', 'std::string', [], is_const=True) ## data-calculator.h (module 'stats'): bool ns3::DataCalculator::GetEnabled() const [member function] cls.add_method('GetEnabled', 'bool', [], is_const=True) ## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetKey() const [member function] cls.add_method('GetKey', 'std::string', [], is_const=True) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Output(ns3::DataOutputCallback & callback) const [member function] cls.add_method('Output', 'void', [param('ns3::DataOutputCallback &', 'callback')], is_pure_virtual=True, is_const=True, is_virtual=True) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetContext(std::string const context) [member function] cls.add_method('SetContext', 'void', [param('std::string const', 'context')]) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetKey(std::string const key) [member function] cls.add_method('SetKey', 'void', [param('std::string const', 'key')]) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Start(ns3::Time const & startTime) [member function] cls.add_method('Start', 'void', [param('ns3::Time const &', 'startTime')], is_virtual=True) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::Stop(ns3::Time const & stopTime) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'stopTime')], is_virtual=True) ## data-calculator.h (module 'stats'): void ns3::DataCalculator::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3DataOutputInterface_methods(root_module, cls): ## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface(ns3::DataOutputInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataOutputInterface const &', 'arg0')]) ## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface() [constructor] cls.add_constructor([]) ## data-output-interface.h (module 'stats'): std::string ns3::DataOutputInterface::GetFilePrefix() const [member function] cls.add_method('GetFilePrefix', 'std::string', [], is_const=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::Output(ns3::DataCollector & dc) [member function] cls.add_method('Output', 'void', [param('ns3::DataCollector &', 'dc')], is_pure_virtual=True, is_virtual=True) ## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::SetFilePrefix(std::string const prefix) [member function] cls.add_method('SetFilePrefix', 'void', [param('std::string const', 'prefix')]) ## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3DataRateChecker_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')]) return def register_Ns3DataRateValue_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor] cls.add_constructor([param('ns3::DataRate const &', 'value')]) ## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): bool ns3::DataRateValue::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) ## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function] cls.add_method('Get', 'ns3::DataRate', [], is_const=True) ## data-rate.h (module 'network'): std::string ns3::DataRateValue::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) ## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function] cls.add_method('Set', 'void', [param('ns3::DataRate const &', 'value')]) 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_Ns3DropTailQueue_methods(root_module, cls): ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue::DropTailQueue(ns3::DropTailQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DropTailQueue const &', 'arg0')]) ## drop-tail-queue.h (module 'network'): ns3::DropTailQueue::DropTailQueue() [constructor] cls.add_constructor([]) ## drop-tail-queue.h (module 'network'): ns3::Queue::QueueMode ns3::DropTailQueue::GetMode() [member function] cls.add_method('GetMode', 'ns3::Queue::QueueMode', []) ## drop-tail-queue.h (module 'network'): static ns3::TypeId ns3::DropTailQueue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## drop-tail-queue.h (module 'network'): void ns3::DropTailQueue::SetMode(ns3::Queue::QueueMode mode) [member function] cls.add_method('SetMode', 'void', [param('ns3::Queue::QueueMode', 'mode')]) ## drop-tail-queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::DropTailQueue::DoDequeue() [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::Packet >', [], visibility='private', is_virtual=True) ## drop-tail-queue.h (module 'network'): bool ns3::DropTailQueue::DoEnqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## drop-tail-queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::DropTailQueue::DoPeek() const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::Packet const >', [], is_const=True, 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_Ns3ErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::ErrorModel::ErrorModel(ns3::ErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::ErrorModel::ErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): void ns3::ErrorModel::Disable() [member function] cls.add_method('Disable', 'void', []) ## error-model.h (module 'network'): void ns3::ErrorModel::Enable() [member function] cls.add_method('Enable', 'void', []) ## error-model.h (module 'network'): static ns3::TypeId ns3::ErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): bool ns3::ErrorModel::IsCorrupt(ns3::Ptr<ns3::Packet> pkt) [member function] cls.add_method('IsCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'pkt')]) ## error-model.h (module 'network'): bool ns3::ErrorModel::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## error-model.h (module 'network'): void ns3::ErrorModel::Reset() [member function] cls.add_method('Reset', 'void', []) ## error-model.h (module 'network'): bool ns3::ErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> arg0) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'arg0')], is_pure_virtual=True, visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::ErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3EthernetHeader_methods(root_module, cls): ## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(ns3::EthernetHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::EthernetHeader const &', 'arg0')]) ## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(bool hasPreamble) [constructor] cls.add_constructor([param('bool', 'hasPreamble')]) ## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader() [constructor] cls.add_constructor([]) ## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Mac48Address', [], is_const=True) ## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetHeaderSize() const [member function] cls.add_method('GetHeaderSize', 'uint32_t', [], is_const=True) ## ethernet-header.h (module 'network'): ns3::TypeId ns3::EthernetHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ethernet-header.h (module 'network'): uint16_t ns3::EthernetHeader::GetLengthType() const [member function] cls.add_method('GetLengthType', 'uint16_t', [], is_const=True) ## ethernet-header.h (module 'network'): ns3::ethernet_header_t ns3::EthernetHeader::GetPacketType() const [member function] cls.add_method('GetPacketType', 'ns3::ethernet_header_t', [], is_const=True) ## ethernet-header.h (module 'network'): uint64_t ns3::EthernetHeader::GetPreambleSfd() const [member function] cls.add_method('GetPreambleSfd', 'uint64_t', [], is_const=True) ## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Mac48Address', [], is_const=True) ## ethernet-header.h (module 'network'): static ns3::TypeId ns3::EthernetHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetDestination(ns3::Mac48Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Mac48Address', 'destination')]) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetLengthType(uint16_t size) [member function] cls.add_method('SetLengthType', 'void', [param('uint16_t', 'size')]) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetPreambleSfd(uint64_t preambleSfd) [member function] cls.add_method('SetPreambleSfd', 'void', [param('uint64_t', 'preambleSfd')]) ## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetSource(ns3::Mac48Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Mac48Address', 'source')]) return def register_Ns3EthernetTrailer_methods(root_module, cls): ## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer(ns3::EthernetTrailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::EthernetTrailer const &', 'arg0')]) ## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer() [constructor] cls.add_constructor([]) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::CalcFcs(ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('CalcFcs', 'void', [param('ns3::Ptr< ns3::Packet const >', 'p')]) ## ethernet-trailer.h (module 'network'): bool ns3::EthernetTrailer::CheckFcs(ns3::Ptr<const ns3::Packet> p) const [member function] cls.add_method('CheckFcs', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p')], is_const=True) ## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_virtual=True) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::EnableFcs(bool enable) [member function] cls.add_method('EnableFcs', 'void', [param('bool', 'enable')]) ## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetFcs() [member function] cls.add_method('GetFcs', 'uint32_t', []) ## ethernet-trailer.h (module 'network'): ns3::TypeId ns3::EthernetTrailer::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetTrailerSize() const [member function] cls.add_method('GetTrailerSize', 'uint32_t', [], is_const=True) ## ethernet-trailer.h (module 'network'): static ns3::TypeId ns3::EthernetTrailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Serialize(ns3::Buffer::Iterator end) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'end')], is_const=True, is_virtual=True) ## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::SetFcs(uint32_t fcs) [member function] cls.add_method('SetFcs', 'void', [param('uint32_t', 'fcs')]) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3ExponentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3GammaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function] cls.add_method('GetBeta', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha'), param('double', 'beta')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha'), param('uint32_t', 'beta')]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_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_Ns3ListErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::ListErrorModel::ListErrorModel(ns3::ListErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ListErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::ListErrorModel::ListErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ListErrorModel::GetList() const [member function] cls.add_method('GetList', 'std::list< unsigned int >', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::ListErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): void ns3::ListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function] cls.add_method('SetList', 'void', [param('std::list< unsigned int > const &', 'packetlist')]) ## error-model.h (module 'network'): bool ns3::ListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::ListErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], 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_Ns3MinMaxAvgTotalCalculator__Double_methods(root_module, cls): ## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<double>::MinMaxAvgTotalCalculator(ns3::MinMaxAvgTotalCalculator<double> const & arg0) [copy constructor] cls.add_constructor([param('ns3::MinMaxAvgTotalCalculator< double > const &', 'arg0')]) ## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<double>::MinMaxAvgTotalCalculator() [constructor] cls.add_constructor([]) ## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<double>::Output(ns3::DataOutputCallback & callback) const [member function] cls.add_method('Output', 'void', [param('ns3::DataOutputCallback &', 'callback')], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<double>::Reset() [member function] cls.add_method('Reset', 'void', []) ## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<double>::Update(double const i) [member function] cls.add_method('Update', 'void', [param('double const', 'i')]) ## basic-data-calculators.h (module 'stats'): long int ns3::MinMaxAvgTotalCalculator<double>::getCount() const [member function] cls.add_method('getCount', 'long int', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getMax() const [member function] cls.add_method('getMax', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getMean() const [member function] cls.add_method('getMean', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getMin() const [member function] cls.add_method('getMin', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getSqrSum() const [member function] cls.add_method('getSqrSum', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getStddev() const [member function] cls.add_method('getStddev', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getSum() const [member function] cls.add_method('getSum', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getVariance() const [member function] cls.add_method('getVariance', 'double', [], is_const=True, is_virtual=True) ## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<double>::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', 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_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_Ns3OnOffApplication_methods(root_module, cls): ## onoff-application.h (module 'applications'): ns3::OnOffApplication::OnOffApplication(ns3::OnOffApplication const & arg0) [copy constructor] cls.add_constructor([param('ns3::OnOffApplication const &', 'arg0')]) ## onoff-application.h (module 'applications'): ns3::OnOffApplication::OnOffApplication() [constructor] cls.add_constructor([]) ## onoff-application.h (module 'applications'): int64_t ns3::OnOffApplication::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## onoff-application.h (module 'applications'): ns3::Ptr<ns3::Socket> ns3::OnOffApplication::GetSocket() const [member function] cls.add_method('GetSocket', 'ns3::Ptr< ns3::Socket >', [], is_const=True) ## onoff-application.h (module 'applications'): static ns3::TypeId ns3::OnOffApplication::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## onoff-application.h (module 'applications'): void ns3::OnOffApplication::SetMaxBytes(uint32_t maxBytes) [member function] cls.add_method('SetMaxBytes', 'void', [param('uint32_t', 'maxBytes')]) ## onoff-application.h (module 'applications'): void ns3::OnOffApplication::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## onoff-application.h (module 'applications'): void ns3::OnOffApplication::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## onoff-application.h (module 'applications'): void ns3::OnOffApplication::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], 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<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) return def register_Ns3PacketSink_methods(root_module, cls): ## packet-sink.h (module 'applications'): ns3::PacketSink::PacketSink(ns3::PacketSink const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketSink const &', 'arg0')]) ## packet-sink.h (module 'applications'): ns3::PacketSink::PacketSink() [constructor] cls.add_constructor([]) ## packet-sink.h (module 'applications'): std::list<ns3::Ptr<ns3::Socket>, std::allocator<ns3::Ptr<ns3::Socket> > > ns3::PacketSink::GetAcceptedSockets() const [member function] cls.add_method('GetAcceptedSockets', 'std::list< ns3::Ptr< ns3::Socket > >', [], is_const=True) ## packet-sink.h (module 'applications'): ns3::Ptr<ns3::Socket> ns3::PacketSink::GetListeningSocket() const [member function] cls.add_method('GetListeningSocket', 'ns3::Ptr< ns3::Socket >', [], is_const=True) ## packet-sink.h (module 'applications'): uint32_t ns3::PacketSink::GetTotalRx() const [member function] cls.add_method('GetTotalRx', 'uint32_t', [], is_const=True) ## packet-sink.h (module 'applications'): static ns3::TypeId ns3::PacketSink::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-sink.h (module 'applications'): void ns3::PacketSink::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## packet-sink.h (module 'applications'): void ns3::PacketSink::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## packet-sink.h (module 'applications'): void ns3::PacketSink::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3PacketSocket_methods(root_module, cls): ## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket(ns3::PacketSocket const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketSocket const &', 'arg0')]) ## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket() [constructor] cls.add_constructor([]) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind() [member function] cls.add_method('Bind', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Close() [member function] cls.add_method('Close', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_virtual=True) ## packet-socket.h (module 'network'): bool ns3::PacketSocket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): ns3::Socket::SocketErrno ns3::PacketSocket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::PacketSocket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): ns3::Socket::SocketType ns3::PacketSocket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_const=True, is_virtual=True) ## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Listen() [member function] cls.add_method('Listen', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_virtual=True) ## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_virtual=True) ## packet-socket.h (module 'network'): bool ns3::PacketSocket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_virtual=True) ## packet-socket.h (module 'network'): void ns3::PacketSocket::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_virtual=True) ## packet-socket.h (module 'network'): void ns3::PacketSocket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3PacketSocketFactory_methods(root_module, cls): ## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory(ns3::PacketSocketFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketSocketFactory const &', 'arg0')]) ## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory() [constructor] cls.add_constructor([]) ## packet-socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::PacketSocketFactory::CreateSocket() [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## packet-socket-factory.h (module 'network'): static ns3::TypeId ns3::PacketSocketFactory::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3ParetoRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3PbbAddressBlock_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock(ns3::PbbAddressBlock const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressBlock const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressBack() const [member function] cls.add_method('AddressBack', 'ns3::Address', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() [member function] cls.add_method('AddressBegin', 'std::_List_iterator< ns3::Address >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() const [member function] cls.add_method('AddressBegin', 'std::_List_const_iterator< ns3::Address >', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressClear() [member function] cls.add_method('AddressClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::AddressEmpty() const [member function] cls.add_method('AddressEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() [member function] cls.add_method('AddressEnd', 'std::_List_iterator< ns3::Address >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() const [member function] cls.add_method('AddressEnd', 'std::_List_const_iterator< ns3::Address >', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> position) [member function] cls.add_method('AddressErase', 'std::_List_iterator< ns3::Address >', [param('std::_List_iterator< ns3::Address >', 'position')]) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> first, std::_List_iterator<ns3::Address> last) [member function] cls.add_method('AddressErase', 'std::_List_iterator< ns3::Address >', [param('std::_List_iterator< ns3::Address >', 'first'), param('std::_List_iterator< ns3::Address >', 'last')]) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressFront() const [member function] cls.add_method('AddressFront', 'ns3::Address', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressInsert(std::_List_iterator<ns3::Address> position, ns3::Address const value) [member function] cls.add_method('AddressInsert', 'std::_List_iterator< ns3::Address >', [param('std::_List_iterator< ns3::Address >', 'position'), param('ns3::Address const', 'value')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopBack() [member function] cls.add_method('AddressPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopFront() [member function] cls.add_method('AddressPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushBack(ns3::Address address) [member function] cls.add_method('AddressPushBack', 'void', [param('ns3::Address', 'address')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushFront(ns3::Address address) [member function] cls.add_method('AddressPushFront', 'void', [param('ns3::Address', 'address')]) ## packetbb.h (module 'network'): int ns3::PbbAddressBlock::AddressSize() const [member function] cls.add_method('AddressSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): uint32_t ns3::PbbAddressBlock::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixBack() const [member function] cls.add_method('PrefixBack', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() [member function] cls.add_method('PrefixBegin', 'std::_List_iterator< unsigned char >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() const [member function] cls.add_method('PrefixBegin', 'std::_List_const_iterator< unsigned char >', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixClear() [member function] cls.add_method('PrefixClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::PrefixEmpty() const [member function] cls.add_method('PrefixEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() [member function] cls.add_method('PrefixEnd', 'std::_List_iterator< unsigned char >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() const [member function] cls.add_method('PrefixEnd', 'std::_List_const_iterator< unsigned char >', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> position) [member function] cls.add_method('PrefixErase', 'std::_List_iterator< unsigned char >', [param('std::_List_iterator< unsigned char >', 'position')]) ## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> first, std::_List_iterator<unsigned char> last) [member function] cls.add_method('PrefixErase', 'std::_List_iterator< unsigned char >', [param('std::_List_iterator< unsigned char >', 'first'), param('std::_List_iterator< unsigned char >', 'last')]) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixFront() const [member function] cls.add_method('PrefixFront', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixInsert(std::_List_iterator<unsigned char> position, uint8_t const value) [member function] cls.add_method('PrefixInsert', 'std::_List_iterator< unsigned char >', [param('std::_List_iterator< unsigned char >', 'position'), param('uint8_t const', 'value')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopBack() [member function] cls.add_method('PrefixPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopFront() [member function] cls.add_method('PrefixPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushBack(uint8_t prefix) [member function] cls.add_method('PrefixPushBack', 'void', [param('uint8_t', 'prefix')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushFront(uint8_t prefix) [member function] cls.add_method('PrefixPushFront', 'void', [param('uint8_t', 'prefix')]) ## packetbb.h (module 'network'): int ns3::PbbAddressBlock::PrefixSize() const [member function] cls.add_method('PrefixSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvBack() [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbAddressTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvBack() const [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbAddressTlv > const', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() [member function] cls.add_method('TlvBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() const [member function] cls.add_method('TlvBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvClear() [member function] cls.add_method('TlvClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::TlvEmpty() const [member function] cls.add_method('TlvEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() [member function] cls.add_method('TlvEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() const [member function] cls.add_method('TlvEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function] cls.add_method('TlvErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')]) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function] cls.add_method('TlvErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvFront() [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbAddressTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvFront() const [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbAddressTlv > const', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvInsert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbTlv> const value) [member function] cls.add_method('TlvInsert', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'value')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopBack() [member function] cls.add_method('TlvPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopFront() [member function] cls.add_method('TlvPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushBack(ns3::Ptr<ns3::PbbAddressTlv> address) [member function] cls.add_method('TlvPushBack', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')]) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushFront(ns3::Ptr<ns3::PbbAddressTlv> address) [member function] cls.add_method('TlvPushFront', 'void', [param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')]) ## packetbb.h (module 'network'): int ns3::PbbAddressBlock::TlvSize() const [member function] cls.add_method('TlvSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::DeserializeAddress(uint8_t * buffer) const [member function] cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'uint8_t', [], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('PrintAddress', 'void', [param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlock::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('SerializeAddress', 'void', [param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbAddressBlockIpv4_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4(ns3::PbbAddressBlockIpv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressBlockIpv4 const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv4::DeserializeAddress(uint8_t * buffer) const [member function] cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv4::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'uint8_t', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('PrintAddress', 'void', [param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('SerializeAddress', 'void', [param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbAddressBlockIpv6_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6(ns3::PbbAddressBlockIpv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressBlockIpv6 const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv6::DeserializeAddress(uint8_t * buffer) const [member function] cls.add_method('DeserializeAddress', 'ns3::Address', [param('uint8_t *', 'buffer')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv6::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'uint8_t', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('PrintAddress', 'void', [param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function] cls.add_method('SerializeAddress', 'void', [param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbMessage_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage(ns3::PbbMessage const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbMessage const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockBack() [member function] cls.add_method('AddressBlockBack', 'ns3::Ptr< ns3::PbbAddressBlock >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockBack() const [member function] cls.add_method('AddressBlockBack', 'ns3::Ptr< ns3::PbbAddressBlock > const', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() [member function] cls.add_method('AddressBlockBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() const [member function] cls.add_method('AddressBlockBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockClear() [member function] cls.add_method('AddressBlockClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbMessage::AddressBlockEmpty() const [member function] cls.add_method('AddressBlockEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() [member function] cls.add_method('AddressBlockEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() const [member function] cls.add_method('AddressBlockEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > position) [member function] cls.add_method('AddressBlockErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'position')]) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > last) [member function] cls.add_method('AddressBlockErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockFront() [member function] cls.add_method('AddressBlockFront', 'ns3::Ptr< ns3::PbbAddressBlock >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockFront() const [member function] cls.add_method('AddressBlockFront', 'ns3::Ptr< ns3::PbbAddressBlock > const', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopBack() [member function] cls.add_method('AddressBlockPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopFront() [member function] cls.add_method('AddressBlockPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushBack(ns3::Ptr<ns3::PbbAddressBlock> block) [member function] cls.add_method('AddressBlockPushBack', 'void', [param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushFront(ns3::Ptr<ns3::PbbAddressBlock> block) [member function] cls.add_method('AddressBlockPushFront', 'void', [param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')]) ## packetbb.h (module 'network'): int ns3::PbbMessage::AddressBlockSize() const [member function] cls.add_method('AddressBlockSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): static ns3::Ptr<ns3::PbbMessage> ns3::PbbMessage::DeserializeMessage(ns3::Buffer::Iterator & start) [member function] cls.add_method('DeserializeMessage', 'ns3::Ptr< ns3::PbbMessage >', [param('ns3::Buffer::Iterator &', 'start')], is_static=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopCount() const [member function] cls.add_method('GetHopCount', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::GetOriginatorAddress() const [member function] cls.add_method('GetOriginatorAddress', 'ns3::Address', [], is_const=True) ## packetbb.h (module 'network'): uint16_t ns3::PbbMessage::GetSequenceNumber() const [member function] cls.add_method('GetSequenceNumber', 'uint16_t', [], is_const=True) ## packetbb.h (module 'network'): uint32_t ns3::PbbMessage::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopCount() const [member function] cls.add_method('HasHopCount', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopLimit() const [member function] cls.add_method('HasHopLimit', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbMessage::HasOriginatorAddress() const [member function] cls.add_method('HasOriginatorAddress', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbMessage::HasSequenceNumber() const [member function] cls.add_method('HasSequenceNumber', 'bool', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopCount(uint8_t hopcount) [member function] cls.add_method('SetHopCount', 'void', [param('uint8_t', 'hopcount')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopLimit(uint8_t hoplimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hoplimit')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetOriginatorAddress(ns3::Address address) [member function] cls.add_method('SetOriginatorAddress', 'void', [param('ns3::Address', 'address')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetSequenceNumber(uint16_t seqnum) [member function] cls.add_method('SetSequenceNumber', 'void', [param('uint16_t', 'seqnum')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvBack() [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvBack() const [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() [member function] cls.add_method('TlvBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() const [member function] cls.add_method('TlvBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvClear() [member function] cls.add_method('TlvClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbMessage::TlvEmpty() const [member function] cls.add_method('TlvEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() [member function] cls.add_method('TlvEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() const [member function] cls.add_method('TlvEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function] cls.add_method('TlvErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')]) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function] cls.add_method('TlvErase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvFront() [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvFront() const [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopBack() [member function] cls.add_method('TlvPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopFront() [member function] cls.add_method('TlvPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushBack', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushFront', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): int ns3::PbbMessage::TlvSize() const [member function] cls.add_method('TlvSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('AddressBlockDeserialize', 'ns3::Ptr< ns3::PbbAddressBlock >', [param('ns3::Buffer::Iterator &', 'start')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('DeserializeOriginatorAddress', 'ns3::Address', [param('ns3::Buffer::Iterator &', 'start')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessage::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'ns3::PbbAddressLength', [], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::PrintOriginatorAddress(std::ostream & os) const [member function] cls.add_method('PrintOriginatorAddress', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessage::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('SerializeOriginatorAddress', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbMessageIpv4_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4(ns3::PbbMessageIpv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbMessageIpv4 const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv4::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('AddressBlockDeserialize', 'ns3::Ptr< ns3::PbbAddressBlock >', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv4::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('DeserializeOriginatorAddress', 'ns3::Address', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv4::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'ns3::PbbAddressLength', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::PrintOriginatorAddress(std::ostream & os) const [member function] cls.add_method('PrintOriginatorAddress', 'void', [param('std::ostream &', 'os')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('SerializeOriginatorAddress', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbMessageIpv6_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6(ns3::PbbMessageIpv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbMessageIpv6 const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv6::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('AddressBlockDeserialize', 'ns3::Ptr< ns3::PbbAddressBlock >', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv6::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('DeserializeOriginatorAddress', 'ns3::Address', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv6::GetAddressLength() const [member function] cls.add_method('GetAddressLength', 'ns3::PbbAddressLength', [], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::PrintOriginatorAddress(std::ostream & os) const [member function] cls.add_method('PrintOriginatorAddress', 'void', [param('std::ostream &', 'os')], is_const=True, visibility='protected', is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function] cls.add_method('SerializeOriginatorAddress', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True, visibility='protected', is_virtual=True) return def register_Ns3PbbPacket_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket(ns3::PbbPacket const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbPacket const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')]) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')]) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > position) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'position')]) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > first, std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > last) [member function] cls.add_method('Erase', 'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', [param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'last')]) ## packetbb.h (module 'network'): ns3::TypeId ns3::PbbPacket::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## packetbb.h (module 'network'): uint16_t ns3::PbbPacket::GetSequenceNumber() const [member function] cls.add_method('GetSequenceNumber', 'uint16_t', [], is_const=True) ## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## packetbb.h (module 'network'): static ns3::TypeId ns3::PbbPacket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbPacket::GetVersion() const [member function] cls.add_method('GetVersion', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbPacket::HasSequenceNumber() const [member function] cls.add_method('HasSequenceNumber', 'bool', [], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageBack() [member function] cls.add_method('MessageBack', 'ns3::Ptr< ns3::PbbMessage >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageBack() const [member function] cls.add_method('MessageBack', 'ns3::Ptr< ns3::PbbMessage > const', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() [member function] cls.add_method('MessageBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() const [member function] cls.add_method('MessageBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessageClear() [member function] cls.add_method('MessageClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbPacket::MessageEmpty() const [member function] cls.add_method('MessageEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() [member function] cls.add_method('MessageEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() const [member function] cls.add_method('MessageEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >', [], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageFront() [member function] cls.add_method('MessageFront', 'ns3::Ptr< ns3::PbbMessage >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageFront() const [member function] cls.add_method('MessageFront', 'ns3::Ptr< ns3::PbbMessage > const', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopBack() [member function] cls.add_method('MessagePopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopFront() [member function] cls.add_method('MessagePopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushBack(ns3::Ptr<ns3::PbbMessage> message) [member function] cls.add_method('MessagePushBack', 'void', [param('ns3::Ptr< ns3::PbbMessage >', 'message')]) ## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushFront(ns3::Ptr<ns3::PbbMessage> message) [member function] cls.add_method('MessagePushFront', 'void', [param('ns3::Ptr< ns3::PbbMessage >', 'message')]) ## packetbb.h (module 'network'): int ns3::PbbPacket::MessageSize() const [member function] cls.add_method('MessageSize', 'int', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::SetSequenceNumber(uint16_t number) [member function] cls.add_method('SetSequenceNumber', 'void', [param('uint16_t', 'number')]) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvBack() [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvBack() const [member function] cls.add_method('TlvBack', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() [member function] cls.add_method('TlvBegin', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() const [member function] cls.add_method('TlvBegin', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvClear() [member function] cls.add_method('TlvClear', 'void', []) ## packetbb.h (module 'network'): bool ns3::PbbPacket::TlvEmpty() const [member function] cls.add_method('TlvEmpty', 'bool', [], is_const=True) ## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() [member function] cls.add_method('TlvEnd', 'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', []) ## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() const [member function] cls.add_method('TlvEnd', 'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >', [], is_const=True) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvFront() [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv >', []) ## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvFront() const [member function] cls.add_method('TlvFront', 'ns3::Ptr< ns3::PbbTlv > const', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopBack() [member function] cls.add_method('TlvPopBack', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopFront() [member function] cls.add_method('TlvPopFront', 'void', []) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushBack', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function] cls.add_method('TlvPushFront', 'void', [param('ns3::Ptr< ns3::PbbTlv >', 'tlv')]) ## packetbb.h (module 'network'): int ns3::PbbPacket::TlvSize() const [member function] cls.add_method('TlvSize', 'int', [], is_const=True) return def register_Ns3PbbTlv_methods(root_module, cls): cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('!=') ## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv(ns3::PbbTlv const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbTlv const &', 'arg0')]) ## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): void ns3::PbbTlv::Deserialize(ns3::Buffer::Iterator & start) [member function] cls.add_method('Deserialize', 'void', [param('ns3::Buffer::Iterator &', 'start')]) ## packetbb.h (module 'network'): uint32_t ns3::PbbTlv::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetType() const [member function] cls.add_method('GetType', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetTypeExt() const [member function] cls.add_method('GetTypeExt', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): ns3::Buffer ns3::PbbTlv::GetValue() const [member function] cls.add_method('GetValue', 'ns3::Buffer', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbTlv::HasTypeExt() const [member function] cls.add_method('HasTypeExt', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbTlv::HasValue() const [member function] cls.add_method('HasValue', 'bool', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os, int level) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os'), param('int', 'level')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlv::Serialize(ns3::Buffer::Iterator & start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator &', 'start')], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbTlv::SetType(uint8_t type) [member function] cls.add_method('SetType', 'void', [param('uint8_t', 'type')]) ## packetbb.h (module 'network'): void ns3::PbbTlv::SetTypeExt(uint8_t type) [member function] cls.add_method('SetTypeExt', 'void', [param('uint8_t', 'type')]) ## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(ns3::Buffer start) [member function] cls.add_method('SetValue', 'void', [param('ns3::Buffer', 'start')]) ## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('SetValue', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStart() const [member function] cls.add_method('GetIndexStart', 'uint8_t', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStop() const [member function] cls.add_method('GetIndexStop', 'uint8_t', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStart() const [member function] cls.add_method('HasIndexStart', 'bool', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStop() const [member function] cls.add_method('HasIndexStop', 'bool', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): bool ns3::PbbTlv::IsMultivalue() const [member function] cls.add_method('IsMultivalue', 'bool', [], is_const=True, visibility='protected') ## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStart(uint8_t index) [member function] cls.add_method('SetIndexStart', 'void', [param('uint8_t', 'index')], visibility='protected') ## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStop(uint8_t index) [member function] cls.add_method('SetIndexStop', 'void', [param('uint8_t', 'index')], visibility='protected') ## packetbb.h (module 'network'): void ns3::PbbTlv::SetMultivalue(bool isMultivalue) [member function] cls.add_method('SetMultivalue', 'void', [param('bool', 'isMultivalue')], visibility='protected') return def register_Ns3Ping6_methods(root_module, cls): ## ping6.h (module 'applications'): ns3::Ping6::Ping6(ns3::Ping6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ping6 const &', 'arg0')]) ## ping6.h (module 'applications'): ns3::Ping6::Ping6() [constructor] cls.add_constructor([]) ## ping6.h (module 'applications'): static ns3::TypeId ns3::Ping6::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ping6.h (module 'applications'): void ns3::Ping6::SetIfIndex(uint32_t ifIndex) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t', 'ifIndex')]) ## ping6.h (module 'applications'): void ns3::Ping6::SetLocal(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## ping6.h (module 'applications'): void ns3::Ping6::SetRemote(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## ping6.h (module 'applications'): void ns3::Ping6::SetRouters(std::vector<ns3::Ipv6Address, std::allocator<ns3::Ipv6Address> > routers) [member function] cls.add_method('SetRouters', 'void', [param('std::vector< ns3::Ipv6Address >', 'routers')]) ## ping6.h (module 'applications'): void ns3::Ping6::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ping6.h (module 'applications'): void ns3::Ping6::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## ping6.h (module 'applications'): void ns3::Ping6::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3Radvd_methods(root_module, cls): ## radvd.h (module 'applications'): ns3::Radvd::Radvd(ns3::Radvd const & arg0) [copy constructor] cls.add_constructor([param('ns3::Radvd const &', 'arg0')]) ## radvd.h (module 'applications'): ns3::Radvd::Radvd() [constructor] cls.add_constructor([]) ## radvd.h (module 'applications'): void ns3::Radvd::AddConfiguration(ns3::Ptr<ns3::RadvdInterface> routerInterface) [member function] cls.add_method('AddConfiguration', 'void', [param('ns3::Ptr< ns3::RadvdInterface >', 'routerInterface')]) ## radvd.h (module 'applications'): int64_t ns3::Radvd::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## radvd.h (module 'applications'): static ns3::TypeId ns3::Radvd::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## radvd.h (module 'applications'): ns3::Radvd::MAX_RA_DELAY_TIME [variable] cls.add_static_attribute('MAX_RA_DELAY_TIME', 'uint32_t const', is_const=True) ## radvd.h (module 'applications'): void ns3::Radvd::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## radvd.h (module 'applications'): void ns3::Radvd::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## radvd.h (module 'applications'): void ns3::Radvd::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3RadvdInterface_methods(root_module, cls): ## radvd-interface.h (module 'applications'): ns3::RadvdInterface::RadvdInterface(ns3::RadvdInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::RadvdInterface const &', 'arg0')]) ## radvd-interface.h (module 'applications'): ns3::RadvdInterface::RadvdInterface(uint32_t interface) [constructor] cls.add_constructor([param('uint32_t', 'interface')]) ## radvd-interface.h (module 'applications'): ns3::RadvdInterface::RadvdInterface(uint32_t interface, uint32_t maxRtrAdvInterval, uint32_t minRtrAdvInterval) [constructor] cls.add_constructor([param('uint32_t', 'interface'), param('uint32_t', 'maxRtrAdvInterval'), param('uint32_t', 'minRtrAdvInterval')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::AddPrefix(ns3::Ptr<ns3::RadvdPrefix> routerPrefix) [member function] cls.add_method('AddPrefix', 'void', [param('ns3::Ptr< ns3::RadvdPrefix >', 'routerPrefix')]) ## radvd-interface.h (module 'applications'): uint8_t ns3::RadvdInterface::GetCurHopLimit() const [member function] cls.add_method('GetCurHopLimit', 'uint8_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetDefaultLifeTime() const [member function] cls.add_method('GetDefaultLifeTime', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint8_t ns3::RadvdInterface::GetDefaultPreference() const [member function] cls.add_method('GetDefaultPreference', 'uint8_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetHomeAgentLifeTime() const [member function] cls.add_method('GetHomeAgentLifeTime', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetHomeAgentPreference() const [member function] cls.add_method('GetHomeAgentPreference', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetInterface() const [member function] cls.add_method('GetInterface', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetLinkMtu() const [member function] cls.add_method('GetLinkMtu', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetMaxRtrAdvInterval() const [member function] cls.add_method('GetMaxRtrAdvInterval', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetMinDelayBetweenRAs() const [member function] cls.add_method('GetMinDelayBetweenRAs', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetMinRtrAdvInterval() const [member function] cls.add_method('GetMinRtrAdvInterval', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): std::list<ns3::Ptr<ns3::RadvdPrefix>, std::allocator<ns3::Ptr<ns3::RadvdPrefix> > > ns3::RadvdInterface::GetPrefixes() const [member function] cls.add_method('GetPrefixes', 'std::list< ns3::Ptr< ns3::RadvdPrefix > >', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetReachableTime() const [member function] cls.add_method('GetReachableTime', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetRetransTimer() const [member function] cls.add_method('GetRetransTimer', 'uint32_t', [], is_const=True) ## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsHomeAgentFlag() const [member function] cls.add_method('IsHomeAgentFlag', 'bool', [], is_const=True) ## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsHomeAgentInfo() const [member function] cls.add_method('IsHomeAgentInfo', 'bool', [], is_const=True) ## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsIntervalOpt() const [member function] cls.add_method('IsIntervalOpt', 'bool', [], is_const=True) ## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsManagedFlag() const [member function] cls.add_method('IsManagedFlag', 'bool', [], is_const=True) ## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsMobRtrSupportFlag() const [member function] cls.add_method('IsMobRtrSupportFlag', 'bool', [], is_const=True) ## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsOtherConfigFlag() const [member function] cls.add_method('IsOtherConfigFlag', 'bool', [], is_const=True) ## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsSendAdvert() const [member function] cls.add_method('IsSendAdvert', 'bool', [], is_const=True) ## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsSourceLLAddress() const [member function] cls.add_method('IsSourceLLAddress', 'bool', [], is_const=True) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetCurHopLimit(uint8_t curHopLimit) [member function] cls.add_method('SetCurHopLimit', 'void', [param('uint8_t', 'curHopLimit')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetDefaultLifeTime(uint32_t defaultLifeTime) [member function] cls.add_method('SetDefaultLifeTime', 'void', [param('uint32_t', 'defaultLifeTime')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetDefaultPreference(uint8_t defaultPreference) [member function] cls.add_method('SetDefaultPreference', 'void', [param('uint8_t', 'defaultPreference')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetHomeAgentFlag(bool homeAgentFlag) [member function] cls.add_method('SetHomeAgentFlag', 'void', [param('bool', 'homeAgentFlag')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetHomeAgentInfo(bool homeAgentFlag) [member function] cls.add_method('SetHomeAgentInfo', 'void', [param('bool', 'homeAgentFlag')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetHomeAgentLifeTime(uint32_t homeAgentLifeTime) [member function] cls.add_method('SetHomeAgentLifeTime', 'void', [param('uint32_t', 'homeAgentLifeTime')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetHomeAgentPreference(uint32_t homeAgentPreference) [member function] cls.add_method('SetHomeAgentPreference', 'void', [param('uint32_t', 'homeAgentPreference')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetIntervalOpt(bool intervalOpt) [member function] cls.add_method('SetIntervalOpt', 'void', [param('bool', 'intervalOpt')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetLinkMtu(uint32_t linkMtu) [member function] cls.add_method('SetLinkMtu', 'void', [param('uint32_t', 'linkMtu')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetManagedFlag(bool managedFlag) [member function] cls.add_method('SetManagedFlag', 'void', [param('bool', 'managedFlag')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetMaxRtrAdvInterval(uint32_t maxRtrAdvInterval) [member function] cls.add_method('SetMaxRtrAdvInterval', 'void', [param('uint32_t', 'maxRtrAdvInterval')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetMinDelayBetweenRAs(uint32_t minDelayBetweenRAs) [member function] cls.add_method('SetMinDelayBetweenRAs', 'void', [param('uint32_t', 'minDelayBetweenRAs')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetMinRtrAdvInterval(uint32_t minRtrAdvInterval) [member function] cls.add_method('SetMinRtrAdvInterval', 'void', [param('uint32_t', 'minRtrAdvInterval')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetMobRtrSupportFlag(bool mobRtrSupportFlag) [member function] cls.add_method('SetMobRtrSupportFlag', 'void', [param('bool', 'mobRtrSupportFlag')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetOtherConfigFlag(bool otherConfigFlag) [member function] cls.add_method('SetOtherConfigFlag', 'void', [param('bool', 'otherConfigFlag')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetReachableTime(uint32_t reachableTime) [member function] cls.add_method('SetReachableTime', 'void', [param('uint32_t', 'reachableTime')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetRetransTimer(uint32_t retransTimer) [member function] cls.add_method('SetRetransTimer', 'void', [param('uint32_t', 'retransTimer')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetSendAdvert(bool sendAdvert) [member function] cls.add_method('SetSendAdvert', 'void', [param('bool', 'sendAdvert')]) ## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetSourceLLAddress(bool sourceLLAddress) [member function] cls.add_method('SetSourceLLAddress', 'void', [param('bool', 'sourceLLAddress')]) return def register_Ns3RadvdPrefix_methods(root_module, cls): ## radvd-prefix.h (module 'applications'): ns3::RadvdPrefix::RadvdPrefix(ns3::RadvdPrefix const & arg0) [copy constructor] cls.add_constructor([param('ns3::RadvdPrefix const &', 'arg0')]) ## radvd-prefix.h (module 'applications'): ns3::RadvdPrefix::RadvdPrefix(ns3::Ipv6Address network, uint8_t prefixLength, uint32_t preferredLifeTime=604800, uint32_t validLifeTime=2592000, bool onLinkFlag=true, bool autonomousFlag=true, bool routerAddrFlag=false) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'network'), param('uint8_t', 'prefixLength'), param('uint32_t', 'preferredLifeTime', default_value='604800'), param('uint32_t', 'validLifeTime', default_value='2592000'), param('bool', 'onLinkFlag', default_value='true'), param('bool', 'autonomousFlag', default_value='true'), param('bool', 'routerAddrFlag', default_value='false')]) ## radvd-prefix.h (module 'applications'): ns3::Ipv6Address ns3::RadvdPrefix::GetNetwork() const [member function] cls.add_method('GetNetwork', 'ns3::Ipv6Address', [], is_const=True) ## radvd-prefix.h (module 'applications'): uint32_t ns3::RadvdPrefix::GetPreferredLifeTime() const [member function] cls.add_method('GetPreferredLifeTime', 'uint32_t', [], is_const=True) ## radvd-prefix.h (module 'applications'): uint8_t ns3::RadvdPrefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## radvd-prefix.h (module 'applications'): uint32_t ns3::RadvdPrefix::GetValidLifeTime() const [member function] cls.add_method('GetValidLifeTime', 'uint32_t', [], is_const=True) ## radvd-prefix.h (module 'applications'): bool ns3::RadvdPrefix::IsAutonomousFlag() const [member function] cls.add_method('IsAutonomousFlag', 'bool', [], is_const=True) ## radvd-prefix.h (module 'applications'): bool ns3::RadvdPrefix::IsOnLinkFlag() const [member function] cls.add_method('IsOnLinkFlag', 'bool', [], is_const=True) ## radvd-prefix.h (module 'applications'): bool ns3::RadvdPrefix::IsRouterAddrFlag() const [member function] cls.add_method('IsRouterAddrFlag', 'bool', [], is_const=True) ## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetAutonomousFlag(bool autonomousFlag) [member function] cls.add_method('SetAutonomousFlag', 'void', [param('bool', 'autonomousFlag')]) ## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetNetwork(ns3::Ipv6Address network) [member function] cls.add_method('SetNetwork', 'void', [param('ns3::Ipv6Address', 'network')]) ## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetOnLinkFlag(bool onLinkFlag) [member function] cls.add_method('SetOnLinkFlag', 'void', [param('bool', 'onLinkFlag')]) ## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetPreferredLifeTime(uint32_t preferredLifeTime) [member function] cls.add_method('SetPreferredLifeTime', 'void', [param('uint32_t', 'preferredLifeTime')]) ## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetPrefixLength(uint8_t prefixLength) [member function] cls.add_method('SetPrefixLength', 'void', [param('uint8_t', 'prefixLength')]) ## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetRouterAddrFlag(bool routerAddrFlag) [member function] cls.add_method('SetRouterAddrFlag', 'void', [param('bool', 'routerAddrFlag')]) ## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetValidLifeTime(uint32_t validLifeTime) [member function] cls.add_method('SetValidLifeTime', 'void', [param('uint32_t', 'validLifeTime')]) return def register_Ns3RateErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel(ns3::RateErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RateErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): int64_t ns3::RateErrorModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## error-model.h (module 'network'): double ns3::RateErrorModel::GetRate() const [member function] cls.add_method('GetRate', 'double', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::RateErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit ns3::RateErrorModel::GetUnit() const [member function] cls.add_method('GetUnit', 'ns3::RateErrorModel::ErrorUnit', [], is_const=True) ## error-model.h (module 'network'): void ns3::RateErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> arg0) [member function] cls.add_method('SetRandomVariable', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'arg0')]) ## error-model.h (module 'network'): void ns3::RateErrorModel::SetRate(double rate) [member function] cls.add_method('SetRate', 'void', [param('double', 'rate')]) ## error-model.h (module 'network'): void ns3::RateErrorModel::SetUnit(ns3::RateErrorModel::ErrorUnit error_unit) [member function] cls.add_method('SetUnit', 'void', [param('ns3::RateErrorModel::ErrorUnit', 'error_unit')]) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptBit(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorruptBit', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptByte(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorruptByte', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptPkt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorruptPkt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::RateErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3ReceiveListErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel(ns3::ReceiveListErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ReceiveListErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ReceiveListErrorModel::GetList() const [member function] cls.add_method('GetList', 'std::list< unsigned int >', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::ReceiveListErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function] cls.add_method('SetList', 'void', [param('std::list< unsigned int > const &', 'packetlist')]) ## error-model.h (module 'network'): bool ns3::ReceiveListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3SimpleChannel_methods(root_module, cls): ## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel(ns3::SimpleChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SimpleChannel const &', 'arg0')]) ## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel() [constructor] cls.add_constructor([]) ## simple-channel.h (module 'network'): void ns3::SimpleChannel::Add(ns3::Ptr<ns3::SimpleNetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::SimpleNetDevice >', 'device')]) ## simple-channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::SimpleChannel::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) ## simple-channel.h (module 'network'): uint32_t ns3::SimpleChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## simple-channel.h (module 'network'): static ns3::TypeId ns3::SimpleChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## simple-channel.h (module 'network'): void ns3::SimpleChannel::Send(ns3::Ptr<ns3::Packet> p, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from, ns3::Ptr<ns3::SimpleNetDevice> sender) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'sender')]) return def register_Ns3SimpleNetDevice_methods(root_module, cls): ## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice(ns3::SimpleNetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::SimpleNetDevice const &', 'arg0')]) ## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice() [constructor] cls.add_constructor([]) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::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) ## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::SimpleNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): uint32_t ns3::SimpleNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): uint16_t ns3::SimpleNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::SimpleNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): static ns3::TypeId ns3::SimpleNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::Receive(ns3::Ptr<ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')]) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::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) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::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) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetChannel(ns3::Ptr<ns3::SimpleChannel> channel) [member function] cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::SimpleChannel >', 'channel')]) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::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) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::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) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetReceiveErrorModel(ns3::Ptr<ns3::ErrorModel> em) [member function] cls.add_method('SetReceiveErrorModel', 'void', [param('ns3::Ptr< ns3::ErrorModel >', 'em')]) ## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) 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_Ns3UdpClient_methods(root_module, cls): ## udp-client.h (module 'applications'): ns3::UdpClient::UdpClient(ns3::UdpClient const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpClient const &', 'arg0')]) ## udp-client.h (module 'applications'): ns3::UdpClient::UdpClient() [constructor] cls.add_constructor([]) ## udp-client.h (module 'applications'): static ns3::TypeId ns3::UdpClient::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## udp-client.h (module 'applications'): void ns3::UdpClient::SetRemote(ns3::Ipv4Address ip, uint16_t port) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')]) ## udp-client.h (module 'applications'): void ns3::UdpClient::SetRemote(ns3::Ipv6Address ip, uint16_t port) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')]) ## udp-client.h (module 'applications'): void ns3::UdpClient::SetRemote(ns3::Address ip, uint16_t port) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Address', 'ip'), param('uint16_t', 'port')]) ## udp-client.h (module 'applications'): void ns3::UdpClient::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## udp-client.h (module 'applications'): void ns3::UdpClient::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## udp-client.h (module 'applications'): void ns3::UdpClient::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3UdpEchoClient_methods(root_module, cls): ## udp-echo-client.h (module 'applications'): ns3::UdpEchoClient::UdpEchoClient(ns3::UdpEchoClient const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpEchoClient const &', 'arg0')]) ## udp-echo-client.h (module 'applications'): ns3::UdpEchoClient::UdpEchoClient() [constructor] cls.add_constructor([]) ## udp-echo-client.h (module 'applications'): uint32_t ns3::UdpEchoClient::GetDataSize() const [member function] cls.add_method('GetDataSize', 'uint32_t', [], is_const=True) ## udp-echo-client.h (module 'applications'): static ns3::TypeId ns3::UdpEchoClient::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetDataSize(uint32_t dataSize) [member function] cls.add_method('SetDataSize', 'void', [param('uint32_t', 'dataSize')]) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetFill(std::string fill) [member function] cls.add_method('SetFill', 'void', [param('std::string', 'fill')]) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetFill(uint8_t fill, uint32_t dataSize) [member function] cls.add_method('SetFill', 'void', [param('uint8_t', 'fill'), param('uint32_t', 'dataSize')]) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetFill(uint8_t * fill, uint32_t fillSize, uint32_t dataSize) [member function] cls.add_method('SetFill', 'void', [param('uint8_t *', 'fill'), param('uint32_t', 'fillSize'), param('uint32_t', 'dataSize')]) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetRemote(ns3::Address ip, uint16_t port) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Address', 'ip'), param('uint16_t', 'port')]) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetRemote(ns3::Ipv4Address ip, uint16_t port) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')]) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetRemote(ns3::Ipv6Address ip, uint16_t port) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')]) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3UdpEchoServer_methods(root_module, cls): ## udp-echo-server.h (module 'applications'): ns3::UdpEchoServer::UdpEchoServer(ns3::UdpEchoServer const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpEchoServer const &', 'arg0')]) ## udp-echo-server.h (module 'applications'): ns3::UdpEchoServer::UdpEchoServer() [constructor] cls.add_constructor([]) ## udp-echo-server.h (module 'applications'): static ns3::TypeId ns3::UdpEchoServer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## udp-echo-server.h (module 'applications'): void ns3::UdpEchoServer::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## udp-echo-server.h (module 'applications'): void ns3::UdpEchoServer::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## udp-echo-server.h (module 'applications'): void ns3::UdpEchoServer::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3UdpServer_methods(root_module, cls): ## udp-server.h (module 'applications'): ns3::UdpServer::UdpServer(ns3::UdpServer const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpServer const &', 'arg0')]) ## udp-server.h (module 'applications'): ns3::UdpServer::UdpServer() [constructor] cls.add_constructor([]) ## udp-server.h (module 'applications'): uint32_t ns3::UdpServer::GetLost() const [member function] cls.add_method('GetLost', 'uint32_t', [], is_const=True) ## udp-server.h (module 'applications'): uint16_t ns3::UdpServer::GetPacketWindowSize() const [member function] cls.add_method('GetPacketWindowSize', 'uint16_t', [], is_const=True) ## udp-server.h (module 'applications'): uint32_t ns3::UdpServer::GetReceived() const [member function] cls.add_method('GetReceived', 'uint32_t', [], is_const=True) ## udp-server.h (module 'applications'): static ns3::TypeId ns3::UdpServer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## udp-server.h (module 'applications'): void ns3::UdpServer::SetPacketWindowSize(uint16_t size) [member function] cls.add_method('SetPacketWindowSize', 'void', [param('uint16_t', 'size')]) ## udp-server.h (module 'applications'): void ns3::UdpServer::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## udp-server.h (module 'applications'): void ns3::UdpServer::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## udp-server.h (module 'applications'): void ns3::UdpServer::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3UdpTraceClient_methods(root_module, cls): ## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient::UdpTraceClient(ns3::UdpTraceClient const & arg0) [copy constructor] cls.add_constructor([param('ns3::UdpTraceClient const &', 'arg0')]) ## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient::UdpTraceClient() [constructor] cls.add_constructor([]) ## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient::UdpTraceClient(ns3::Ipv4Address ip, uint16_t port, char * traceFile) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port'), param('char *', 'traceFile')]) ## udp-trace-client.h (module 'applications'): uint16_t ns3::UdpTraceClient::GetMaxPacketSize() [member function] cls.add_method('GetMaxPacketSize', 'uint16_t', []) ## udp-trace-client.h (module 'applications'): static ns3::TypeId ns3::UdpTraceClient::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetMaxPacketSize(uint16_t maxPacketSize) [member function] cls.add_method('SetMaxPacketSize', 'void', [param('uint16_t', 'maxPacketSize')]) ## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetRemote(ns3::Address ip, uint16_t port) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Address', 'ip'), param('uint16_t', 'port')]) ## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetRemote(ns3::Ipv4Address ip, uint16_t port) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')]) ## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetRemote(ns3::Ipv6Address ip, uint16_t port) [member function] cls.add_method('SetRemote', 'void', [param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')]) ## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetTraceFile(std::string filename) [member function] cls.add_method('SetTraceFile', 'void', [param('std::string', 'filename')]) ## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3V4Ping_methods(root_module, cls): ## v4ping.h (module 'applications'): ns3::V4Ping::V4Ping(ns3::V4Ping const & arg0) [copy constructor] cls.add_constructor([param('ns3::V4Ping const &', 'arg0')]) ## v4ping.h (module 'applications'): ns3::V4Ping::V4Ping() [constructor] cls.add_constructor([]) ## v4ping.h (module 'applications'): static ns3::TypeId ns3::V4Ping::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## v4ping.h (module 'applications'): void ns3::V4Ping::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## v4ping.h (module 'applications'): void ns3::V4Ping::StartApplication() [member function] cls.add_method('StartApplication', 'void', [], visibility='private', is_virtual=True) ## v4ping.h (module 'applications'): void ns3::V4Ping::StopApplication() [member function] cls.add_method('StopApplication', 'void', [], visibility='private', is_virtual=True) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3BurstErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::BurstErrorModel::BurstErrorModel(ns3::BurstErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::BurstErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::BurstErrorModel::BurstErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): int64_t ns3::BurstErrorModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## error-model.h (module 'network'): double ns3::BurstErrorModel::GetBurstRate() const [member function] cls.add_method('GetBurstRate', 'double', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::BurstErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): void ns3::BurstErrorModel::SetBurstRate(double rate) [member function] cls.add_method('SetBurstRate', 'void', [param('double', 'rate')]) ## error-model.h (module 'network'): void ns3::BurstErrorModel::SetRandomBurstSize(ns3::Ptr<ns3::RandomVariableStream> arg0) [member function] cls.add_method('SetRandomBurstSize', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'arg0')]) ## error-model.h (module 'network'): void ns3::BurstErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> arg0) [member function] cls.add_method('SetRandomVariable', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'arg0')]) ## error-model.h (module 'network'): bool ns3::BurstErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::BurstErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3PbbAddressTlv_methods(root_module, cls): ## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv() [constructor] cls.add_constructor([]) ## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv(ns3::PbbAddressTlv const & arg0) [copy constructor] cls.add_constructor([param('ns3::PbbAddressTlv const &', 'arg0')]) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStart() const [member function] cls.add_method('GetIndexStart', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStop() const [member function] cls.add_method('GetIndexStop', 'uint8_t', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStart() const [member function] cls.add_method('HasIndexStart', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStop() const [member function] cls.add_method('HasIndexStop', 'bool', [], is_const=True) ## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::IsMultivalue() const [member function] cls.add_method('IsMultivalue', 'bool', [], is_const=True) ## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStart(uint8_t index) [member function] cls.add_method('SetIndexStart', 'void', [param('uint8_t', 'index')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStop(uint8_t index) [member function] cls.add_method('SetIndexStop', 'void', [param('uint8_t', 'index')]) ## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetMultivalue(bool isMultivalue) [member function] cls.add_method('SetMultivalue', 'void', [param('bool', 'isMultivalue')]) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_addressUtils(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
google-code/android-scripting
python/src/Lib/test/test_tcl.py
75
4645
#!/usr/bin/env python import unittest import os from test import test_support from Tkinter import Tcl from _tkinter import TclError class TclTest(unittest.TestCase): def setUp(self): self.interp = Tcl() def testEval(self): tcl = self.interp tcl.eval('set a 1') self.assertEqual(tcl.eval('set a'),'1') def testEvalException(self): tcl = self.interp self.assertRaises(TclError,tcl.eval,'set a') def testEvalException2(self): tcl = self.interp self.assertRaises(TclError,tcl.eval,'this is wrong') def testCall(self): tcl = self.interp tcl.call('set','a','1') self.assertEqual(tcl.call('set','a'),'1') def testCallException(self): tcl = self.interp self.assertRaises(TclError,tcl.call,'set','a') def testCallException2(self): tcl = self.interp self.assertRaises(TclError,tcl.call,'this','is','wrong') def testSetVar(self): tcl = self.interp tcl.setvar('a','1') self.assertEqual(tcl.eval('set a'),'1') def testSetVarArray(self): tcl = self.interp tcl.setvar('a(1)','1') self.assertEqual(tcl.eval('set a(1)'),'1') def testGetVar(self): tcl = self.interp tcl.eval('set a 1') self.assertEqual(tcl.getvar('a'),'1') def testGetVarArray(self): tcl = self.interp tcl.eval('set a(1) 1') self.assertEqual(tcl.getvar('a(1)'),'1') def testGetVarException(self): tcl = self.interp self.assertRaises(TclError,tcl.getvar,'a') def testGetVarArrayException(self): tcl = self.interp self.assertRaises(TclError,tcl.getvar,'a(1)') def testUnsetVar(self): tcl = self.interp tcl.setvar('a',1) self.assertEqual(tcl.eval('info exists a'),'1') tcl.unsetvar('a') self.assertEqual(tcl.eval('info exists a'),'0') def testUnsetVarArray(self): tcl = self.interp tcl.setvar('a(1)',1) tcl.setvar('a(2)',2) self.assertEqual(tcl.eval('info exists a(1)'),'1') self.assertEqual(tcl.eval('info exists a(2)'),'1') tcl.unsetvar('a(1)') self.assertEqual(tcl.eval('info exists a(1)'),'0') self.assertEqual(tcl.eval('info exists a(2)'),'1') def testUnsetVarException(self): tcl = self.interp self.assertRaises(TclError,tcl.unsetvar,'a') def testEvalFile(self): tcl = self.interp filename = "testEvalFile.tcl" fd = open(filename,'w') script = """set a 1 set b 2 set c [ expr $a + $b ] """ fd.write(script) fd.close() tcl.evalfile(filename) os.remove(filename) self.assertEqual(tcl.eval('set a'),'1') self.assertEqual(tcl.eval('set b'),'2') self.assertEqual(tcl.eval('set c'),'3') def testEvalFileException(self): tcl = self.interp filename = "doesnotexists" try: os.remove(filename) except Exception,e: pass self.assertRaises(TclError,tcl.evalfile,filename) def testPackageRequireException(self): tcl = self.interp self.assertRaises(TclError,tcl.eval,'package require DNE') def testLoadTk(self): import os if 'DISPLAY' not in os.environ: # skipping test of clean upgradeability return tcl = Tcl() self.assertRaises(TclError,tcl.winfo_geometry) tcl.loadtk() self.assertEqual('1x1+0+0', tcl.winfo_geometry()) tcl.destroy() def testLoadTkFailure(self): import os old_display = None import sys if sys.platform.startswith(('win', 'darwin', 'cygwin')): return # no failure possible on windows? if 'DISPLAY' in os.environ: old_display = os.environ['DISPLAY'] del os.environ['DISPLAY'] # on some platforms, deleting environment variables # doesn't actually carry through to the process level # because they don't support unsetenv # If that's the case, abort. display = os.popen('echo $DISPLAY').read().strip() if display: return try: tcl = Tcl() self.assertRaises(TclError, tcl.winfo_geometry) self.assertRaises(TclError, tcl.loadtk) finally: if old_display is not None: os.environ['DISPLAY'] = old_display def test_main(): test_support.run_unittest(TclTest) if __name__ == "__main__": test_main()
apache-2.0
koobonil/Boss2D
Boss2D/addon/tensorflow-1.2.1_for_boss/tensorflow/contrib/distributions/python/kernel_tests/vector_student_t_test.py
40
11863
# 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. # ============================================================================== """Tests for MultivariateStudentsT Distribution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from scipy import linalg from scipy import special from tensorflow.contrib.distributions.python.ops.vector_student_t import _VectorStudentT from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.platform import test class _FakeVectorStudentT(object): """Fake scipy implementation for Multivariate Student's t-distribution. Technically we don't need to test the `Vector Student's t-distribution` since its composed of only unit-tested parts. However this _FakeVectorStudentT serves as something like an end-to-end test of the `TransformedDistribution + Affine` API. Other `Vector*` implementations need only test new code. That we don't need to test every Vector* distribution is good because there aren't SciPy analogues and reimplementing everything in NumPy sort of defeats the point of having the `TransformedDistribution + Affine` API. """ def __init__(self, df, loc, scale_tril): self._df = np.asarray(df) self._loc = np.asarray(loc) self._scale_tril = np.asarray(scale_tril) def log_prob(self, x): def _compute(df, loc, scale_tril, x): k = scale_tril.shape[-1] ildj = np.sum(np.log(np.abs(np.diag(scale_tril))), axis=-1) logz = ildj + k * (0.5 * np.log(df) + 0.5 * np.log(np.pi) + special.gammaln(0.5 * df) - special.gammaln(0.5 * (df + 1.))) y = linalg.solve_triangular(scale_tril, np.matrix(x - loc).T, lower=True, overwrite_b=True) logs = -0.5 * (df + 1.) * np.sum(np.log1p(y**2. / df), axis=-2) return logs - logz if not self._df.shape: return _compute(self._df, self._loc, self._scale_tril, x) return np.concatenate([ [_compute(self._df[i], self._loc[i], self._scale_tril[i], x[:, i, :])] for i in range(len(self._df))]).T def prob(self, x): return np.exp(self.log_prob(x)) class VectorStudentTTest(test.TestCase): def setUp(self): self._rng = np.random.RandomState(42) def testProbStaticScalar(self): with self.test_session(): # Scalar batch_shape. df = np.asarray(3., dtype=np.float32) # Scalar batch_shape. loc = np.asarray([1], dtype=np.float32) scale_diag = np.asarray([2.], dtype=np.float32) scale_tril = np.diag(scale_diag) expected_mst = _FakeVectorStudentT( df=df, loc=loc, scale_tril=scale_tril) actual_mst = _VectorStudentT(df=df, loc=loc, scale_diag=scale_diag, validate_args=True) x = 2. * self._rng.rand(4, 1).astype(np.float32) - 1. self.assertAllClose(expected_mst.log_prob(x), actual_mst.log_prob(x).eval(), rtol=0., atol=1e-5) self.assertAllClose(expected_mst.prob(x), actual_mst.prob(x).eval(), rtol=0., atol=1e-5) def testProbStatic(self): # Non-scalar batch_shape. df = np.asarray([1., 2, 3], dtype=np.float32) # Non-scalar batch_shape. loc = np.asarray([[0., 0, 0], [1, 2, 3], [1, 0, 1]], dtype=np.float32) scale_diag = np.asarray([[1., 2, 3], [2, 3, 4], [4, 5, 6]], dtype=np.float32) scale_tril = np.concatenate([[np.diag(scale_diag[i])] for i in range(len(scale_diag))]) x = 2. * self._rng.rand(4, 3, 3).astype(np.float32) - 1. expected_mst = _FakeVectorStudentT( df=df, loc=loc, scale_tril=scale_tril) with self.test_session(): actual_mst = _VectorStudentT(df=df, loc=loc, scale_diag=scale_diag, validate_args=True) self.assertAllClose(expected_mst.log_prob(x), actual_mst.log_prob(x).eval(), rtol=0., atol=1e-5) self.assertAllClose(expected_mst.prob(x), actual_mst.prob(x).eval(), rtol=0., atol=1e-5) def testProbDynamic(self): # Non-scalar batch_shape. df = np.asarray([1., 2, 3], dtype=np.float32) # Non-scalar batch_shape. loc = np.asarray([[0., 0, 0], [1, 2, 3], [1, 0, 1]], dtype=np.float32) scale_diag = np.asarray([[1., 2, 3], [2, 3, 4], [4, 5, 6]], dtype=np.float32) scale_tril = np.concatenate([[np.diag(scale_diag[i])] for i in range(len(scale_diag))]) x = 2. * self._rng.rand(4, 3, 3).astype(np.float32) - 1. expected_mst = _FakeVectorStudentT( df=df, loc=loc, scale_tril=scale_tril) with self.test_session(): df_pl = array_ops.placeholder(dtypes.float32, name="df") loc_pl = array_ops.placeholder(dtypes.float32, name="loc") scale_diag_pl = array_ops.placeholder(dtypes.float32, name="scale_diag") feed_dict = {df_pl: df, loc_pl: loc, scale_diag_pl: scale_diag} actual_mst = _VectorStudentT(df=df, loc=loc, scale_diag=scale_diag, validate_args=True) self.assertAllClose(expected_mst.log_prob(x), actual_mst.log_prob(x).eval(feed_dict=feed_dict), rtol=0., atol=1e-5) self.assertAllClose(expected_mst.prob(x), actual_mst.prob(x).eval(feed_dict=feed_dict), rtol=0., atol=1e-5) def testProbScalarBaseDistributionNonScalarTransform(self): # Scalar batch_shape. df = np.asarray(2., dtype=np.float32) # Non-scalar batch_shape. loc = np.asarray([[0., 0, 0], [1, 2, 3], [1, 0, 1]], dtype=np.float32) scale_diag = np.asarray([[1., 2, 3], [2, 3, 4], [4, 5, 6]], dtype=np.float32) scale_tril = np.concatenate([[np.diag(scale_diag[i])] for i in range(len(scale_diag))]) x = 2. * self._rng.rand(4, 3, 3).astype(np.float32) - 1. expected_mst = _FakeVectorStudentT( df=np.tile(df, reps=len(scale_diag)), loc=loc, scale_tril=scale_tril) with self.test_session(): actual_mst = _VectorStudentT(df=df, loc=loc, scale_diag=scale_diag, validate_args=True) self.assertAllClose(expected_mst.log_prob(x), actual_mst.log_prob(x).eval(), rtol=0., atol=1e-5) self.assertAllClose(expected_mst.prob(x), actual_mst.prob(x).eval(), rtol=0., atol=1e-5) def testProbScalarBaseDistributionNonScalarTransformDynamic(self): # Scalar batch_shape. df = np.asarray(2., dtype=np.float32) # Non-scalar batch_shape. loc = np.asarray([[0., 0, 0], [1, 2, 3], [1, 0, 1]], dtype=np.float32) scale_diag = np.asarray([[1., 2, 3], [2, 3, 4], [4, 5, 6]], dtype=np.float32) scale_tril = np.concatenate([[np.diag(scale_diag[i])] for i in range(len(scale_diag))]) x = 2. * self._rng.rand(4, 3, 3).astype(np.float32) - 1. expected_mst = _FakeVectorStudentT( df=np.tile(df, reps=len(scale_diag)), loc=loc, scale_tril=scale_tril) with self.test_session(): df_pl = array_ops.placeholder(dtypes.float32, name="df") loc_pl = array_ops.placeholder(dtypes.float32, name="loc") scale_diag_pl = array_ops.placeholder(dtypes.float32, name="scale_diag") feed_dict = {df_pl: df, loc_pl: loc, scale_diag_pl: scale_diag} actual_mst = _VectorStudentT(df=df, loc=loc, scale_diag=scale_diag, validate_args=True) self.assertAllClose(expected_mst.log_prob(x), actual_mst.log_prob(x).eval(feed_dict=feed_dict), rtol=0., atol=1e-5) self.assertAllClose(expected_mst.prob(x), actual_mst.prob(x).eval(feed_dict=feed_dict), rtol=0., atol=1e-5) def testProbNonScalarBaseDistributionScalarTransform(self): # Non-scalar batch_shape. df = np.asarray([1., 2., 3.], dtype=np.float32) # Scalar batch_shape. loc = np.asarray([1, 2, 3], dtype=np.float32) scale_diag = np.asarray([2, 3, 4], dtype=np.float32) scale_tril = np.diag(scale_diag) x = 2. * self._rng.rand(4, 3, 3).astype(np.float32) - 1. expected_mst = _FakeVectorStudentT( df=df, loc=np.tile(loc[array_ops.newaxis, :], reps=[len(df), 1]), scale_tril=np.tile(scale_tril[array_ops.newaxis, :, :], reps=[len(df), 1, 1])) with self.test_session(): actual_mst = _VectorStudentT(df=df, loc=loc, scale_diag=scale_diag, validate_args=True) self.assertAllClose(expected_mst.log_prob(x), actual_mst.log_prob(x).eval(), rtol=0., atol=1e-5) self.assertAllClose(expected_mst.prob(x), actual_mst.prob(x).eval(), rtol=0., atol=1e-5) def testProbNonScalarBaseDistributionScalarTransformDynamic(self): # Non-scalar batch_shape. df = np.asarray([1., 2., 3.], dtype=np.float32) # Scalar batch_shape. loc = np.asarray([1, 2, 3], dtype=np.float32) scale_diag = np.asarray([2, 3, 4], dtype=np.float32) scale_tril = np.diag(scale_diag) x = 2. * self._rng.rand(4, 3, 3).astype(np.float32) - 1. expected_mst = _FakeVectorStudentT( df=df, loc=np.tile(loc[array_ops.newaxis, :], reps=[len(df), 1]), scale_tril=np.tile(scale_tril[array_ops.newaxis, :, :], reps=[len(df), 1, 1])) with self.test_session(): df_pl = array_ops.placeholder(dtypes.float32, name="df") loc_pl = array_ops.placeholder(dtypes.float32, name="loc") scale_diag_pl = array_ops.placeholder(dtypes.float32, name="scale_diag") feed_dict = {df_pl: df, loc_pl: loc, scale_diag_pl: scale_diag} actual_mst = _VectorStudentT(df=df, loc=loc, scale_diag=scale_diag, validate_args=True) self.assertAllClose(expected_mst.log_prob(x), actual_mst.log_prob(x).eval(feed_dict=feed_dict), rtol=0., atol=1e-5) self.assertAllClose(expected_mst.prob(x), actual_mst.prob(x).eval(feed_dict=feed_dict), rtol=0., atol=1e-5) if __name__ == "__main__": test.main()
mit
samanehsan/osf.io
framework/sessions/__init__.py
6
6422
# -*- coding: utf-8 -*- import furl import urllib import urlparse import bson.objectid import httplib as http from datetime import datetime import itsdangerous from flask import request from werkzeug.local import LocalProxy from weakref import WeakKeyDictionary from framework.flask import redirect from framework.mongo import database from website import settings from .model import Session def add_key_to_url(url, scheme, key): """Redirects the user to the requests URL with the given key appended to the query parameters. """ query = request.args.to_dict() query['view_only'] = key replacements = {'query': urllib.urlencode(query)} if scheme: replacements['scheme'] = scheme parsed_url = urlparse.urlparse(url) if parsed_url.fragment: # Fragments should exists server side so this mean some one set up a # in the url # WSGI sucks and auto unescapes it so we just shove it back into the path with the escaped hash replacements['path'] = '{}%23{}'.format(parsed_url.path, parsed_url.fragment) replacements['fragment'] = '' parsed_redirect_url = parsed_url._replace(**replacements) return urlparse.urlunparse(parsed_redirect_url) def prepare_private_key(): """`before_request` handler that checks the Referer header to see if the user is requesting from a view-only link. If so, reappend the view-only key. NOTE: In order to ensure the execution order of the before_request callbacks, this is attached in website.app.init_app rather than using @app.before_request. """ # Done if not GET request if request.method != 'GET': return # Done if private_key in args key_from_args = request.args.get('view_only', '') if key_from_args: return # grab query key from previous request for not login user if request.referrer: referrer_parsed = urlparse.urlparse(request.referrer) scheme = referrer_parsed.scheme key = urlparse.parse_qs( urlparse.urlparse(request.referrer).query ).get('view_only') if key: key = key[0] else: scheme = None key = None # Update URL and redirect if key and not session.is_authenticated: new_url = add_key_to_url(request.url, scheme, key) return redirect(new_url, code=http.TEMPORARY_REDIRECT) def get_session(): session = sessions.get(request._get_current_object()) if not session: session = Session() set_session(session) return session def set_session(session): sessions[request._get_current_object()] = session def create_session(response, data=None): current_session = get_session() if current_session: current_session.data.update(data or {}) current_session.save() cookie_value = itsdangerous.Signer(settings.SECRET_KEY).sign(current_session._id) else: session_id = str(bson.objectid.ObjectId()) session = Session(_id=session_id, data=data or {}) session.save() cookie_value = itsdangerous.Signer(settings.SECRET_KEY).sign(session_id) set_session(session) if response is not None: response.set_cookie(settings.COOKIE_NAME, value=cookie_value, domain=settings.OSF_COOKIE_DOMAIN) return response sessions = WeakKeyDictionary() session = LocalProxy(get_session) # Request callbacks # NOTE: This gets attached in website.app.init_app to ensure correct callback # order def before_request(): from framework.auth import cas # Central Authentication Server Ticket Validation and Authentication ticket = request.args.get('ticket') if ticket: service_url = furl.furl(request.url) service_url.args.pop('ticket') # Attempt autn wih CAS, and return a proper redirect response resp = cas.make_response_from_ticket(ticket=ticket, service_url=service_url.url) if request.cookies.get(settings.COOKIE_NAME): # TODO: Delete legacy cookie, this special case can be removed anytime after 1/1/2016. # A cookie is received which could potentially be a legacy (pre multi-domain) cookie. # Issuing a targeted delete of the legacy cookie ensures the user does not end up in a # login loop whereby both cookies are sent to the server and one of them at random # read for authentication. resp.delete_cookie(settings.COOKIE_NAME, domain=None) return resp if request.authorization: # TODO: Fix circular import from framework.auth.core import get_user user = get_user( email=request.authorization.username, password=request.authorization.password ) # Create empty session # TODO: Shoudn't need to create a session for Basic Auth session = Session() set_session(session) if user: user_addon = user.get_addon('twofactor') if user_addon and user_addon.is_confirmed: otp = request.headers.get('X-OSF-OTP') if otp is None or not user_addon.verify_code(otp): # Must specify two-factor authentication OTP code or invalid two-factor # authentication OTP code. session.data['auth_error_code'] = http.UNAUTHORIZED return session.data['auth_user_username'] = user.username session.data['auth_user_id'] = user._primary_key session.data['auth_user_fullname'] = user.fullname user.date_last_login = datetime.utcnow() user.save() else: # Invalid key: Not found in database session.data['auth_error_code'] = http.UNAUTHORIZED return cookie = request.cookies.get(settings.COOKIE_NAME) if cookie: try: session_id = itsdangerous.Signer(settings.SECRET_KEY).unsign(cookie) session = Session.load(session_id) or Session(_id=session_id) except itsdangerous.BadData: return if session.data.get('auth_user_id'): database['user'].update({'_id': session.data.get('auth_user_id')}, {'$set': {'date_last_login': datetime.utcnow()}}, w=0) set_session(session) def after_request(response): if session.data.get('auth_user_id'): session.save() return response
apache-2.0
ted-ross/qpid-dispatch
tests/friendship_pb2_grpc.py
5
6998
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import friendship_pb2 as friendship__pb2 class FriendshipStub(object): """Missing associated documentation comment in .proto file.""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.Create = channel.unary_unary( '/Friendship/Create', request_serializer=friendship__pb2.Person.SerializeToString, response_deserializer=friendship__pb2.CreateResult.FromString, ) self.ListFriends = channel.unary_stream( '/Friendship/ListFriends', request_serializer=friendship__pb2.PersonEmail.SerializeToString, response_deserializer=friendship__pb2.Person.FromString, ) self.CommonFriendsCount = channel.stream_unary( '/Friendship/CommonFriendsCount', request_serializer=friendship__pb2.PersonEmail.SerializeToString, response_deserializer=friendship__pb2.CommonFriendsResult.FromString, ) self.MakeFriends = channel.stream_stream( '/Friendship/MakeFriends', request_serializer=friendship__pb2.FriendshipRequest.SerializeToString, response_deserializer=friendship__pb2.FriendshipResponse.FromString, ) class FriendshipServicer(object): """Missing associated documentation comment in .proto file.""" def Create(self, request, context): """returns email (as the id) """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListFriends(self, request, context): """lists all friends for a given email """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def CommonFriendsCount(self, request_iterator, context): """list number of friends for all given emails """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def MakeFriends(self, request_iterator, context): """associate friends and returns true if friendship created or false if a given Person cannot be found """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_FriendshipServicer_to_server(servicer, server): rpc_method_handlers = { 'Create': grpc.unary_unary_rpc_method_handler( servicer.Create, request_deserializer=friendship__pb2.Person.FromString, response_serializer=friendship__pb2.CreateResult.SerializeToString, ), 'ListFriends': grpc.unary_stream_rpc_method_handler( servicer.ListFriends, request_deserializer=friendship__pb2.PersonEmail.FromString, response_serializer=friendship__pb2.Person.SerializeToString, ), 'CommonFriendsCount': grpc.stream_unary_rpc_method_handler( servicer.CommonFriendsCount, request_deserializer=friendship__pb2.PersonEmail.FromString, response_serializer=friendship__pb2.CommonFriendsResult.SerializeToString, ), 'MakeFriends': grpc.stream_stream_rpc_method_handler( servicer.MakeFriends, request_deserializer=friendship__pb2.FriendshipRequest.FromString, response_serializer=friendship__pb2.FriendshipResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'Friendship', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Friendship(object): """Missing associated documentation comment in .proto file.""" @staticmethod def Create(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/Friendship/Create', friendship__pb2.Person.SerializeToString, friendship__pb2.CreateResult.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def ListFriends(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_stream(request, target, '/Friendship/ListFriends', friendship__pb2.PersonEmail.SerializeToString, friendship__pb2.Person.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def CommonFriendsCount(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.stream_unary(request_iterator, target, '/Friendship/CommonFriendsCount', friendship__pb2.PersonEmail.SerializeToString, friendship__pb2.CommonFriendsResult.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def MakeFriends(request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.stream_stream(request_iterator, target, '/Friendship/MakeFriends', friendship__pb2.FriendshipRequest.SerializeToString, friendship__pb2.FriendshipResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
apache-2.0
OniOniOn-/MCEdit-Unified
pymclevel/leveldbpocket.py
1
39392
import itertools import time from math import floor from level import FakeChunk, MCLevel import logging from materials import pocketMaterials import os from mclevelbase import ChunkNotPresent, ChunkMalformed import nbt import numpy import struct from infiniteworld import ChunkedLevelMixin, SessionLockLost, AnvilChunkData from level import LightedChunk from contextlib import contextmanager from pymclevel import entity, BoundingBox, Entity, TileEntity logger = logging.getLogger(__name__) leveldb_available = True leveldb_mcpe = None try: import leveldb_mcpe leveldb_mcpe.Options() except Exception as e: leveldb_available = False logger.info("Error while trying to import leveldb_mcpe, starting without PE support ({0})".format(e)) leveldb_mcpe = None def loadNBTCompoundList(data, littleEndian=True): """ Loads a list of NBT Compound tags from a bunch of data. Uses sep to determine where the next Compound tag starts. :param data: str, the NBT to load from :param littleEndian: bool. Determines endianness :return: list of TAG_Compounds """ if type(data) is unicode: data = str(data) def load(_data): sep = "\x00\x00\x00\x00\n" sep_data = _data.split(sep) compounds = [] for d in sep_data: if len(d) != 0: if not d.startswith("\n"): d = "\n" + d tag = (nbt.load(buf=(d + '\x00\x00\x00\x00'))) compounds.append(tag) return compounds if littleEndian: with nbt.littleEndianNBT(): return load(data) else: return load(data) def TagProperty(tagName, tagType, default_or_func=None): """ Copied from infiniteworld.py. Custom property object to handle NBT-tag properties. :param tagName: str, Name of the NBT-tag :param tagType: int, (nbt.TAG_TYPE) Type of the NBT-tag :param default_or_func: function or default value. If function, function should return the default. :return: property """ def getter(self): if tagName not in self.root_tag: if hasattr(default_or_func, "__call__"): default = default_or_func(self) else: default = default_or_func self.root_tag[tagName] = tagType(default) return self.root_tag[tagName].value def setter(self, val): self.root_tag[tagName] = tagType(value=val) return property(getter, setter) class PocketLeveldbDatabase(object): """ Not to be confused with leveldb_mcpe.DB A PocketLeveldbDatabase is an interface around leveldb_mcpe.DB, providing various functions to load/write chunk data, and access the level.dat file. The leveldb_mcpe.DB object handles the actual leveldb database. To access the actual database, world_db() should be called. """ holdDatabaseOpen = True _world_db = None @contextmanager def world_db(self): """ Opens a leveldb and keeps it open until editing finished. :yield: DB """ if PocketLeveldbDatabase.holdDatabaseOpen: if self._world_db is None: self._world_db = leveldb_mcpe.DB(self.options, os.path.join(str(self.path), 'db')) yield self._world_db pass else: db = leveldb_mcpe.DB(self.options, os.path.join(str(self.path), 'db')) yield db del db def __init__(self, path, create=False): """ :param path: string, path to file :return: None """ self.path = path if not os.path.exists(path): file(path, 'w').close() self.options = leveldb_mcpe.Options() self.writeOptions = leveldb_mcpe.WriteOptions() self.readOptions = leveldb_mcpe.ReadOptions() if create: self.options.create_if_missing = True # The database will be created once needed first. return needsRepair = False try: with self.world_db() as db: it = db.NewIterator(self.readOptions) it.SeekToFirst() if not db.Get(self.readOptions, it.key()) == it.value(): needsRepair = True it.status() del it except RuntimeError as err: logger.error("Error while opening world database from %s (%s)" % path, err) needsRepair = True if needsRepair: logger.info("Trying to repair world %s", path) try: leveldb_mcpe.RepairWrapper(os.path.join(path, 'db')) except RuntimeError as err: logger.error("Error while repairing world %s %s" % path, err) def close(self): """ Should be called before deleting this instance of the level. Not calling this method may result in corrupted worlds :return: None """ if PocketLeveldbDatabase.holdDatabaseOpen: if self._world_db is not None: del self._world_db self._world_db = None def _readChunk(self, cx, cz, readOptions=None): """ :param cx, cz: int Coordinates of the chunk :param readOptions: ReadOptions :return: None """ key = struct.pack('<i', cx) + struct.pack('<i', cz) with self.world_db() as db: rop = self.readOptions if readOptions is None else readOptions # Only way to see if value exists is by failing db.Get() try: terrain = db.Get(rop, key + "0") except RuntimeError: return None try: tile_entities = db.Get(rop, key + "1") except RuntimeError: tile_entities = None try: entities = db.Get(rop, key + "2") except RuntimeError: entities = None if len(terrain) != 83200: raise ChunkMalformed(str(len(terrain))) logger.debug("CHUNK LOAD %s %s", cx, cz) return terrain, tile_entities, entities def saveChunk(self, chunk, batch=None, writeOptions=None): """ :param chunk: PocketLeveldbChunk :param batch: WriteBatch :param writeOptions: WriteOptions :return: None """ cx, cz = chunk.chunkPosition data = chunk.savedData() key = struct.pack('<i', cx) + struct.pack('<i', cz) if batch is None: with self.world_db() as db: wop = self.writeOptions if writeOptions is None else writeOptions db.Put(wop, key + "0", data[0]) if data[1] is not None: db.Put(wop, key + "1", data[1]) if data[2] is not None: db.Put(wop, key + "2", data[2]) else: batch.Put(key + "0", data[0]) if data[1] is not None: batch.Put(key + "1", data[1]) if data[2] is not None: batch.Put(key + "2", data[2]) def loadChunk(self, cx, cz, world): """ :param cx, cz: int Coordinates of the chunk :param world: PocketLeveldbWorld :return: PocketLeveldbChunk """ data = self._readChunk(cx, cz) if data is None: raise ChunkNotPresent((cx, cz, self)) chunk = PocketLeveldbChunk(cx, cz, world, data) return chunk _allChunks = None def deleteChunk(self, cx, cz, batch=None, writeOptions=None): if batch is None: with self.world_db() as db: key = struct.pack('<i', cx) + struct.pack('<i', cz) + "0" wop = self.writeOptions if writeOptions is None else writeOptions db.Delete(wop, key) else: key = struct.pack('<i', cx) + struct.pack('<i', cz) + "0" batch.Delete(key) logger.debug("DELETED CHUNK %s %s", cx, cz) def getAllChunks(self, readOptions=None): """ Returns a list of all chunks that have terrain data in the database. Chunks with only Entities or TileEntities are ignored. :param readOptions: ReadOptions :return: list """ with self.world_db() as db: allChunks = [] rop = self.readOptions if readOptions is None else readOptions it = db.NewIterator(rop) it.SeekToFirst() while it.Valid(): key = it.key() raw_x = key[0:4] raw_z = key[4:8] t = key[8] if t == "0": cx, cz = struct.unpack('<i', raw_x), struct.unpack('<i', raw_z) allChunks.append((cx[0], cz[0])) it.Next() it.status() # All this does is cause an exception if something went wrong. Might be unneeded? del it return allChunks def getAllPlayerData(self, readOptions=None): """ Returns the raw NBT data of all players in the database. Every player is stored as player_<player-id>. The single-player player is stored as ~local_player :param readOptions: :return: dictonary key, value: key: player-id, value = player nbt data as str """ with self.world_db() as db: allPlayers = {} rop = self.readOptions if readOptions is None else readOptions it = db.NewIterator(rop) it.SeekToFirst() while it.Valid(): key = it.key() if key == "~local_player": # Singleplayer allPlayers[key] = it.value() elif key.startswith('player_'): # Multiplayer player allPlayers[key] = it.value() it.Next() it.status() del it return allPlayers def savePlayer(self, player, playerData, batch=None, writeOptions=None): if writeOptions is None: writeOptions = self.writeOptions if batch is None: with self.world_db() as db: db.Put(writeOptions, player, playerData) else: batch.Put(player, playerData) class InvalidPocketLevelDBWorldException(Exception): pass class PocketLeveldbWorld(ChunkedLevelMixin, MCLevel): Height = 128 Width = 0 Length = 0 isInfinite = True materials = pocketMaterials noTileTicks = True _bounds = None oldPlayerFolderFormat = False _allChunks = None # An array of cx, cz pairs. _loadedChunks = {} # A dictionary of actual PocketLeveldbChunk objects mapped by (cx, cz) _playerData = None playerTagCache = {} _playerList = None @property def LevelName(self): if "LevelName" not in self.root_tag: with open(os.path.join(self.worldFile.path, "levelname.txt"), 'r') as f: name = f.read() if name is None: name = os.path.basename(self.worldFile.path) self.root_tag["LevelName"] = name return self.root_tag["LevelName"] @LevelName.setter def LevelName(self, name): self.root_tag["LevelName"] = nbt.TAG_String(value=name) with open(os.path.join(self.worldFile.path, "levelname.txt"), 'w') as f: f.write(name) @property def allChunks(self): """ :return: list with all chunks in the world. """ if self._allChunks is None: self._allChunks = self.worldFile.getAllChunks() return self._allChunks @property def players(self): if self._playerList is None: self._playerList = [] for key in self.playerData.keys(): self._playerList.append(key) return self._playerList @property def playerData(self): if self._playerData is None: self._playerData = self.worldFile.getAllPlayerData() return self._playerData @staticmethod def getPlayerPath(player, dim=0): """ player.py loads players from files, but PE caches them differently. This is necessary to make it work. :param player: str :param dim: int :return: str """ if dim == 0: return player def __init__(self, filename=None, create=False, random_seed=None, last_played=None, readonly=False): """ :param filename: path to the root dir of the level :return: """ if not os.path.isdir(filename): filename = os.path.dirname(filename) self.filename = filename self.worldFile = PocketLeveldbDatabase(filename, create=create) self.readonly = readonly self.loadLevelDat(create, random_seed, last_played) def _createLevelDat(self, random_seed, last_played): """ Creates a new level.dat root_tag, and puts it in self.root_tag. To write it to the disk, self.save() should be called. :param random_seed: long :param last_played: long :return: None """ with nbt.littleEndianNBT(): root_tag = nbt.TAG_Compound() root_tag["SpawnX"] = nbt.TAG_Int(0) root_tag["SpawnY"] = nbt.TAG_Int(2) root_tag["SpawnZ"] = nbt.TAG_Int(0) if last_played is None: last_played = long(time.time() * 100) if random_seed is None: random_seed = long(numpy.random.random() * 0xffffffffffffffffL) - 0x8000000000000000L self.root_tag = root_tag self.LastPlayed = long(last_played) self.RandomSeed = long(random_seed) self.SizeOnDisk = 0 self.Time = 1 self.LevelName = os.path.basename(self.worldFile.path) def loadLevelDat(self, create=False, random_seed=None, last_played=None): """ Loads the level.dat from the worldfolder. :param create: bool. If it's True, a fresh level.dat will be created instead. :param random_seed: long :param last_played: long :return: None """ def _loadLevelDat(filename): root_tag_buf = open(filename, 'rb').read() magic, length, root_tag_buf = root_tag_buf[:4], root_tag_buf[4:8], root_tag_buf[8:] if struct.Struct('<i').unpack(magic)[0] < 3: logger.info("Found an old level.dat file. Aborting world load") raise InvalidPocketLevelDBWorldException() # Maybe try convert/load old PE world? if len(root_tag_buf) != struct.Struct('<i').unpack(length)[0]: raise nbt.NBTFormatError() self.root_tag = nbt.load(buf=root_tag_buf) if create: self._createLevelDat(random_seed, last_played) return try: with nbt.littleEndianNBT(): _loadLevelDat(os.path.join(self.worldFile.path, "level.dat")) return except (nbt.NBTFormatError, IOError) as err: logger.info("Failed to load level.dat, trying to load level.dat_old ({0})".format(err)) try: with nbt.littleEndianNBT(): _loadLevelDat(os.path.join(self.worldFile.path, "level.dat_old")) return except (nbt.NBTFormatError, IOError) as err: logger.info("Failed to load level.dat_old, creating new level.dat ({0})".format(err)) self._createLevelDat(random_seed, last_played) # --- NBT Tag variables --- SizeOnDisk = TagProperty('SizeOnDisk', nbt.TAG_Int, 0) RandomSeed = TagProperty('RandomSeed', nbt.TAG_Long, 0) # TODO PE worlds have a different day length, this has to be changed to that. Time = TagProperty('Time', nbt.TAG_Long, 0) LastPlayed = TagProperty('LastPlayed', nbt.TAG_Long, lambda self: long(time.time() * 1000)) GeneratorName = TagProperty('Generator', nbt.TAG_String, 'Infinite') GameType = TagProperty('GameType', nbt.TAG_Int, 0) def defaultDisplayName(self): return os.path.basename(os.path.dirname(self.filename)) def __str__(self): """ How to represent this level :return: str """ return "PocketLeveldbWorld(\"%s\")" % os.path.basename(os.path.dirname(self.worldFile.path)) def getChunk(self, cx, cz): """ Used to obtain a chunk from the database. :param cx, cz: cx, cz coordinates of the chunk :return: PocketLeveldbChunk """ c = self._loadedChunks.get((cx, cz)) if c is None: c = self.worldFile.loadChunk(cx, cz, self) self._loadedChunks[(cx, cz)] = c return c def unload(self): """ Unload all chunks and close all open file-handlers. """ self._loadedChunks.clear() self._allChunks = None self.worldFile.close() def close(self): """ Unload all chunks and close all open file-handlers. Discard any unsaved data. """ self.unload() try: pass # Setup a way to close a work-folder? except SessionLockLost: pass def deleteChunk(self, cx, cz, batch=None): """ Deletes a chunk at given cx, cz. Deletes using the batch if batch is given, uses world_db() otherwise. :param cx, cz Coordinates of the chunk :param batch WriteBatch :return: None """ self.worldFile.deleteChunk(cx, cz, batch=batch) if self._loadedChunks is not None and (cx, cz) in self._loadedChunks: # Unnecessary check? del self._loadedChunks[(cx, cz)] self.allChunks.remove((cx, cz)) def deleteChunksInBox(self, box): """ Deletes all chunks in a given box. :param box pymclevel.box.BoundingBox :return: None """ logger.info(u"Deleting {0} chunks in {1}".format((box.maxcx - box.mincx) * (box.maxcz - box.mincz), ((box.mincx, box.mincz), (box.maxcx, box.maxcz)))) i = 0 ret = [] batch = leveldb_mcpe.WriteBatch() for cx, cz in itertools.product(xrange(box.mincx, box.maxcx), xrange(box.mincz, box.maxcz)): i += 1 if self.containsChunk(cx, cz): self.deleteChunk(cx, cz, batch=batch) ret.append((cx, cz)) assert not self.containsChunk(cx, cz), "Just deleted {0} but it didn't take".format((cx, cz)) if i % 100 == 0: logger.info(u"Chunk {0}...".format(i)) with self.worldFile.world_db() as db: wop = self.worldFile.writeOptions db.Write(wop, batch) del batch return ret @property def bounds(self): """ Returns a boundingbox containing the entire level :return: pymclevel.box.BoundingBox """ if self._bounds is None: self._bounds = self._getWorldBounds() return self._bounds @property def size(self): return self.bounds.size def _getWorldBounds(self): if len(self.allChunks) == 0: return BoundingBox((0, 0, 0), (0, 0, 0)) allChunks = numpy.array(list(self.allChunks)) min_cx = (allChunks[:, 0]).min() max_cx = (allChunks[:, 0]).max() min_cz = (allChunks[:, 1]).min() max_cz = (allChunks[:, 1]).max() origin = (min_cx << 4, 0, min_cz << 4) size = ((max_cx - min_cx + 1) << 4, self.Height, (max_cz - min_cz + 1) << 4) return BoundingBox(origin, size) @classmethod def _isLevel(cls, filename): """ Determines whether or not the path in filename has a Pocket Edition 0.9.0 or later in it :param filename string with path to level root directory. """ clp = ("db", "level.dat") if not os.path.isdir(filename): f = os.path.basename(filename) if f not in clp: return False filename = os.path.dirname(filename) return all([os.path.exists(os.path.join(filename, fl)) for fl in clp]) def saveInPlaceGen(self): """ Save all chunks to the database, and write the root_tag back to level.dat. """ self.saving = True batch = leveldb_mcpe.WriteBatch() dirtyChunkCount = 0 for chunk in self._loadedChunks.itervalues(): if chunk.dirty: dirtyChunkCount += 1 self.worldFile.saveChunk(chunk, batch=batch) chunk.dirty = False yield with nbt.littleEndianNBT(): for p in self.players: playerData = self.playerTagCache[p] if playerData is not None: playerData = playerData.save(compressed=False) # It will get compressed in the DB itself self.worldFile.savePlayer(p, playerData, batch=batch) with self.worldFile.world_db() as db: wop = self.worldFile.writeOptions db.Write(wop, batch) self.saving = False logger.info(u"Saved {0} chunks to the database".format(dirtyChunkCount)) path = os.path.join(self.worldFile.path, 'level.dat') with nbt.littleEndianNBT(): rootTagData = self.root_tag.save(compressed=False) rootTagData = struct.Struct('<i').pack(4) + struct.Struct('<i').pack(len(rootTagData)) + rootTagData with open(path, 'w') as f: f.write(rootTagData) def containsChunk(self, cx, cz): """ Determines if the chunk exist in this world. :param cx, cz: int, Coordinates of the chunk :return: bool (if chunk exists) """ return (cx, cz) in self.allChunks def createChunk(self, cx, cz): """ Creates an empty chunk at given cx, cz coordinates, and stores it in self._loadedChunks :param cx, cz: int, Coordinates of the chunk :return: """ if self.containsChunk(cx, cz): raise ValueError("{0}:Chunk {1} already present!".format(self, (cx, cz))) if self.allChunks is not None: self.allChunks.append((cx, cz)) self._loadedChunks[(cx, cz)] = PocketLeveldbChunk(cx, cz, self, create=True) self._bounds = None def saveGeneratedChunk(self, cx, cz, tempChunkBytes): """ Chunks get generated using Anvil generation. This is a (slow) way of importing anvil chunk bytes and converting them to MCPE chunk data. Could definitely use some improvements, but at least it works. :param cx, cx: Coordinates of the chunk :param tempChunkBytes: str. Raw MCRegion chunk data. :return: """ loaded_data = nbt.load(buf=tempChunkBytes) class fake: def __init__(self): self.Height = 128 tempChunk = AnvilChunkData(fake(), (0, 0), loaded_data) if not self.containsChunk(cx, cz): self.createChunk(cx, cz) chunk = self.getChunk(cx, cz) chunk.Blocks = numpy.array(tempChunk.Blocks, dtype='uint16') chunk.Data = numpy.array(tempChunk.Data, dtype='uint8') chunk.SkyLight = numpy.array(tempChunk.SkyLight, dtype='uint8') chunk.BlockLight = numpy.array(tempChunk.BlockLight, dtype='uint8') chunk.dirty = True self.worldFile.saveChunk(chunk) else: logger.info("Tried to import generated chunk at %s, %s but the chunk already existed." % cx, cz) @property def chunksNeedingLighting(self): """ Generator containing all chunks that need lighting. :yield: int (cx, cz) Coordinates of the chunk """ for chunk in self._loadedChunks.itervalues(): if chunk.needsLighting: yield chunk.chunkPosition # -- Entity Stuff -- # A lot of this code got copy-pasted from MCInfDevOldLevel # Slight modifications to make it work with MCPE def getTileEntitiesInBox(self, box): """ Returns the Tile Entities in given box. :param box: pymclevel.box.BoundingBox :return: list of nbt.TAG_Compound """ tileEntites = [] for chunk, slices, point in self.getChunkSlices(box): tileEntites += chunk.getTileEntitiesInBox(box) return tileEntites def getEntitiesInBox(self, box): """ Returns the Entities in given box. :param box: pymclevel.box.BoundingBox :return: list of nbt.TAG_Compound """ entities = [] for chunk, slices, point in self.getChunkSlices(box): entities += chunk.getEntitiesInBox(box) return entities def getTileTicksInBox(self, box): """ Always returns None, as MCPE has no TileTicks. :param box: pymclevel.box.BoundingBox :return: list """ return [] def addEntity(self, entityTag): """ Adds an entity to the level. :param entityTag: nbt.TAG_Compound containing the entity's data. :return: """ assert isinstance(entityTag, nbt.TAG_Compound) x, y, z = map(lambda p: int(floor(p)), Entity.pos(entityTag)) try: chunk = self.getChunk(x >> 4, z >> 4) except (ChunkNotPresent, ChunkMalformed): return chunk.addEntity(entityTag) chunk.dirty = True def addTileEntity(self, tileEntityTag): """ Adds an entity to the level. :param tileEntityTag: nbt.TAG_Compound containing the Tile entity's data. :return: """ assert isinstance(tileEntityTag, nbt.TAG_Compound) if 'x' not in tileEntityTag: return x, y, z = TileEntity.pos(tileEntityTag) try: chunk = self.getChunk(x >> 4, z >> 4) except (ChunkNotPresent, ChunkMalformed): return chunk.addTileEntity(tileEntityTag) chunk.dirty = True def addTileTick(self, tickTag): """ MCPE doesn't have Tile Ticks, so this can't be added. :param tickTag: nbt.TAG_Compound :return: None """ return def tileEntityAt(self, x, y, z): """ Retrieves a tile tick at given x, y, z coordinates :param x: int :param y: int :param z: int :return: nbt.TAG_Compound or None """ chunk = self.getChunk(x >> 4, z >> 4) return chunk.tileEntityAt(x, y, z) def removeEntitiesInBox(self, box): """ Removes all entities in given box :param box: pymclevel.box.BoundingBox :return: int, count of entities removed """ count = 0 for chunk, slices, point in self.getChunkSlices(box): count += chunk.removeEntitiesInBox(box) logger.info("Removed {0} entities".format(count)) return count def removeTileEntitiesInBox(self, box): """ Removes all tile entities in given box :param box: pymclevel.box.BoundingBox :return: int, count of tile entities removed """ count = 0 for chunk, slices, point in self.getChunkSlices(box): count += chunk.removeTileEntitiesInBox(box) logger.info("Removed {0} tile entities".format(count)) return count def removeTileTicksInBox(self, box): """ MCPE doesn't have TileTicks, so this does nothing. :param box: pymclevel.box.BoundingBox :return: int, count of TileTicks removed. """ return 0 # -- Player and spawn stuff def playerSpawnPosition(self, player=None): """ Returns the default spawn position for the world. If player is given, the players spawn is returned instead. :param player: nbt.TAG_Compound, root tag of the player. :return: tuple int (x, y, z), coordinates of the spawn. """ dataTag = self.root_tag if player is None: playerSpawnTag = dataTag else: playerSpawnTag = self.getPlayerTag(player) return [playerSpawnTag.get(i, dataTag[i]).value for i in ("SpawnX", "SpawnY", "SpawnZ")] def setPlayerSpawnPosition(self, pos, player=None): """ Sets the worlds spawn point to pos. If player is given, sets that players spawn point instead. :param pos: tuple int (x, y, z) :param player: nbt.TAG_Compound, root tag of the player :return: None """ if player is None: playerSpawnTag = self.root_tag else: playerSpawnTag = self.getPlayerTag(player) for name, val in zip(("SpawnX", "SpawnY", "SpawnZ"), pos): playerSpawnTag[name] = nbt.TAG_Int(val) def getPlayerTag(self, player='Player'): """ Obtains a player from the world. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: nbt.TAG_Compound, root tag of the player. """ if player == '[No players]': # Apparently this is being called somewhere? return None if player == 'Player': player = '~local_player' _player = self.playerTagCache.get(player) if _player is not None: return _player playerData = self.playerData[player] with nbt.littleEndianNBT(): _player = nbt.load(buf=playerData) self.playerTagCache[player] = _player return _player def getPlayerDimension(self, player="Player"): """ Always returns 0, as MCPE only has the overworld dimension. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: int """ return 0 def setPlayerPosition(self, (x, y, z), player="Player"): """ Sets the players position to x, y, z :param (x, y, z): tuple of the coordinates of the player :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: """ posList = nbt.TAG_List([nbt.TAG_Double(p) for p in (x, y - 1.75, z)]) playerTag = self.getPlayerTag(player) playerTag["Pos"] = posList def getPlayerPosition(self, player="Player"): """ Gets the players position :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: tuple int (x, y, z): Coordinates of the player. """ playerTag = self.getPlayerTag(player) posList = playerTag["Pos"] x, y, z = map(lambda c: c.value, posList) return x, y + 1.75, z def setPlayerOrientation(self, yp, player="Player"): """ Gets the players orientation. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :param yp: int tuple (yaw, pitch) :return: None """ self.getPlayerTag(player)["Rotation"] = nbt.TAG_List([nbt.TAG_Float(p) for p in yp]) def getPlayerOrientation(self, player="Player"): """ Gets the players orientation. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: tuple int (yaw, pitch) """ yp = map(lambda x: x.value, self.getPlayerTag(player)["Rotation"]) y, p = yp if p == 0: p = 0.000000001 if p == 180.0: p -= 0.000000001 yp = y, p return numpy.array(yp) @staticmethod # Editor keeps putting this in. Probably unnecesary def setPlayerAbilities(gametype, player="Player"): """ This method is just to override the standard one, as MCPE has no abilities, as it seems. :parm gametype, int of gamemode player gets set at. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. """ pass def setPlayerGameType(self, gametype, player="Player"): """ Sets the game type for player :param gametype: int (0=survival, 1=creative, 2=adventure, 3=spectator) :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: None """ # This annoyingly works differently between single- and multi-player. if player == "Player": self.GameType = gametype self.setPlayerAbilities(gametype, player) else: playerTag = self.getPlayerTag(player) playerTag['playerGameType'] = nbt.TAG_Int(gametype) self.setPlayerAbilities(gametype, player) def getPlayerGameType(self, player="Player"): """ Obtains the players gametype. :param player: string of the name of the player. "Player" for SSP player, player_<client-id> for SMP player. :return: int (0=survival, 1=creative, 2=adventure, 3=spectator) """ if player == "Player": return self.GameType else: playerTag = self.getPlayerTag(player) return playerTag["playerGameType"].value class PocketLeveldbChunk(LightedChunk): HeightMap = FakeChunk.HeightMap # _Entities = _TileEntities = nbt.TAG_List() _Entities = nbt.TAG_List() _TileEntities = nbt.TAG_List() dirty = False def __init__(self, cx, cz, world, data=None, create=False): """ :param cx, cz int, int Coordinates of the chunk :param data List of 3 strings. (83200 bytes of terrain data, tile-entity data, entity data) :param world PocketLeveldbWorld, instance of the world the chunk belongs too """ self.chunkPosition = (cx, cz) self.world = world if create: self.Blocks = numpy.zeros(32768, 'uint16') self.Data = numpy.zeros(16384, 'uint8') self.SkyLight = numpy.zeros(16384, 'uint8') self.BlockLight = numpy.zeros(16384, 'uint8') self.DirtyColumns = numpy.zeros(256, 'uint8') self.GrassColors = numpy.zeros(1024, 'uint8') self.TileEntities = nbt.TAG_List() self.Entities = nbt.TAG_List() else: terrain = numpy.fromstring(data[0], dtype='uint8') if data[1] is not None: TileEntities = loadNBTCompoundList(data[1]) self.TileEntities = nbt.TAG_List(TileEntities, list_type=nbt.TAG_COMPOUND) if data[2] is not None: Entities = loadNBTCompoundList(data[2]) # PE saves entities with their int ID instead of string name. We swap them to make it work in mcedit. # Whenever we save an entity, we need to make sure to swap back. invertEntities = {v: k for k, v in entity.PocketEntity.entityList.items()} for ent in Entities: ent["id"] = nbt.TAG_String(invertEntities[ent["id"].value]) self.Entities = nbt.TAG_List(Entities, list_type=nbt.TAG_COMPOUND) self.Blocks, terrain = terrain[:32768], terrain[32768:] self.Data, terrain = terrain[:16384], terrain[16384:] self.SkyLight, terrain = terrain[:16384], terrain[16384:] self.BlockLight, terrain = terrain[:16384], terrain[16384:] self.DirtyColumns, terrain = terrain[:256], terrain[256:] # Unused at the moment. Might need a special editor? Maybe hooked up to biomes? self.GrassColors = terrain[:1024] self.unpackChunkData() self.shapeChunkData() def unpackChunkData(self): """ Unpacks the terrain data to match mcedit's formatting. """ for key in ('SkyLight', 'BlockLight', 'Data'): dataArray = getattr(self, key) dataArray.shape = (16, 16, 64) s = dataArray.shape unpackedData = numpy.zeros((s[0], s[1], s[2] * 2), dtype='uint8') unpackedData[:, :, ::2] = dataArray unpackedData[:, :, ::2] &= 0xf unpackedData[:, :, 1::2] = dataArray unpackedData[:, :, 1::2] >>= 4 setattr(self, key, unpackedData) def shapeChunkData(self): """ Determines the shape of the terrain data. :return: """ chunkSize = 16 self.Blocks.shape = (chunkSize, chunkSize, self.world.Height) self.SkyLight.shape = (chunkSize, chunkSize, self.world.Height) self.BlockLight.shape = (chunkSize, chunkSize, self.world.Height) self.Data.shape = (chunkSize, chunkSize, self.world.Height) self.DirtyColumns.shape = chunkSize, chunkSize def savedData(self): """ Returns the data of the chunk to save to the database. :return: str of 83200 bytes of chunk data. """ def packData(dataArray): """ Repacks the terrain data to Mojang's leveldb library's format. """ assert dataArray.shape[2] == self.world.Height data = numpy.array(dataArray).reshape(16, 16, self.world.Height / 2, 2) data[..., 1] <<= 4 data[..., 1] |= data[..., 0] return numpy.array(data[:, :, :, 1]) if self.dirty: # elements of DirtyColumns are bitfields. Each bit corresponds to a # 16-block segment of the column. We set all of the bits because # we only track modifications at the chunk level. self.DirtyColumns[:] = 255 with nbt.littleEndianNBT(): entityData = "" tileEntityData = "" for ent in self.TileEntities: tileEntityData += ent.save(compressed=False) for ent in self.Entities: v = ent["id"].value ent["id"] = nbt.TAG_Int(entity.PocketEntity.entityList[v]) entityData += ent.save(compressed=False) # We have to re-invert after saving otherwise the next save will fail. ent["id"] = nbt.TAG_String(v) terrain = ''.join([self.Blocks.tostring(), packData(self.Data).tostring(), packData(self.SkyLight).tostring(), packData(self.BlockLight).tostring(), self.DirtyColumns.tostring(), self.GrassColors.tostring(), ]) return terrain, tileEntityData, entityData # -- Entities and TileEntities @property def Entities(self): return self._Entities @Entities.setter def Entities(self, Entities): """ :param Entities: list :return: """ self._Entities = Entities @property def TileEntities(self): return self._TileEntities @TileEntities.setter def TileEntities(self, TileEntities): """ :param TileEntities: list :return: """ self._TileEntities = TileEntities
isc
pravic/pysciter
examples/handlers.py
1
3868
"""Sciter handlers sample (Go examples port).""" import sciter class RootEventHandler(sciter.EventHandler): def __init__(self, el, frame): super().__init__(element=el) self.parent = frame pass def on_event(self, source, target, code, phase, reason): he = sciter.Element(source) #print("-> event:", code, phase, he) pass @sciter.script("mcall") def method_call(self, *args): # # `root.mcall()` (see handlers.htm) calls behavior method of the root dom element (native equivalent is `Element.call_method()`), # so we need to attach a "behavior" to that element to catch and handle such calls. # Also it can be handled at script by several ways: # * `behavior` - Element subclassing with full control # * `aspect` - provides partial handling by attaching a single function to the dom element # * manually attaching function to Element via code like `root.mcall = function(args..) {};` # print("->mcall args:", "\t".join(map(str, args))) # explicit null for example, in other cases you can return any python object like None or True return sciter.Value.null() pass class Frame(sciter.Window): def __init__(self): super().__init__(ismain=True, uni_theme=False, debug=False) self.set_dispatch_options(enable=True, require_attribute=False) pass def test_call(self): # test sciter call v = self.call_function('gFunc', "kkk", 555) print("sciter call successfully:", v) # test method call root = self.get_root() v = root.call_method('mfn', "method call", 10300) print("method call successfully:", v) # test function call v = root.call_function('gFunc', "function call", 10300) print("function call successfully:", v) pass # Functions called from script: #@sciter.script - optional attribute here because of self.set_dispatch_options() def kkk(self): print("kkk called!") def fn(*args): print("%d: %s" % ( len(args), ",".join(map(str, args)) )) return "native functor called" rv = {} rv['num'] = 1000 rv['str'] = "a string" rv['f'] = fn return rv @sciter.script def sumall(self, *args): sum = 0 for v in args: sum += v return sum @sciter.script("gprintln") def gprint(self, *args): print("->", " ".join(map(str, args))) pass def on_load_data(self, nm): print("loading", nm.uri) pass def on_data_loaded(self, nm): print("loaded ", nm.uri) pass def on_event(self, source, target, code, phase, reason): # events from html controls (behaviors) he = sciter.Element(source) #print(".. event:", code, phase) # TODO: following statement looks ugly. # Guess it wasn't a nice idea to split event mask to separate code and phase values # Or we may pack all event arguments to single object (dict) to eliminate such parameters bloat # if code == sciter.event.BEHAVIOR_EVENTS.BUTTON_CLICK and phase == sciter.event.PHASE_MASK.SINKING and he.test('#native'): print("native button clicked!") return True pass pass if __name__ == "__main__": print("Sciter version:", sciter.version(as_str=True)) # create window frame = Frame() # enable debug only for this window frame.setup_debug() # load file frame.load_file("examples/handlers.htm") #frame.load_html(b"""<html><body><button id='native'>Click</button></body></html>""") # install additional handler ev2 = RootEventHandler(frame.get_root(), frame) frame.test_call() frame.run_app()
mit
azurestandard/django
tests/regressiontests/bash_completion/tests.py
16
3195
""" A series of tests to establish that the command-line bash completion works. """ import os import sys import StringIO from django.conf import settings from django.core.management import ManagementUtility from django.utils import unittest class BashCompletionTests(unittest.TestCase): """ Testing the Python level bash completion code. This requires setting up the environment as if we got passed data from bash. """ def setUp(self): self.old_DJANGO_AUTO_COMPLETE = os.environ.get('DJANGO_AUTO_COMPLETE') os.environ['DJANGO_AUTO_COMPLETE'] = '1' self.output = StringIO.StringIO() self.old_stdout = sys.stdout sys.stdout = self.output def tearDown(self): sys.stdout = self.old_stdout if self.old_DJANGO_AUTO_COMPLETE: os.environ['DJANGO_AUTO_COMPLETE'] = self.old_DJANGO_AUTO_COMPLETE else: del os.environ['DJANGO_AUTO_COMPLETE'] def _user_input(self, input_str): os.environ['COMP_WORDS'] = input_str os.environ['COMP_CWORD'] = str(len(input_str.split()) - 1) sys.argv = input_str.split(' ') def _run_autocomplete(self): util = ManagementUtility(argv=sys.argv) try: util.autocomplete() except SystemExit: pass return self.output.getvalue().strip().split('\n') def test_django_admin_py(self): "django_admin.py will autocomplete option flags" self._user_input('django-admin.py sqlall --v') output = self._run_autocomplete() self.assertEqual(output, ['--verbosity=']) def test_manage_py(self): "manage.py will autocomplete option flags" self._user_input('manage.py sqlall --v') output = self._run_autocomplete() self.assertEqual(output, ['--verbosity=']) def test_custom_command(self): "A custom command can autocomplete option flags" self._user_input('django-admin.py test_command --l') output = self._run_autocomplete() self.assertEqual(output, ['--list']) def test_subcommands(self): "Subcommands can be autocompleted" self._user_input('django-admin.py sql') output = self._run_autocomplete() self.assertEqual(output, ['sql sqlall sqlclear sqlcustom sqlflush sqlindexes sqlinitialdata sqlsequencereset']) def test_help(self): "No errors, just an empty list if there are no autocomplete options" self._user_input('django-admin.py help --') output = self._run_autocomplete() self.assertEqual(output, ['']) def test_runfcgi(self): "Command arguments will be autocompleted" self._user_input('django-admin.py runfcgi h') output = self._run_autocomplete() self.assertEqual(output, ['host=']) def test_app_completion(self): "Application names will be autocompleted for an AppCommand" self._user_input('django-admin.py sqlall a') output = self._run_autocomplete() app_labels = [name.split('.')[-1] for name in settings.INSTALLED_APPS] self.assertEqual(output, sorted(label for label in app_labels if label.startswith('a')))
bsd-3-clause
CUFCTL/DLBD
face-detection-code/object_detection/core/keypoint_ops.py
6
11240
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Keypoint operations. Keypoints are represented as tensors of shape [num_instances, num_keypoints, 2], where the last dimension holds rank 2 tensors of the form [y, x] representing the coordinates of the keypoint. """ import numpy as np import tensorflow as tf def scale(keypoints, y_scale, x_scale, scope=None): """Scales keypoint coordinates in x and y dimensions. Args: keypoints: a tensor of shape [num_instances, num_keypoints, 2] y_scale: (float) scalar tensor x_scale: (float) scalar tensor scope: name scope. Returns: new_keypoints: a tensor of shape [num_instances, num_keypoints, 2] """ with tf.name_scope(scope, 'Scale'): y_scale = tf.cast(y_scale, tf.float32) x_scale = tf.cast(x_scale, tf.float32) new_keypoints = keypoints * [[[y_scale, x_scale]]] return new_keypoints def clip_to_window(keypoints, window, scope=None): """Clips keypoints to a window. This op clips any input keypoints to a window. Args: keypoints: a tensor of shape [num_instances, num_keypoints, 2] window: a tensor of shape [4] representing the [y_min, x_min, y_max, x_max] window to which the op should clip the keypoints. scope: name scope. Returns: new_keypoints: a tensor of shape [num_instances, num_keypoints, 2] """ with tf.name_scope(scope, 'ClipToWindow'): y, x = tf.split(value=keypoints, num_or_size_splits=2, axis=2) win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window) y = tf.maximum(tf.minimum(y, win_y_max), win_y_min) x = tf.maximum(tf.minimum(x, win_x_max), win_x_min) new_keypoints = tf.concat([y, x], 2) return new_keypoints def prune_outside_window(keypoints, window, scope=None): """Prunes keypoints that fall outside a given window. This function replaces keypoints that fall outside the given window with nan. See also clip_to_window which clips any keypoints that fall outside the given window. Args: keypoints: a tensor of shape [num_instances, num_keypoints, 2] window: a tensor of shape [4] representing the [y_min, x_min, y_max, x_max] window outside of which the op should prune the keypoints. scope: name scope. Returns: new_keypoints: a tensor of shape [num_instances, num_keypoints, 2] """ with tf.name_scope(scope, 'PruneOutsideWindow'): y, x = tf.split(value=keypoints, num_or_size_splits=2, axis=2) win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window) valid_indices = tf.logical_and( tf.logical_and(y >= win_y_min, y <= win_y_max), tf.logical_and(x >= win_x_min, x <= win_x_max)) new_y = tf.where(valid_indices, y, np.nan * tf.ones_like(y)) new_x = tf.where(valid_indices, x, np.nan * tf.ones_like(x)) new_keypoints = tf.concat([new_y, new_x], 2) return new_keypoints def change_coordinate_frame(keypoints, window, scope=None): """Changes coordinate frame of the keypoints to be relative to window's frame. Given a window of the form [y_min, x_min, y_max, x_max], changes keypoint coordinates from keypoints of shape [num_instances, num_keypoints, 2] to be relative to this window. An example use case is data augmentation: where we are given groundtruth keypoints and would like to randomly crop the image to some window. In this case we need to change the coordinate frame of each groundtruth keypoint to be relative to this new window. Args: keypoints: a tensor of shape [num_instances, num_keypoints, 2] window: a tensor of shape [4] representing the [y_min, x_min, y_max, x_max] window we should change the coordinate frame to. scope: name scope. Returns: new_keypoints: a tensor of shape [num_instances, num_keypoints, 2] """ with tf.name_scope(scope, 'ChangeCoordinateFrame'): win_height = window[2] - window[0] win_width = window[3] - window[1] new_keypoints = scale(keypoints - [window[0], window[1]], 1.0 / win_height, 1.0 / win_width) return new_keypoints def to_normalized_coordinates(keypoints, height, width, check_range=True, scope=None): """Converts absolute keypoint coordinates to normalized coordinates in [0, 1]. Usually one uses the dynamic shape of the image or conv-layer tensor: keypoints = keypoint_ops.to_normalized_coordinates(keypoints, tf.shape(images)[1], tf.shape(images)[2]), This function raises an assertion failed error at graph execution time when the maximum coordinate is smaller than 1.01 (which means that coordinates are already normalized). The value 1.01 is to deal with small rounding errors. Args: keypoints: A tensor of shape [num_instances, num_keypoints, 2]. height: Maximum value for y coordinate of absolute keypoint coordinates. width: Maximum value for x coordinate of absolute keypoint coordinates. check_range: If True, checks if the coordinates are normalized. scope: name scope. Returns: tensor of shape [num_instances, num_keypoints, 2] with normalized coordinates in [0, 1]. """ with tf.name_scope(scope, 'ToNormalizedCoordinates'): height = tf.cast(height, tf.float32) width = tf.cast(width, tf.float32) if check_range: max_val = tf.reduce_max(keypoints) max_assert = tf.Assert(tf.greater(max_val, 1.01), ['max value is lower than 1.01: ', max_val]) with tf.control_dependencies([max_assert]): width = tf.identity(width) return scale(keypoints, 1.0 / height, 1.0 / width) def to_absolute_coordinates(keypoints, height, width, check_range=True, scope=None): """Converts normalized keypoint coordinates to absolute pixel coordinates. This function raises an assertion failed error when the maximum keypoint coordinate value is larger than 1.01 (in which case coordinates are already absolute). Args: keypoints: A tensor of shape [num_instances, num_keypoints, 2] height: Maximum value for y coordinate of absolute keypoint coordinates. width: Maximum value for x coordinate of absolute keypoint coordinates. check_range: If True, checks if the coordinates are normalized or not. scope: name scope. Returns: tensor of shape [num_instances, num_keypoints, 2] with absolute coordinates in terms of the image size. """ with tf.name_scope(scope, 'ToAbsoluteCoordinates'): height = tf.cast(height, tf.float32) width = tf.cast(width, tf.float32) # Ensure range of input keypoints is correct. if check_range: max_val = tf.reduce_max(keypoints) max_assert = tf.Assert(tf.greater_equal(1.01, max_val), ['maximum keypoint coordinate value is larger ' 'than 1.01: ', max_val]) with tf.control_dependencies([max_assert]): width = tf.identity(width) return scale(keypoints, height, width) def flip_horizontal(keypoints, flip_point, flip_permutation, scope=None): """Flips the keypoints horizontally around the flip_point. This operation flips the x coordinate for each keypoint around the flip_point and also permutes the keypoints in a manner specified by flip_permutation. Args: keypoints: a tensor of shape [num_instances, num_keypoints, 2] flip_point: (float) scalar tensor representing the x coordinate to flip the keypoints around. flip_permutation: rank 1 int32 tensor containing the keypoint flip permutation. This specifies the mapping from original keypoint indices to the flipped keypoint indices. This is used primarily for keypoints that are not reflection invariant. E.g. Suppose there are 3 keypoints representing ['head', 'right_eye', 'left_eye'], then a logical choice for flip_permutation might be [0, 2, 1] since we want to swap the 'left_eye' and 'right_eye' after a horizontal flip. scope: name scope. Returns: new_keypoints: a tensor of shape [num_instances, num_keypoints, 2] """ with tf.name_scope(scope, 'FlipHorizontal'): keypoints = tf.transpose(keypoints, [1, 0, 2]) keypoints = tf.gather(keypoints, flip_permutation) v, u = tf.split(value=keypoints, num_or_size_splits=2, axis=2) u = flip_point * 2.0 - u new_keypoints = tf.concat([v, u], 2) new_keypoints = tf.transpose(new_keypoints, [1, 0, 2]) return new_keypoints def flip_vertical(keypoints, flip_point, flip_permutation, scope=None): """Flips the keypoints vertically around the flip_point. This operation flips the y coordinate for each keypoint around the flip_point and also permutes the keypoints in a manner specified by flip_permutation. Args: keypoints: a tensor of shape [num_instances, num_keypoints, 2] flip_point: (float) scalar tensor representing the y coordinate to flip the keypoints around. flip_permutation: rank 1 int32 tensor containing the keypoint flip permutation. This specifies the mapping from original keypoint indices to the flipped keypoint indices. This is used primarily for keypoints that are not reflection invariant. E.g. Suppose there are 3 keypoints representing ['head', 'right_eye', 'left_eye'], then a logical choice for flip_permutation might be [0, 2, 1] since we want to swap the 'left_eye' and 'right_eye' after a horizontal flip. scope: name scope. Returns: new_keypoints: a tensor of shape [num_instances, num_keypoints, 2] """ with tf.name_scope(scope, 'FlipVertical'): keypoints = tf.transpose(keypoints, [1, 0, 2]) keypoints = tf.gather(keypoints, flip_permutation) v, u = tf.split(value=keypoints, num_or_size_splits=2, axis=2) v = flip_point * 2.0 - v new_keypoints = tf.concat([v, u], 2) new_keypoints = tf.transpose(new_keypoints, [1, 0, 2]) return new_keypoints def rot90(keypoints, scope=None): """Rotates the keypoints counter-clockwise by 90 degrees. Args: keypoints: a tensor of shape [num_instances, num_keypoints, 2] scope: name scope. Returns: new_keypoints: a tensor of shape [num_instances, num_keypoints, 2] """ with tf.name_scope(scope, 'Rot90'): keypoints = tf.transpose(keypoints, [1, 0, 2]) v, u = tf.split(value=keypoints[:, :, ::-1], num_or_size_splits=2, axis=2) v = 1.0 - v new_keypoints = tf.concat([v, u], 2) new_keypoints = tf.transpose(new_keypoints, [1, 0, 2]) return new_keypoints
mit
grlee77/nipype
nipype/interfaces/afni/tests/test_auto_Despike.py
9
1114
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from nipype.testing import assert_equal from nipype.interfaces.afni.preprocess import Despike def test_Despike_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), in_file=dict(argstr='%s', copyfile=False, mandatory=True, position=-1, ), out_file=dict(argstr='-prefix %s', name_source='in_file', name_template='%s_despike', ), outputtype=dict(), terminal_output=dict(nohash=True, ), ) inputs = Despike.input_spec() for key, metadata in input_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_Despike_outputs(): output_map = dict(out_file=dict(), ) outputs = Despike.output_spec() for key, metadata in output_map.items(): for metakey, value in metadata.items(): yield assert_equal, getattr(outputs.traits()[key], metakey), value
bsd-3-clause
israeltobias/DownMedia
youtube-dl/youtube_dl/extractor/ard.py
26
11725
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from .generic import GenericIE from ..utils import ( determine_ext, ExtractorError, qualities, int_or_none, parse_duration, unified_strdate, xpath_text, update_url_query, ) from ..compat import compat_etree_fromstring class ARDMediathekIE(InfoExtractor): IE_NAME = 'ARD:mediathek' _VALID_URL = r'^https?://(?:(?:www\.)?ardmediathek\.de|mediathek\.(?:daserste|rbb-online)\.de)/(?:.*/)(?P<video_id>[0-9]+|[^0-9][^/\?]+)[^/\?]*(?:\?.*)?' _TESTS = [{ 'url': 'http://www.ardmediathek.de/tv/Dokumentation-und-Reportage/Ich-liebe-das-Leben-trotzdem/rbb-Fernsehen/Video?documentId=29582122&bcastId=3822114', 'info_dict': { 'id': '29582122', 'ext': 'mp4', 'title': 'Ich liebe das Leben trotzdem', 'description': 'md5:45e4c225c72b27993314b31a84a5261c', 'duration': 4557, }, 'params': { # m3u8 download 'skip_download': True, }, 'skip': 'HTTP Error 404: Not Found', }, { 'url': 'http://www.ardmediathek.de/tv/Tatort/Tatort-Scheinwelten-H%C3%B6rfassung-Video/Das-Erste/Video?documentId=29522730&bcastId=602916', 'md5': 'f4d98b10759ac06c0072bbcd1f0b9e3e', 'info_dict': { 'id': '29522730', 'ext': 'mp4', 'title': 'Tatort: Scheinwelten - Hörfassung (Video tgl. ab 20 Uhr)', 'description': 'md5:196392e79876d0ac94c94e8cdb2875f1', 'duration': 5252, }, 'skip': 'HTTP Error 404: Not Found', }, { # audio 'url': 'http://www.ardmediathek.de/tv/WDR-H%C3%B6rspiel-Speicher/Tod-eines-Fu%C3%9Fballers/WDR-3/Audio-Podcast?documentId=28488308&bcastId=23074086', 'md5': '219d94d8980b4f538c7fcb0865eb7f2c', 'info_dict': { 'id': '28488308', 'ext': 'mp3', 'title': 'Tod eines Fußballers', 'description': 'md5:f6e39f3461f0e1f54bfa48c8875c86ef', 'duration': 3240, }, 'skip': 'HTTP Error 404: Not Found', }, { 'url': 'http://mediathek.daserste.de/sendungen_a-z/328454_anne-will/22429276_vertrauen-ist-gut-spionieren-ist-besser-geht', 'only_matching': True, }, { # audio 'url': 'http://mediathek.rbb-online.de/radio/Hörspiel/Vor-dem-Fest/kulturradio/Audio?documentId=30796318&topRessort=radio&bcastId=9839158', 'md5': '4e8f00631aac0395fee17368ac0e9867', 'info_dict': { 'id': '30796318', 'ext': 'mp3', 'title': 'Vor dem Fest', 'description': 'md5:c0c1c8048514deaed2a73b3a60eecacb', 'duration': 3287, }, 'skip': 'Video is no longer available', }] def _extract_media_info(self, media_info_url, webpage, video_id): media_info = self._download_json( media_info_url, video_id, 'Downloading media JSON') formats = self._extract_formats(media_info, video_id) if not formats: if '"fsk"' in webpage: raise ExtractorError( 'This video is only available after 20:00', expected=True) elif media_info.get('_geoblocked'): raise ExtractorError('This video is not available due to geo restriction', expected=True) self._sort_formats(formats) duration = int_or_none(media_info.get('_duration')) thumbnail = media_info.get('_previewImage') subtitles = {} subtitle_url = media_info.get('_subtitleUrl') if subtitle_url: subtitles['de'] = [{ 'ext': 'ttml', 'url': subtitle_url, }] return { 'id': video_id, 'duration': duration, 'thumbnail': thumbnail, 'formats': formats, 'subtitles': subtitles, } def _extract_formats(self, media_info, video_id): type_ = media_info.get('_type') media_array = media_info.get('_mediaArray', []) formats = [] for num, media in enumerate(media_array): for stream in media.get('_mediaStreamArray', []): stream_urls = stream.get('_stream') if not stream_urls: continue if not isinstance(stream_urls, list): stream_urls = [stream_urls] quality = stream.get('_quality') server = stream.get('_server') for stream_url in stream_urls: ext = determine_ext(stream_url) if quality != 'auto' and ext in ('f4m', 'm3u8'): continue if ext == 'f4m': formats.extend(self._extract_f4m_formats( update_url_query(stream_url, { 'hdcore': '3.1.1', 'plugin': 'aasp-3.1.1.69.124' }), video_id, f4m_id='hds', fatal=False)) elif ext == 'm3u8': formats.extend(self._extract_m3u8_formats( stream_url, video_id, 'mp4', m3u8_id='hls', fatal=False)) else: if server and server.startswith('rtmp'): f = { 'url': server, 'play_path': stream_url, 'format_id': 'a%s-rtmp-%s' % (num, quality), } elif stream_url.startswith('http'): f = { 'url': stream_url, 'format_id': 'a%s-%s-%s' % (num, ext, quality) } else: continue m = re.search(r'_(?P<width>\d+)x(?P<height>\d+)\.mp4$', stream_url) if m: f.update({ 'width': int(m.group('width')), 'height': int(m.group('height')), }) if type_ == 'audio': f['vcodec'] = 'none' formats.append(f) return formats def _real_extract(self, url): # determine video id from url m = re.match(self._VALID_URL, url) numid = re.search(r'documentId=([0-9]+)', url) if numid: video_id = numid.group(1) else: video_id = m.group('video_id') webpage = self._download_webpage(url, video_id) ERRORS = ( ('>Leider liegt eine Störung vor.', 'Video %s is unavailable'), ('>Der gewünschte Beitrag ist nicht mehr verfügbar.<', 'Video %s is no longer available'), ) for pattern, message in ERRORS: if pattern in webpage: raise ExtractorError(message % video_id, expected=True) if re.search(r'[\?&]rss($|[=&])', url): doc = compat_etree_fromstring(webpage.encode('utf-8')) if doc.tag == 'rss': return GenericIE()._extract_rss(url, video_id, doc) title = self._html_search_regex( [r'<h1(?:\s+class="boxTopHeadline")?>(.*?)</h1>', r'<meta name="dcterms.title" content="(.*?)"/>', r'<h4 class="headline">(.*?)</h4>'], webpage, 'title') description = self._html_search_meta( 'dcterms.abstract', webpage, 'description', default=None) if description is None: description = self._html_search_meta( 'description', webpage, 'meta description') # Thumbnail is sometimes not present. # It is in the mobile version, but that seems to use a different URL # structure altogether. thumbnail = self._og_search_thumbnail(webpage, default=None) media_streams = re.findall(r'''(?x) mediaCollection\.addMediaStream\([0-9]+,\s*[0-9]+,\s*"[^"]*",\s* "([^"]+)"''', webpage) if media_streams: QUALITIES = qualities(['lo', 'hi', 'hq']) formats = [] for furl in set(media_streams): if furl.endswith('.f4m'): fid = 'f4m' else: fid_m = re.match(r'.*\.([^.]+)\.[^.]+$', furl) fid = fid_m.group(1) if fid_m else None formats.append({ 'quality': QUALITIES(fid), 'format_id': fid, 'url': furl, }) self._sort_formats(formats) info = { 'formats': formats, } else: # request JSON file info = self._extract_media_info( 'http://www.ardmediathek.de/play/media/%s' % video_id, webpage, video_id) info.update({ 'id': video_id, 'title': title, 'description': description, 'thumbnail': thumbnail, }) return info class ARDIE(InfoExtractor): _VALID_URL = r'(?P<mainurl>https?://(www\.)?daserste\.de/[^?#]+/videos/(?P<display_id>[^/?#]+)-(?P<id>[0-9]+))\.html' _TEST = { 'url': 'http://www.daserste.de/information/reportage-dokumentation/dokus/videos/die-story-im-ersten-mission-unter-falscher-flagge-100.html', 'md5': 'd216c3a86493f9322545e045ddc3eb35', 'info_dict': { 'display_id': 'die-story-im-ersten-mission-unter-falscher-flagge', 'id': '100', 'ext': 'mp4', 'duration': 2600, 'title': 'Die Story im Ersten: Mission unter falscher Flagge', 'upload_date': '20140804', 'thumbnail': r're:^https?://.*\.jpg$', }, 'skip': 'HTTP Error 404: Not Found', } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) display_id = mobj.group('display_id') player_url = mobj.group('mainurl') + '~playerXml.xml' doc = self._download_xml(player_url, display_id) video_node = doc.find('./video') upload_date = unified_strdate(xpath_text( video_node, './broadcastDate')) thumbnail = xpath_text(video_node, './/teaserImage//variant/url') formats = [] for a in video_node.findall('.//asset'): f = { 'format_id': a.attrib['type'], 'width': int_or_none(a.find('./frameWidth').text), 'height': int_or_none(a.find('./frameHeight').text), 'vbr': int_or_none(a.find('./bitrateVideo').text), 'abr': int_or_none(a.find('./bitrateAudio').text), 'vcodec': a.find('./codecVideo').text, 'tbr': int_or_none(a.find('./totalBitrate').text), } if a.find('./serverPrefix').text: f['url'] = a.find('./serverPrefix').text f['playpath'] = a.find('./fileName').text else: f['url'] = a.find('./fileName').text formats.append(f) self._sort_formats(formats) return { 'id': mobj.group('id'), 'formats': formats, 'display_id': display_id, 'title': video_node.find('./title').text, 'duration': parse_duration(video_node.find('./duration').text), 'upload_date': upload_date, 'thumbnail': thumbnail, }
gpl-3.0
markeTIC/OCB
addons/account/wizard/account_vat.py
378
2896
# -*- 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 class account_vat_declaration(osv.osv_memory): _name = 'account.vat.declaration' _description = 'Account Vat Declaration' _inherit = "account.common.report" _columns = { 'based_on': fields.selection([('invoices', 'Invoices'), ('payments', 'Payments'),], 'Based on', required=True), 'chart_tax_id': fields.many2one('account.tax.code', 'Chart of Tax', help='Select Charts of Taxes', required=True, domain = [('parent_id','=', False)]), 'display_detail': fields.boolean('Display Detail'), } def _get_tax(self, cr, uid, context=None): user = self.pool.get('res.users').browse(cr, uid, uid, context=context) taxes = self.pool.get('account.tax.code').search(cr, uid, [('parent_id', '=', False), ('company_id', '=', user.company_id.id)], limit=1) return taxes and taxes[0] or False _defaults = { 'based_on': 'invoices', 'chart_tax_id': _get_tax } def create_vat(self, cr, uid, ids, context=None): if context is None: context = {} datas = {'ids': context.get('active_ids', [])} datas['model'] = 'account.tax.code' datas['form'] = self.read(cr, uid, ids, context=context)[0] for field in datas['form'].keys(): if isinstance(datas['form'][field], tuple): datas['form'][field] = datas['form'][field][0] taxcode_obj = self.pool.get('account.tax.code') taxcode_id = datas['form']['chart_tax_id'] taxcode = taxcode_obj.browse(cr, uid, [taxcode_id], context=context)[0] datas['form']['company_id'] = taxcode.company_id.id return self.pool['report'].get_action(cr, uid, [], 'account.report_vat', data=datas, context=context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
henryiii/plumbum
plumbum/machines/session.py
4
9381
import time import random import logging import threading from plumbum.commands import BaseCommand, run_proc from plumbum.lib import six class ShellSessionError(Exception): """Raises when something goes wrong when calling :func:`ShellSession.popen <plumbum.session.ShellSession.popen>`""" pass class SSHCommsError(EOFError): """Raises when the communication channel can't be created on the remote host or it times out.""" class SSHCommsChannel2Error(SSHCommsError): """Raises when channel 2 (stderr) is not available""" shell_logger = logging.getLogger("plumbum.shell") #=================================================================================================== # Shell Session Popen #=================================================================================================== class MarkedPipe(object): """A pipe-like object from which you can read lines; the pipe will return report EOF (the empty string) when a special marker is detected""" __slots__ = ["pipe", "marker"] def __init__(self, pipe, marker): self.pipe = pipe self.marker = marker if six.PY3: self.marker = six.bytes(self.marker, "ascii") def close(self): """'Closes' the marked pipe; following calls to ``readline`` will return """"" # consume everything while self.readline(): pass self.pipe = None def readline(self): """Reads the next line from the pipe; returns "" when the special marker is reached. Raises ``EOFError`` if the underlying pipe has closed""" if self.pipe is None: return six.b("") line = self.pipe.readline() if not line: raise EOFError() if line.strip() == self.marker: self.pipe = None line = six.b("") return line class SessionPopen(object): """A shell-session-based ``Popen``-like object (has the following attributes: ``stdin``, ``stdout``, ``stderr``, ``returncode``)""" def __init__(self, argv, isatty, stdin, stdout, stderr, encoding): self.argv = argv self.isatty = isatty self.stdin = stdin self.stdout = stdout self.stderr = stderr self.encoding = encoding self.returncode = None self._done = False def poll(self): """Returns the process' exit code or ``None`` if it's still running""" if self._done: return self.returncode else: return None def wait(self): """Waits for the process to terminate and returns its exit code""" self.communicate() return self.returncode def communicate(self, input = None): """Consumes the process' stdout and stderr until the it terminates. :param input: An optional bytes/buffer object to send to the process over stdin :returns: A tuple of (stdout, stderr) """ stdout = [] stderr = [] sources = [("1", stdout, self.stdout)] if not self.isatty: # in tty mode, stdout and stderr are unified sources.append(("2", stderr, self.stderr)) i = 0 while sources: if input: chunk = input[:1000] self.stdin.write(chunk) self.stdin.flush() input = input[1000:] i = (i + 1) % len(sources) name, coll, pipe = sources[i] try: line = pipe.readline() shell_logger.debug("%s> %r", name, line) except EOFError: shell_logger.debug("%s> Nothing returned.", name) msg = "No communication channel detected. Does the remote exist?" msgerr = "No stderr result detected. Does the remote have Bash as the default shell?" raise SSHCommsChannel2Error(msgerr) if name=="2" else SSHCommsError(msg) if not line: del sources[i] else: coll.append(line) if self.isatty: stdout.pop(0) # discard first line of prompt try: self.returncode = int(stdout.pop(-1)) except (IndexError, ValueError): self.returncode = "Unknown" self._done = True stdout = six.b("").join(stdout) stderr = six.b("").join(stderr) return stdout, stderr class ShellSession(object): """An abstraction layer over *shell sessions*. A shell session is the execution of an interactive shell (``/bin/sh`` or something compatible), over which you may run commands (sent over stdin). The output of is then read from stdout and stderr. Shell sessions are less "robust" than executing a process on its own, and they are susseptible to all sorts of malformatted-strings attacks, and there is little benefit from using them locally. However, they can greatly speed up remote connections, and are required for the implementation of :class:`SshMachine <plumbum.machines.remote.SshMachine>`, as they allow us to send multiple commands over a single SSH connection (setting up separate SSH connections incurs a high overhead). Try to avoid using shell sessions, unless you know what you're doing. Instances of this class may be used as *context-managers*. :param proc: The underlying shell process (with open stdin, stdout and stderr) :param encoding: The encoding to use for the shell session. If ``"auto"``, the underlying process' encoding is used. :param isatty: If true, assume the shell has a TTY and that stdout and stderr are unified :param connect_timeout: The timeout to connect to the shell, after which, if no prompt is seen, the shell process is killed """ def __init__(self, proc, encoding = "auto", isatty = False, connect_timeout = 5): self.proc = proc self.encoding = proc.encoding if encoding == "auto" else encoding self.isatty = isatty self._current = None if connect_timeout: def closer(): shell_logger.error("Connection to %s timed out (%d sec)", proc, connect_timeout) self.close() timer = threading.Timer(connect_timeout, self.close) timer.start() self.run("") if connect_timeout: timer.cancel() def __enter__(self): return self def __exit__(self, t, v, tb): self.close() def __del__(self): try: self.close() except Exception: pass def alive(self): """Returns ``True`` if the underlying shell process is alive, ``False`` otherwise""" return self.proc and self.proc.poll() is None def close(self): """Closes (terminates) the shell session""" if not self.alive(): return try: self.proc.stdin.write(six.b("\nexit\n\n\nexit\n\n")) self.proc.stdin.flush() time.sleep(0.05) except (ValueError, EnvironmentError): pass for p in [self.proc.stdin, self.proc.stdout, self.proc.stderr]: try: p.close() except Exception: pass try: self.proc.kill() except EnvironmentError: pass self.proc = None def popen(self, cmd): """Runs the given command in the shell, adding some decoration around it. Only a single command can be executed at any given time. :param cmd: The command (string or :class:`Command <plumbum.commands.BaseCommand>` object) to run :returns: A :class:`SessionPopen <plumbum.session.SessionPopen>` instance """ if self.proc is None: raise ShellSessionError("Shell session has already been closed") if self._current and not self._current._done: raise ShellSessionError("Each shell may start only one process at a time") if isinstance(cmd, BaseCommand): full_cmd = cmd.formulate(1) else: full_cmd = cmd marker = "--.END%s.--" % (time.time() * random.random(),) if full_cmd.strip(): full_cmd += " ; " else: full_cmd = "true ; " full_cmd += "echo $? ; echo '%s'" % (marker,) if not self.isatty: full_cmd += " ; echo '%s' 1>&2" % (marker,) if self.encoding: full_cmd = full_cmd.encode(self.encoding) shell_logger.debug("Running %r", full_cmd) self.proc.stdin.write(full_cmd + six.b("\n")) self.proc.stdin.flush() self._current = SessionPopen(full_cmd, self.isatty, self.proc.stdin, MarkedPipe(self.proc.stdout, marker), MarkedPipe(self.proc.stderr, marker), self.encoding) return self._current def run(self, cmd, retcode = 0): """Runs the given command :param cmd: The command (string or :class:`Command <plumbum.commands.BaseCommand>` object) to run :param retcode: The expected return code (0 by default). Set to ``None`` in order to ignore erroneous return codes :returns: A tuple of (return code, stdout, stderr) """ return run_proc(self.popen(cmd), retcode)
mit
ysywh/ryu
ryu/services/protocols/bgp/operator/commands/show/count.py
52
1840
import logging from ryu.services.protocols.bgp.operator.command import Command from ryu.services.protocols.bgp.operator.command import CommandsResponse from ryu.services.protocols.bgp.operator.command import STATUS_ERROR from ryu.services.protocols.bgp.operator.command import STATUS_OK from ryu.services.protocols.bgp.operator.commands.responses import \ WrongParamResp LOG = logging.getLogger('bgpspeaker.operator.commands.show.count') class Count(Command): help_msg = 'show counters' param_help_msg = '<vpn-name> <route-family>{ipv4, ipv6}' command = 'count' cli_resp_line_template = 'BGP route count for VPN {0} is {1}\n' def __init__(self, *args, **kwargs): super(Count, self).__init__(*args, **kwargs) self.subcommands = { 'all': self.All } def action(self, params): if len(params) < 1: return CommandsResponse(STATUS_ERROR, 'Not enough params') else: vrf_name = params[0] if len(params) == 2: vrf_rf = params[1] else: vrf_rf = 'ipv4' from ryu.services.protocols.bgp.operator.internal_api import \ WrongParamError try: return CommandsResponse( STATUS_OK, self.api.count_single_vrf_routes(vrf_name, vrf_rf) ) except WrongParamError as e: return WrongParamResp(e) class All(Command): help_msg = 'shows number of routes for all VRFs' command = 'all' cli_resp_line_template = 'BGP route count for VPN {0} is {1}\n' def action(self, params): if len(params) > 0: return WrongParamResp() return CommandsResponse(STATUS_OK, self.api.count_all_vrf_routes())
apache-2.0
travislbrundage/geonode
geonode/security/views.py
11
5628
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2016 OSGeo # # 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/>. # ######################################################################### try: import json except ImportError: from django.utils import simplejson as json from django.core.exceptions import PermissionDenied from django.http import HttpResponse from django.views.decorators.http import require_POST from django.shortcuts import get_object_or_404 from django.conf import settings from geonode.utils import resolve_object from geonode.base.models import ResourceBase if "notification" in settings.INSTALLED_APPS: from notification import models as notification def _perms_info(obj): info = obj.get_all_level_info() return info def _perms_info_json(obj): info = _perms_info(obj) info['users'] = dict([(u.username, perms) for u, perms in info['users'].items()]) info['groups'] = dict([(g.name, perms) for g, perms in info['groups'].items()]) return json.dumps(info) def resource_permissions(request, resource_id): try: resource = resolve_object( request, ResourceBase, { 'id': resource_id}, 'base.change_resourcebase_permissions') except PermissionDenied: # we are handling this in a non-standard way return HttpResponse( 'You are not allowed to change permissions for this resource', status=401, content_type='text/plain') if request.method == 'POST': success = True message = "Permissions successfully updated!" try: permission_spec = json.loads(request.body) resource.set_permissions(permission_spec) # Check Users Permissions Consistency info = _perms_info(resource) info_users = dict([(u.username, perms) for u, perms in info['users'].items()]) for user, perms in info_users.items(): if 'download_resourcebase' in perms and 'view_resourcebase' not in perms: success = False message = 'User ' + str(user) + ' has Download permissions but ' \ 'cannot access the resource. ' \ 'Please update permissions consistently!' return HttpResponse( json.dumps({'success': success, 'message': message}), status=200, content_type='text/plain' ) except: success = False message = "Error updating permissions :(" return HttpResponse( json.dumps({'success': success, 'message': message}), status=500, content_type='text/plain' ) elif request.method == 'GET': permission_spec = _perms_info_json(resource) return HttpResponse( json.dumps({'success': True, 'permissions': permission_spec}), status=200, content_type='text/plain' ) else: return HttpResponse( 'No methods other than get and post are allowed', status=401, content_type='text/plain') @require_POST def set_bulk_permissions(request): permission_spec = json.loads(request.POST.get('permissions', None)) resource_ids = request.POST.getlist('resources', []) if permission_spec is not None: not_permitted = [] for resource_id in resource_ids: try: resource = resolve_object( request, ResourceBase, { 'id': resource_id }, 'base.change_resourcebase_permissions') resource.set_permissions(permission_spec) except PermissionDenied: not_permitted.append(ResourceBase.objects.get(id=resource_id).title) return HttpResponse( json.dumps({'success': 'ok', 'not_changed': not_permitted}), status=200, content_type='text/plain' ) else: return HttpResponse( json.dumps({'error': 'Wrong permissions specification'}), status=400, content_type='text/plain') @require_POST def request_permissions(request): """ Request permission to download a resource. """ uuid = request.POST['uuid'] resource = get_object_or_404(ResourceBase, uuid=uuid) try: notification.send( [resource.owner], 'request_download_resourcebase', {'from_user': request.user, 'resource': resource} ) return HttpResponse( json.dumps({'success': 'ok', }), status=200, content_type='text/plain') except: return HttpResponse( json.dumps({'error': 'error delivering notification'}), status=400, content_type='text/plain')
gpl-3.0
VAMDC/NodeSoftware
nodes/umist/manage.py
24
3909
#!/usr/bin/env python """ Set up the node. A first startup consists of giving the command 'python manage'. This will create an empty settings file. Copy&paste variables you want to change from settings_default.py to setup your node. Next define your models. You'll need to add the folder containing the 'models' directory to the INSTALLED_APPS tuple at least. Don't edit settings_default.py directly. Next run 'python manage.py syncdb'. This will read your settings file and create an empty database using your models. If you change the models you need to run syncdb again. """ import sys import os import traceback # Tack on the vamdc root directory to the python path. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) _CREATED_SETTINGS = False if not os.path.exists('settings.py'): # If settings.py doesn't already exist, create it string = "-"*50 + "\n Welcome to the VAMDC node setup." string += "\n\n Created a fresh settings.py file for you." print string settings_file = open('settings.py', 'w') _CREATED_SETTINGS = True string = \ """# # VAMDC-node config file # # You may customize your setup by copy&pasting the variables you want to # change from the default config file in nodes/settings_default.py to # this file. Try to only copy over things you really need to customize # and do *not* make any changes to settings_defaults.py directly. That # way you'll always have a sane default to fall back on (also, the # master file may change with updates). from settings_default import * # Comment out the following line once your node goes live. DEBUG=True ################################################### # Database connection # Setting up the database type and information. # Simplest for testing is sqlite3. ################################################### DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'node.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } ######################################### # Admin information ######################################### ADMINS = (\ ('Admin 1 Name', 'name1@mail.net'), ('Admin 2 Name', 'name2@mail.net'), ) """ settings_file.write(string) settings_file.close() # Settings file created or already existed. Test it. try: import settings except Exception: string = "\n" + traceback.format_exc() string += \ """ Error: Couldn't import the file 'settings.py' in the directory containing %r. There can be two reasons for this: 1) You moved your settings.py elsewhere. In that case you need to run django-admin.py, passing it the true location of your settings module. 2) The settings module is where it's supposed to be, but an exception was raised when trying to load it. Review the traceback above to resolve the problem, then try again. \n""" sys.stderr.write(string % __file__) sys.exit(1) # At this point we have an imported settings module, although it may be empty. if __name__ == "__main__": if _CREATED_SETTINGS: string = "\n Edit your new settings.py file as needed, then run\n" string += " 'python manage syncdb'.\n" string += "-"*50 print string sys.exit() # Run the django setup using our settings file. from django.core.management import execute_manager #from xml.sax import saxutils execute_manager(settings)
gpl-3.0
JIoJIaJIu/servo
tests/wpt/web-platform-tests/tools/pywebsocket/src/test/testdata/handlers/sub/exception_in_transfer_wsh.py
499
1816
# Copyright 2009, 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. """Exception in web_socket_transfer_data(). """ def web_socket_do_extra_handshake(request): pass def web_socket_transfer_data(request): raise Exception('Intentional Exception for %s, %s' % (request.ws_resource, request.ws_protocol)) # vi:sts=4 sw=4 et
mpl-2.0
leonardowolf/bookfree
flask/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py
34
41607
# util/langhelpers.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Routines to help with the creation, loading and introspection of modules, classes, hierarchies, attributes, functions, and methods. """ import itertools import inspect import operator import re import sys import types import warnings from functools import update_wrapper from .. import exc import hashlib from . import compat from . import _collections def md5_hex(x): if compat.py3k: x = x.encode('utf-8') m = hashlib.md5() m.update(x) return m.hexdigest() class safe_reraise(object): """Reraise an exception after invoking some handler code. Stores the existing exception info before invoking so that it is maintained across a potential coroutine context switch. e.g.:: try: sess.commit() except: with safe_reraise(): sess.rollback() """ def __enter__(self): self._exc_info = sys.exc_info() def __exit__(self, type_, value, traceback): # see #2703 for notes if type_ is None: exc_type, exc_value, exc_tb = self._exc_info self._exc_info = None # remove potential circular references compat.reraise(exc_type, exc_value, exc_tb) else: if not compat.py3k and self._exc_info and self._exc_info[1]: # emulate Py3K's behavior of telling us when an exception # occurs in an exception handler. warn( "An exception has occurred during handling of a " "previous exception. The previous exception " "is:\n %s %s\n" % (self._exc_info[0], self._exc_info[1])) self._exc_info = None # remove potential circular references compat.reraise(type_, value, traceback) def decode_slice(slc): """decode a slice object as sent to __getitem__. takes into account the 2.5 __index__() method, basically. """ ret = [] for x in slc.start, slc.stop, slc.step: if hasattr(x, '__index__'): x = x.__index__() ret.append(x) return tuple(ret) def _unique_symbols(used, *bases): used = set(used) for base in bases: pool = itertools.chain((base,), compat.itertools_imap(lambda i: base + str(i), range(1000))) for sym in pool: if sym not in used: used.add(sym) yield sym break else: raise NameError("exhausted namespace for symbol base %s" % base) def map_bits(fn, n): """Call the given function given each nonzero bit from n.""" while n: b = n & (~n + 1) yield fn(b) n ^= b def decorator(target): """A signature-matching decorator factory.""" def decorate(fn): if not inspect.isfunction(fn): raise Exception("not a decoratable function") spec = compat.inspect_getfullargspec(fn) names = tuple(spec[0]) + spec[1:3] + (fn.__name__,) targ_name, fn_name = _unique_symbols(names, 'target', 'fn') metadata = dict(target=targ_name, fn=fn_name) metadata.update(format_argspec_plus(spec, grouped=False)) metadata['name'] = fn.__name__ code = """\ def %(name)s(%(args)s): return %(target)s(%(fn)s, %(apply_kw)s) """ % metadata decorated = _exec_code_in_env(code, {targ_name: target, fn_name: fn}, fn.__name__) decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__ decorated.__wrapped__ = fn return update_wrapper(decorated, fn) return update_wrapper(decorate, target) def _exec_code_in_env(code, env, fn_name): exec(code, env) return env[fn_name] def public_factory(target, location): """Produce a wrapping function for the given cls or classmethod. Rationale here is so that the __init__ method of the class can serve as documentation for the function. """ if isinstance(target, type): fn = target.__init__ callable_ = target doc = "Construct a new :class:`.%s` object. \n\n"\ "This constructor is mirrored as a public API function; "\ "see :func:`~%s` "\ "for a full usage and argument description." % ( target.__name__, location, ) else: fn = callable_ = target doc = "This function is mirrored; see :func:`~%s` "\ "for a description of arguments." % location location_name = location.split(".")[-1] spec = compat.inspect_getfullargspec(fn) del spec[0][0] metadata = format_argspec_plus(spec, grouped=False) metadata['name'] = location_name code = """\ def %(name)s(%(args)s): return cls(%(apply_kw)s) """ % metadata env = {'cls': callable_, 'symbol': symbol} exec(code, env) decorated = env[location_name] decorated.__doc__ = fn.__doc__ decorated.__module__ = "sqlalchemy" + location.rsplit(".", 1)[0] if compat.py2k or hasattr(fn, '__func__'): fn.__func__.__doc__ = doc else: fn.__doc__ = doc return decorated class PluginLoader(object): def __init__(self, group, auto_fn=None): self.group = group self.impls = {} self.auto_fn = auto_fn def load(self, name): if name in self.impls: return self.impls[name]() if self.auto_fn: loader = self.auto_fn(name) if loader: self.impls[name] = loader return loader() try: import pkg_resources except ImportError: pass else: for impl in pkg_resources.iter_entry_points( self.group, name): self.impls[name] = impl.load return impl.load() raise exc.NoSuchModuleError( "Can't load plugin: %s:%s" % (self.group, name)) def register(self, name, modulepath, objname): def load(): mod = compat.import_(modulepath) for token in modulepath.split(".")[1:]: mod = getattr(mod, token) return getattr(mod, objname) self.impls[name] = load def get_cls_kwargs(cls, _set=None): """Return the full set of inherited kwargs for the given `cls`. Probes a class's __init__ method, collecting all named arguments. If the __init__ defines a \**kwargs catch-all, then the constructor is presumed to pass along unrecognized keywords to its base classes, and the collection process is repeated recursively on each of the bases. Uses a subset of inspect.getargspec() to cut down on method overhead. No anonymous tuple arguments please ! """ toplevel = _set is None if toplevel: _set = set() ctr = cls.__dict__.get('__init__', False) has_init = ctr and isinstance(ctr, types.FunctionType) and \ isinstance(ctr.__code__, types.CodeType) if has_init: names, has_kw = inspect_func_args(ctr) _set.update(names) if not has_kw and not toplevel: return None if not has_init or has_kw: for c in cls.__bases__: if get_cls_kwargs(c, _set) is None: break _set.discard('self') return _set try: # TODO: who doesn't have this constant? from inspect import CO_VARKEYWORDS def inspect_func_args(fn): co = fn.__code__ nargs = co.co_argcount names = co.co_varnames args = list(names[:nargs]) has_kw = bool(co.co_flags & CO_VARKEYWORDS) return args, has_kw except ImportError: def inspect_func_args(fn): names, _, has_kw, _ = inspect.getargspec(fn) return names, bool(has_kw) def get_func_kwargs(func): """Return the set of legal kwargs for the given `func`. Uses getargspec so is safe to call for methods, functions, etc. """ return compat.inspect_getargspec(func)[0] def get_callable_argspec(fn, no_self=False, _is_init=False): """Return the argument signature for any callable. All pure-Python callables are accepted, including functions, methods, classes, objects with __call__; builtins and other edge cases like functools.partial() objects raise a TypeError. """ if inspect.isbuiltin(fn): raise TypeError("Can't inspect builtin: %s" % fn) elif inspect.isfunction(fn): if _is_init and no_self: spec = compat.inspect_getargspec(fn) return compat.ArgSpec(spec.args[1:], spec.varargs, spec.keywords, spec.defaults) else: return compat.inspect_getargspec(fn) elif inspect.ismethod(fn): if no_self and (_is_init or fn.__self__): spec = compat.inspect_getargspec(fn.__func__) return compat.ArgSpec(spec.args[1:], spec.varargs, spec.keywords, spec.defaults) else: return compat.inspect_getargspec(fn.__func__) elif inspect.isclass(fn): return get_callable_argspec( fn.__init__, no_self=no_self, _is_init=True) elif hasattr(fn, '__func__'): return compat.inspect_getargspec(fn.__func__) elif hasattr(fn, '__call__'): if inspect.ismethod(fn.__call__): return get_callable_argspec(fn.__call__, no_self=no_self) else: raise TypeError("Can't inspect callable: %s" % fn) else: raise TypeError("Can't inspect callable: %s" % fn) def format_argspec_plus(fn, grouped=True): """Returns a dictionary of formatted, introspected function arguments. A enhanced variant of inspect.formatargspec to support code generation. fn An inspectable callable or tuple of inspect getargspec() results. grouped Defaults to True; include (parens, around, argument) lists Returns: args Full inspect.formatargspec for fn self_arg The name of the first positional argument, varargs[0], or None if the function defines no positional arguments. apply_pos args, re-written in calling rather than receiving syntax. Arguments are passed positionally. apply_kw Like apply_pos, except keyword-ish args are passed as keywords. Example:: >>> format_argspec_plus(lambda self, a, b, c=3, **d: 123) {'args': '(self, a, b, c=3, **d)', 'self_arg': 'self', 'apply_kw': '(self, a, b, c=c, **d)', 'apply_pos': '(self, a, b, c, **d)'} """ if compat.callable(fn): spec = compat.inspect_getfullargspec(fn) else: # we accept an existing argspec... spec = fn args = inspect.formatargspec(*spec) if spec[0]: self_arg = spec[0][0] elif spec[1]: self_arg = '%s[0]' % spec[1] else: self_arg = None if compat.py3k: apply_pos = inspect.formatargspec(spec[0], spec[1], spec[2], None, spec[4]) num_defaults = 0 if spec[3]: num_defaults += len(spec[3]) if spec[4]: num_defaults += len(spec[4]) name_args = spec[0] + spec[4] else: apply_pos = inspect.formatargspec(spec[0], spec[1], spec[2]) num_defaults = 0 if spec[3]: num_defaults += len(spec[3]) name_args = spec[0] if num_defaults: defaulted_vals = name_args[0 - num_defaults:] else: defaulted_vals = () apply_kw = inspect.formatargspec(name_args, spec[1], spec[2], defaulted_vals, formatvalue=lambda x: '=' + x) if grouped: return dict(args=args, self_arg=self_arg, apply_pos=apply_pos, apply_kw=apply_kw) else: return dict(args=args[1:-1], self_arg=self_arg, apply_pos=apply_pos[1:-1], apply_kw=apply_kw[1:-1]) def format_argspec_init(method, grouped=True): """format_argspec_plus with considerations for typical __init__ methods Wraps format_argspec_plus with error handling strategies for typical __init__ cases:: object.__init__ -> (self) other unreflectable (usually C) -> (self, *args, **kwargs) """ if method is object.__init__: args = grouped and '(self)' or 'self' else: try: return format_argspec_plus(method, grouped=grouped) except TypeError: args = (grouped and '(self, *args, **kwargs)' or 'self, *args, **kwargs') return dict(self_arg='self', args=args, apply_pos=args, apply_kw=args) def getargspec_init(method): """inspect.getargspec with considerations for typical __init__ methods Wraps inspect.getargspec with error handling for typical __init__ cases:: object.__init__ -> (self) other unreflectable (usually C) -> (self, *args, **kwargs) """ try: return compat.inspect_getargspec(method) except TypeError: if method is object.__init__: return (['self'], None, None, None) else: return (['self'], 'args', 'kwargs', None) def unbound_method_to_callable(func_or_cls): """Adjust the incoming callable such that a 'self' argument is not required. """ if isinstance(func_or_cls, types.MethodType) and not func_or_cls.__self__: return func_or_cls.__func__ else: return func_or_cls def generic_repr(obj, additional_kw=(), to_inspect=None, omit_kwarg=()): """Produce a __repr__() based on direct association of the __init__() specification vs. same-named attributes present. """ if to_inspect is None: to_inspect = [obj] else: to_inspect = _collections.to_list(to_inspect) missing = object() pos_args = [] kw_args = _collections.OrderedDict() vargs = None for i, insp in enumerate(to_inspect): try: (_args, _vargs, vkw, defaults) = \ compat.inspect_getargspec(insp.__init__) except TypeError: continue else: default_len = defaults and len(defaults) or 0 if i == 0: if _vargs: vargs = _vargs if default_len: pos_args.extend(_args[1:-default_len]) else: pos_args.extend(_args[1:]) else: kw_args.update([ (arg, missing) for arg in _args[1:-default_len] ]) if default_len: kw_args.update([ (arg, default) for arg, default in zip(_args[-default_len:], defaults) ]) output = [] output.extend(repr(getattr(obj, arg, None)) for arg in pos_args) if vargs is not None and hasattr(obj, vargs): output.extend([repr(val) for val in getattr(obj, vargs)]) for arg, defval in kw_args.items(): if arg in omit_kwarg: continue try: val = getattr(obj, arg, missing) if val is not missing and val != defval: output.append('%s=%r' % (arg, val)) except Exception: pass if additional_kw: for arg, defval in additional_kw: try: val = getattr(obj, arg, missing) if val is not missing and val != defval: output.append('%s=%r' % (arg, val)) except Exception: pass return "%s(%s)" % (obj.__class__.__name__, ", ".join(output)) class portable_instancemethod(object): """Turn an instancemethod into a (parent, name) pair to produce a serializable callable. """ __slots__ = 'target', 'name', '__weakref__' def __getstate__(self): return {'target': self.target, 'name': self.name} def __setstate__(self, state): self.target = state['target'] self.name = state['name'] def __init__(self, meth): self.target = meth.__self__ self.name = meth.__name__ def __call__(self, *arg, **kw): return getattr(self.target, self.name)(*arg, **kw) def class_hierarchy(cls): """Return an unordered sequence of all classes related to cls. Traverses diamond hierarchies. Fibs slightly: subclasses of builtin types are not returned. Thus class_hierarchy(class A(object)) returns (A, object), not A plus every class systemwide that derives from object. Old-style classes are discarded and hierarchies rooted on them will not be descended. """ if compat.py2k: if isinstance(cls, types.ClassType): return list() hier = set([cls]) process = list(cls.__mro__) while process: c = process.pop() if compat.py2k: if isinstance(c, types.ClassType): continue bases = (_ for _ in c.__bases__ if _ not in hier and not isinstance(_, types.ClassType)) else: bases = (_ for _ in c.__bases__ if _ not in hier) for b in bases: process.append(b) hier.add(b) if compat.py3k: if c.__module__ == 'builtins' or not hasattr(c, '__subclasses__'): continue else: if c.__module__ == '__builtin__' or not hasattr( c, '__subclasses__'): continue for s in [_ for _ in c.__subclasses__() if _ not in hier]: process.append(s) hier.add(s) return list(hier) def iterate_attributes(cls): """iterate all the keys and attributes associated with a class, without using getattr(). Does not use getattr() so that class-sensitive descriptors (i.e. property.__get__()) are not called. """ keys = dir(cls) for key in keys: for c in cls.__mro__: if key in c.__dict__: yield (key, c.__dict__[key]) break def monkeypatch_proxied_specials(into_cls, from_cls, skip=None, only=None, name='self.proxy', from_instance=None): """Automates delegation of __specials__ for a proxying type.""" if only: dunders = only else: if skip is None: skip = ('__slots__', '__del__', '__getattribute__', '__metaclass__', '__getstate__', '__setstate__') dunders = [m for m in dir(from_cls) if (m.startswith('__') and m.endswith('__') and not hasattr(into_cls, m) and m not in skip)] for method in dunders: try: fn = getattr(from_cls, method) if not hasattr(fn, '__call__'): continue fn = getattr(fn, 'im_func', fn) except AttributeError: continue try: spec = compat.inspect_getargspec(fn) fn_args = inspect.formatargspec(spec[0]) d_args = inspect.formatargspec(spec[0][1:]) except TypeError: fn_args = '(self, *args, **kw)' d_args = '(*args, **kw)' py = ("def %(method)s%(fn_args)s: " "return %(name)s.%(method)s%(d_args)s" % locals()) env = from_instance is not None and {name: from_instance} or {} compat.exec_(py, env) try: env[method].__defaults__ = fn.__defaults__ except AttributeError: pass setattr(into_cls, method, env[method]) def methods_equivalent(meth1, meth2): """Return True if the two methods are the same implementation.""" return getattr(meth1, '__func__', meth1) is getattr( meth2, '__func__', meth2) def as_interface(obj, cls=None, methods=None, required=None): """Ensure basic interface compliance for an instance or dict of callables. Checks that ``obj`` implements public methods of ``cls`` or has members listed in ``methods``. If ``required`` is not supplied, implementing at least one interface method is sufficient. Methods present on ``obj`` that are not in the interface are ignored. If ``obj`` is a dict and ``dict`` does not meet the interface requirements, the keys of the dictionary are inspected. Keys present in ``obj`` that are not in the interface will raise TypeErrors. Raises TypeError if ``obj`` does not meet the interface criteria. In all passing cases, an object with callable members is returned. In the simple case, ``obj`` is returned as-is; if dict processing kicks in then an anonymous class is returned. obj A type, instance, or dictionary of callables. cls Optional, a type. All public methods of cls are considered the interface. An ``obj`` instance of cls will always pass, ignoring ``required``.. methods Optional, a sequence of method names to consider as the interface. required Optional, a sequence of mandatory implementations. If omitted, an ``obj`` that provides at least one interface method is considered sufficient. As a convenience, required may be a type, in which case all public methods of the type are required. """ if not cls and not methods: raise TypeError('a class or collection of method names are required') if isinstance(cls, type) and isinstance(obj, cls): return obj interface = set(methods or [m for m in dir(cls) if not m.startswith('_')]) implemented = set(dir(obj)) complies = operator.ge if isinstance(required, type): required = interface elif not required: required = set() complies = operator.gt else: required = set(required) if complies(implemented.intersection(interface), required): return obj # No dict duck typing here. if not isinstance(obj, dict): qualifier = complies is operator.gt and 'any of' or 'all of' raise TypeError("%r does not implement %s: %s" % ( obj, qualifier, ', '.join(interface))) class AnonymousInterface(object): """A callable-holding shell.""" if cls: AnonymousInterface.__name__ = 'Anonymous' + cls.__name__ found = set() for method, impl in dictlike_iteritems(obj): if method not in interface: raise TypeError("%r: unknown in this interface" % method) if not compat.callable(impl): raise TypeError("%r=%r is not callable" % (method, impl)) setattr(AnonymousInterface, method, staticmethod(impl)) found.add(method) if complies(found, required): return AnonymousInterface raise TypeError("dictionary does not contain required keys %s" % ', '.join(required - found)) class memoized_property(object): """A read-only @property that is only evaluated once.""" def __init__(self, fget, doc=None): self.fget = fget self.__doc__ = doc or fget.__doc__ self.__name__ = fget.__name__ def __get__(self, obj, cls): if obj is None: return self obj.__dict__[self.__name__] = result = self.fget(obj) return result def _reset(self, obj): memoized_property.reset(obj, self.__name__) @classmethod def reset(cls, obj, name): obj.__dict__.pop(name, None) def memoized_instancemethod(fn): """Decorate a method memoize its return value. Best applied to no-arg methods: memoization is not sensitive to argument values, and will always return the same value even when called with different arguments. """ def oneshot(self, *args, **kw): result = fn(self, *args, **kw) memo = lambda *a, **kw: result memo.__name__ = fn.__name__ memo.__doc__ = fn.__doc__ self.__dict__[fn.__name__] = memo return result return update_wrapper(oneshot, fn) class group_expirable_memoized_property(object): """A family of @memoized_properties that can be expired in tandem.""" def __init__(self, attributes=()): self.attributes = [] if attributes: self.attributes.extend(attributes) def expire_instance(self, instance): """Expire all memoized properties for *instance*.""" stash = instance.__dict__ for attribute in self.attributes: stash.pop(attribute, None) def __call__(self, fn): self.attributes.append(fn.__name__) return memoized_property(fn) def method(self, fn): self.attributes.append(fn.__name__) return memoized_instancemethod(fn) class MemoizedSlots(object): """Apply memoized items to an object using a __getattr__ scheme. This allows the functionality of memoized_property and memoized_instancemethod to be available to a class using __slots__. """ __slots__ = () def _fallback_getattr(self, key): raise AttributeError(key) def __getattr__(self, key): if key.startswith('_memoized'): raise AttributeError(key) elif hasattr(self, '_memoized_attr_%s' % key): value = getattr(self, '_memoized_attr_%s' % key)() setattr(self, key, value) return value elif hasattr(self, '_memoized_method_%s' % key): fn = getattr(self, '_memoized_method_%s' % key) def oneshot(*args, **kw): result = fn(*args, **kw) memo = lambda *a, **kw: result memo.__name__ = fn.__name__ memo.__doc__ = fn.__doc__ setattr(self, key, memo) return result oneshot.__doc__ = fn.__doc__ return oneshot else: return self._fallback_getattr(key) def dependency_for(modulename): def decorate(obj): # TODO: would be nice to improve on this import silliness, # unfortunately importlib doesn't work that great either tokens = modulename.split(".") mod = compat.import_( ".".join(tokens[0:-1]), globals(), locals(), tokens[-1]) mod = getattr(mod, tokens[-1]) setattr(mod, obj.__name__, obj) return obj return decorate class dependencies(object): """Apply imported dependencies as arguments to a function. E.g.:: @util.dependencies( "sqlalchemy.sql.widget", "sqlalchemy.engine.default" ); def some_func(self, widget, default, arg1, arg2, **kw): # ... Rationale is so that the impact of a dependency cycle can be associated directly with the few functions that cause the cycle, and not pollute the module-level namespace. """ def __init__(self, *deps): self.import_deps = [] for dep in deps: tokens = dep.split(".") self.import_deps.append( dependencies._importlater( ".".join(tokens[0:-1]), tokens[-1] ) ) def __call__(self, fn): import_deps = self.import_deps spec = compat.inspect_getfullargspec(fn) spec_zero = list(spec[0]) hasself = spec_zero[0] in ('self', 'cls') for i in range(len(import_deps)): spec[0][i + (1 if hasself else 0)] = "import_deps[%r]" % i inner_spec = format_argspec_plus(spec, grouped=False) for impname in import_deps: del spec_zero[1 if hasself else 0] spec[0][:] = spec_zero outer_spec = format_argspec_plus(spec, grouped=False) code = 'lambda %(args)s: fn(%(apply_kw)s)' % { "args": outer_spec['args'], "apply_kw": inner_spec['apply_kw'] } decorated = eval(code, locals()) decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__ return update_wrapper(decorated, fn) @classmethod def resolve_all(cls, path): for m in list(dependencies._unresolved): if m._full_path.startswith(path): m._resolve() _unresolved = set() _by_key = {} class _importlater(object): _unresolved = set() _by_key = {} def __new__(cls, path, addtl): key = path + "." + addtl if key in dependencies._by_key: return dependencies._by_key[key] else: dependencies._by_key[key] = imp = object.__new__(cls) return imp def __init__(self, path, addtl): self._il_path = path self._il_addtl = addtl dependencies._unresolved.add(self) @property def _full_path(self): return self._il_path + "." + self._il_addtl @memoized_property def module(self): if self in dependencies._unresolved: raise ImportError( "importlater.resolve_all() hasn't " "been called (this is %s %s)" % (self._il_path, self._il_addtl)) return getattr(self._initial_import, self._il_addtl) def _resolve(self): dependencies._unresolved.discard(self) self._initial_import = compat.import_( self._il_path, globals(), locals(), [self._il_addtl]) def __getattr__(self, key): if key == 'module': raise ImportError("Could not resolve module %s" % self._full_path) try: attr = getattr(self.module, key) except AttributeError: raise AttributeError( "Module %s has no attribute '%s'" % (self._full_path, key) ) self.__dict__[key] = attr return attr # from paste.deploy.converters def asbool(obj): if isinstance(obj, compat.string_types): obj = obj.strip().lower() if obj in ['true', 'yes', 'on', 'y', 't', '1']: return True elif obj in ['false', 'no', 'off', 'n', 'f', '0']: return False else: raise ValueError("String is not true/false: %r" % obj) return bool(obj) def bool_or_str(*text): """Return a callable that will evaluate a string as boolean, or one of a set of "alternate" string values. """ def bool_or_value(obj): if obj in text: return obj else: return asbool(obj) return bool_or_value def asint(value): """Coerce to integer.""" if value is None: return value return int(value) def coerce_kw_type(kw, key, type_, flexi_bool=True): """If 'key' is present in dict 'kw', coerce its value to type 'type\_' if necessary. If 'flexi_bool' is True, the string '0' is considered false when coercing to boolean. """ if key in kw and not isinstance(kw[key], type_) and kw[key] is not None: if type_ is bool and flexi_bool: kw[key] = asbool(kw[key]) else: kw[key] = type_(kw[key]) def constructor_copy(obj, cls, *args, **kw): """Instantiate cls using the __dict__ of obj as constructor arguments. Uses inspect to match the named arguments of ``cls``. """ names = get_cls_kwargs(cls) kw.update((k, obj.__dict__[k]) for k in names if k in obj.__dict__) return cls(*args, **kw) def counter(): """Return a threadsafe counter function.""" lock = compat.threading.Lock() counter = itertools.count(1) # avoid the 2to3 "next" transformation... def _next(): lock.acquire() try: return next(counter) finally: lock.release() return _next def duck_type_collection(specimen, default=None): """Given an instance or class, guess if it is or is acting as one of the basic collection types: list, set and dict. If the __emulates__ property is present, return that preferentially. """ if hasattr(specimen, '__emulates__'): # canonicalize set vs sets.Set to a standard: the builtin set if (specimen.__emulates__ is not None and issubclass(specimen.__emulates__, set)): return set else: return specimen.__emulates__ isa = isinstance(specimen, type) and issubclass or isinstance if isa(specimen, list): return list elif isa(specimen, set): return set elif isa(specimen, dict): return dict if hasattr(specimen, 'append'): return list elif hasattr(specimen, 'add'): return set elif hasattr(specimen, 'set'): return dict else: return default def assert_arg_type(arg, argtype, name): if isinstance(arg, argtype): return arg else: if isinstance(argtype, tuple): raise exc.ArgumentError( "Argument '%s' is expected to be one of type %s, got '%s'" % (name, ' or '.join("'%s'" % a for a in argtype), type(arg))) else: raise exc.ArgumentError( "Argument '%s' is expected to be of type '%s', got '%s'" % (name, argtype, type(arg))) def dictlike_iteritems(dictlike): """Return a (key, value) iterator for almost any dict-like object.""" if compat.py3k: if hasattr(dictlike, 'items'): return list(dictlike.items()) else: if hasattr(dictlike, 'iteritems'): return dictlike.iteritems() elif hasattr(dictlike, 'items'): return iter(dictlike.items()) getter = getattr(dictlike, '__getitem__', getattr(dictlike, 'get', None)) if getter is None: raise TypeError( "Object '%r' is not dict-like" % dictlike) if hasattr(dictlike, 'iterkeys'): def iterator(): for key in dictlike.iterkeys(): yield key, getter(key) return iterator() elif hasattr(dictlike, 'keys'): return iter((key, getter(key)) for key in dictlike.keys()) else: raise TypeError( "Object '%r' is not dict-like" % dictlike) class classproperty(property): """A decorator that behaves like @property except that operates on classes rather than instances. The decorator is currently special when using the declarative module, but note that the :class:`~.sqlalchemy.ext.declarative.declared_attr` decorator should be used for this purpose with declarative. """ def __init__(self, fget, *arg, **kw): super(classproperty, self).__init__(fget, *arg, **kw) self.__doc__ = fget.__doc__ def __get__(desc, self, cls): return desc.fget(cls) class hybridproperty(object): def __init__(self, func): self.func = func def __get__(self, instance, owner): if instance is None: clsval = self.func(owner) clsval.__doc__ = self.func.__doc__ return clsval else: return self.func(instance) class hybridmethod(object): """Decorate a function as cls- or instance- level.""" def __init__(self, func): self.func = func def __get__(self, instance, owner): if instance is None: return self.func.__get__(owner, owner.__class__) else: return self.func.__get__(instance, owner) class _symbol(int): def __new__(self, name, doc=None, canonical=None): """Construct a new named symbol.""" assert isinstance(name, compat.string_types) if canonical is None: canonical = hash(name) v = int.__new__(_symbol, canonical) v.name = name if doc: v.__doc__ = doc return v def __reduce__(self): return symbol, (self.name, "x", int(self)) def __str__(self): return repr(self) def __repr__(self): return "symbol(%r)" % self.name _symbol.__name__ = 'symbol' class symbol(object): """A constant symbol. >>> symbol('foo') is symbol('foo') True >>> symbol('foo') <symbol 'foo> A slight refinement of the MAGICCOOKIE=object() pattern. The primary advantage of symbol() is its repr(). They are also singletons. Repeated calls of symbol('name') will all return the same instance. The optional ``doc`` argument assigns to ``__doc__``. This is strictly so that Sphinx autoattr picks up the docstring we want (it doesn't appear to pick up the in-module docstring if the datamember is in a different module - autoattribute also blows up completely). If Sphinx fixes/improves this then we would no longer need ``doc`` here. """ symbols = {} _lock = compat.threading.Lock() def __new__(cls, name, doc=None, canonical=None): cls._lock.acquire() try: sym = cls.symbols.get(name) if sym is None: cls.symbols[name] = sym = _symbol(name, doc, canonical) return sym finally: symbol._lock.release() _creation_order = 1 def set_creation_order(instance): """Assign a '_creation_order' sequence to the given instance. This allows multiple instances to be sorted in order of creation (typically within a single thread; the counter is not particularly threadsafe). """ global _creation_order instance._creation_order = _creation_order _creation_order += 1 def warn_exception(func, *args, **kwargs): """executes the given function, catches all exceptions and converts to a warning. """ try: return func(*args, **kwargs) except Exception: warn("%s('%s') ignored" % sys.exc_info()[0:2]) def ellipses_string(value, len_=25): try: if len(value) > len_: return "%s..." % value[0:len_] else: return value except TypeError: return value class _hash_limit_string(compat.text_type): """A string subclass that can only be hashed on a maximum amount of unique values. This is used for warnings so that we can send out parameterized warnings without the __warningregistry__ of the module, or the non-overridable "once" registry within warnings.py, overloading memory, """ def __new__(cls, value, num, args): interpolated = (value % args) + \ (" (this warning may be suppressed after %d occurrences)" % num) self = super(_hash_limit_string, cls).__new__(cls, interpolated) self._hash = hash("%s_%d" % (value, hash(interpolated) % num)) return self def __hash__(self): return self._hash def __eq__(self, other): return hash(self) == hash(other) def warn(msg): """Issue a warning. If msg is a string, :class:`.exc.SAWarning` is used as the category. """ warnings.warn(msg, exc.SAWarning, stacklevel=2) def warn_limited(msg, args): """Issue a warning with a paramterized string, limiting the number of registrations. """ if args: msg = _hash_limit_string(msg, 10, args) warnings.warn(msg, exc.SAWarning, stacklevel=2) def only_once(fn): """Decorate the given function to be a no-op after it is called exactly once.""" once = [fn] def go(*arg, **kw): if once: once_fn = once.pop() return once_fn(*arg, **kw) return go _SQLA_RE = re.compile(r'sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.py') _UNITTEST_RE = re.compile(r'unit(?:2|test2?/)') def chop_traceback(tb, exclude_prefix=_UNITTEST_RE, exclude_suffix=_SQLA_RE): """Chop extraneous lines off beginning and end of a traceback. :param tb: a list of traceback lines as returned by ``traceback.format_stack()`` :param exclude_prefix: a regular expression object matching lines to skip at beginning of ``tb`` :param exclude_suffix: a regular expression object matching lines to skip at end of ``tb`` """ start = 0 end = len(tb) - 1 while start <= end and exclude_prefix.search(tb[start]): start += 1 while start <= end and exclude_suffix.search(tb[end]): end -= 1 return tb[start:end + 1] NoneType = type(None) def attrsetter(attrname): code = \ "def set(obj, value):"\ " obj.%s = value" % attrname env = locals().copy() exec(code, env) return env['set'] class EnsureKWArgType(type): """Apply translation of functions to accept **kw arguments if they don't already. """ def __init__(cls, clsname, bases, clsdict): fn_reg = cls.ensure_kwarg if fn_reg: for key in clsdict: m = re.match(fn_reg, key) if m: fn = clsdict[key] spec = compat.inspect_getargspec(fn) if not spec.keywords: clsdict[key] = wrapped = cls._wrap_w_kw(fn) setattr(cls, key, wrapped) super(EnsureKWArgType, cls).__init__(clsname, bases, clsdict) def _wrap_w_kw(self, fn): def wrap(*arg, **kw): return fn(*arg) return update_wrapper(wrap, fn)
mit
Yangqing/caffe2
caffe2/contrib/playground/AnyExpOnTerm.py
2
1046
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import json import caffe2.contrib.playground.AnyExp as AnyExp import logging logging.basicConfig() log = logging.getLogger("AnyExpOnTerm") log.setLevel(logging.DEBUG) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Any Experiment training.') parser.add_argument("--parameters-json", type=json.loads, help='model options in json format', dest="params") args = parser.parse_args() opts = args.params['opts'] opts = AnyExp.initOpts(opts) log.info('opts is: {}'.format(str(opts))) AnyExp.initDefaultModuleMap() opts['input']['datasets'] = AnyExp.aquireDatasets(opts) # defined this way so that AnyExp.trainFun(opts) can be replaced with # some other custermized training function. ret = AnyExp.runShardedTrainLoop(opts, AnyExp.trainFun()) log.info('ret is: {}'.format(str(ret)))
apache-2.0
eloquence/unisubs
apps/testhelpers/tests.py
6
1309
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase from videos import models import os import json from django.conf import settings from auth.models import CustomUser as User class SimpleTest(TestCase): def test_create_videos(self): data = { "url": "http://www.example.com/sdf.mp4", "langs": [ { "code": "ar", "num_subs": 0, "is_complete": False, "is_original": True, "translations": [] }, { "code": "en", "num_subs": 10, "is_complete": True, "is_original": False, "translations": [] }], "title": "c" } from testhelpers.views import _create_videos videos = _create_videos([data], []) v = models.Video.objects.get(title='c') en = v.subtitle_language('en') self.assertTrue(en.is_forked) self.assertEquals('ar', v.subtitle_language().language_code)
agpl-3.0
arximboldi/jagsat
src/test/base_event.py
1
2560
# # Copyright (C) 2009, 2010 JAGSAT Development Team (see below) # # This file is part of JAGSAT. # # JAGSAT 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. # # JAGSAT 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/>. # # JAGSAT Development Team is: # - Juan Pedro Bolivar Puente # - Alberto Villegas Erce # - Guillem Medina # - Sarah Lindstrom # - Aksel Junkkila # - Thomas Forss # # along with this program. If not, see <http://www.gnu.org/licenses/>. # import unittest from base.event import * from base.sender import * class TestEventManager (unittest.TestCase): def test_add_del (self): e = EventManager () x = Receiver () y = Receiver () e.connect (x) self.assertEqual (e.count, 1) e.connect (y) self.assertEqual (e.count, 2) e.disconnect (x) self.assertEqual (e.count, 1) e.disconnect (y) self.assertEqual (e.count, 0) self.assertRaises (ValueError, e.disconnect, x) def test_forward_and_quiet (self): class DummyForwarder (Receiver): def __init__ (self): self.last = '' def receive (self, name, *a, **k): self.last = name fw = DummyForwarder () mgr = EventManager () mgr.connect (fw) a = mgr.event ('a').notify () self.assertEqual (fw.last, 'a') b = mgr.notify ('b') self.assertEqual (fw.last, 'b') mgr.quiet = True mgr.notify ('a') self.assertEqual (fw.last, 'b') def test_notify_and_quiet (self): l = [] def accum (x): l.append (x) mgr = EventManager () mgr.event ('ac').connect (accum) mgr.notify ('ac', 1) self.assertEqual (l, [1]) mgr.event ('ac') (2) self.assertEqual (l, [1, 2]) mgr.quiet = True mgr.notify ('ac', 3) self.assertEqual (l, [1, 2]) mgr.event ('ac') (3) self.assertEqual (l, [1, 2, 3])
gpl-3.0
stephenmcd/django-forms-builder
forms_builder/forms/models.py
2
11009
from __future__ import unicode_literals from django import VERSION as DJANGO_VERSION from django.contrib.sites.models import Site try: from django.urls import reverse except ImportError: # For Django 1.8 compatibility from django.core.urlresolvers import reverse from django.db import models from django.db.models import Q from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext, ugettext_lazy as _ from future.builtins import str from forms_builder.forms import fields from forms_builder.forms import settings from forms_builder.forms.utils import now, slugify, unique_slug STATUS_DRAFT = 1 STATUS_PUBLISHED = 2 STATUS_CHOICES = ( (STATUS_DRAFT, _("Draft")), (STATUS_PUBLISHED, _("Published")), ) class FormManager(models.Manager): """ Only show published forms for non-staff users. """ def published(self, for_user=None): if for_user is not None and for_user.is_staff: return self.all() filters = [ Q(publish_date__lte=now()) | Q(publish_date__isnull=True), Q(expiry_date__gte=now()) | Q(expiry_date__isnull=True), Q(status=STATUS_PUBLISHED), ] if settings.USE_SITES: filters.append(Q(sites=Site.objects.get_current())) return self.filter(*filters) ###################################################################### # # # Each of the models are implemented as abstract to allow for # # subclassing. Default concrete implementations are then defined # # at the end of this module. # # # ###################################################################### @python_2_unicode_compatible class AbstractForm(models.Model): """ A user-built form. """ sites = models.ManyToManyField(Site, default=[settings.SITE_ID], related_name="%(app_label)s_%(class)s_forms") title = models.CharField(_("Title"), max_length=50) slug = models.SlugField(_("Slug"), editable=settings.EDITABLE_SLUGS, max_length=100, unique=True) intro = models.TextField(_("Intro"), blank=True) button_text = models.CharField(_("Button text"), max_length=50, default=_("Submit")) response = models.TextField(_("Response"), blank=True) redirect_url = models.CharField(_("Redirect url"), max_length=200, null=True, blank=True, help_text=_("An alternate URL to redirect to after form submission")) status = models.IntegerField(_("Status"), choices=STATUS_CHOICES, default=STATUS_PUBLISHED) publish_date = models.DateTimeField(_("Published from"), help_text=_("With published selected, won't be shown until this time"), blank=True, null=True) expiry_date = models.DateTimeField(_("Expires on"), help_text=_("With published selected, won't be shown after this time"), blank=True, null=True) login_required = models.BooleanField(_("Login required"), default=False, help_text=_("If checked, only logged in users can view the form")) send_email = models.BooleanField(_("Send email"), default=True, help_text= _("If checked, the person entering the form will be sent an email")) email_from = models.EmailField(_("From address"), blank=True, help_text=_("The address the email will be sent from")) email_copies = models.CharField(_("Send copies to"), blank=True, help_text=_("One or more email addresses, separated by commas"), max_length=200) email_subject = models.CharField(_("Subject"), max_length=200, blank=True) email_message = models.TextField(_("Message"), blank=True) objects = FormManager() class Meta: verbose_name = _("Form") verbose_name_plural = _("Forms") abstract = True def __str__(self): return str(self.title) def save(self, *args, **kwargs): """ Create a unique slug from title - append an index and increment if it already exists. """ if not self.slug: slug = slugify(self) self.slug = unique_slug(self.__class__.objects, "slug", slug) super(AbstractForm, self).save(*args, **kwargs) def published(self, for_user=None): """ Mimics the queryset logic in ``FormManager.published``, so we can check a form is published when it wasn't loaded via the queryset's ``published`` method, and is passed to the ``render_built_form`` template tag. """ if for_user is not None and for_user.is_staff: return True status = self.status == STATUS_PUBLISHED publish_date = self.publish_date is None or self.publish_date <= now() expiry_date = self.expiry_date is None or self.expiry_date >= now() authenticated = for_user is not None and for_user.is_authenticated if DJANGO_VERSION <= (1, 9): # Django 1.8 compatibility, is_authenticated has to be called as a method. authenticated = for_user is not None and for_user.is_authenticated() login_required = (not self.login_required or authenticated) return status and publish_date and expiry_date and login_required def total_entries(self): """ Called by the admin list view where the queryset is annotated with the number of entries. """ return self.total_entries total_entries.admin_order_field = "total_entries" def get_absolute_url(self): return reverse("form_detail", kwargs={"slug": self.slug}) def admin_links(self): kw = {"args": (self.id,)} links = [ (_("View form on site"), self.get_absolute_url()), (_("Filter entries"), reverse("admin:form_entries", **kw)), (_("View all entries"), reverse("admin:form_entries_show", **kw)), (_("Export all entries"), reverse("admin:form_entries_export", **kw)), ] for i, (text, url) in enumerate(links): links[i] = "<a href='%s'>%s</a>" % (url, ugettext(text)) return "<br>".join(links) admin_links.allow_tags = True admin_links.short_description = "" class FieldManager(models.Manager): """ Only show visible fields when displaying actual form.. """ def visible(self): return self.filter(visible=True) @python_2_unicode_compatible class AbstractField(models.Model): """ A field for a user-built form. """ label = models.CharField(_("Label"), max_length=settings.LABEL_MAX_LENGTH) slug = models.SlugField(_('Slug'), max_length=2000, blank=True, default="") field_type = models.IntegerField(_("Type"), choices=fields.NAMES) required = models.BooleanField(_("Required"), default=True) visible = models.BooleanField(_("Visible"), default=True) choices = models.CharField(_("Choices"), max_length=settings.CHOICES_MAX_LENGTH, blank=True, help_text="Comma separated options where applicable. If an option " "itself contains commas, surround the option starting with the %s" "character and ending with the %s character." % (settings.CHOICES_QUOTE, settings.CHOICES_UNQUOTE)) default = models.CharField(_("Default value"), blank=True, max_length=settings.FIELD_MAX_LENGTH) placeholder_text = models.CharField(_("Placeholder Text"), null=True, blank=True, max_length=100, editable=settings.USE_HTML5) help_text = models.CharField(_("Help text"), blank=True, max_length=settings.HELPTEXT_MAX_LENGTH) objects = FieldManager() class Meta: verbose_name = _("Field") verbose_name_plural = _("Fields") abstract = True def __str__(self): return str(self.label) def get_choices(self): """ Parse a comma separated choice string into a list of choices taking into account quoted choices using the ``settings.CHOICES_QUOTE`` and ``settings.CHOICES_UNQUOTE`` settings. """ choice = "" quoted = False for char in self.choices: if not quoted and char == settings.CHOICES_QUOTE: quoted = True elif quoted and char == settings.CHOICES_UNQUOTE: quoted = False elif char == "," and not quoted: choice = choice.strip() if choice: yield choice, choice choice = "" else: choice += char choice = choice.strip() if choice: yield choice, choice def is_a(self, *args): """ Helper that returns True if the field's type is given in any arg. """ return self.field_type in args class AbstractFormEntry(models.Model): """ An entry submitted via a user-built form. """ entry_time = models.DateTimeField(_("Date/time")) class Meta: verbose_name = _("Form entry") verbose_name_plural = _("Form entries") abstract = True class AbstractFieldEntry(models.Model): """ A single field value for a form entry submitted via a user-built form. """ field_id = models.IntegerField() value = models.CharField(max_length=settings.FIELD_MAX_LENGTH, null=True) class Meta: verbose_name = _("Form field entry") verbose_name_plural = _("Form field entries") abstract = True ################################################### # # # Default concrete implementations are below. # # # ################################################### class FormEntry(AbstractFormEntry): form = models.ForeignKey("Form", related_name="entries", on_delete=models.CASCADE) class FieldEntry(AbstractFieldEntry): entry = models.ForeignKey("FormEntry", related_name="fields", on_delete=models.CASCADE) class Form(AbstractForm): pass class Field(AbstractField): """ Implements automated field ordering. """ form = models.ForeignKey("Form", related_name="fields", on_delete=models.CASCADE) order = models.IntegerField(_("Order"), null=True, blank=True) class Meta(AbstractField.Meta): ordering = ("order",) def save(self, *args, **kwargs): if self.order is None: self.order = self.form.fields.count() if not self.slug: slug = slugify(self).replace('-', '_') self.slug = unique_slug(self.form.fields, "slug", slug) super(Field, self).save(*args, **kwargs) def delete(self, *args, **kwargs): fields_after = self.form.fields.filter(order__gte=self.order) fields_after.update(order=models.F("order") - 1) super(Field, self).delete(*args, **kwargs)
bsd-2-clause
hechtus/mopidy-gmusic
mopidy_gmusic/translator.py
2
1370
import hashlib from mopidy.models import Ref def album_to_ref(album): """Convert a mopidy album to a mopidy ref.""" name = "" for artist in album.artists: if len(name) > 0: name += ", " name += artist.name if (len(name)) > 0: name += " - " if album.name: name += album.name else: name += "Unknown Album" return Ref.directory(uri=album.uri, name=name) def artist_to_ref(artist): """Convert a mopidy artist to a mopidy ref.""" if artist.name: name = artist.name else: name = "Unknown artist" return Ref.directory(uri=artist.uri, name=name) def track_to_ref(track, with_track_no=False): """Convert a mopidy track to a mopidy ref.""" if with_track_no and track.track_no > 0: name = "%d - " % track.track_no else: name = "" for artist in track.artists: if len(name) > 0: name += ", " name += artist.name if (len(name)) > 0: name += " - " name += track.name return Ref.track(uri=track.uri, name=name) def get_images(song): if "albumArtRef" in song: return [ art_ref["url"] for art_ref in song["albumArtRef"] if "url" in art_ref ] return [] def create_id(u): return hashlib.md5(u.encode("utf-8")).hexdigest()
apache-2.0
openpermissions/perch
tests/unit/model/test_can_approve.py
1
8272
# -*- coding: utf-8 -*- # Copyright 2016 Open Permissions Platform Coalition # 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 unicode_literals from copy import deepcopy from functools import partial import couch import pytest from mock import patch from tornado.ioloop import IOLoop from tornado.httpclient import HTTPError from perch import Organisation, Service, Repository, UserOrganisation, User from ..util import make_future USER = { '_id': 'user0', 'type': 'user', 'email': 'user0@mail.test', 'password': User.hash_password('password0'), 'state': 'approved', 'role': 'user', 'has_agreed_to_terms': True, 'organisations': {} } sys_role = [ ('administrator', True), ('user', False) ] org_user_role = [ ({ 'state': 'pending', 'role': 'user' }, False), ({ 'state': 'approved', 'role': 'user' }, False), ({ 'state': 'rejected', 'role': 'user' }, False), ({ 'state': 'deactivated', 'role': 'user' }, False), ] org_admin_role = [ ({ 'state': 'pending', 'role': 'administrator' }, False), ({ 'state': 'approved', 'role': 'administrator' }, True), ({ 'state': 'rejected', 'role': 'administrator' }, False), ({ 'state': 'deactivated', 'role': 'administrator' }, False) ] class TestOrganisation(): organisation = Organisation(id='org0') @pytest.mark.parametrize("role,expected", sys_role) def test_can_approve(self, role, expected): u = deepcopy(USER) u['role'] = role user = User(**u) func = partial(self.organisation.can_approve, user) result = IOLoop.instance().run_sync(func) assert result == expected class TestService(): @pytest.mark.parametrize("role,expected", sys_role) def test_can_approve_external(self, role, expected): service = Service(id='serv0', service_type="external") u = deepcopy(USER) u['role'] = role user = User(**u) func = partial(service.can_approve, user) result = IOLoop.instance().run_sync(func) # External services should always be approvable assert result is True @pytest.mark.parametrize("role,expected", sys_role) def test_can_approve_external_provided(self, role, expected): service = Service(id='serv0', service_type="repository") u = deepcopy(USER) u['role'] = role user = User(**u) func = partial(service.can_approve, user, service_type='external') result = IOLoop.instance().run_sync(func) # External services should always be approvable assert result is True @pytest.mark.parametrize("role,expected", sys_role) def test_can_approve_non_external(self, role, expected): service = Service(id='serv0', service_type="repository") u = deepcopy(USER) u['role'] = role user = User(**u) func = partial(service.can_approve, user) result = IOLoop.instance().run_sync(func) assert result == expected @pytest.mark.parametrize("role,expected", sys_role) def test_can_approve_non_external_provided(self, role, expected): service = Service(id='serv0', service_type="external") u = deepcopy(USER) u['role'] = role user = User(**u) func = partial(service.can_approve, user, service_type='repository') result = IOLoop.instance().run_sync(func) assert result == expected class TestRepository(): repo = Repository(id='repo0', organistaion_id='org1', service_id='serv0') service = Service(id='serv0', organisation_id='org0') def test_can_approve_existing_service(self): with patch.object(Service, 'get', return_value=make_future(self.service)) as mock_response: user = User(**USER) func = partial(self.repo.can_approve, user) IOLoop.instance().run_sync(func) mock_response.assert_called_once_with('serv0') def test_can_approve_service_provided(self): with patch.object(Service, 'get', return_value=make_future(self.service)) as mock_response: user = User(**USER) func = partial(self.repo.can_approve, user, service_id='serv1') IOLoop.instance().run_sync(func) mock_response.assert_called_once_with('serv1') @pytest.mark.parametrize("role,expected", sys_role) def test_can_approve_no_org(self, role, expected): with patch.object(Service, 'get', return_value=make_future(self.service)): u = deepcopy(USER) u['role'] = role user = User(**u) func = partial(self.repo.can_approve, user) result = IOLoop.instance().run_sync(func) assert result == expected @pytest.mark.parametrize("org_info,expected", org_user_role) def test_can_approve_user_joins(self, org_info, expected): with patch.object(Service, 'get', return_value=make_future(self.service)): u = deepcopy(USER) u['organisations']['org0'] = org_info user = User(**u) func = partial(self.repo.can_approve, user) result = IOLoop.instance().run_sync(func) assert result == expected @pytest.mark.parametrize("org_info,expected", org_admin_role) def test_can_approve_repo_admin_joins(self, org_info, expected): with patch.object(Service, 'get', return_value=make_future(self.service)): u = deepcopy(USER) u['organisations']['org0'] = org_info user = User(**u) func = partial(self.repo.can_approve, user) result = IOLoop.instance().run_sync(func) assert result == expected @pytest.mark.parametrize("org_info,expected", org_admin_role) def test_can_approve_srv_admin_joins(self, org_info, expected): with patch.object(Service, 'get', return_value=make_future(self.service)): u = deepcopy(USER) u['organisations']['org1'] = org_info user = User(**u) func = partial(self.repo.can_approve, user) result = IOLoop.instance().run_sync(func) assert result is False def test_can_approve_no_service(self): with patch.object(Service, 'get', side_effect=couch.NotFound(HTTPError(404, 'Not Found'))): user = User(**USER) func = partial(self.repo.can_approve, user) result = IOLoop.instance().run_sync(func) assert result is False class TestUserOrganisation(): user_org = UserOrganisation(organisation_id='org0') @pytest.mark.parametrize("org_info,expected", sys_role) def test_can_approve_no_org(self, org_info, expected): u = deepcopy(USER) u['role'] = org_info user = User(**u) func = partial(self.user_org.can_approve, user) result = IOLoop.instance().run_sync(func) assert result == expected @pytest.mark.parametrize("org_info,expected", org_user_role) def test_can_approve_user_joins(self, org_info, expected): u = deepcopy(USER) u['organisations']['org0'] = org_info user = User(**u) func = partial(self.user_org.can_approve, user) result = IOLoop.instance().run_sync(func) assert result == expected @pytest.mark.parametrize("org_info,expected", org_admin_role) def test_can_approve_admin_joins(self, org_info, expected): u = deepcopy(USER) u['organisations']['org0'] = org_info user = User(**u) func = partial(self.user_org.can_approve, user) result = IOLoop.instance().run_sync(func) assert result == expected
apache-2.0
pdellaert/ansible
lib/ansible/plugins/callback/yaml.py
38
4869
# (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' callback: yaml type: stdout short_description: yaml-ized Ansible screen output version_added: 2.5 description: - Ansible output that can be quite a bit easier to read than the default JSON formatting. extends_documentation_fragment: - default_callback requirements: - set as stdout in configuration ''' import yaml import json import re import string import sys from ansible.module_utils._text import to_bytes, to_text from ansible.module_utils.six import string_types from ansible.parsing.yaml.dumper import AnsibleDumper from ansible.plugins.callback import CallbackBase, strip_internal_keys, module_response_deepcopy from ansible.plugins.callback.default import CallbackModule as Default # from http://stackoverflow.com/a/15423007/115478 def should_use_block(value): """Returns true if string should be in block format""" for c in u"\u000a\u000d\u001c\u001d\u001e\u0085\u2028\u2029": if c in value: return True return False def my_represent_scalar(self, tag, value, style=None): """Uses block style for multi-line strings""" if style is None: if should_use_block(value): style = '|' # we care more about readable than accuracy, so... # ...no trailing space value = value.rstrip() # ...and non-printable characters value = ''.join(x for x in value if x in string.printable) # ...tabs prevent blocks from expanding value = value.expandtabs() # ...and odd bits of whitespace value = re.sub(r'[\x0b\x0c\r]', '', value) # ...as does trailing space value = re.sub(r' +\n', '\n', value) else: style = self.default_style node = yaml.representer.ScalarNode(tag, value, style=style) if self.alias_key is not None: self.represented_objects[self.alias_key] = node return node class CallbackModule(Default): """ Variation of the Default output which uses nicely readable YAML instead of JSON for printing results. """ CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'stdout' CALLBACK_NAME = 'yaml' def __init__(self): super(CallbackModule, self).__init__() yaml.representer.BaseRepresenter.represent_scalar = my_represent_scalar def _dump_results(self, result, indent=None, sort_keys=True, keep_invocation=False): if result.get('_ansible_no_log', False): return json.dumps(dict(censored="The output has been hidden due to the fact that 'no_log: true' was specified for this result")) # All result keys stating with _ansible_ are internal, so remove them from the result before we output anything. abridged_result = strip_internal_keys(module_response_deepcopy(result)) # remove invocation unless specifically wanting it if not keep_invocation and self._display.verbosity < 3 and 'invocation' in result: del abridged_result['invocation'] # remove diff information from screen output if self._display.verbosity < 3 and 'diff' in result: del abridged_result['diff'] # remove exception from screen output if 'exception' in abridged_result: del abridged_result['exception'] dumped = '' # put changed and skipped into a header line if 'changed' in abridged_result: dumped += 'changed=' + str(abridged_result['changed']).lower() + ' ' del abridged_result['changed'] if 'skipped' in abridged_result: dumped += 'skipped=' + str(abridged_result['skipped']).lower() + ' ' del abridged_result['skipped'] # if we already have stdout, we don't need stdout_lines if 'stdout' in abridged_result and 'stdout_lines' in abridged_result: abridged_result['stdout_lines'] = '<omitted>' # if we already have stderr, we don't need stderr_lines if 'stderr' in abridged_result and 'stderr_lines' in abridged_result: abridged_result['stderr_lines'] = '<omitted>' if abridged_result: dumped += '\n' dumped += to_text(yaml.dump(abridged_result, allow_unicode=True, width=1000, Dumper=AnsibleDumper, default_flow_style=False)) # indent by a couple of spaces dumped = '\n '.join(dumped.split('\n')).rstrip() return dumped def _serialize_diff(self, diff): return to_text(yaml.dump(diff, allow_unicode=True, width=1000, Dumper=AnsibleDumper, default_flow_style=False))
gpl-3.0
iABC2XYZ/abc
BPM/Paper/DealData.py
1
1583
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ @author: Peiyong Jiang 作者: 姜培勇 jiangpeiyong@impcas.ac.cn 本文件解释: """ import numpy as np import matplotlib.pyplot as plt nameFolder='/home/e/ABC/abc/BPM/Paper/' nameData=nameFolder+'Rec_1106_2046.dat' exData=np.loadtxt(nameData) ''' for i in range(24): plt.figure(1) plt.clf() plt.plot(exData[:,i],'.') plt.title(i) plt.pause(1) ''' ''' for i in range(10,24): plt.figure(1) plt.clf() plt.hist(exData[:,i],1000) plt.title(i) plt.pause(1) ''' exDataMean=[] for i in range(14,24): exDataMeanTmp= np.mean(exData[:,i]) exDataMean.append(exDataMeanTmp) print "+" print str(np.round(np.array(exDataMean)*100.)/100.).replace(' ',' ').replace(' ',' ').replace(' ',' ').replace(' ',' ').replace(' ',',') print ('\n') exDataMean[0]=0.00 exDataMean[7]=0.00 print "-" print str(np.round(-np.array(exDataMean)*100.)/100.).replace(' ',' ').replace(' ',' ').replace(' ',' ').replace(' ',' ').replace(' ',',') ## exDataMean=[] for i in range(14,24): exDataMeanTmp= np.mean(exData[:,i]) exDataMean.append(exDataMeanTmp) bpms=exData[:,14:24] for i in range(10): bpms[:,i]-=exDataMean[i] rBPM=[] for i in range(np.shape(bpms)[0]): rBPM.append(np.sum(np.square(bpms[i,:]))) idMinR=np.argmin(rBPM) print idMinR,rBPM[idMinR] print '---- I -------' print (exData[idMinR,14:24]) print exDataMean print np.sum(np.square(exData[idMinR+1,14:24]-exDataMean)) #plt.plot(rBPM) #plt.show() #print np.where(np.min(rBPM)==rBPM)
gpl-3.0
soldag/home-assistant
homeassistant/components/nzbget/config_flow.py
10
4404
"""Config flow for NZBGet.""" import logging from typing import Any, Dict, Optional import voluptuous as vol from homeassistant.config_entries import CONN_CLASS_LOCAL_POLL, ConfigFlow, OptionsFlow from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_SCAN_INTERVAL, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import callback from homeassistant.helpers.typing import ConfigType, HomeAssistantType from .const import ( DEFAULT_NAME, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DEFAULT_SSL, DEFAULT_VERIFY_SSL, ) from .const import DOMAIN # pylint: disable=unused-import from .coordinator import NZBGetAPI, NZBGetAPIException _LOGGER = logging.getLogger(__name__) def validate_input(hass: HomeAssistantType, data: dict) -> Dict[str, Any]: """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ nzbget_api = NZBGetAPI( data[CONF_HOST], data.get(CONF_USERNAME), data.get(CONF_PASSWORD), data[CONF_SSL], data[CONF_VERIFY_SSL], data[CONF_PORT], ) nzbget_api.version() return True class NZBGetConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for NZBGet.""" VERSION = 1 CONNECTION_CLASS = CONN_CLASS_LOCAL_POLL @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return NZBGetOptionsFlowHandler(config_entry) async def async_step_import( self, user_input: Optional[ConfigType] = None ) -> Dict[str, Any]: """Handle a flow initiated by configuration file.""" if CONF_SCAN_INTERVAL in user_input: user_input[CONF_SCAN_INTERVAL] = user_input[CONF_SCAN_INTERVAL].seconds return await self.async_step_user(user_input) async def async_step_user( self, user_input: Optional[ConfigType] = None ) -> Dict[str, Any]: """Handle a flow initiated by the user.""" if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") errors = {} if user_input is not None: if CONF_VERIFY_SSL not in user_input: user_input[CONF_VERIFY_SSL] = DEFAULT_VERIFY_SSL try: await self.hass.async_add_executor_job( validate_input, self.hass, user_input ) except NZBGetAPIException: errors["base"] = "cannot_connect" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") return self.async_abort(reason="unknown") else: return self.async_create_entry( title=user_input[CONF_HOST], data=user_input, ) data_schema = { vol.Required(CONF_HOST): str, vol.Optional(CONF_NAME, default=DEFAULT_NAME): str, vol.Optional(CONF_USERNAME): str, vol.Optional(CONF_PASSWORD): str, vol.Optional(CONF_PORT, default=DEFAULT_PORT): int, vol.Optional(CONF_SSL, default=DEFAULT_SSL): bool, } if self.show_advanced_options: data_schema[ vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL) ] = bool return self.async_show_form( step_id="user", data_schema=vol.Schema(data_schema), errors=errors or {}, ) class NZBGetOptionsFlowHandler(OptionsFlow): """Handle NZBGet client options.""" def __init__(self, config_entry): """Initialize options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input: Optional[ConfigType] = None): """Manage NZBGet options.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) options = { vol.Optional( CONF_SCAN_INTERVAL, default=self.config_entry.options.get( CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL ), ): int, } return self.async_show_form(step_id="init", data_schema=vol.Schema(options))
apache-2.0
sxpert/ansible-modules-core
packaging/language/gem.py
76
8146
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Johan Wiren <johan.wiren.se@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = ''' --- module: gem short_description: Manage Ruby gems description: - Manage installation and uninstallation of Ruby gems. version_added: "1.1" options: name: description: - The name of the gem to be managed. required: true state: description: - The desired state of the gem. C(latest) ensures that the latest version is installed. required: false choices: [present, absent, latest] default: present gem_source: description: - The path to a local gem used as installation source. required: false include_dependencies: description: - Whether to include dependencies or not. required: false choices: [ "yes", "no" ] default: "yes" repository: description: - The repository from which the gem will be installed required: false aliases: [source] user_install: description: - Install gem in user's local gems cache or for all users required: false default: "yes" version_added: "1.3" executable: description: - Override the path to the gem executable required: false version_added: "1.4" version: description: - Version of the gem to be installed/removed. required: false pre_release: description: - Allow installation of pre-release versions of the gem. required: false default: "no" version_added: "1.6" include_doc: description: - Install with or without docs. required: false default: "no" version_added: "2.0" build_flags: description: - Allow adding build flags for gem compilation required: false version_added: "2.0" author: - "Ansible Core Team" - "Johan Wiren" ''' EXAMPLES = ''' # Installs version 1.0 of vagrant. - gem: name=vagrant version=1.0 state=present # Installs latest available version of rake. - gem: name=rake state=latest # Installs rake version 1.0 from a local gem on disk. - gem: name=rake gem_source=/path/to/gems/rake-1.0.gem state=present ''' import re def get_rubygems_path(module): if module.params['executable']: return module.params['executable'].split(' ') else: return [ module.get_bin_path('gem', True) ] def get_rubygems_version(module): cmd = get_rubygems_path(module) + [ '--version' ] (rc, out, err) = module.run_command(cmd, check_rc=True) match = re.match(r'^(\d+)\.(\d+)\.(\d+)', out) if not match: return None return tuple(int(x) for x in match.groups()) def get_installed_versions(module, remote=False): cmd = get_rubygems_path(module) cmd.append('query') if remote: cmd.append('--remote') if module.params['repository']: cmd.extend([ '--source', module.params['repository'] ]) cmd.append('-n') cmd.append('^%s$' % module.params['name']) (rc, out, err) = module.run_command(cmd, check_rc=True) installed_versions = [] for line in out.splitlines(): match = re.match(r"\S+\s+\((.+)\)", line) if match: versions = match.group(1) for version in versions.split(', '): installed_versions.append(version.split()[0]) return installed_versions def exists(module): if module.params['state'] == 'latest': remoteversions = get_installed_versions(module, remote=True) if remoteversions: module.params['version'] = remoteversions[0] installed_versions = get_installed_versions(module) if module.params['version']: if module.params['version'] in installed_versions: return True else: if installed_versions: return True return False def uninstall(module): if module.check_mode: return cmd = get_rubygems_path(module) cmd.append('uninstall') if module.params['version']: cmd.extend([ '--version', module.params['version'] ]) else: cmd.append('--all') cmd.append('--executable') cmd.append(module.params['name']) module.run_command(cmd, check_rc=True) def install(module): if module.check_mode: return ver = get_rubygems_version(module) if ver: major = ver[0] else: major = None cmd = get_rubygems_path(module) cmd.append('install') if module.params['version']: cmd.extend([ '--version', module.params['version'] ]) if module.params['repository']: cmd.extend([ '--source', module.params['repository'] ]) if not module.params['include_dependencies']: cmd.append('--ignore-dependencies') else: if major and major < 2: cmd.append('--include-dependencies') if module.params['user_install']: cmd.append('--user-install') else: cmd.append('--no-user-install') if module.params['pre_release']: cmd.append('--pre') if not module.params['include_doc']: if major and major < 2: cmd.append('--no-rdoc') cmd.append('--no-ri') else: cmd.append('--no-document') cmd.append(module.params['gem_source']) if module.params['build_flags']: cmd.extend([ '--', module.params['build_flags'] ]) module.run_command(cmd, check_rc=True) def main(): module = AnsibleModule( argument_spec = dict( executable = dict(required=False, type='str'), gem_source = dict(required=False, type='str'), include_dependencies = dict(required=False, default=True, type='bool'), name = dict(required=True, type='str'), repository = dict(required=False, aliases=['source'], type='str'), state = dict(required=False, default='present', choices=['present','absent','latest'], type='str'), user_install = dict(required=False, default=True, type='bool'), pre_release = dict(required=False, default=False, type='bool'), include_doc = dict(required=False, default=False, type='bool'), version = dict(required=False, type='str'), build_flags = dict(required=False, type='str'), ), supports_check_mode = True, mutually_exclusive = [ ['gem_source','repository'], ['gem_source','version'] ], ) if module.params['version'] and module.params['state'] == 'latest': module.fail_json(msg="Cannot specify version when state=latest") if module.params['gem_source'] and module.params['state'] == 'latest': module.fail_json(msg="Cannot maintain state=latest when installing from local source") if not module.params['gem_source']: module.params['gem_source'] = module.params['name'] changed = False if module.params['state'] in [ 'present', 'latest']: if not exists(module): install(module) changed = True elif module.params['state'] == 'absent': if exists(module): uninstall(module) changed = True result = {} result['name'] = module.params['name'] result['state'] = module.params['state'] if module.params['version']: result['version'] = module.params['version'] result['changed'] = changed module.exit_json(**result) # import module snippets from ansible.module_utils.basic import * main()
gpl-3.0
rmak/splunk-sdk-python
examples/abc/a.py
1
2201
# Copyright 2011 Splunk, 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. """Retrieves a list of installed apps from Splunk by making REST API calls using Python's httplib module.""" import httplib import urllib from xml.etree import ElementTree HOST = "localhost" PORT = 8089 USERNAME = "admin" PASSWORD = "changeme" # Present credentials to Splunk and retrieve the session key connection = httplib.HTTPSConnection(HOST, PORT) body = urllib.urlencode({'username': USERNAME, 'password': PASSWORD}) headers = { 'Content-Type': "application/x-www-form-urlencoded", 'Content-Length': str(len(body)), 'Host': HOST, 'User-Agent': "a.py/1.0", 'Accept': "*/*" } try: connection.request("POST", "/services/auth/login", body, headers) response = connection.getresponse() finally: connection.close() if response.status != 200: raise Exception, "%d (%s)" % (response.status, response.reason) body = response.read() sessionKey = ElementTree.XML(body).findtext("./sessionKey") # Now make the request to Splunk for list of installed apps connection = httplib.HTTPSConnection(HOST, PORT) headers = { 'Content-Length': "0", 'Host': HOST, 'User-Agent': "a.py/1.0", 'Accept': "*/*", 'Authorization': "Splunk %s" % sessionKey, } try: connection.request("GET", "/services/apps/local", "", headers) response = connection.getresponse() finally: connection.close() if response.status != 200: raise Exception, "%d (%s)" % (response.status, response.reason) body = response.read() data = ElementTree.XML(body) apps = data.findall("{http://www.w3.org/2005/Atom}entry/{http://www.w3.org/2005/Atom}title") for app in apps: print app.text
apache-2.0
AgentN/namebench
nb_third_party/dns/rdtypes/mxbase.py
248
3969
# Copyright (C) 2003-2007, 2009, 2010 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """MX-like base classes.""" import cStringIO import struct import dns.exception import dns.rdata import dns.name class MXBase(dns.rdata.Rdata): """Base class for rdata that is like an MX record. @ivar preference: the preference value @type preference: int @ivar exchange: the exchange name @type exchange: dns.name.Name object""" __slots__ = ['preference', 'exchange'] def __init__(self, rdclass, rdtype, preference, exchange): super(MXBase, self).__init__(rdclass, rdtype) self.preference = preference self.exchange = exchange def to_text(self, origin=None, relativize=True, **kw): exchange = self.exchange.choose_relativity(origin, relativize) return '%d %s' % (self.preference, exchange) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): preference = tok.get_uint16() exchange = tok.get_name() exchange = exchange.choose_relativity(origin, relativize) tok.get_eol() return cls(rdclass, rdtype, preference, exchange) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): pref = struct.pack("!H", self.preference) file.write(pref) self.exchange.to_wire(file, compress, origin) def to_digestable(self, origin = None): return struct.pack("!H", self.preference) + \ self.exchange.to_digestable(origin) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): (preference, ) = struct.unpack('!H', wire[current : current + 2]) current += 2 rdlen -= 2 (exchange, cused) = dns.name.from_wire(wire[: current + rdlen], current) if cused != rdlen: raise dns.exception.FormError if not origin is None: exchange = exchange.relativize(origin) return cls(rdclass, rdtype, preference, exchange) from_wire = classmethod(from_wire) def choose_relativity(self, origin = None, relativize = True): self.exchange = self.exchange.choose_relativity(origin, relativize) def _cmp(self, other): sp = struct.pack("!H", self.preference) op = struct.pack("!H", other.preference) v = cmp(sp, op) if v == 0: v = cmp(self.exchange, other.exchange) return v class UncompressedMX(MXBase): """Base class for rdata that is like an MX record, but whose name is not compressed when converted to DNS wire format, and whose digestable form is not downcased.""" def to_wire(self, file, compress = None, origin = None): super(UncompressedMX, self).to_wire(file, None, origin) def to_digestable(self, origin = None): f = cStringIO.StringIO() self.to_wire(f, None, origin) return f.getvalue() class UncompressedDowncasingMX(MXBase): """Base class for rdata that is like an MX record, but whose name is not compressed when convert to DNS wire format.""" def to_wire(self, file, compress = None, origin = None): super(UncompressedDowncasingMX, self).to_wire(file, None, origin)
apache-2.0
prezi/python-github3
pygithub3/tests/requests/test_core.py
8
3455
# -*- encoding: utf-8 -*- from pygithub3.exceptions import (UriInvalid, RequestDoesNotExist, ValidationError, InvalidBodySchema) from pygithub3.requests.base import Factory, Body, Request from pygithub3.tests.utils.base import DummyRequest, dummy_json from pygithub3.tests.utils.core import TestCase from pygithub3.tests.utils.requests import (RequestWithArgs, RequestCleanedUri, RequestBodyInvalidSchema, RequestCleanedBody) class TestFactory(TestCase): def setUp(self): self.f = Factory() def test_BUILDER_with_invalid_action(self): self.assertRaises(UriInvalid, self.f, 'invalid') self.assertRaises(UriInvalid, self.f, 'invalid.') self.assertRaises(UriInvalid, self.f, '.invalid') def test_BUILDER_with_fake_action(self): self.assertRaises(RequestDoesNotExist, self.f, 'users.fake') self.assertRaises(RequestDoesNotExist, self.f, 'fake.users') def test_BUILDER_builds_users(self): """ Users.get as real test because it wouldn't be useful mock the import-jit process """ request = self.f('users.get') self.assertIsInstance(request, Request) class TestRequest(TestCase): def test_SIMPLE_with_correct_args(self): request = RequestWithArgs(arg1='arg1', arg2='arg2') self.assertEqual(str(request), 'URI/arg1/arg2') def test_SIMPLE_without_needed_args(self): request = RequestWithArgs() self.assertRaises(ValidationError, str, request) def test_with_cleaned_uri(self): """ Its real uri has args but I override `clean_uri` method, so if `nomatters` arg exists, change uri to `URI` """ request = RequestCleanedUri(notmatters='test') self.assertEqual(str(request), 'URI') def test_with_cleaned_body(self): self.assertRaises(ValidationError, RequestCleanedBody) def test_with_invalid_schema(self): self.assertRaises(InvalidBodySchema, RequestBodyInvalidSchema) def test_body_without_schema(self): request = DummyRequest(body=dict(arg1='test')) self.assertEqual(request.get_body(), dict(arg1='test')) self.assertEqual(request.body.schema, set(())) self.assertEqual(request.body.required, set(())) def test_without_body_and_without_schema(self): request = DummyRequest() self.assertIsNone(request.get_body()) @dummy_json class TestRequestBodyWithSchema(TestCase): def setUp(self): valid_body = dict(schema=('arg1', 'arg2'), required=('arg1', )) self.b = Body({}, **valid_body) def test_with_body_empty_and_schema_permissive(self): self.b.schema = ('arg1', 'arg2', '...') self.b.required = () self.assertEqual(self.b.dumps(), {}) def test_with_required(self): self.b.content = dict(arg1='arg1') self.assertEqual(self.b.dumps(), dict(arg1='arg1')) def test_without_required(self): self.b.content = dict(arg2='arg2') self.assertRaises(ValidationError, self.b.dumps) def test_with_invalid(self): self.b.content = 'invalid' self.assertRaises(ValidationError, self.b.dumps) def test_with_body_as_None(self): self.b.content = None self.assertRaises(ValidationError, self.b.dumps) def test_only_valid_keys(self): self.b.content = dict(arg1='arg1', arg2='arg2', fake='test') self.assertEqual(self.b.dumps(), dict(arg1='arg1', arg2='arg2'))
isc
sk7/django-social-auth
setup.py
4
2193
# -*- coding: utf-8 -*- """Setup file for easy installation""" from os.path import join, dirname from setuptools import setup version = __import__('social_auth').__version__ LONG_DESCRIPTION = """ Django Social Auth is an easy to setup social authentication/registration mechanism for Django projects. Crafted using base code from django-twitter-oauth_ and django-openid-auth_, implements a common interface to define new authentication providers from third parties. """ def long_description(): """Return long description from README.rst if it's present because it doesn't get installed.""" try: return open(join(dirname(__file__), 'README.rst')).read() except IOError: return LONG_DESCRIPTION setup(name='django-social-auth', version=version, author='Matías Aguirre', author_email='matiasaguirre@gmail.com', description='Django social authentication made simple.', license='BSD', keywords='django, openid, oauth, social auth, application', url='https://github.com/omab/django-social-auth', packages=['social_auth', 'social_auth.management', 'social_auth.management.commands', 'social_auth.backends', 'social_auth.backends.contrib', 'social_auth.backends.pipeline', 'social_auth.migrations', 'social_auth.tests', 'social_auth.db'], package_data={'social_auth': ['locale/*/LC_MESSAGES/*']}, long_description=long_description(), install_requires=['Django>=1.2.5', 'oauth2>=1.5.167', 'python-openid>=2.2'], classifiers=['Framework :: Django', 'Development Status :: 4 - Beta', 'Topic :: Internet', 'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Environment :: Web Environment', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7'], zip_safe=False)
bsd-3-clause
grap/OpenUpgrade
openerp/addons/base/tests/test_res_lang.py
384
2104
import unittest2 import openerp.tests.common as common class test_res_lang(common.TransactionCase): def test_00_intersperse(self): from openerp.addons.base.res.res_lang import intersperse assert intersperse("", []) == ("", 0) assert intersperse("0", []) == ("0", 0) assert intersperse("012", []) == ("012", 0) assert intersperse("1", []) == ("1", 0) assert intersperse("12", []) == ("12", 0) assert intersperse("123", []) == ("123", 0) assert intersperse("1234", []) == ("1234", 0) assert intersperse("123456789", []) == ("123456789", 0) assert intersperse("&ab%#@1", []) == ("&ab%#@1", 0) assert intersperse("0", []) == ("0", 0) assert intersperse("0", [1]) == ("0", 0) assert intersperse("0", [2]) == ("0", 0) assert intersperse("0", [200]) == ("0", 0) assert intersperse("12345678", [1], '.') == ('1234567.8', 1) assert intersperse("12345678", [1], '.') == ('1234567.8', 1) assert intersperse("12345678", [2], '.') == ('123456.78', 1) assert intersperse("12345678", [2,1], '.') == ('12345.6.78', 2) assert intersperse("12345678", [2,0], '.') == ('12.34.56.78', 3) assert intersperse("12345678", [-1,2], '.') == ('12345678', 0) assert intersperse("12345678", [2,-1], '.') == ('123456.78', 1) assert intersperse("12345678", [2,0,1], '.') == ('12.34.56.78', 3) assert intersperse("12345678", [2,0,0], '.') == ('12.34.56.78', 3) assert intersperse("12345678", [2,0,-1], '.') == ('12.34.56.78', 3) assert intersperse("12345678", [3,3,3,3], '.') == ('12.345.678', 2) assert intersperse("abc1234567xy", [2], '.') == ('abc1234567.xy', 1) assert intersperse("abc1234567xy8", [2], '.') == ('abc1234567x.y8', 1) # ... w.r.t. here. assert intersperse("abc12", [3], '.') == ('abc12', 0) assert intersperse("abc12", [2], '.') == ('abc12', 0) assert intersperse("abc12", [1], '.') == ('abc1.2', 1) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
QualiSystems/Ansible-Shell
package/tests/test_zip_service.py
1
1509
from unittest import TestCase from zipfile import ZipFile from io import BytesIO from mock import patch, Mock from cloudshell.cm.ansible.domain.zip_service import ZipService from tests.helpers import Any class TestZipService(TestCase): def setUp(self): self.zip_file = ZipFile(BytesIO(), 'w') self.zip_file.extractall = Mock() self.zip_file.extract = Mock() self.zip_patcher = patch('cloudshell.cm.ansible.domain.zip_service.ZipFile') self.zip_patcher.start().return_value = self.zip_file self.zip_service = ZipService() def tearDown(self): self.zip_patcher.stop() def test_regulsr_zip(self): self.zip_file.writestr('playbook.yml', 'some yml code') self.zip_file.writestr('Roles/', 'some yml code') self.zip_file.writestr('Roles/a.yml', 'some yml code') self.zip_service.extract_all('') self.zip_file.extractall.assert_called_once() def test_inner_folder_zip(self): self.zip_file.writestr('myzip/', '') self.zip_file.writestr('myzip/playbook.yml', 'some yml code') self.zip_file.writestr('myzip/Roles/', '') self.zip_file.writestr('myzip/Roles/a.yml', 'some yml code') self.zip_service.extract_all('') self.assertEqual(self.zip_file.extract.call_count, 2) self.zip_file.extract.assert_any_call(Any(lambda x: x.filename == 'playbook.yml')) self.zip_file.extract.assert_any_call(Any(lambda x: x.filename == 'Roles/a.yml'))
apache-2.0
zstyblik/infernal-twin
build/reportlab/build/lib.linux-i686-2.7/reportlab/graphics/barcode/qr.py
29
6538
# # ReportLab QRCode widget # # Ported from the Javascript library QRCode for Javascript by Sam Curren # # URL: http://www.d-project.com/ # http://d-project.googlecode.com/svn/trunk/misc/qrcode/js/qrcode.js # qrcode.js is copyright (c) 2009 Kazuhiko Arase # # Original ReportLab module by German M. Bravo # # modified and improved by Anders Hammarquist <iko@openend.se> # and used with permission under the ReportLab License # # The word "QR Code" is registered trademark of # DENSO WAVE INCORPORATED # http://www.denso-wave.com/qrcode/faqpatent-e.html __all__ = ('QrCodeWidget') import itertools from reportlab.platypus.flowables import Flowable from reportlab.graphics.shapes import Group, Rect from reportlab.lib import colors from reportlab.lib.validators import isNumber, isNumberOrNone, isColor, isString, Validator from reportlab.lib.attrmap import AttrMap, AttrMapValue from reportlab.graphics.widgetbase import Widget from reportlab.lib.units import mm try: from reportlab.lib.utils import asUnicodeEx, isUnicode except ImportError: # ReportLab 2.x compatibility def asUnicodeEx(v, enc='utf8'): if isinstance(v, unicode): return v if isinstance(v, str): return v.decode(enc) return str(v).decode(enc) def isUnicode(v): return isinstance(v, unicode) from reportlab.graphics.barcode import qrencoder class isLevel(Validator): def test(self, x): return x in ['L', 'M', 'Q', 'H'] isLevel = isLevel() class isUnicodeOrQRList(Validator): def _test(self, x): if isUnicode(x): return True if all(isinstance(v, qrencoder.QR) for v in x): return True return False def test(self, x): return self._test(x) or self.normalizeTest(x) def normalize(self, x): if self._test(x): return x try: return asUnicodeEx(x) except UnicodeError: raise ValueError("Can't convert to unicode: %r" % x) isUnicodeOrQRList = isUnicodeOrQRList() class SRect(Rect): def __init__(self, x, y, width, height, fillColor=colors.black): Rect.__init__(self, x, y, width, height, fillColor=fillColor, strokeColor=None, strokeWidth=0) class QrCodeWidget(Widget): codeName = "QR" _attrMap = AttrMap( BASE = Widget, value = AttrMapValue(isUnicodeOrQRList, desc='QRCode data'), x = AttrMapValue(isNumber, desc='x-coord'), y = AttrMapValue(isNumber, desc='y-coord'), barFillColor = AttrMapValue(isColor, desc='bar color'), barWidth = AttrMapValue(isNumber, desc='Width of bars.'), # maybe should be named just width? barHeight = AttrMapValue(isNumber, desc='Height of bars.'), # maybe should be named just height? barBorder = AttrMapValue(isNumber, desc='Width of QR border.'), # maybe should be named qrBorder? barLevel = AttrMapValue(isLevel, desc='QR Code level.'), # maybe should be named qrLevel qrVersion = AttrMapValue(isNumberOrNone, desc='QR Code version. None for auto'), # Below are ignored, they make no sense barStrokeWidth = AttrMapValue(isNumber, desc='Width of bar borders.'), barStrokeColor = AttrMapValue(isColor, desc='Color of bar borders.'), ) x = 0 y = 0 barFillColor = colors.black barStrokeColor = None barStrokeWidth = 0 barHeight = 32*mm barWidth = 32*mm barBorder = 4 barLevel = 'L' qrVersion = None value = None def __init__(self, value='Hello World', **kw): self.value = isUnicodeOrQRList.normalize(value) for k, v in kw.items(): setattr(self, k, v) ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.barLevel) self.__dict__['qr'] = qrencoder.QRCode(self.qrVersion, ec_level) if isUnicode(self.value): self.addData(self.value) elif self.value: for v in self.value: self.addData(v) def addData(self, value): self.qr.addData(value) def draw(self): self.qr.make() g = Group() color = self.barFillColor border = self.barBorder width = self.barWidth height = self.barHeight x = self.x y = self.y g.add(SRect(x, y, width, height, fillColor=None)) moduleCount = self.qr.getModuleCount() minwh = float(min(width, height)) boxsize = minwh / (moduleCount + border * 2.0) offsetX = (width - minwh) / 2.0 offsetY = (minwh - height) / 2.0 for r, row in enumerate(self.qr.modules): row = map(bool, row) c = 0 for t, tt in itertools.groupby(row): isDark = t count = len(list(tt)) if isDark: x = (c + border) * boxsize y = (r + border + 1) * boxsize s = SRect(offsetX + x, offsetY + height - y, count * boxsize, boxsize) g.add(s) c += count return g # Flowable version class QrCode(Flowable): height = 32*mm width = 32*mm qrBorder = 4 qrLevel = 'L' qrVersion = None value = None def __init__(self, value=None, **kw): self.value = isUnicodeOrQRList.normalize(value) for k, v in kw.items(): setattr(self, k, v) ec_level = getattr(qrencoder.QRErrorCorrectLevel, self.qrLevel) self.qr = qrencoder.QRCode(self.qrVersion, ec_level) if isUnicode(self.value): self.addData(self.value) elif self.value: for v in self.value: self.addData(v) def addData(self, value): self.qr.addData(value) def draw(self): self.qr.make() moduleCount = self.qr.getModuleCount() border = self.qrBorder xsize = self.width / (moduleCount + border * 2.0) ysize = self.height / (moduleCount + border * 2.0) for r, row in enumerate(self.qr.modules): row = map(bool, row) c = 0 for t, tt in itertools.groupby(row): isDark = t count = len(list(tt)) if isDark: x = (c + border) * xsize y = self.height - (r + border + 1) * ysize self.rect(x, y, count * xsize, ysize * 1.05) c += count def rect(self, x, y, w, h): self.canv.rect(x, y, w, h, stroke=0, fill=1)
gpl-3.0
beni55/ChatterBot
examples/terminal_mongo_example.py
5
1297
from chatterbot import ChatBot # Create a new instance of a ChatBot bot = ChatBot("Terminal", storage_adapter="chatterbot.adapters.storage.MongoDatabaseAdapter", logic_adapter="chatterbot.adapters.logic.ClosestMatchAdapter", io_adapter="chatterbot.adapters.io.TerminalAdapter", database="chatterbot-database") user_input = "Type something to begin..." print(user_input) ''' In this example we use a while loop combined with a try-except statement. This allows us to have a conversation with the chat bot until we press ctrl-c or ctrl-d on the keyboard. ''' while True: try: ''' ChatterBot's get_input method uses io adapter to get new input for the bot to respond to. In this example, the TerminalAdapter gets the input from the user's terminal. Other io adapters might retrieve input differently, such as from various web APIs. ''' user_input = bot.get_input() ''' The get_response method also uses the io adapter to determine how the bot's output should be returned. In the case of the TerminalAdapter, the output is printed to the user's terminal. ''' bot_input = bot.get_response(user_input) except (KeyboardInterrupt, EOFError, SystemExit): break
bsd-3-clause
msebire/intellij-community
python/testData/typeshed/stdlib/2/collections_test.py
12
4791
def test_namedtuple(): from collections import namedtuple assert namedtuple("Point", "x y")(1, 2).x == 1 assert namedtuple(u"Point", u"x y", verbose=False, rename=False)(1, 2).x == 1 assert namedtuple(b"Point", b"x y", verbose=True, rename=True)(1, 2).x == 1 assert namedtuple("Point", ["x", "y"])(1, 2).x == 1 assert namedtuple(u"Point", [u"x", u"y"])(1, 2).x == 1 assert namedtuple(b"Point", [b"x", b"y"])(1, 2).x == 1 assert namedtuple("Point", [b"x", u"y"])(1, 2).x == 1 Point = namedtuple('Point', 'x y') p = Point(1, 2) assert p == Point(1, 2) assert p._replace(y=3.14).y == 3.14 assert p._asdict()['x'] == 1 assert p._fields == ('x', 'y') assert p == (1, 2) assert (p.x, p.y) == (1, 2) assert p[0] + p[1] == 3 assert p.index(1) == 0 assert Point._make([1, 3.14]).y == 3.14 def test_deque(): from collections import deque d = deque([2]) assert list(deque([1, 2, 3])) == [1, 2, 3] assert list(deque([1, 2, 3], 2)) == [2, 3] assert deque([1, 2, 3]).maxlen is None assert deque([1, 2, 3], 2).maxlen == 2 d.append(3) d.appendleft(1) assert list(d) == [1, 2, 3] d.clear() assert len(d) == 0 d.extend([1, 2, 3]) d.extendleft([5, 3, 1]) assert d.count(3) == 2 assert list(d) == [1, 3, 5, 1, 2, 3] assert d.pop() == 3 assert d.popleft() == 1 d.remove(5) assert list(d) == [3, 1, 2] d.reverse() assert list(d) == [2, 1, 3] d.rotate(1) assert list(d) == [3, 2, 1] d.rotate(-2) assert list(d) == [1, 3, 2] assert len(d) == 3 assert 3 in d assert d[1] == 3 d[1] = 4 assert list(d) == [1, 4, 2] assert list(reversed(d)) == [2, 4, 1] def test_counter(): from collections import Counter c = Counter() assert Counter("abc") == {"a": 1, "b": 1, "c": 1} assert Counter({"a": 1, "b": 2, "c": 3}) == {"a": 1, "b": 2, "c": 3} assert Counter(a=1, b=2, c=3) == {"a": 1, "b": 2, "c": 3} c["abc"] = 1 c["def"] = 2 assert c == {"abc": 1, "def": 2} c["def"] = 0 assert c == {"abc": 1, "def": 0} del c["def"] assert c["ghi"] == 0 c.update({"ghi": 2}) assert list(c.elements()) == ["abc", "ghi", "ghi"] c.update(["a", "a", "b", "a", "a", "a", "b", "a"]) assert c == {"abc": 1, "ghi": 2, "a": 6, "b": 2} c.update(a=-3, b=-1) assert c == {"abc": 1, "ghi": 2, "a": 3, "b": 1} assert c.most_common(2) == [("a", 3), ("ghi", 2)] assert c.most_common() == [("a", 3), ("ghi", 2), ("abc", 1), ("b", 1)] c.subtract({"abc": 1, "ghi": -2, "a": 3, "b": -1}) assert c == {"abc": 0, "ghi": 4, "a": 0, "b": 2} c = Counter(a=3, b=1) d = Counter(a=1, b=2) assert c + d == Counter({'a': 4, 'b': 3}) assert c - d == Counter({'a': 2}) assert c & d == Counter({'a': 1, 'b': 1}) assert c | d == Counter({'a': 3, 'b': 2}) c = Counter(a=3, b=1) c += d assert c == Counter({'a': 4, 'b': 3}) c = Counter(a=3, b=1) c -= d assert c == Counter({'a': 2}) c = Counter(a=3, b=1) c &= d assert c == Counter({'a': 1, 'b': 1}) c = Counter(a=3, b=1) c |= d assert c == Counter({'a': 3, 'b': 2}) c = Counter(a=3, b=1) c.subtract(["a", "b"]) assert c == {"a": 2, "b": 0} def test_ordered_dict(): from collections import OrderedDict od = OrderedDict([("a", 1), ("b", 2), ("c", 3), ("d", 4)]) assert od.popitem() == ("d", 4) assert od == OrderedDict([("a", 1), ("b", 2), ("c", 3)]) assert od.popitem(last=False) == ("a", 1) assert od == OrderedDict([("b", 2), ("c", 3)]) assert od.popitem(last=True) == ("c", 3) assert od == OrderedDict([("b", 2)]) assert od == {"b": 2} def test_defaultdict(): from collections import defaultdict assert defaultdict() == {} assert defaultdict(k1=1, k2=2) == {"k1": 1, "k2": 2} assert defaultdict(lambda: 1) == {} assert defaultdict(lambda: 2, {"k1": 1, "k2": 2}) == {"k1": 1, "k2": 2} assert defaultdict(lambda: 3, [("k1", 1), ("k2", 2)]) == {"k1": 1, "k2": 2} assert defaultdict(None) == {} assert defaultdict(None, {"k1": 1, "k2": 2}) == {"k1": 1, "k2": 2} assert defaultdict(None, [("k1", 1), ("k2", 2)]) == {"k1": 1, "k2": 2} assert defaultdict(lambda: 4).__missing__("key") == 4 def test_abc(): from collections import (Container, Hashable, Iterable, Iterator, Sized, Callable, Sequence, MutableSequence, Set, MutableSet, Mapping, MutableMapping, MappingView, ItemsView, KeysView, ValuesView) assert [Container, Hashable, Iterable, Iterator, Sized, Callable, Sequence, MutableSequence, Set, MutableSet, Mapping, MutableMapping, MappingView, ItemsView, KeysView, ValuesView]
apache-2.0
joeywen/nlpy
nlpy/model/tests/test_adolcmodel.py
3
2480
# Tests relative to algorithmic differentiation with ADOL-C. from numpy.testing import * from nlpy.model import AdolcModel import numpy as np class AdolcRosenbrock(AdolcModel): "The standard Rosenbrock function." def obj(self, x, **kwargs): return np.sum( 100*(x[1:] - x[:-1]**2)**2 + (1 - x[:-1])**2 ) class AdolcHS7(AdolcModel): "Problem #7 in the Hock and Schittkowski collection." def obj(self, x, **kwargs): return np.log(1 + x[0]**2) - x[1] def cons(self, x, **kwargs): return (1 + x[0]**2)**2 + x[1]**2 - 4 def get_derivatives(nlp): g = nlp.grad(nlp.x0) H = nlp.dense_hess(nlp.x0, nlp.x0) if nlp.m > 0: J = nlp.dense_jac(nlp.x0) v = -np.ones(nlp.n) w = 2*np.ones(nlp.m) Jv = nlp.jac_vec(nlp.x0,v) JTw = nlp.vec_jac(nlp.x0,w) return (g,H,J,Jv,JTw) else: return (g,H) class Test_AdolcRosenbrock(TestCase): def setUp(self): self.rosenbrock = AdolcRosenbrock(n=5,name='Rosenbrock',x0=-np.ones(5)) def test_rosenbrock(self): (g,H) = get_derivatives(self.rosenbrock) expected_g = np.array([-804., -1204., -1204., -1204., -400.]) expected_H = np.array([[1602., 400., 0., 0., 0.], [ 400., 1802., 400., 0., 0.], [ 0., 400., 1802., 400., 0.], [ 0., 0., 400., 1802., 400.], [ 0., 0., 0., 400., 200.]]) assert(np.allclose(g,expected_g)) assert(np.allclose(H,expected_H)) class Test_AdolcHS7(TestCase): def setUp(self): self.hs7 = AdolcHS7(n=2, m=1, name='HS7', x0=2*np.ones(2)) def test_hs7(self): hs7 = self.hs7 (g,H,J,Jv,JTw) = get_derivatives(hs7) expected_g = np.array([0.8, -1.]) expected_H = np.array([[-0.24, 0.],[0., 0.]]) expected_J = np.array([[40., 4.]]) expected_Jv = np.array([-44.]) expected_JTw = np.array([80., 8.]) assert(np.allclose(g,expected_g)) assert(np.allclose(H,expected_H)) assert(np.allclose(J,expected_J)) assert(np.allclose(Jv,expected_Jv)) assert(np.allclose(JTw,expected_JTw)) Jop = hs7.get_jac_linop(hs7.x0) Jopv = Jop * (-np.ones(hs7.n)) JopTw = Jop.T * (2*np.ones(hs7.m)) assert(np.allclose(Jopv,expected_Jv)) assert(np.allclose(JopTw,expected_JTw))
gpl-3.0
tiagochiavericosta/edx-platform
common/djangoapps/util/tests/test_submit_feedback.py
126
16598
"""Tests for the Zendesk""" from django.contrib.auth.models import AnonymousUser from django.http import Http404 from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from student.tests.factories import UserFactory from util import views from zendesk import ZendeskError import json import mock from student.tests.test_microsite import fake_microsite_get_value @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_FEEDBACK_SUBMISSION": True}) @override_settings(ZENDESK_URL="dummy", ZENDESK_USER="dummy", ZENDESK_API_KEY="dummy") @mock.patch("util.views.dog_stats_api") @mock.patch("util.views._ZendeskApi", autospec=True) class SubmitFeedbackTest(TestCase): def setUp(self): """Set up data for the test case""" super(SubmitFeedbackTest, self).setUp() self._request_factory = RequestFactory() self._anon_user = AnonymousUser() self._auth_user = UserFactory.create( email="test@edx.org", username="test", profile__name="Test User" ) # This contains issue_type and course_id to ensure that tags are submitted correctly self._anon_fields = { "email": "test@edx.org", "name": "Test User", "subject": "a subject", "details": "some details", "issue_type": "test_issue", "course_id": "test_course" } # This does not contain issue_type nor course_id to ensure that they are optional self._auth_fields = {"subject": "a subject", "details": "some details"} def _build_and_run_request(self, user, fields): """ Generate a request and invoke the view, returning the response. The request will be a POST request from the given `user`, with the given `fields` in the POST body. """ req = self._request_factory.post( "/submit_feedback", data=fields, HTTP_REFERER="test_referer", HTTP_USER_AGENT="test_user_agent", REMOTE_ADDR="1.2.3.4", SERVER_NAME="test_server", ) req.user = user return views.submit_feedback(req) def _assert_bad_request(self, response, field, zendesk_mock_class, datadog_mock): """ Assert that the given `response` contains correct failure data. It should have a 400 status code, and its content should be a JSON object containing the specified `field` and an `error`. """ self.assertEqual(response.status_code, 400) resp_json = json.loads(response.content) self.assertTrue("field" in resp_json) self.assertEqual(resp_json["field"], field) self.assertTrue("error" in resp_json) # There should be absolutely no interaction with Zendesk self.assertFalse(zendesk_mock_class.return_value.mock_calls) self.assertFalse(datadog_mock.mock_calls) def _test_bad_request_omit_field(self, user, fields, omit_field, zendesk_mock_class, datadog_mock): """ Invoke the view with a request missing a field and assert correctness. The request will be a POST request from the given `user`, with POST fields taken from `fields` minus the entry specified by `omit_field`. The response should have a 400 (bad request) status code and specify the invalid field and an error message, and the Zendesk API should not have been invoked. """ filtered_fields = {k: v for (k, v) in fields.items() if k != omit_field} resp = self._build_and_run_request(user, filtered_fields) self._assert_bad_request(resp, omit_field, zendesk_mock_class, datadog_mock) def _test_bad_request_empty_field(self, user, fields, empty_field, zendesk_mock_class, datadog_mock): """ Invoke the view with an empty field and assert correctness. The request will be a POST request from the given `user`, with POST fields taken from `fields`, replacing the entry specified by `empty_field` with the empty string. The response should have a 400 (bad request) status code and specify the invalid field and an error message, and the Zendesk API should not have been invoked. """ altered_fields = fields.copy() altered_fields[empty_field] = "" resp = self._build_and_run_request(user, altered_fields) self._assert_bad_request(resp, empty_field, zendesk_mock_class, datadog_mock) def _test_success(self, user, fields): """ Generate a request, invoke the view, and assert success. The request will be a POST request from the given `user`, with the given `fields` in the POST body. The response should have a 200 (success) status code. """ resp = self._build_and_run_request(user, fields) self.assertEqual(resp.status_code, 200) def _assert_datadog_called(self, datadog_mock, with_tags): expected_datadog_calls = [ mock.call.increment( views.DATADOG_FEEDBACK_METRIC, tags=(["course_id:test_course", "issue_type:test_issue"] if with_tags else []) ) ] self.assertEqual(datadog_mock.mock_calls, expected_datadog_calls) def test_bad_request_anon_user_no_name(self, zendesk_mock_class, datadog_mock): """Test a request from an anonymous user not specifying `name`.""" self._test_bad_request_omit_field(self._anon_user, self._anon_fields, "name", zendesk_mock_class, datadog_mock) self._test_bad_request_empty_field(self._anon_user, self._anon_fields, "name", zendesk_mock_class, datadog_mock) def test_bad_request_anon_user_no_email(self, zendesk_mock_class, datadog_mock): """Test a request from an anonymous user not specifying `email`.""" self._test_bad_request_omit_field(self._anon_user, self._anon_fields, "email", zendesk_mock_class, datadog_mock) self._test_bad_request_empty_field(self._anon_user, self._anon_fields, "email", zendesk_mock_class, datadog_mock) def test_bad_request_anon_user_invalid_email(self, zendesk_mock_class, datadog_mock): """Test a request from an anonymous user specifying an invalid `email`.""" fields = self._anon_fields.copy() fields["email"] = "This is not a valid email address!" resp = self._build_and_run_request(self._anon_user, fields) self._assert_bad_request(resp, "email", zendesk_mock_class, datadog_mock) def test_bad_request_anon_user_no_subject(self, zendesk_mock_class, datadog_mock): """Test a request from an anonymous user not specifying `subject`.""" self._test_bad_request_omit_field(self._anon_user, self._anon_fields, "subject", zendesk_mock_class, datadog_mock) self._test_bad_request_empty_field(self._anon_user, self._anon_fields, "subject", zendesk_mock_class, datadog_mock) def test_bad_request_anon_user_no_details(self, zendesk_mock_class, datadog_mock): """Test a request from an anonymous user not specifying `details`.""" self._test_bad_request_omit_field(self._anon_user, self._anon_fields, "details", zendesk_mock_class, datadog_mock) self._test_bad_request_empty_field(self._anon_user, self._anon_fields, "details", zendesk_mock_class, datadog_mock) def test_valid_request_anon_user(self, zendesk_mock_class, datadog_mock): """ Test a valid request from an anonymous user. The response should have a 200 (success) status code, and a ticket with the given information should have been submitted via the Zendesk API. """ zendesk_mock_instance = zendesk_mock_class.return_value zendesk_mock_instance.create_ticket.return_value = 42 self._test_success(self._anon_user, self._anon_fields) expected_zendesk_calls = [ mock.call.create_ticket( { "ticket": { "requester": {"name": "Test User", "email": "test@edx.org"}, "subject": "a subject", "comment": {"body": "some details"}, "tags": ["test_course", "test_issue", "LMS"] } } ), mock.call.update_ticket( 42, { "ticket": { "comment": { "public": False, "body": "Additional information:\n\n" "Client IP: 1.2.3.4\n" "Host: test_server\n" "Page: test_referer\n" "Browser: test_user_agent" } } } ) ] self.assertEqual(zendesk_mock_instance.mock_calls, expected_zendesk_calls) self._assert_datadog_called(datadog_mock, with_tags=True) @mock.patch("microsite_configuration.microsite.get_value", fake_microsite_get_value) def test_valid_request_anon_user_microsite(self, zendesk_mock_class, datadog_mock): """ Test a valid request from an anonymous user to a mocked out microsite The response should have a 200 (success) status code, and a ticket with the given information should have been submitted via the Zendesk API with the additional tag that will come from microsite configuration """ zendesk_mock_instance = zendesk_mock_class.return_value zendesk_mock_instance.create_ticket.return_value = 42 self._test_success(self._anon_user, self._anon_fields) expected_zendesk_calls = [ mock.call.create_ticket( { "ticket": { "requester": {"name": "Test User", "email": "test@edx.org"}, "subject": "a subject", "comment": {"body": "some details"}, "tags": ["test_course", "test_issue", "LMS", "whitelabel_fakeorg"] } } ), mock.call.update_ticket( 42, { "ticket": { "comment": { "public": False, "body": "Additional information:\n\n" "Client IP: 1.2.3.4\n" "Host: test_server\n" "Page: test_referer\n" "Browser: test_user_agent" } } } ) ] self.assertEqual(zendesk_mock_instance.mock_calls, expected_zendesk_calls) self._assert_datadog_called(datadog_mock, with_tags=True) def test_bad_request_auth_user_no_subject(self, zendesk_mock_class, datadog_mock): """Test a request from an authenticated user not specifying `subject`.""" self._test_bad_request_omit_field(self._auth_user, self._auth_fields, "subject", zendesk_mock_class, datadog_mock) self._test_bad_request_empty_field(self._auth_user, self._auth_fields, "subject", zendesk_mock_class, datadog_mock) def test_bad_request_auth_user_no_details(self, zendesk_mock_class, datadog_mock): """Test a request from an authenticated user not specifying `details`.""" self._test_bad_request_omit_field(self._auth_user, self._auth_fields, "details", zendesk_mock_class, datadog_mock) self._test_bad_request_empty_field(self._auth_user, self._auth_fields, "details", zendesk_mock_class, datadog_mock) def test_valid_request_auth_user(self, zendesk_mock_class, datadog_mock): """ Test a valid request from an authenticated user. The response should have a 200 (success) status code, and a ticket with the given information should have been submitted via the Zendesk API. """ zendesk_mock_instance = zendesk_mock_class.return_value zendesk_mock_instance.create_ticket.return_value = 42 self._test_success(self._auth_user, self._auth_fields) expected_zendesk_calls = [ mock.call.create_ticket( { "ticket": { "requester": {"name": "Test User", "email": "test@edx.org"}, "subject": "a subject", "comment": {"body": "some details"}, "tags": ["LMS"] } } ), mock.call.update_ticket( 42, { "ticket": { "comment": { "public": False, "body": "Additional information:\n\n" "username: test\n" "Client IP: 1.2.3.4\n" "Host: test_server\n" "Page: test_referer\n" "Browser: test_user_agent" } } } ) ] self.assertEqual(zendesk_mock_instance.mock_calls, expected_zendesk_calls) self._assert_datadog_called(datadog_mock, with_tags=False) def test_get_request(self, zendesk_mock_class, datadog_mock): """Test that a GET results in a 405 even with all required fields""" req = self._request_factory.get("/submit_feedback", data=self._anon_fields) req.user = self._anon_user resp = views.submit_feedback(req) self.assertEqual(resp.status_code, 405) self.assertIn("Allow", resp) self.assertEqual(resp["Allow"], "POST") # There should be absolutely no interaction with Zendesk self.assertFalse(zendesk_mock_class.mock_calls) self.assertFalse(datadog_mock.mock_calls) def test_zendesk_error_on_create(self, zendesk_mock_class, datadog_mock): """ Test Zendesk returning an error on ticket creation. We should return a 500 error with no body """ err = ZendeskError(msg="", error_code=404) zendesk_mock_instance = zendesk_mock_class.return_value zendesk_mock_instance.create_ticket.side_effect = err resp = self._build_and_run_request(self._anon_user, self._anon_fields) self.assertEqual(resp.status_code, 500) self.assertFalse(resp.content) self._assert_datadog_called(datadog_mock, with_tags=True) def test_zendesk_error_on_update(self, zendesk_mock_class, datadog_mock): """ Test for Zendesk returning an error on ticket update. If Zendesk returns any error on ticket update, we return a 200 to the browser because the update contains additional information that is not necessary for the user to have submitted their feedback. """ err = ZendeskError(msg="", error_code=500) zendesk_mock_instance = zendesk_mock_class.return_value zendesk_mock_instance.update_ticket.side_effect = err resp = self._build_and_run_request(self._anon_user, self._anon_fields) self.assertEqual(resp.status_code, 200) self._assert_datadog_called(datadog_mock, with_tags=True) @mock.patch.dict("django.conf.settings.FEATURES", {"ENABLE_FEEDBACK_SUBMISSION": False}) def test_not_enabled(self, zendesk_mock_class, datadog_mock): """ Test for Zendesk submission not enabled in `settings`. We should raise Http404. """ with self.assertRaises(Http404): self._build_and_run_request(self._anon_user, self._anon_fields) def test_zendesk_not_configured(self, zendesk_mock_class, datadog_mock): """ Test for Zendesk not fully configured in `settings`. For each required configuration parameter, test that setting it to `None` causes an otherwise valid request to return a 500 error. """ def test_case(missing_config): with mock.patch(missing_config, None): with self.assertRaises(Exception): self._build_and_run_request(self._anon_user, self._anon_fields) test_case("django.conf.settings.ZENDESK_URL") test_case("django.conf.settings.ZENDESK_USER") test_case("django.conf.settings.ZENDESK_API_KEY")
agpl-3.0
Heathckliff/SU2
SU2_PY/SU2/eval/functions.py
3
18001
#!/usr/bin/env python ## \file functions.py # \brief python package for functions # \author T. Lukaczyk, F. Palacios # \version 4.0.1 "Cardinal" # # SU2 Lead Developers: Dr. Francisco Palacios (Francisco.D.Palacios@boeing.com). # Dr. Thomas D. Economon (economon@stanford.edu). # # SU2 Developers: Prof. Juan J. Alonso's group at Stanford University. # Prof. Piero Colonna's group at Delft University of Technology. # Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology. # Prof. Alberto Guardone's group at Polytechnic University of Milan. # Prof. Rafael Palacios' group at Imperial College London. # # Copyright (C) 2012-2015 SU2, the open-source CFD code. # # SU2 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. # # SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>. # ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- import os, sys, shutil, copy, time from .. import run as su2run from .. import io as su2io from .. import util as su2util from ..io import redirect_folder, redirect_output # ---------------------------------------------------------------------- # Main Function Interface # ---------------------------------------------------------------------- def function( func_name, config, state=None ): """ val = SU2.eval.func(func_name,config,state=None) Evaluates the aerodynamics and geometry functions. Wraps: SU2.eval.aerodynamics() SU2.eval.geometry() Assumptions: Config is already setup for deformation. Mesh need not be deformed. Updates config and state by reference. Redundancy if state.FUNCTIONS is not empty. Executes in: ./DIRECT or ./GEOMETRY Inputs: func_name - SU2 objective function name or 'ALL' config - an SU2 config state - optional, an SU2 state Outputs: If func_name is 'ALL', returns a Bunch() of functions with keys of objective function names and values of objective function floats. Otherwise returns a float. """ # initialize state = su2io.State(state) # redundancy check if not state['FUNCTIONS'].has_key(func_name): # Aerodynamics if func_name == 'ALL' or func_name in su2io.optnames_aero + su2io.grad_names_directdiff: aerodynamics( config, state ) # Stability elif func_name in su2io.optnames_stab: stability( config, state ) # Geometry elif func_name in su2io.optnames_geo: geometry( func_name, config, state ) else: raise Exception, 'unknown function name, %s' % func_name #: if not redundant # prepare output if func_name == 'ALL': func_out = state['FUNCTIONS'] else: func_out = state['FUNCTIONS'][func_name] return copy.deepcopy(func_out) #: def function() # ---------------------------------------------------------------------- # Aerodynamic Functions # ---------------------------------------------------------------------- def aerodynamics( config, state=None ): """ vals = SU2.eval.aerodynamics(config,state=None) Evaluates aerodynamics with the following: SU2.run.deform() SU2.run.direct() Assumptions: Config is already setup for deformation. Mesh may or may not be deformed. Updates config and state by reference. Redundancy if state.FUNCTIONS is not empty. Executes in: ./DIRECT Inputs: config - an SU2 config state - optional, an SU2 state Outputs: Bunch() of functions with keys of objective function names and values of objective function floats. """ # ---------------------------------------------------- # Initialize # ---------------------------------------------------- # initialize state = su2io.State(state) if not state.FILES.has_key('MESH'): state.FILES.MESH = config['MESH_FILENAME'] special_cases = su2io.get_specialCases(config) # console output if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: log_direct = 'log_Direct.out' else: log_direct = None # ---------------------------------------------------- # Update Mesh # ---------------------------------------------------- # does decomposition and deformation info = update_mesh(config,state) # ---------------------------------------------------- # Adaptation (not implemented) # ---------------------------------------------------- #if not state.['ADAPTED_FUNC']: # config = su2run.adaptation(config) # state['ADAPTED_FUNC'] = True # ---------------------------------------------------- # Direct Solution # ---------------------------------------------------- # redundancy check direct_done = all( [ state.FUNCTIONS.has_key(key) for key in su2io.optnames_aero[:9] ] ) if direct_done: # return aerodynamic function values aero = su2util.ordered_bunch() for key in su2io.optnames_aero: if state.FUNCTIONS.has_key(key): aero[key] = state.FUNCTIONS[key] return copy.deepcopy(aero) #: if redundant # files to pull files = state.FILES pull = []; link = [] # files: mesh name = files['MESH'] name = su2io.expand_part(name,config) link.extend(name) # files: direct solution if files.has_key('DIRECT'): name = files['DIRECT'] name = su2io.expand_time(name,config) link.extend( name ) ##config['RESTART_SOL'] = 'YES' # don't override config file else: config['RESTART_SOL'] = 'NO' # files: target equivarea distribution if ( 'EQUIV_AREA' in special_cases and 'TARGET_EA' in files ) : pull.append( files['TARGET_EA'] ) # files: target pressure distribution if ( 'INV_DESIGN_CP' in special_cases and 'TARGET_CP' in files ) : pull.append( files['TARGET_CP'] ) # files: target heat flux distribution if ( 'INV_DESIGN_HEATFLUX' in special_cases and 'TARGET_HEATFLUX' in files ) : pull.append( files['TARGET_HEATFLUX'] ) # output redirection with redirect_folder( 'DIRECT', pull, link ) as push: with redirect_output(log_direct): # # RUN DIRECT SOLUTION # # info = su2run.direct(config) su2io.restart2solution(config,info) state.update(info) # direct files to push name = info.FILES['DIRECT'] name = su2io.expand_time(name,config) push.extend(name) # equivarea files to push if 'WEIGHT_NF' in info.FILES: push.append(info.FILES['WEIGHT_NF']) # pressure files to push if 'TARGET_CP' in info.FILES: push.append(info.FILES['TARGET_CP']) # heat flux files to push if 'TARGET_HEATFLUX' in info.FILES: push.append(info.FILES['TARGET_HEATFLUX']) #: with output redirection # return output funcs = su2util.ordered_bunch() for key in su2io.optnames_aero + su2io.grad_names_directdiff: if state['FUNCTIONS'].has_key(key): funcs[key] = state['FUNCTIONS'][key] return funcs #: def aerodynamics() # ---------------------------------------------------------------------- # Stability Functions # ---------------------------------------------------------------------- def stability( config, state=None, step=1e-2 ): folder = 'STABILITY' # os.path.join('STABILITY',func_name) #STABILITY/D_MOMENT_Y_D_ALPHA/ # ---------------------------------------------------- # Initialize # ---------------------------------------------------- # initialize state = su2io.State(state) if not state.FILES.has_key('MESH'): state.FILES.MESH = config['MESH_FILENAME'] special_cases = su2io.get_specialCases(config) # console output if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: log_direct = 'log_Direct.out' else: log_direct = None # ---------------------------------------------------- # Update Mesh # ---------------------------------------------------- # does decomposition and deformation info = update_mesh(config,state) # ---------------------------------------------------- # CENTRAL POINT # ---------------------------------------------------- # will run in DIRECT/ func_0 = aerodynamics(config,state) # ---------------------------------------------------- # Run Forward Point # ---------------------------------------------------- # files to pull files = state.FILES pull = []; link = [] # files: mesh name = files['MESH'] name = su2io.expand_part(name,config) link.extend(name) # files: direct solution if files.has_key('DIRECT'): name = files['DIRECT'] name = su2io.expand_time(name,config) link.extend( name ) ##config['RESTART_SOL'] = 'YES' # don't override config file else: config['RESTART_SOL'] = 'NO' # files: target equivarea distribution if ( 'EQUIV_AREA' in special_cases and 'TARGET_EA' in files ) : pull.append( files['TARGET_EA'] ) # files: target pressure distribution if ( 'INV_DESIGN_CP' in special_cases and 'TARGET_CP' in files ) : pull.append( files['TARGET_CP'] ) # files: target heat flux distribution if ( 'INV_DESIGN_HEATFLUX' in special_cases and 'TARGET_HEATFLUX' in files ) : pull.append( files['TARGET_HEATFLUX'] ) # pull needed files, start folder with redirect_folder( folder, pull, link ) as push: with redirect_output(log_direct): konfig = copy.deepcopy(config) ztate = copy.deepcopy(state) # TODO: GENERALIZE konfig.AoA = konfig.AoA + step ztate.FUNCTIONS.clear() func_1 = aerodynamics(konfig,ztate) ## direct files to store #name = ztate.FILES['DIRECT'] #if not state.FILES.has_key('STABILITY'): #state.FILES.STABILITY = su2io.ordered_bunch() #state.FILES.STABILITY['DIRECT'] = name ## equivarea files to store #if 'WEIGHT_NF' in ztate.FILES: #state.FILES.STABILITY['WEIGHT_NF'] = ztate.FILES['WEIGHT_NF'] # ---------------------------------------------------- # DIFFERENCING # ---------------------------------------------------- for derv_name in su2io.optnames_stab: matches = [ k for k in su2io.optnames_aero if k in derv_name ] if not len(matches) == 1: continue func_name = matches[0] obj_func = ( func_1[func_name] - func_0[func_name] ) / step state.FUNCTIONS[derv_name] = obj_func # return output funcs = su2util.ordered_bunch() for key in su2io.optnames_stab: if state['FUNCTIONS'].has_key(key): funcs[key] = state['FUNCTIONS'][key] return funcs # ---------------------------------------------------------------------- # Geometric Functions # ---------------------------------------------------------------------- def geometry( func_name, config, state=None ): """ val = SU2.eval.geometry(config,state=None) Evaluates geometry with the following: SU2.run.deform() SU2.run.geometry() Assumptions: Config is already setup for deformation. Mesh may or may not be deformed. Updates config and state by reference. Redundancy if state.FUNCTIONS does not have func_name. Executes in: ./GEOMETRY Inputs: config - an SU2 config state - optional, an SU2 state Outputs: Bunch() of functions with keys of objective function names and values of objective function floats. """ # ---------------------------------------------------- # Initialize # ---------------------------------------------------- # initialize state = su2io.State(state) if not state.FILES.has_key('MESH'): state.FILES.MESH = config['MESH_FILENAME'] special_cases = su2io.get_specialCases(config) # console output if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: log_geom = 'log_Geometry.out' else: log_geom = None # ---------------------------------------------------- # Update Mesh (check with Trent) # ---------------------------------------------------- # does decomposition and deformation #info = update_mesh(config,state) # ---------------------------------------------------- # Geometry Solution # ---------------------------------------------------- # redundancy check geometry_done = state.FUNCTIONS.has_key(func_name) #geometry_done = all( [ state.FUNCTIONS.has_key(key) for key in su2io.optnames_geo ] ) if not geometry_done: # files to pull files = state.FILES pull = []; link = [] # files: mesh name = files['MESH'] name = su2io.expand_part(name,config) link.extend(name) # update function name ## TODO # output redirection with redirect_folder( 'GEOMETRY', pull, link ) as push: with redirect_output(log_geom): # setup config config.GEO_PARAM = func_name config.GEO_MODE = 'FUNCTION' # # RUN GEOMETRY SOLUTION # # info = su2run.geometry(config) state.update(info) # no files to push #: with output redirection #: if not redundant # return output funcs = su2util.ordered_bunch() for key in su2io.optnames_geo: if state['FUNCTIONS'].has_key(key): funcs[key] = state['FUNCTIONS'][key] return funcs #: def geometry() def update_mesh(config,state=None): """ SU2.eval.update_mesh(config,state=None) updates mesh with the following: SU2.run.deform() Assumptions: Config is already setup for deformation. Mesh may or may not be deformed. Updates config and state by reference. Executes in: ./DECOMP and ./DEFORM Inputs: config - an SU2 config state - optional, an SU2 state Outputs: nothing Modifies: config and state by reference """ # ---------------------------------------------------- # Initialize # ---------------------------------------------------- # initialize state = su2io.State(state) if not state.FILES.has_key('MESH'): state.FILES.MESH = config['MESH_FILENAME'] special_cases = su2io.get_specialCases(config) # console output if config.get('CONSOLE','VERBOSE') in ['QUIET','CONCISE']: log_decomp = 'log_Decomp.out' log_deform = 'log_Deform.out' else: log_decomp = None log_deform = None # ---------------------------------------------------- # Deformation # ---------------------------------------------------- # redundancy check deform_set = config['DV_KIND'] == config['DEFINITION_DV']['KIND'] deform_todo = not config['DV_VALUE_NEW'] == config['DV_VALUE_OLD'] if deform_set and deform_todo: # files to pull pull = [] link = config['MESH_FILENAME'] link = su2io.expand_part(link,config) # output redirection with redirect_folder('DEFORM',pull,link) as push: with redirect_output(log_deform): # # RUN DEFORMATION # # info = su2run.deform(config) state.update(info) # data to push meshname = info.FILES.MESH names = su2io.expand_part( meshname , config ) push.extend( names ) #: with redirect output elif deform_set and not deform_todo: state.VARIABLES.DV_VALUE_NEW = config.DV_VALUE_NEW #: if not redundant return
lgpl-2.1
towc/secret-ox
node_modules/node-gyp/gyp/pylib/gyp/generator/ninja.py
1284
100329
# Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import copy import hashlib import json import multiprocessing import os.path import re import signal import subprocess import sys import gyp import gyp.common from gyp.common import OrderedSet import gyp.msvs_emulation import gyp.MSVSUtil as MSVSUtil import gyp.xcode_emulation from cStringIO import StringIO from gyp.common import GetEnvironFallback import gyp.ninja_syntax as ninja_syntax generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'SHARED_LIB_PREFIX': 'lib', # Gyp expects the following variables to be expandable by the build # system to the appropriate locations. Ninja prefers paths to be # known at gyp time. To resolve this, introduce special # variables starting with $! and $| (which begin with a $ so gyp knows it # should be treated specially, but is otherwise an invalid # ninja/shell variable) that are passed to gyp here but expanded # before writing out into the target .ninja files; see # ExpandSpecial. # $! is used for variables that represent a path and that can only appear at # the start of a string, while $| is used for variables that can appear # anywhere in a string. 'INTERMEDIATE_DIR': '$!INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR': '$!PRODUCT_DIR/gen', 'PRODUCT_DIR': '$!PRODUCT_DIR', 'CONFIGURATION_NAME': '$|CONFIGURATION_NAME', # Special variables that may be used by gyp 'rule' targets. # We generate definitions for these variables on the fly when processing a # rule. 'RULE_INPUT_ROOT': '${root}', 'RULE_INPUT_DIRNAME': '${dirname}', 'RULE_INPUT_PATH': '${source}', 'RULE_INPUT_EXT': '${ext}', 'RULE_INPUT_NAME': '${name}', } # Placates pylint. generator_additional_non_configuration_keys = [] generator_additional_path_sections = [] generator_extra_sources_for_rules = [] generator_filelist_paths = None generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() def StripPrefix(arg, prefix): if arg.startswith(prefix): return arg[len(prefix):] return arg def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # whitelist common OK ones and quote anything else. if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg): return arg # No quoting necessary. if flavor == 'win': return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'" def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == 'win': # cl.exe replaces literal # characters with = in preprocesor definitions for # some reason. Octal-encode to work around that. d = d.replace('#', '\\%03o' % ord('#')) return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor) def AddArch(output, arch): """Adds an arch string to an output path.""" output, extension = os.path.splitext(output) return '%s.%s%s' % (output, arch, extension) class Target(object): """Target represents the paths used within a single gyp target. Conceptually, building a single target A is a series of steps: 1) actions/rules/copies generates source/resources/etc. 2) compiles generates .o files 3) link generates a binary (library/executable) 4) bundle merges the above in a mac bundle (Any of these steps can be optional.) From a build ordering perspective, a dependent target B could just depend on the last output of this series of steps. But some dependent commands sometimes need to reach inside the box. For example, when linking B it needs to get the path to the static library generated by A. This object stores those paths. To keep things simple, member variables only store concrete paths to single files, while methods compute derived values like "the last output of the target". """ def __init__(self, type): # Gyp type ("static_library", etc.) of this target. self.type = type # File representing whether any input dependencies necessary for # dependent actions have completed. self.preaction_stamp = None # File representing whether any input dependencies necessary for # dependent compiles have completed. self.precompile_stamp = None # File representing the completion of actions/rules/copies, if any. self.actions_stamp = None # Path to the output of the link step, if any. self.binary = None # Path to the file representing the completion of building the bundle, # if any. self.bundle = None # On Windows, incremental linking requires linking against all the .objs # that compose a .lib (rather than the .lib itself). That list is stored # here. In this case, we also need to save the compile_deps for the target, # so that the the target that directly depends on the .objs can also depend # on those. self.component_objs = None self.compile_deps = None # Windows only. The import .lib is the output of a build step, but # because dependents only link against the lib (not both the lib and the # dll) we keep track of the import library here. self.import_lib = None def Linkable(self): """Return true if this is a target that can be linked against.""" return self.type in ('static_library', 'shared_library') def UsesToc(self, flavor): """Return true if the target should produce a restat rule based on a TOC file.""" # For bundles, the .TOC should be produced for the binary, not for # FinalOutput(). But the naive approach would put the TOC file into the # bundle, so don't do this for bundles for now. if flavor == 'win' or self.bundle: return False return self.type in ('shared_library', 'loadable_module') def PreActionInput(self, flavor): """Return the path, if any, that should be used as a dependency of any dependent action step.""" if self.UsesToc(flavor): return self.FinalOutput() + '.TOC' return self.FinalOutput() or self.preaction_stamp def PreCompileInput(self): """Return the path, if any, that should be used as a dependency of any dependent compile step.""" return self.actions_stamp or self.precompile_stamp def FinalOutput(self): """Return the last output of the target, which depends on all prior steps.""" return self.bundle or self.binary or self.actions_stamp # A small discourse on paths as used within the Ninja build: # All files we produce (both at gyp and at build time) appear in the # build directory (e.g. out/Debug). # # Paths within a given .gyp file are always relative to the directory # containing the .gyp file. Call these "gyp paths". This includes # sources as well as the starting directory a given gyp rule/action # expects to be run from. We call the path from the source root to # the gyp file the "base directory" within the per-.gyp-file # NinjaWriter code. # # All paths as written into the .ninja files are relative to the build # directory. Call these paths "ninja paths". # # We translate between these two notions of paths with two helper # functions: # # - GypPathToNinja translates a gyp path (i.e. relative to the .gyp file) # into the equivalent ninja path. # # - GypPathToUniqueOutput translates a gyp path into a ninja path to write # an output file; the result can be namespaced such that it is unique # to the input file name as well as the output target name. class NinjaWriter(object): def __init__(self, hash_for_rules, target_outputs, base_dir, build_dir, output_file, toplevel_build, output_file_name, flavor, toplevel_dir=None): """ base_dir: path from source root to directory containing this gyp file, by gyp semantics, all input paths are relative to this build_dir: path from source root to build output toplevel_dir: path to the toplevel directory """ self.hash_for_rules = hash_for_rules self.target_outputs = target_outputs self.base_dir = base_dir self.build_dir = build_dir self.ninja = ninja_syntax.Writer(output_file) self.toplevel_build = toplevel_build self.output_file_name = output_file_name self.flavor = flavor self.abs_build_dir = None if toplevel_dir is not None: self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir)) self.obj_ext = '.obj' if flavor == 'win' else '.o' if flavor == 'win': # See docstring of msvs_emulation.GenerateEnvironmentFiles(). self.win_env = {} for arch in ('x86', 'x64'): self.win_env[arch] = 'environment.' + arch # Relative path from build output dir to base dir. build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir) self.build_to_base = os.path.join(build_to_top, base_dir) # Relative path from base dir to build dir. base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir) self.base_to_build = os.path.join(base_to_top, build_dir) def ExpandSpecial(self, path, product_dir=None): """Expand specials like $!PRODUCT_DIR in |path|. If |product_dir| is None, assumes the cwd is already the product dir. Otherwise, |product_dir| is the relative path to the product dir. """ PRODUCT_DIR = '$!PRODUCT_DIR' if PRODUCT_DIR in path: if product_dir: path = path.replace(PRODUCT_DIR, product_dir) else: path = path.replace(PRODUCT_DIR + '/', '') path = path.replace(PRODUCT_DIR + '\\', '') path = path.replace(PRODUCT_DIR, '.') INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR' if INTERMEDIATE_DIR in path: int_dir = self.GypPathToUniqueOutput('gen') # GypPathToUniqueOutput generates a path relative to the product dir, # so insert product_dir in front if it is provided. path = path.replace(INTERMEDIATE_DIR, os.path.join(product_dir or '', int_dir)) CONFIGURATION_NAME = '$|CONFIGURATION_NAME' path = path.replace(CONFIGURATION_NAME, self.config_name) return path def ExpandRuleVariables(self, path, root, dirname, source, ext, name): if self.flavor == 'win': path = self.msvs_settings.ConvertVSMacros( path, config=self.config_name) path = path.replace(generator_default_variables['RULE_INPUT_ROOT'], root) path = path.replace(generator_default_variables['RULE_INPUT_DIRNAME'], dirname) path = path.replace(generator_default_variables['RULE_INPUT_PATH'], source) path = path.replace(generator_default_variables['RULE_INPUT_EXT'], ext) path = path.replace(generator_default_variables['RULE_INPUT_NAME'], name) return path def GypPathToNinja(self, path, env=None): """Translate a gyp path to a ninja path, optionally expanding environment variable references in |path| with |env|. See the above discourse on path conversions.""" if env: if self.flavor == 'mac': path = gyp.xcode_emulation.ExpandEnvVars(path, env) elif self.flavor == 'win': path = gyp.msvs_emulation.ExpandMacros(path, env) if path.startswith('$!'): expanded = self.ExpandSpecial(path) if self.flavor == 'win': expanded = os.path.normpath(expanded) return expanded if '$|' in path: path = self.ExpandSpecial(path) assert '$' not in path, path return os.path.normpath(os.path.join(self.build_to_base, path)) def GypPathToUniqueOutput(self, path, qualified=True): """Translate a gyp path to a ninja path for writing output. If qualified is True, qualify the resulting filename with the name of the target. This is necessary when e.g. compiling the same path twice for two separate output targets. See the above discourse on path conversions.""" path = self.ExpandSpecial(path) assert not path.startswith('$'), path # Translate the path following this scheme: # Input: foo/bar.gyp, target targ, references baz/out.o # Output: obj/foo/baz/targ.out.o (if qualified) # obj/foo/baz/out.o (otherwise) # (and obj.host instead of obj for cross-compiles) # # Why this scheme and not some other one? # 1) for a given input, you can compute all derived outputs by matching # its path, even if the input is brought via a gyp file with '..'. # 2) simple files like libraries and stamps have a simple filename. obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset path_dir, path_basename = os.path.split(path) assert not os.path.isabs(path_dir), ( "'%s' can not be absolute path (see crbug.com/462153)." % path_dir) if qualified: path_basename = self.name + '.' + path_basename return os.path.normpath(os.path.join(obj, self.base_dir, path_dir, path_basename)) def WriteCollapsedDependencies(self, name, targets, order_only=None): """Given a list of targets, return a path for a single file representing the result of building all the targets or None. Uses a stamp file if necessary.""" assert targets == filter(None, targets), targets if len(targets) == 0: assert not order_only return None if len(targets) > 1 or order_only: stamp = self.GypPathToUniqueOutput(name + '.stamp') targets = self.ninja.build(stamp, 'stamp', targets, order_only=order_only) self.ninja.newline() return targets[0] def _SubninjaNameForArch(self, arch): output_file_base = os.path.splitext(self.output_file_name)[0] return '%s.%s.ninja' % (output_file_base, arch) def WriteSpec(self, spec, config_name, generator_flags): """The main entry point for NinjaWriter: write the build rules for a spec. Returns a Target object, which represents the output paths for this spec. Returns None if there are no outputs (e.g. a settings-only 'none' type target).""" self.config_name = config_name self.name = spec['target_name'] self.toolset = spec['toolset'] config = spec['configurations'][config_name] self.target = Target(spec['type']) self.is_standalone_static_library = bool( spec.get('standalone_static_library', 0)) # Track if this target contains any C++ files, to decide if gcc or g++ # should be used for linking. self.uses_cpp = False self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) self.xcode_settings = self.msvs_settings = None if self.flavor == 'mac': self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) if self.flavor == 'win': self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, generator_flags) arch = self.msvs_settings.GetArch(config_name) self.ninja.variable('arch', self.win_env[arch]) self.ninja.variable('cc', '$cl_' + arch) self.ninja.variable('cxx', '$cl_' + arch) self.ninja.variable('cc_host', '$cl_' + arch) self.ninja.variable('cxx_host', '$cl_' + arch) self.ninja.variable('asm', '$ml_' + arch) if self.flavor == 'mac': self.archs = self.xcode_settings.GetActiveArchs(config_name) if len(self.archs) > 1: self.arch_subninjas = dict( (arch, ninja_syntax.Writer( OpenOutput(os.path.join(self.toplevel_build, self._SubninjaNameForArch(arch)), 'w'))) for arch in self.archs) # Compute predepends for all rules. # actions_depends is the dependencies this target depends on before running # any of its action/rule/copy steps. # compile_depends is the dependencies this target depends on before running # any of its compile steps. actions_depends = [] compile_depends = [] # TODO(evan): it is rather confusing which things are lists and which # are strings. Fix these. if 'dependencies' in spec: for dep in spec['dependencies']: if dep in self.target_outputs: target = self.target_outputs[dep] actions_depends.append(target.PreActionInput(self.flavor)) compile_depends.append(target.PreCompileInput()) actions_depends = filter(None, actions_depends) compile_depends = filter(None, compile_depends) actions_depends = self.WriteCollapsedDependencies('actions_depends', actions_depends) compile_depends = self.WriteCollapsedDependencies('compile_depends', compile_depends) self.target.preaction_stamp = actions_depends self.target.precompile_stamp = compile_depends # Write out actions, rules, and copies. These must happen before we # compile any sources, so compute a list of predependencies for sources # while we do it. extra_sources = [] mac_bundle_depends = [] self.target.actions_stamp = self.WriteActionsRulesCopies( spec, extra_sources, actions_depends, mac_bundle_depends) # If we have actions/rules/copies, we depend directly on those, but # otherwise we depend on dependent target's actions/rules/copies etc. # We never need to explicitly depend on previous target's link steps, # because no compile ever depends on them. compile_depends_stamp = (self.target.actions_stamp or compile_depends) # Write out the compilation steps, if any. link_deps = [] sources = extra_sources + spec.get('sources', []) if sources: if self.flavor == 'mac' and len(self.archs) > 1: # Write subninja file containing compile and link commands scoped to # a single arch if a fat binary is being built. for arch in self.archs: self.ninja.subninja(self._SubninjaNameForArch(arch)) pch = None if self.flavor == 'win': gyp.msvs_emulation.VerifyMissingSources( sources, self.abs_build_dir, generator_flags, self.GypPathToNinja) pch = gyp.msvs_emulation.PrecompiledHeader( self.msvs_settings, config_name, self.GypPathToNinja, self.GypPathToUniqueOutput, self.obj_ext) else: pch = gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, self.GypPathToNinja, lambda path, lang: self.GypPathToUniqueOutput(path + '-' + lang)) link_deps = self.WriteSources( self.ninja, config_name, config, sources, compile_depends_stamp, pch, spec) # Some actions/rules output 'sources' that are already object files. obj_outputs = [f for f in sources if f.endswith(self.obj_ext)] if obj_outputs: if self.flavor != 'mac' or len(self.archs) == 1: link_deps += [self.GypPathToNinja(o) for o in obj_outputs] else: print "Warning: Actions/rules writing object files don't work with " \ "multiarch targets, dropping. (target %s)" % spec['target_name'] elif self.flavor == 'mac' and len(self.archs) > 1: link_deps = collections.defaultdict(list) compile_deps = self.target.actions_stamp or actions_depends if self.flavor == 'win' and self.target.type == 'static_library': self.target.component_objs = link_deps self.target.compile_deps = compile_deps # Write out a link step, if needed. output = None is_empty_bundle = not link_deps and not mac_bundle_depends if link_deps or self.target.actions_stamp or actions_depends: output = self.WriteTarget(spec, config_name, config, link_deps, compile_deps) if self.is_mac_bundle: mac_bundle_depends.append(output) # Bundle all of the above together, if needed. if self.is_mac_bundle: output = self.WriteMacBundle(spec, mac_bundle_depends, is_empty_bundle) if not output: return None assert self.target.FinalOutput(), output return self.target def _WinIdlRule(self, source, prebuild, outputs): """Handle the implicit VS .idl rule for one source file. Fills |outputs| with files that are generated.""" outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData( source, self.config_name) outdir = self.GypPathToNinja(outdir) def fix_path(path, rel=None): path = os.path.join(outdir, path) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) path = self.ExpandRuleVariables( path, root, dirname, source, ext, basename) if rel: path = os.path.relpath(path, rel) return path vars = [(name, fix_path(value, outdir)) for name, value in vars] output = [fix_path(p) for p in output] vars.append(('outdir', outdir)) vars.append(('idlflags', flags)) input = self.GypPathToNinja(source) self.ninja.build(output, 'idl', input, variables=vars, order_only=prebuild) outputs.extend(output) def WriteWinIdlFiles(self, spec, prebuild): """Writes rules to match MSVS's implicit idl handling.""" assert self.flavor == 'win' if self.msvs_settings.HasExplicitIdlRulesOrActions(spec): return [] outputs = [] for source in filter(lambda x: x.endswith('.idl'), spec['sources']): self._WinIdlRule(source, prebuild, outputs) return outputs def WriteActionsRulesCopies(self, spec, extra_sources, prebuild, mac_bundle_depends): """Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.""" outputs = [] if self.is_mac_bundle: mac_bundle_resources = spec.get('mac_bundle_resources', [])[:] else: mac_bundle_resources = [] extra_mac_bundle_resources = [] if 'actions' in spec: outputs += self.WriteActions(spec['actions'], extra_sources, prebuild, extra_mac_bundle_resources) if 'rules' in spec: outputs += self.WriteRules(spec['rules'], extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources) if 'copies' in spec: outputs += self.WriteCopies(spec['copies'], prebuild, mac_bundle_depends) if 'sources' in spec and self.flavor == 'win': outputs += self.WriteWinIdlFiles(spec, prebuild) stamp = self.WriteCollapsedDependencies('actions_rules_copies', outputs) if self.is_mac_bundle: xcassets = self.WriteMacBundleResources( extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends) partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends) self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends) return stamp def GenerateDescription(self, verb, message, fallback): """Generate and return a description of a build step. |verb| is the short summary, e.g. ACTION or RULE. |message| is a hand-written description, or None if not available. |fallback| is the gyp-level name of the step, usable as a fallback. """ if self.toolset != 'target': verb += '(%s)' % self.toolset if message: return '%s %s' % (verb, self.ExpandSpecial(message)) else: return '%s %s: %s' % (verb, self.name, fallback) def WriteActions(self, actions, extra_sources, prebuild, extra_mac_bundle_resources): # Actions cd into the base directory. env = self.GetToolchainEnv() all_outputs = [] for action in actions: # First write out a rule for the action. name = '%s_%s' % (action['action_name'], self.hash_for_rules) description = self.GenerateDescription('ACTION', action.get('message', None), name) is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(action) if self.flavor == 'win' else False) args = action['action'] depfile = action.get('depfile', None) if depfile: depfile = self.ExpandSpecial(depfile, self.base_to_build) pool = 'console' if int(action.get('ninja_use_console', 0)) else None rule_name, _ = self.WriteNewNinjaRule(name, args, description, is_cygwin, env, pool, depfile=depfile) inputs = [self.GypPathToNinja(i, env) for i in action['inputs']] if int(action.get('process_outputs_as_sources', False)): extra_sources += action['outputs'] if int(action.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += action['outputs'] outputs = [self.GypPathToNinja(o, env) for o in action['outputs']] # Then write out an edge using the rule. self.ninja.build(outputs, rule_name, inputs, order_only=prebuild) all_outputs += outputs self.ninja.newline() return all_outputs def WriteRules(self, rules, extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources): env = self.GetToolchainEnv() all_outputs = [] for rule in rules: # Skip a rule with no action and no inputs. if 'action' not in rule and not rule.get('rule_sources', []): continue # First write out a rule for the rule action. name = '%s_%s' % (rule['rule_name'], self.hash_for_rules) args = rule['action'] description = self.GenerateDescription( 'RULE', rule.get('message', None), ('%s ' + generator_default_variables['RULE_INPUT_PATH']) % name) is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(rule) if self.flavor == 'win' else False) pool = 'console' if int(rule.get('ninja_use_console', 0)) else None rule_name, args = self.WriteNewNinjaRule( name, args, description, is_cygwin, env, pool) # TODO: if the command references the outputs directly, we should # simplify it to just use $out. # Rules can potentially make use of some special variables which # must vary per source file. # Compute the list of variables we'll need to provide. special_locals = ('source', 'root', 'dirname', 'ext', 'name') needed_variables = set(['source']) for argument in args: for var in special_locals: if '${%s}' % var in argument: needed_variables.add(var) def cygwin_munge(path): # pylint: disable=cell-var-from-loop if is_cygwin: return path.replace('\\', '/') return path inputs = [self.GypPathToNinja(i, env) for i in rule.get('inputs', [])] # If there are n source files matching the rule, and m additional rule # inputs, then adding 'inputs' to each build edge written below will # write m * n inputs. Collapsing reduces this to m + n. sources = rule.get('rule_sources', []) num_inputs = len(inputs) if prebuild: num_inputs += 1 if num_inputs > 2 and len(sources) > 2: inputs = [self.WriteCollapsedDependencies( rule['rule_name'], inputs, order_only=prebuild)] prebuild = [] # For each source file, write an edge that generates all the outputs. for source in sources: source = os.path.normpath(source) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) # Gather the list of inputs and outputs, expanding $vars if possible. outputs = [self.ExpandRuleVariables(o, root, dirname, source, ext, basename) for o in rule['outputs']] if int(rule.get('process_outputs_as_sources', False)): extra_sources += outputs was_mac_bundle_resource = source in mac_bundle_resources if was_mac_bundle_resource or \ int(rule.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs # Note: This is n_resources * n_outputs_in_rule. Put to-be-removed # items in a set and remove them all in a single pass if this becomes # a performance issue. if was_mac_bundle_resource: mac_bundle_resources.remove(source) extra_bindings = [] for var in needed_variables: if var == 'root': extra_bindings.append(('root', cygwin_munge(root))) elif var == 'dirname': # '$dirname' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. dirname_expanded = self.ExpandSpecial(dirname, self.base_to_build) extra_bindings.append(('dirname', cygwin_munge(dirname_expanded))) elif var == 'source': # '$source' is a parameter to the rule action, which means # it shouldn't be converted to a Ninja path. But we don't # want $!PRODUCT_DIR in there either. source_expanded = self.ExpandSpecial(source, self.base_to_build) extra_bindings.append(('source', cygwin_munge(source_expanded))) elif var == 'ext': extra_bindings.append(('ext', ext)) elif var == 'name': extra_bindings.append(('name', cygwin_munge(basename))) else: assert var == None, repr(var) outputs = [self.GypPathToNinja(o, env) for o in outputs] if self.flavor == 'win': # WriteNewNinjaRule uses unique_name for creating an rsp file on win. extra_bindings.append(('unique_name', hashlib.md5(outputs[0]).hexdigest())) self.ninja.build(outputs, rule_name, self.GypPathToNinja(source), implicit=inputs, order_only=prebuild, variables=extra_bindings) all_outputs.extend(outputs) return all_outputs def WriteCopies(self, copies, prebuild, mac_bundle_depends): outputs = [] env = self.GetToolchainEnv() for copy in copies: for path in copy['files']: # Normalize the path so trailing slashes don't confuse us. path = os.path.normpath(path) basename = os.path.split(path)[1] src = self.GypPathToNinja(path, env) dst = self.GypPathToNinja(os.path.join(copy['destination'], basename), env) outputs += self.ninja.build(dst, 'copy', src, order_only=prebuild) if self.is_mac_bundle: # gyp has mac_bundle_resources to copy things into a bundle's # Resources folder, but there's no built-in way to copy files to other # places in the bundle. Hence, some targets use copies for this. Check # if this file is copied into the current bundle, and if so add it to # the bundle depends so that dependent targets get rebuilt if the copy # input changes. if dst.startswith(self.xcode_settings.GetBundleContentsFolderPath()): mac_bundle_depends.append(dst) return outputs def WriteMacBundleResources(self, resources, bundle_depends): """Writes ninja edges for 'mac_bundle_resources'.""" xcassets = [] for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, map(self.GypPathToNinja, resources)): output = self.ExpandSpecial(output) if os.path.splitext(output)[-1] != '.xcassets': isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build(output, 'mac_tool', res, variables=[('mactool_cmd', 'copy-bundle-resource'), \ ('binary', isBinary)]) bundle_depends.append(output) else: xcassets.append(res) return xcassets def WriteMacXCassets(self, xcassets, bundle_depends): """Writes ninja edges for 'mac_bundle_resources' .xcassets files. This add an invocation of 'actool' via the 'mac_tool.py' helper script. It assumes that the assets catalogs define at least one imageset and thus an Assets.car file will be generated in the application resources directory. If this is not the case, then the build will probably be done at each invocation of ninja.""" if not xcassets: return extra_arguments = {} settings_to_arg = { 'XCASSETS_APP_ICON': 'app-icon', 'XCASSETS_LAUNCH_IMAGE': 'launch-image', } settings = self.xcode_settings.xcode_settings[self.config_name] for settings_key, arg_name in settings_to_arg.iteritems(): value = settings.get(settings_key) if value: extra_arguments[arg_name] = value partial_info_plist = None if extra_arguments: partial_info_plist = self.GypPathToUniqueOutput( 'assetcatalog_generated_info.plist') extra_arguments['output-partial-info-plist'] = partial_info_plist outputs = [] outputs.append( os.path.join( self.xcode_settings.GetBundleResourceFolder(), 'Assets.car')) if partial_info_plist: outputs.append(partial_info_plist) keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor) extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) bundle_depends.extend(self.ninja.build( outputs, 'compile_xcassets', xcassets, variables=[('env', env), ('keys', keys)])) return partial_info_plist def WriteMacInfoPlist(self, partial_info_plist, bundle_depends): """Write build rules for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, self.GypPathToNinja) if not info_plist: return out = self.ExpandSpecial(out) if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = self.GypPathToUniqueOutput( os.path.basename(info_plist)) defines = ' '.join([Define(d, self.flavor) for d in defines]) info_plist = self.ninja.build( intermediate_plist, 'preprocess_infoplist', info_plist, variables=[('defines',defines)]) env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) if partial_info_plist: intermediate_plist = self.GypPathToUniqueOutput('merged_info.plist') info_plist = self.ninja.build( intermediate_plist, 'merge_infoplist', [partial_info_plist, info_plist]) keys = self.xcode_settings.GetExtraPlistItems(self.config_name) keys = QuoteShellArgument(json.dumps(keys), self.flavor) isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build(out, 'copy_infoplist', info_plist, variables=[('env', env), ('keys', keys), ('binary', isBinary)]) bundle_depends.append(out) def WriteSources(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec): """Write build rules to compile all of |sources|.""" if self.toolset == 'host': self.ninja.variable('ar', '$ar_host') self.ninja.variable('cc', '$cc_host') self.ninja.variable('cxx', '$cxx_host') self.ninja.variable('ld', '$ld_host') self.ninja.variable('ldxx', '$ldxx_host') self.ninja.variable('nm', '$nm_host') self.ninja.variable('readelf', '$readelf_host') if self.flavor != 'mac' or len(self.archs) == 1: return self.WriteSourcesForArch( self.ninja, config_name, config, sources, predepends, precompiled_header, spec) else: return dict((arch, self.WriteSourcesForArch( self.arch_subninjas[arch], config_name, config, sources, predepends, precompiled_header, spec, arch=arch)) for arch in self.archs) def WriteSourcesForArch(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, arch=None): """Write build rules to compile all of |sources|.""" extra_defines = [] if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(config_name, arch=arch) cflags_c = self.xcode_settings.GetCflagsC(config_name) cflags_cc = self.xcode_settings.GetCflagsCC(config_name) cflags_objc = ['$cflags_c'] + \ self.xcode_settings.GetCflagsObjC(config_name) cflags_objcc = ['$cflags_cc'] + \ self.xcode_settings.GetCflagsObjCC(config_name) elif self.flavor == 'win': asmflags = self.msvs_settings.GetAsmflags(config_name) cflags = self.msvs_settings.GetCflags(config_name) cflags_c = self.msvs_settings.GetCflagsC(config_name) cflags_cc = self.msvs_settings.GetCflagsCC(config_name) extra_defines = self.msvs_settings.GetComputedDefines(config_name) # See comment at cc_command for why there's two .pdb files. pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName( config_name, self.ExpandSpecial) if not pdbpath_c: obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name)) pdbpath_c = pdbpath + '.c.pdb' pdbpath_cc = pdbpath + '.cc.pdb' self.WriteVariableList(ninja_file, 'pdbname_c', [pdbpath_c]) self.WriteVariableList(ninja_file, 'pdbname_cc', [pdbpath_cc]) self.WriteVariableList(ninja_file, 'pchprefix', [self.name]) else: cflags = config.get('cflags', []) cflags_c = config.get('cflags_c', []) cflags_cc = config.get('cflags_cc', []) # Respect environment variables related to build, but target-specific # flags can still override them. if self.toolset == 'target': cflags_c = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CFLAGS', '').split() + cflags_c) cflags_cc = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CXXFLAGS', '').split() + cflags_cc) elif self.toolset == 'host': cflags_c = (os.environ.get('CPPFLAGS_host', '').split() + os.environ.get('CFLAGS_host', '').split() + cflags_c) cflags_cc = (os.environ.get('CPPFLAGS_host', '').split() + os.environ.get('CXXFLAGS_host', '').split() + cflags_cc) defines = config.get('defines', []) + extra_defines self.WriteVariableList(ninja_file, 'defines', [Define(d, self.flavor) for d in defines]) if self.flavor == 'win': self.WriteVariableList(ninja_file, 'asmflags', map(self.ExpandSpecial, asmflags)) self.WriteVariableList(ninja_file, 'rcflags', [QuoteShellArgument(self.ExpandSpecial(f), self.flavor) for f in self.msvs_settings.GetRcflags(config_name, self.GypPathToNinja)]) include_dirs = config.get('include_dirs', []) env = self.GetToolchainEnv() if self.flavor == 'win': include_dirs = self.msvs_settings.AdjustIncludeDirs(include_dirs, config_name) self.WriteVariableList(ninja_file, 'includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in include_dirs]) if self.flavor == 'win': midl_include_dirs = config.get('midl_include_dirs', []) midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs( midl_include_dirs, config_name) self.WriteVariableList(ninja_file, 'midl_includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in midl_include_dirs]) pch_commands = precompiled_header.GetPchBuildCommands(arch) if self.flavor == 'mac': # Most targets use no precompiled headers, so only write these if needed. for ext, var in [('c', 'cflags_pch_c'), ('cc', 'cflags_pch_cc'), ('m', 'cflags_pch_objc'), ('mm', 'cflags_pch_objcc')]: include = precompiled_header.GetInclude(ext, arch) if include: ninja_file.variable(var, include) arflags = config.get('arflags', []) self.WriteVariableList(ninja_file, 'cflags', map(self.ExpandSpecial, cflags)) self.WriteVariableList(ninja_file, 'cflags_c', map(self.ExpandSpecial, cflags_c)) self.WriteVariableList(ninja_file, 'cflags_cc', map(self.ExpandSpecial, cflags_cc)) if self.flavor == 'mac': self.WriteVariableList(ninja_file, 'cflags_objc', map(self.ExpandSpecial, cflags_objc)) self.WriteVariableList(ninja_file, 'cflags_objcc', map(self.ExpandSpecial, cflags_objcc)) self.WriteVariableList(ninja_file, 'arflags', map(self.ExpandSpecial, arflags)) ninja_file.newline() outputs = [] has_rc_source = False for source in sources: filename, ext = os.path.splitext(source) ext = ext[1:] obj_ext = self.obj_ext if ext in ('cc', 'cpp', 'cxx'): command = 'cxx' self.uses_cpp = True elif ext == 'c' or (ext == 'S' and self.flavor != 'win'): command = 'cc' elif ext == 's' and self.flavor != 'win': # Doesn't generate .o.d files. command = 'cc_s' elif (self.flavor == 'win' and ext == 'asm' and not self.msvs_settings.HasExplicitAsmRules(spec)): command = 'asm' # Add the _asm suffix as msvs is capable of handling .cc and # .asm files of the same name without collision. obj_ext = '_asm.obj' elif self.flavor == 'mac' and ext == 'm': command = 'objc' elif self.flavor == 'mac' and ext == 'mm': command = 'objcxx' self.uses_cpp = True elif self.flavor == 'win' and ext == 'rc': command = 'rc' obj_ext = '.res' has_rc_source = True else: # Ignore unhandled extensions. continue input = self.GypPathToNinja(source) output = self.GypPathToUniqueOutput(filename + obj_ext) if arch is not None: output = AddArch(output, arch) implicit = precompiled_header.GetObjDependencies([input], [output], arch) variables = [] if self.flavor == 'win': variables, output, implicit = precompiled_header.GetFlagsModifications( input, output, implicit, command, cflags_c, cflags_cc, self.ExpandSpecial) ninja_file.build(output, command, input, implicit=[gch for _, _, gch in implicit], order_only=predepends, variables=variables) outputs.append(output) if has_rc_source: resource_include_dirs = config.get('resource_include_dirs', include_dirs) self.WriteVariableList(ninja_file, 'resource_includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in resource_include_dirs]) self.WritePchTargets(ninja_file, pch_commands) ninja_file.newline() return outputs def WritePchTargets(self, ninja_file, pch_commands): """Writes ninja rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: var_name = { 'c': 'cflags_pch_c', 'cc': 'cflags_pch_cc', 'm': 'cflags_pch_objc', 'mm': 'cflags_pch_objcc', }[lang] map = { 'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx', } cmd = map.get(lang) ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)]) def WriteLink(self, spec, config_name, config, link_deps): """Write out a link step. Fills out target.binary. """ if self.flavor != 'mac' or len(self.archs) == 1: return self.WriteLinkForArch( self.ninja, spec, config_name, config, link_deps) else: output = self.ComputeOutput(spec) inputs = [self.WriteLinkForArch(self.arch_subninjas[arch], spec, config_name, config, link_deps[arch], arch=arch) for arch in self.archs] extra_bindings = [] build_output = output if not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) # TODO(yyanagisawa): more work needed to fix: # https://code.google.com/p/gyp/issues/detail?id=411 if (spec['type'] in ('shared_library', 'loadable_module') and not self.is_mac_bundle): extra_bindings.append(('lib', output)) self.ninja.build([output, output + '.TOC'], 'solipo', inputs, variables=extra_bindings) else: self.ninja.build(build_output, 'lipo', inputs, variables=extra_bindings) return output def WriteLinkForArch(self, ninja_file, spec, config_name, config, link_deps, arch=None): """Write out a link step. Fills out target.binary. """ command = { 'executable': 'link', 'loadable_module': 'solink_module', 'shared_library': 'solink', }[spec['type']] command_suffix = '' implicit_deps = set() solibs = set() order_deps = set() if 'dependencies' in spec: # Two kinds of dependencies: # - Linkable dependencies (like a .a or a .so): add them to the link line. # - Non-linkable dependencies (like a rule that generates a file # and writes a stamp file): add them to implicit_deps extra_link_deps = set() for dep in spec['dependencies']: target = self.target_outputs.get(dep) if not target: continue linkable = target.Linkable() if linkable: new_deps = [] if (self.flavor == 'win' and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name)): new_deps = target.component_objs if target.compile_deps: order_deps.add(target.compile_deps) elif self.flavor == 'win' and target.import_lib: new_deps = [target.import_lib] elif target.UsesToc(self.flavor): solibs.add(target.binary) implicit_deps.add(target.binary + '.TOC') else: new_deps = [target.binary] for new_dep in new_deps: if new_dep not in extra_link_deps: extra_link_deps.add(new_dep) link_deps.append(new_dep) final_output = target.FinalOutput() if not linkable or final_output != target.binary: implicit_deps.add(final_output) extra_bindings = [] if self.uses_cpp and self.flavor != 'win': extra_bindings.append(('ld', '$ldxx')) output = self.ComputeOutput(spec, arch) if arch is None and not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) is_executable = spec['type'] == 'executable' # The ldflags config key is not used on mac or win. On those platforms # linker flags are set via xcode_settings and msvs_settings, respectively. env_ldflags = os.environ.get('LDFLAGS', '').split() if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(config_name, self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self.GypPathToNinja, arch) ldflags = env_ldflags + ldflags elif self.flavor == 'win': manifest_base_name = self.GypPathToUniqueOutput( self.ComputeOutputFileName(spec)) ldflags, intermediate_manifest, manifest_files = \ self.msvs_settings.GetLdflags(config_name, self.GypPathToNinja, self.ExpandSpecial, manifest_base_name, output, is_executable, self.toplevel_build) ldflags = env_ldflags + ldflags self.WriteVariableList(ninja_file, 'manifests', manifest_files) implicit_deps = implicit_deps.union(manifest_files) if intermediate_manifest: self.WriteVariableList( ninja_file, 'intermediatemanifest', [intermediate_manifest]) command_suffix = _GetWinLinkRuleNameSuffix( self.msvs_settings.IsEmbedManifest(config_name)) def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja) if def_file: implicit_deps.add(def_file) else: # Respect environment variables related to build, but target-specific # flags can still override them. ldflags = env_ldflags + config.get('ldflags', []) if is_executable and len(solibs): rpath = 'lib/' if self.toolset != 'target': rpath += self.toolset ldflags.append(r'-Wl,-rpath=\$$ORIGIN/%s' % rpath) ldflags.append('-Wl,-rpath-link=%s' % rpath) self.WriteVariableList(ninja_file, 'ldflags', map(self.ExpandSpecial, ldflags)) library_dirs = config.get('library_dirs', []) if self.flavor == 'win': library_dirs = [self.msvs_settings.ConvertVSMacros(l, config_name) for l in library_dirs] library_dirs = ['/LIBPATH:' + QuoteShellArgument(self.GypPathToNinja(l), self.flavor) for l in library_dirs] else: library_dirs = [QuoteShellArgument('-L' + self.GypPathToNinja(l), self.flavor) for l in library_dirs] libraries = gyp.common.uniquer(map(self.ExpandSpecial, spec.get('libraries', []))) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries, config_name) elif self.flavor == 'win': libraries = self.msvs_settings.AdjustLibraries(libraries) self.WriteVariableList(ninja_file, 'libs', library_dirs + libraries) linked_binary = output if command in ('solink', 'solink_module'): extra_bindings.append(('soname', os.path.split(output)[1])) extra_bindings.append(('lib', gyp.common.EncodePOSIXShellArgument(output))) if self.flavor != 'win': link_file_list = output if self.is_mac_bundle: # 'Dependency Framework.framework/Versions/A/Dependency Framework' -> # 'Dependency Framework.framework.rsp' link_file_list = self.xcode_settings.GetWrapperName() if arch: link_file_list += '.' + arch link_file_list += '.rsp' # If an rspfile contains spaces, ninja surrounds the filename with # quotes around it and then passes it to open(), creating a file with # quotes in its name (and when looking for the rsp file, the name # makes it through bash which strips the quotes) :-/ link_file_list = link_file_list.replace(' ', '_') extra_bindings.append( ('link_file_list', gyp.common.EncodePOSIXShellArgument(link_file_list))) if self.flavor == 'win': extra_bindings.append(('binary', output)) if ('/NOENTRY' not in ldflags and not self.msvs_settings.GetNoImportLibrary(config_name)): self.target.import_lib = output + '.lib' extra_bindings.append(('implibflag', '/IMPLIB:%s' % self.target.import_lib)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') output = [output, self.target.import_lib] if pdbname: output.append(pdbname) elif not self.is_mac_bundle: output = [output, output + '.TOC'] else: command = command + '_notoc' elif self.flavor == 'win': extra_bindings.append(('binary', output)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') if pdbname: output = [output, pdbname] if len(solibs): extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(solibs))) ninja_file.build(output, command + command_suffix, link_deps, implicit=list(implicit_deps), order_only=list(order_deps), variables=extra_bindings) return linked_binary def WriteTarget(self, spec, config_name, config, link_deps, compile_deps): extra_link_deps = any(self.target_outputs.get(dep).Linkable() for dep in spec.get('dependencies', []) if dep in self.target_outputs) if spec['type'] == 'none' or (not link_deps and not extra_link_deps): # TODO(evan): don't call this function for 'none' target types, as # it doesn't do anything, and we fake out a 'binary' with a stamp file. self.target.binary = compile_deps self.target.type = 'none' elif spec['type'] == 'static_library': self.target.binary = self.ComputeOutput(spec) if (self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not self.is_standalone_static_library): self.ninja.build(self.target.binary, 'alink_thin', link_deps, order_only=compile_deps) else: variables = [] if self.xcode_settings: libtool_flags = self.xcode_settings.GetLibtoolflags(config_name) if libtool_flags: variables.append(('libtool_flags', libtool_flags)) if self.msvs_settings: libflags = self.msvs_settings.GetLibFlags(config_name, self.GypPathToNinja) variables.append(('libflags', libflags)) if self.flavor != 'mac' or len(self.archs) == 1: self.AppendPostbuildVariable(variables, spec, self.target.binary, self.target.binary) self.ninja.build(self.target.binary, 'alink', link_deps, order_only=compile_deps, variables=variables) else: inputs = [] for arch in self.archs: output = self.ComputeOutput(spec, arch) self.arch_subninjas[arch].build(output, 'alink', link_deps[arch], order_only=compile_deps, variables=variables) inputs.append(output) # TODO: It's not clear if libtool_flags should be passed to the alink # call that combines single-arch .a files into a fat .a file. self.AppendPostbuildVariable(variables, spec, self.target.binary, self.target.binary) self.ninja.build(self.target.binary, 'alink', inputs, # FIXME: test proving order_only=compile_deps isn't # needed. variables=variables) else: self.target.binary = self.WriteLink(spec, config_name, config, link_deps) return self.target.binary def WriteMacBundle(self, spec, mac_bundle_depends, is_empty): assert self.is_mac_bundle package_framework = spec['type'] in ('shared_library', 'loadable_module') output = self.ComputeMacBundleOutput() if is_empty: output += '.stamp' variables = [] self.AppendPostbuildVariable(variables, spec, output, self.target.binary, is_command_start=not package_framework) if package_framework and not is_empty: variables.append(('version', self.xcode_settings.GetFrameworkVersion())) self.ninja.build(output, 'package_framework', mac_bundle_depends, variables=variables) else: self.ninja.build(output, 'stamp', mac_bundle_depends, variables=variables) self.target.bundle = output return output def GetToolchainEnv(self, additional_settings=None): """Returns the variables toolchain would set for build steps.""" env = self.GetSortedXcodeEnv(additional_settings=additional_settings) if self.flavor == 'win': env = self.GetMsvsToolchainEnv( additional_settings=additional_settings) return env def GetMsvsToolchainEnv(self, additional_settings=None): """Returns the variables Visual Studio would set for build steps.""" return self.msvs_settings.GetVSMacroEnv('$!PRODUCT_DIR', config=self.config_name) def GetSortedXcodeEnv(self, additional_settings=None): """Returns the variables Xcode would set for build steps.""" assert self.abs_build_dir abs_build_dir = self.abs_build_dir return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, abs_build_dir, os.path.join(abs_build_dir, self.build_to_base), self.config_name, additional_settings) def GetSortedXcodePostbuildEnv(self): """Returns the variables Xcode would set for postbuild steps.""" postbuild_settings = {} # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( 'CHROMIUM_STRIP_SAVE_FILE') if strip_save_file: postbuild_settings['CHROMIUM_STRIP_SAVE_FILE'] = strip_save_file return self.GetSortedXcodeEnv(additional_settings=postbuild_settings) def AppendPostbuildVariable(self, variables, spec, output, binary, is_command_start=False): """Adds a 'postbuild' variable if there is a postbuild for |output|.""" postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start) if postbuild: variables.append(('postbuilds', postbuild)) def GetPostbuildCommand(self, spec, output, output_binary, is_command_start): """Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.""" if not self.xcode_settings or spec['type'] == 'none' or not output: return '' output = QuoteShellArgument(output, self.flavor) postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True) if output_binary is not None: postbuilds = self.xcode_settings.AddImplicitPostbuilds( self.config_name, os.path.normpath(os.path.join(self.base_to_build, output)), QuoteShellArgument( os.path.normpath(os.path.join(self.base_to_build, output_binary)), self.flavor), postbuilds, quiet=True) if not postbuilds: return '' # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList( ['cd', self.build_to_base])) env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv()) # G will be non-null if any postbuild fails. Run all postbuilds in a # subshell. commands = env + ' (' + \ ' && '.join([ninja_syntax.escape(command) for command in postbuilds]) command_string = (commands + '); G=$$?; ' # Remove the final output if any postbuild failed. '((exit $$G) || rm -rf %s) ' % output + '&& exit $$G)') if is_command_start: return '(' + command_string + ' && ' else: return '$ && (' + command_string def ComputeExportEnvString(self, env): """Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.""" export_str = [] for k, v in env: export_str.append('export %s=%s;' % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v)))) return ' '.join(export_str) def ComputeMacBundleOutput(self): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables['PRODUCT_DIR'] return self.ExpandSpecial( os.path.join(path, self.xcode_settings.GetWrapperName())) def ComputeOutputFileName(self, spec, type=None): """Compute the filename of the final output for the current target.""" if not type: type = spec['type'] default_variables = copy.copy(generator_default_variables) CalculateVariables(default_variables, {'flavor': self.flavor}) # Compute filename prefix: the product prefix, or a default for # the product type. DEFAULT_PREFIX = { 'loadable_module': default_variables['SHARED_LIB_PREFIX'], 'shared_library': default_variables['SHARED_LIB_PREFIX'], 'static_library': default_variables['STATIC_LIB_PREFIX'], 'executable': default_variables['EXECUTABLE_PREFIX'], } prefix = spec.get('product_prefix', DEFAULT_PREFIX.get(type, '')) # Compute filename extension: the product extension, or a default # for the product type. DEFAULT_EXTENSION = { 'loadable_module': default_variables['SHARED_LIB_SUFFIX'], 'shared_library': default_variables['SHARED_LIB_SUFFIX'], 'static_library': default_variables['STATIC_LIB_SUFFIX'], 'executable': default_variables['EXECUTABLE_SUFFIX'], } extension = spec.get('product_extension') if extension: extension = '.' + extension else: extension = DEFAULT_EXTENSION.get(type, '') if 'product_name' in spec: # If we were given an explicit name, use that. target = spec['product_name'] else: # Otherwise, derive a name from the target name. target = spec['target_name'] if prefix == 'lib': # Snip out an extra 'lib' from libs if appropriate. target = StripPrefix(target, 'lib') if type in ('static_library', 'loadable_module', 'shared_library', 'executable'): return '%s%s%s' % (prefix, target, extension) elif type == 'none': return '%s.stamp' % target else: raise Exception('Unhandled output type %s' % type) def ComputeOutput(self, spec, arch=None): """Compute the path for the final output of the spec.""" type = spec['type'] if self.flavor == 'win': override = self.msvs_settings.GetOutputName(self.config_name, self.ExpandSpecial) if override: return override if arch is None and self.flavor == 'mac' and type in ( 'static_library', 'executable', 'shared_library', 'loadable_module'): filename = self.xcode_settings.GetExecutablePath() else: filename = self.ComputeOutputFileName(spec, type) if arch is None and 'product_dir' in spec: path = os.path.join(spec['product_dir'], filename) return self.ExpandSpecial(path) # Some products go into the output root, libraries go into shared library # dir, and everything else goes into the normal place. type_in_output_root = ['executable', 'loadable_module'] if self.flavor == 'mac' and self.toolset == 'target': type_in_output_root += ['shared_library', 'static_library'] elif self.flavor == 'win' and self.toolset == 'target': type_in_output_root += ['shared_library'] if arch is not None: # Make sure partial executables don't end up in a bundle or the regular # output directory. archdir = 'arch' if self.toolset != 'target': archdir = os.path.join('arch', '%s' % self.toolset) return os.path.join(archdir, AddArch(filename, arch)) elif type in type_in_output_root or self.is_standalone_static_library: return filename elif type == 'shared_library': libdir = 'lib' if self.toolset != 'target': libdir = os.path.join('lib', '%s' % self.toolset) return os.path.join(libdir, filename) else: return self.GypPathToUniqueOutput(filename, qualified=False) def WriteVariableList(self, ninja_file, var, values): assert not isinstance(values, str) if values is None: values = [] ninja_file.variable(var, ' '.join(values)) def WriteNewNinjaRule(self, name, args, description, is_cygwin, env, pool, depfile=None): """Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.""" if self.flavor == 'win': args = [self.msvs_settings.ConvertVSMacros( arg, self.base_to_build, config=self.config_name) for arg in args] description = self.msvs_settings.ConvertVSMacros( description, config=self.config_name) elif self.flavor == 'mac': # |env| is an empty list on non-mac. args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args] description = gyp.xcode_emulation.ExpandEnvVars(description, env) # TODO: we shouldn't need to qualify names; we do it because # currently the ninja rule namespace is global, but it really # should be scoped to the subninja. rule_name = self.name if self.toolset == 'target': rule_name += '.' + self.toolset rule_name += '.' + name rule_name = re.sub('[^a-zA-Z0-9_]', '_', rule_name) # Remove variable references, but not if they refer to the magic rule # variables. This is not quite right, as it also protects these for # actions, not just for rules where they are valid. Good enough. protect = [ '${root}', '${dirname}', '${source}', '${ext}', '${name}' ] protect = '(?!' + '|'.join(map(re.escape, protect)) + ')' description = re.sub(protect + r'\$', '_', description) # gyp dictates that commands are run from the base directory. # cd into the directory before running, and adjust paths in # the arguments to point to the proper locations. rspfile = None rspfile_content = None args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args] if self.flavor == 'win': rspfile = rule_name + '.$unique_name.rsp' # The cygwin case handles this inside the bash sub-shell. run_in = '' if is_cygwin else ' ' + self.build_to_base if is_cygwin: rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine( args, self.build_to_base) else: rspfile_content = gyp.msvs_emulation.EncodeRspFileList(args) command = ('%s gyp-win-tool action-wrapper $arch ' % sys.executable + rspfile + run_in) else: env = self.ComputeExportEnvString(env) command = gyp.common.EncodePOSIXShellList(args) command = 'cd %s; ' % self.build_to_base + env + command # GYP rules/actions express being no-ops by not touching their outputs. # Avoid executing downstream dependencies in this case by specifying # restat=1 to ninja. self.ninja.rule(rule_name, command, description, depfile=depfile, restat=True, pool=pool, rspfile=rspfile, rspfile_content=rspfile_content) self.ninja.newline() return rule_name, args def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" global generator_additional_non_configuration_keys global generator_additional_path_sections flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. import gyp.generator.xcode as xcode_generator generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) elif flavor == 'win': exts = gyp.MSVSUtil.TARGET_TYPE_EXT default_variables.setdefault('OS', 'win') default_variables['EXECUTABLE_SUFFIX'] = '.' + exts['executable'] default_variables['STATIC_LIB_PREFIX'] = '' default_variables['STATIC_LIB_SUFFIX'] = '.' + exts['static_library'] default_variables['SHARED_LIB_PREFIX'] = '' default_variables['SHARED_LIB_SUFFIX'] = '.' + exts['shared_library'] # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR', os.path.join('$!PRODUCT_DIR', 'lib')) default_variables.setdefault('LIB_DIR', os.path.join('$!PRODUCT_DIR', 'obj')) def ComputeOutputDir(params): """Returns the path from the toplevel_dir to the build output directory.""" # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to ninja easier, ninja doesn't put anything here. generator_dir = os.path.relpath(params['options'].generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = params.get('generator_flags', {}).get('output_dir', 'out') # Relative path from source root to our output files. e.g. "out" return os.path.normpath(os.path.join(generator_dir, output_dir)) def CalculateGeneratorInputInfo(params): """Called by __init__ to initialize generator values based on params.""" # E.g. "out/gypfiles" toplevel = params['options'].toplevel_dir qualified_out_dir = os.path.normpath(os.path.join( toplevel, ComputeOutputDir(params), 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': toplevel, 'qualified_out_dir': qualified_out_dir, } def OpenOutput(path, mode='w'): """Open |path| for writing, creating directories if necessary.""" gyp.common.EnsureDirExists(path) return open(path, mode) def CommandWithWrapper(cmd, wrappers, prog): wrapper = wrappers.get(cmd, '') if wrapper: return wrapper + ' ' + prog return prog def GetDefaultConcurrentLinks(): """Returns a best-guess for a number of concurrent links.""" pool_size = int(os.environ.get('GYP_LINK_CONCURRENCY', 0)) if pool_size: return pool_size if sys.platform in ('win32', 'cygwin'): import ctypes class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("sullAvailExtendedVirtual", ctypes.c_ulonglong), ] stat = MEMORYSTATUSEX() stat.dwLength = ctypes.sizeof(stat) ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) # VS 2015 uses 20% more working set than VS 2013 and can consume all RAM # on a 64 GB machine. mem_limit = max(1, stat.ullTotalPhys / (5 * (2 ** 30))) # total / 5GB hard_cap = max(1, int(os.environ.get('GYP_LINK_CONCURRENCY_MAX', 2**32))) return min(mem_limit, hard_cap) elif sys.platform.startswith('linux'): if os.path.exists("/proc/meminfo"): with open("/proc/meminfo") as meminfo: memtotal_re = re.compile(r'^MemTotal:\s*(\d*)\s*kB') for line in meminfo: match = memtotal_re.match(line) if not match: continue # Allow 8Gb per link on Linux because Gold is quite memory hungry return max(1, int(match.group(1)) / (8 * (2 ** 20))) return 1 elif sys.platform == 'darwin': try: avail_bytes = int(subprocess.check_output(['sysctl', '-n', 'hw.memsize'])) # A static library debug build of Chromium's unit_tests takes ~2.7GB, so # 4GB per ld process allows for some more bloat. return max(1, avail_bytes / (4 * (2 ** 30))) # total / 4GB except: return 1 else: # TODO(scottmg): Implement this for other platforms. return 1 def _GetWinLinkRuleNameSuffix(embed_manifest): """Returns the suffix used to select an appropriate linking rule depending on whether the manifest embedding is enabled.""" return '_embed' if embed_manifest else '' def _AddWinLinkRules(master_ninja, embed_manifest): """Adds link rules for Windows platform to |master_ninja|.""" def FullLinkCommand(ldcmd, out, binary_type): resource_name = { 'exe': '1', 'dll': '2', }[binary_type] return '%(python)s gyp-win-tool link-with-manifests $arch %(embed)s ' \ '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' \ '$manifests' % { 'python': sys.executable, 'out': out, 'ldcmd': ldcmd, 'resname': resource_name, 'embed': embed_manifest } rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest) use_separate_mspdbsrv = ( int(os.environ.get('GYP_USE_SEPARATE_MSPDBSRV', '0')) != 0) dlldesc = 'LINK%s(DLL) $binary' % rule_name_suffix.upper() dllcmd = ('%s gyp-win-tool link-wrapper $arch %s ' '$ld /nologo $implibflag /DLL /OUT:$binary ' '@$binary.rsp' % (sys.executable, use_separate_mspdbsrv)) dllcmd = FullLinkCommand(dllcmd, '$binary', 'dll') master_ninja.rule('solink' + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile='$binary.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True, pool='link_pool') master_ninja.rule('solink_module' + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile='$binary.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True, pool='link_pool') # Note that ldflags goes at the end so that it has the option of # overriding default settings earlier in the command line. exe_cmd = ('%s gyp-win-tool link-wrapper $arch %s ' '$ld /nologo /OUT:$binary @$binary.rsp' % (sys.executable, use_separate_mspdbsrv)) exe_cmd = FullLinkCommand(exe_cmd, '$binary', 'exe') master_ninja.rule('link' + rule_name_suffix, description='LINK%s $binary' % rule_name_suffix.upper(), command=exe_cmd, rspfile='$binary.rsp', rspfile_content='$in_newline $libs $ldflags', pool='link_pool') def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params['options'] flavor = gyp.common.GetFlavor(params) generator_flags = params.get('generator_flags', {}) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.normpath( os.path.join(ComputeOutputDir(params), config_name)) toplevel_build = os.path.join(options.toplevel_dir, build_dir) master_ninja_file = OpenOutput(os.path.join(toplevel_build, 'build.ninja')) master_ninja = ninja_syntax.Writer(master_ninja_file, width=120) # Put build-time support tools in out/{config_name}. gyp.common.CopyTool(flavor, toplevel_build) # Grab make settings for CC/CXX. # The rules are # - The priority from low to high is gcc/g++, the 'make_global_settings' in # gyp, the environment variable. # - If there is no 'make_global_settings' for CC.host/CXX.host or # 'CC_host'/'CXX_host' enviroment variable, cc_host/cxx_host should be set # to cc/cxx. if flavor == 'win': ar = 'lib.exe' # cc and cxx must be set to the correct architecture by overriding with one # of cl_x86 or cl_x64 below. cc = 'UNSET' cxx = 'UNSET' ld = 'link.exe' ld_host = '$ld' else: ar = 'ar' cc = 'cc' cxx = 'c++' ld = '$cc' ldxx = '$cxx' ld_host = '$cc_host' ldxx_host = '$cxx_host' ar_host = 'ar' cc_host = None cxx_host = None cc_host_global_setting = None cxx_host_global_setting = None clang_cl = None nm = 'nm' nm_host = 'nm' readelf = 'readelf' readelf_host = 'readelf' build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings = data[build_file].get('make_global_settings', []) build_to_root = gyp.common.InvertRelativePath(build_dir, options.toplevel_dir) wrappers = {} for key, value in make_global_settings: if key == 'AR': ar = os.path.join(build_to_root, value) if key == 'AR.host': ar_host = os.path.join(build_to_root, value) if key == 'CC': cc = os.path.join(build_to_root, value) if cc.endswith('clang-cl'): clang_cl = cc if key == 'CXX': cxx = os.path.join(build_to_root, value) if key == 'CC.host': cc_host = os.path.join(build_to_root, value) cc_host_global_setting = value if key == 'CXX.host': cxx_host = os.path.join(build_to_root, value) cxx_host_global_setting = value if key == 'LD': ld = os.path.join(build_to_root, value) if key == 'LD.host': ld_host = os.path.join(build_to_root, value) if key == 'NM': nm = os.path.join(build_to_root, value) if key == 'NM.host': nm_host = os.path.join(build_to_root, value) if key == 'READELF': readelf = os.path.join(build_to_root, value) if key == 'READELF.host': readelf_host = os.path.join(build_to_root, value) if key.endswith('_wrapper'): wrappers[key[:-len('_wrapper')]] = os.path.join(build_to_root, value) # Support wrappers from environment variables too. for key, value in os.environ.iteritems(): if key.lower().endswith('_wrapper'): key_prefix = key[:-len('_wrapper')] key_prefix = re.sub(r'\.HOST$', '.host', key_prefix) wrappers[key_prefix] = os.path.join(build_to_root, value) if flavor == 'win': configs = [target_dicts[qualified_target]['configurations'][config_name] for qualified_target in target_list] shared_system_includes = None if not generator_flags.get('ninja_use_custom_environment_files', 0): shared_system_includes = \ gyp.msvs_emulation.ExtractSharedMSVSSystemIncludes( configs, generator_flags) cl_paths = gyp.msvs_emulation.GenerateEnvironmentFiles( toplevel_build, generator_flags, shared_system_includes, OpenOutput) for arch, path in cl_paths.iteritems(): if clang_cl: # If we have selected clang-cl, use that instead. path = clang_cl command = CommandWithWrapper('CC', wrappers, QuoteShellArgument(path, 'win')) if clang_cl: # Use clang-cl to cross-compile for x86 or x86_64. command += (' -m32' if arch == 'x86' else ' -m64') master_ninja.variable('cl_' + arch, command) cc = GetEnvironFallback(['CC_target', 'CC'], cc) master_ninja.variable('cc', CommandWithWrapper('CC', wrappers, cc)) cxx = GetEnvironFallback(['CXX_target', 'CXX'], cxx) master_ninja.variable('cxx', CommandWithWrapper('CXX', wrappers, cxx)) if flavor == 'win': master_ninja.variable('ld', ld) master_ninja.variable('idl', 'midl.exe') master_ninja.variable('ar', ar) master_ninja.variable('rc', 'rc.exe') master_ninja.variable('ml_x86', 'ml.exe') master_ninja.variable('ml_x64', 'ml64.exe') master_ninja.variable('mt', 'mt.exe') else: master_ninja.variable('ld', CommandWithWrapper('LINK', wrappers, ld)) master_ninja.variable('ldxx', CommandWithWrapper('LINK', wrappers, ldxx)) master_ninja.variable('ar', GetEnvironFallback(['AR_target', 'AR'], ar)) if flavor != 'mac': # Mac does not use readelf/nm for .TOC generation, so avoiding polluting # the master ninja with extra unused variables. master_ninja.variable( 'nm', GetEnvironFallback(['NM_target', 'NM'], nm)) master_ninja.variable( 'readelf', GetEnvironFallback(['READELF_target', 'READELF'], readelf)) if generator_supports_multiple_toolsets: if not cc_host: cc_host = cc if not cxx_host: cxx_host = cxx master_ninja.variable('ar_host', GetEnvironFallback(['AR_host'], ar_host)) master_ninja.variable('nm_host', GetEnvironFallback(['NM_host'], nm_host)) master_ninja.variable('readelf_host', GetEnvironFallback(['READELF_host'], readelf_host)) cc_host = GetEnvironFallback(['CC_host'], cc_host) cxx_host = GetEnvironFallback(['CXX_host'], cxx_host) # The environment variable could be used in 'make_global_settings', like # ['CC.host', '$(CC)'] or ['CXX.host', '$(CXX)'], transform them here. if '$(CC)' in cc_host and cc_host_global_setting: cc_host = cc_host_global_setting.replace('$(CC)', cc) if '$(CXX)' in cxx_host and cxx_host_global_setting: cxx_host = cxx_host_global_setting.replace('$(CXX)', cxx) master_ninja.variable('cc_host', CommandWithWrapper('CC.host', wrappers, cc_host)) master_ninja.variable('cxx_host', CommandWithWrapper('CXX.host', wrappers, cxx_host)) if flavor == 'win': master_ninja.variable('ld_host', ld_host) else: master_ninja.variable('ld_host', CommandWithWrapper( 'LINK', wrappers, ld_host)) master_ninja.variable('ldxx_host', CommandWithWrapper( 'LINK', wrappers, ldxx_host)) master_ninja.newline() master_ninja.pool('link_pool', depth=GetDefaultConcurrentLinks()) master_ninja.newline() deps = 'msvc' if flavor == 'win' else 'gcc' if flavor != 'win': master_ninja.rule( 'cc', description='CC $out', command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c ' '$cflags_pch_c -c $in -o $out'), depfile='$out.d', deps=deps) master_ninja.rule( 'cc_s', description='CC $out', command=('$cc $defines $includes $cflags $cflags_c ' '$cflags_pch_c -c $in -o $out')) master_ninja.rule( 'cxx', description='CXX $out', command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc ' '$cflags_pch_cc -c $in -o $out'), depfile='$out.d', deps=deps) else: # TODO(scottmg) Separate pdb names is a test to see if it works around # http://crbug.com/142362. It seems there's a race between the creation of # the .pdb by the precompiled header step for .cc and the compilation of # .c files. This should be handled by mspdbsrv, but rarely errors out with # c1xx : fatal error C1033: cannot open program database # By making the rules target separate pdb files this might be avoided. cc_command = ('ninja -t msvc -e $arch ' + '-- ' '$cc /nologo /showIncludes /FC ' '@$out.rsp /c $in /Fo$out /Fd$pdbname_c ') cxx_command = ('ninja -t msvc -e $arch ' + '-- ' '$cxx /nologo /showIncludes /FC ' '@$out.rsp /c $in /Fo$out /Fd$pdbname_cc ') master_ninja.rule( 'cc', description='CC $out', command=cc_command, rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_c', deps=deps) master_ninja.rule( 'cxx', description='CXX $out', command=cxx_command, rspfile='$out.rsp', rspfile_content='$defines $includes $cflags $cflags_cc', deps=deps) master_ninja.rule( 'idl', description='IDL $in', command=('%s gyp-win-tool midl-wrapper $arch $outdir ' '$tlb $h $dlldata $iid $proxy $in ' '$midl_includes $idlflags' % sys.executable)) master_ninja.rule( 'rc', description='RC $in', # Note: $in must be last otherwise rc.exe complains. command=('%s gyp-win-tool rc-wrapper ' '$arch $rc $defines $resource_includes $rcflags /fo$out $in' % sys.executable)) master_ninja.rule( 'asm', description='ASM $out', command=('%s gyp-win-tool asm-wrapper ' '$arch $asm $defines $includes $asmflags /c /Fo $out $in' % sys.executable)) if flavor != 'mac' and flavor != 'win': master_ninja.rule( 'alink', description='AR $out', command='rm -f $out && $ar rcs $arflags $out $in') master_ninja.rule( 'alink_thin', description='AR $out', command='rm -f $out && $ar rcsT $arflags $out $in') # This allows targets that only need to depend on $lib's API to declare an # order-only dependency on $lib.TOC and avoid relinking such downstream # dependencies when $lib changes only in non-public ways. # The resulting string leaves an uninterpolated %{suffix} which # is used in the final substitution below. mtime_preserving_solink_base = ( 'if [ ! -e $lib -o ! -e $lib.TOC ]; then ' '%(solink)s && %(extract_toc)s > $lib.TOC; else ' '%(solink)s && %(extract_toc)s > $lib.tmp && ' 'if ! cmp -s $lib.tmp $lib.TOC; then mv $lib.tmp $lib.TOC ; ' 'fi; fi' % { 'solink': '$ld -shared $ldflags -o $lib -Wl,-soname=$soname %(suffix)s', 'extract_toc': ('{ $readelf -d $lib | grep SONAME ; ' '$nm -gD -f p $lib | cut -f1-2 -d\' \'; }')}) master_ninja.rule( 'solink', description='SOLINK $lib', restat=True, command=mtime_preserving_solink_base % {'suffix': '@$link_file_list'}, rspfile='$link_file_list', rspfile_content= '-Wl,--whole-archive $in $solibs -Wl,--no-whole-archive $libs', pool='link_pool') master_ninja.rule( 'solink_module', description='SOLINK(module) $lib', restat=True, command=mtime_preserving_solink_base % {'suffix': '@$link_file_list'}, rspfile='$link_file_list', rspfile_content='-Wl,--start-group $in -Wl,--end-group $solibs $libs', pool='link_pool') master_ninja.rule( 'link', description='LINK $out', command=('$ld $ldflags -o $out ' '-Wl,--start-group $in -Wl,--end-group $solibs $libs'), pool='link_pool') elif flavor == 'win': master_ninja.rule( 'alink', description='LIB $out', command=('%s gyp-win-tool link-wrapper $arch False ' '$ar /nologo /ignore:4221 /OUT:$out @$out.rsp' % sys.executable), rspfile='$out.rsp', rspfile_content='$in_newline $libflags') _AddWinLinkRules(master_ninja, embed_manifest=True) _AddWinLinkRules(master_ninja, embed_manifest=False) else: master_ninja.rule( 'objc', description='OBJC $out', command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_objc ' '$cflags_pch_objc -c $in -o $out'), depfile='$out.d', deps=deps) master_ninja.rule( 'objcxx', description='OBJCXX $out', command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_objcc ' '$cflags_pch_objcc -c $in -o $out'), depfile='$out.d', deps=deps) master_ninja.rule( 'alink', description='LIBTOOL-STATIC $out, POSTBUILDS', command='rm -f $out && ' './gyp-mac-tool filter-libtool libtool $libtool_flags ' '-static -o $out $in' '$postbuilds') master_ninja.rule( 'lipo', description='LIPO $out, POSTBUILDS', command='rm -f $out && lipo -create $in -output $out$postbuilds') master_ninja.rule( 'solipo', description='SOLIPO $out, POSTBUILDS', command=( 'rm -f $lib $lib.TOC && lipo -create $in -output $lib$postbuilds &&' '%(extract_toc)s > $lib.TOC' % { 'extract_toc': '{ otool -l $lib | grep LC_ID_DYLIB -A 5; ' 'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'})) # Record the public interface of $lib in $lib.TOC. See the corresponding # comment in the posix section above for details. solink_base = '$ld %(type)s $ldflags -o $lib %(suffix)s' mtime_preserving_solink_base = ( 'if [ ! -e $lib -o ! -e $lib.TOC ] || ' # Always force dependent targets to relink if this library # reexports something. Handling this correctly would require # recursive TOC dumping but this is rare in practice, so punt. 'otool -l $lib | grep -q LC_REEXPORT_DYLIB ; then ' '%(solink)s && %(extract_toc)s > $lib.TOC; ' 'else ' '%(solink)s && %(extract_toc)s > $lib.tmp && ' 'if ! cmp -s $lib.tmp $lib.TOC; then ' 'mv $lib.tmp $lib.TOC ; ' 'fi; ' 'fi' % { 'solink': solink_base, 'extract_toc': '{ otool -l $lib | grep LC_ID_DYLIB -A 5; ' 'nm -gP $lib | cut -f1-2 -d\' \' | grep -v U$$; true; }'}) solink_suffix = '@$link_file_list$postbuilds' master_ninja.rule( 'solink', description='SOLINK $lib, POSTBUILDS', restat=True, command=mtime_preserving_solink_base % {'suffix': solink_suffix, 'type': '-shared'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'solink_notoc', description='SOLINK $lib, POSTBUILDS', restat=True, command=solink_base % {'suffix':solink_suffix, 'type': '-shared'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'solink_module', description='SOLINK(module) $lib, POSTBUILDS', restat=True, command=mtime_preserving_solink_base % {'suffix': solink_suffix, 'type': '-bundle'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'solink_module_notoc', description='SOLINK(module) $lib, POSTBUILDS', restat=True, command=solink_base % {'suffix': solink_suffix, 'type': '-bundle'}, rspfile='$link_file_list', rspfile_content='$in $solibs $libs', pool='link_pool') master_ninja.rule( 'link', description='LINK $out, POSTBUILDS', command=('$ld $ldflags -o $out ' '$in $solibs $libs$postbuilds'), pool='link_pool') master_ninja.rule( 'preprocess_infoplist', description='PREPROCESS INFOPLIST $out', command=('$cc -E -P -Wno-trigraphs -x c $defines $in -o $out && ' 'plutil -convert xml1 $out $out')) master_ninja.rule( 'copy_infoplist', description='COPY INFOPLIST $in', command='$env ./gyp-mac-tool copy-info-plist $in $out $binary $keys') master_ninja.rule( 'merge_infoplist', description='MERGE INFOPLISTS $in', command='$env ./gyp-mac-tool merge-info-plist $out $in') master_ninja.rule( 'compile_xcassets', description='COMPILE XCASSETS $in', command='$env ./gyp-mac-tool compile-xcassets $keys $in') master_ninja.rule( 'mac_tool', description='MACTOOL $mactool_cmd $in', command='$env ./gyp-mac-tool $mactool_cmd $in $out $binary') master_ninja.rule( 'package_framework', description='PACKAGE FRAMEWORK $out, POSTBUILDS', command='./gyp-mac-tool package-framework $out $version$postbuilds ' '&& touch $out') if flavor == 'win': master_ninja.rule( 'stamp', description='STAMP $out', command='%s gyp-win-tool stamp $out' % sys.executable) master_ninja.rule( 'copy', description='COPY $in $out', command='%s gyp-win-tool recursive-mirror $in $out' % sys.executable) else: master_ninja.rule( 'stamp', description='STAMP $out', command='${postbuilds}touch $out') master_ninja.rule( 'copy', description='COPY $in $out', command='rm -rf $out && cp -af $in $out') master_ninja.newline() all_targets = set() for build_file in params['build_files']: for target in gyp.common.AllTargets(target_list, target_dicts, os.path.normpath(build_file)): all_targets.add(target) all_outputs = set() # target_outputs is a map from qualified target name to a Target object. target_outputs = {} # target_short_names is a map from target short name to a list of Target # objects. target_short_names = {} # short name of targets that were skipped because they didn't contain anything # interesting. # NOTE: there may be overlap between this an non_empty_target_names. empty_target_names = set() # Set of non-empty short target names. # NOTE: there may be overlap between this an empty_target_names. non_empty_target_names = set() for qualified_target in target_list: # qualified_target is like: third_party/icu/icu.gyp:icui18n#target build_file, name, toolset = \ gyp.common.ParseQualifiedTarget(qualified_target) this_make_global_settings = data[build_file].get('make_global_settings', []) assert make_global_settings == this_make_global_settings, ( "make_global_settings needs to be the same for all targets. %s vs. %s" % (this_make_global_settings, make_global_settings)) spec = target_dicts[qualified_target] if flavor == 'mac': gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec) # If build_file is a symlink, we must not follow it because there's a chance # it could point to a path above toplevel_dir, and we cannot correctly deal # with that case at the moment. build_file = gyp.common.RelativePath(build_file, options.toplevel_dir, False) qualified_target_for_hash = gyp.common.QualifiedTarget(build_file, name, toolset) hash_for_rules = hashlib.md5(qualified_target_for_hash).hexdigest() base_path = os.path.dirname(build_file) obj = 'obj' if toolset != 'target': obj += '.' + toolset output_file = os.path.join(obj, base_path, name + '.ninja') ninja_output = StringIO() writer = NinjaWriter(hash_for_rules, target_outputs, base_path, build_dir, ninja_output, toplevel_build, output_file, flavor, toplevel_dir=options.toplevel_dir) target = writer.WriteSpec(spec, config_name, generator_flags) if ninja_output.tell() > 0: # Only create files for ninja files that actually have contents. with OpenOutput(os.path.join(toplevel_build, output_file)) as ninja_file: ninja_file.write(ninja_output.getvalue()) ninja_output.close() master_ninja.subninja(output_file) if target: if name != target.FinalOutput() and spec['toolset'] == 'target': target_short_names.setdefault(name, []).append(target) target_outputs[qualified_target] = target if qualified_target in all_targets: all_outputs.add(target.FinalOutput()) non_empty_target_names.add(name) else: empty_target_names.add(name) if target_short_names: # Write a short name to build this target. This benefits both the # "build chrome" case as well as the gyp tests, which expect to be # able to run actions and build libraries by their short name. master_ninja.newline() master_ninja.comment('Short names for targets.') for short_name in target_short_names: master_ninja.build(short_name, 'phony', [x.FinalOutput() for x in target_short_names[short_name]]) # Write phony targets for any empty targets that weren't written yet. As # short names are not necessarily unique only do this for short names that # haven't already been output for another target. empty_target_names = empty_target_names - non_empty_target_names if empty_target_names: master_ninja.newline() master_ninja.comment('Empty targets (output for completeness).') for name in sorted(empty_target_names): master_ninja.build(name, 'phony') if all_outputs: master_ninja.newline() master_ninja.build('all', 'phony', list(all_outputs)) master_ninja.default(generator_flags.get('default_target', 'all')) master_ninja_file.close() def PerformBuild(data, configurations, params): options = params['options'] for config in configurations: builddir = os.path.join(options.toplevel_dir, 'out', config) arguments = ['ninja', '-C', builddir] print 'Building [%s]: %s' % (config, arguments) subprocess.check_call(arguments) def CallGenerateOutputForConfig(arglist): # Ignore the interrupt signal so that the parent process catches it and # kills all multiprocessing children. signal.signal(signal.SIGINT, signal.SIG_IGN) (target_list, target_dicts, data, params, config_name) = arglist GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) def GenerateOutput(target_list, target_dicts, data, params): # Update target_dicts for iOS device builds. target_dicts = gyp.xcode_emulation.CloneConfigurationForDeviceAndEmulator( target_dicts) user_config = params.get('generator_flags', {}).get('config', None) if gyp.common.GetFlavor(params) == 'win': target_list, target_dicts = MSVSUtil.ShardTargets(target_list, target_dicts) target_list, target_dicts = MSVSUtil.InsertLargePdbShims( target_list, target_dicts, generator_default_variables) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['configurations'].keys() if params['parallel']: try: pool = multiprocessing.Pool(len(config_names)) arglists = [] for config_name in config_names: arglists.append( (target_list, target_dicts, data, params, config_name)) pool.map(CallGenerateOutputForConfig, arglists) except KeyboardInterrupt, e: pool.terminate() raise e else: for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
mit
sergeykolychev/mxnet
example/rcnn/rcnn/tools/test_rcnn.py
41
5671
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import argparse import pprint import mxnet as mx from ..logger import logger from ..config import config, default, generate_config from ..symbol import * from ..dataset import * from ..core.loader import TestLoader from ..core.tester import Predictor, pred_eval from ..utils.load_model import load_param def test_rcnn(network, dataset, image_set, root_path, dataset_path, ctx, prefix, epoch, vis, shuffle, has_rpn, proposal, thresh): # set config if has_rpn: config.TEST.HAS_RPN = True # print config pprint.pprint(config) # load symbol and testing data if has_rpn: sym = eval('get_' + network + '_test')(num_classes=config.NUM_CLASSES, num_anchors=config.NUM_ANCHORS) imdb = eval(dataset)(image_set, root_path, dataset_path) roidb = imdb.gt_roidb() else: sym = eval('get_' + network + '_rcnn_test')(num_classes=config.NUM_CLASSES) imdb = eval(dataset)(image_set, root_path, dataset_path) gt_roidb = imdb.gt_roidb() roidb = eval('imdb.' + proposal + '_roidb')(gt_roidb) # get test data iter test_data = TestLoader(roidb, batch_size=1, shuffle=shuffle, has_rpn=has_rpn) # load model arg_params, aux_params = load_param(prefix, epoch, convert=True, ctx=ctx, process=True) # infer shape data_shape_dict = dict(test_data.provide_data) arg_shape, _, aux_shape = sym.infer_shape(**data_shape_dict) arg_shape_dict = dict(zip(sym.list_arguments(), arg_shape)) aux_shape_dict = dict(zip(sym.list_auxiliary_states(), aux_shape)) # check parameters for k in sym.list_arguments(): if k in data_shape_dict or 'label' in k: continue assert k in arg_params, k + ' not initialized' assert arg_params[k].shape == arg_shape_dict[k], \ 'shape inconsistent for ' + k + ' inferred ' + str(arg_shape_dict[k]) + ' provided ' + str(arg_params[k].shape) for k in sym.list_auxiliary_states(): assert k in aux_params, k + ' not initialized' assert aux_params[k].shape == aux_shape_dict[k], \ 'shape inconsistent for ' + k + ' inferred ' + str(aux_shape_dict[k]) + ' provided ' + str(aux_params[k].shape) # decide maximum shape data_names = [k[0] for k in test_data.provide_data] label_names = None max_data_shape = [('data', (1, 3, max([v[0] for v in config.SCALES]), max([v[1] for v in config.SCALES])))] if not has_rpn: max_data_shape.append(('rois', (1, config.TEST.PROPOSAL_POST_NMS_TOP_N + 30, 5))) # create predictor predictor = Predictor(sym, data_names, label_names, context=ctx, max_data_shapes=max_data_shape, provide_data=test_data.provide_data, provide_label=test_data.provide_label, arg_params=arg_params, aux_params=aux_params) # start detection pred_eval(predictor, test_data, imdb, vis=vis, thresh=thresh) def parse_args(): parser = argparse.ArgumentParser(description='Test a Fast R-CNN network') # general parser.add_argument('--network', help='network name', default=default.network, type=str) parser.add_argument('--dataset', help='dataset name', default=default.dataset, type=str) args, rest = parser.parse_known_args() generate_config(args.network, args.dataset) parser.add_argument('--image_set', help='image_set name', default=default.test_image_set, type=str) parser.add_argument('--root_path', help='output data folder', default=default.root_path, type=str) parser.add_argument('--dataset_path', help='dataset path', default=default.dataset_path, type=str) # testing parser.add_argument('--prefix', help='model to test with', default=default.rcnn_prefix, type=str) parser.add_argument('--epoch', help='model to test with', default=default.rcnn_epoch, type=int) parser.add_argument('--gpu', help='GPU device to test with', default=0, type=int) # rcnn parser.add_argument('--vis', help='turn on visualization', action='store_true') parser.add_argument('--thresh', help='valid detection threshold', default=1e-3, type=float) parser.add_argument('--shuffle', help='shuffle data on visualization', action='store_true') parser.add_argument('--has_rpn', help='generate proposals on the fly', action='store_true') parser.add_argument('--proposal', help='can be ss for selective search or rpn', default='rpn', type=str) args = parser.parse_args() return args def main(): args = parse_args() logger.info('Called with argument: %s' % args) ctx = mx.gpu(args.gpu) test_rcnn(args.network, args.dataset, args.image_set, args.root_path, args.dataset_path, ctx, args.prefix, args.epoch, args.vis, args.shuffle, args.has_rpn, args.proposal, args.thresh) if __name__ == '__main__': main()
apache-2.0
azumimuo/family-xbmc-addon
plugin.video.genesisreborn/resources/lib/modules/executor.py
14
1046
import concurrent.futures from itertools import islice import xbmc import threading Executor = concurrent.futures.ThreadPoolExecutor def execute(f, iterable, stop_flag=None, workers=10, timeout = 30): with Executor(max_workers=workers) as executor: threading.Timer(timeout, stop_flag.set) for future in _batched_pool_runner(executor, workers, f, iterable): if xbmc.abortRequested: break if stop_flag and stop_flag.isSet(): break yield future.result() def _batched_pool_runner(pool, batch_size, f, iterable): it = iter(iterable) # Submit the first batch of tasks. futures = set(pool.submit(f, x) for x in islice(it, batch_size)) while futures: done, futures = concurrent.futures.wait(futures, return_when=concurrent.futures.FIRST_COMPLETED) # Replenish submitted tasks up to the number that completed. futures.update(pool.submit(f, x) for x in islice(it, len(done))) for d in done: yield d
gpl-2.0
TansyArron/pants
src/python/pants/base/source_mapper.py
4
7193
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from collections import defaultdict from pants.base.build_environment import get_buildroot from pants.base.payload_field import DeferredSourcesField class SourceMapper(object): """A utility for making a mapping of source files to targets that own them.""" def target_addresses_for_source(self, source): raise NotImplementedError class SpecSourceMapper(SourceMapper): """ Uses sources specs to identify an owner target of a source. Note: it doesn't check if a file exists. """ def __init__(self, address_mapper, build_graph, stop_after_match=False): """ :param AddressMapper address_mapper: An address mapper that can be used to populate the `build_graph` with targets source mappings are needed for. :param BuildGraph build_graph: The build graph to map sources from. :param bool stop_after_match: If `True` a search will not traverse into parent directories once an owner is identified. """ self._stop_after_match = stop_after_match self._build_graph = build_graph self._address_mapper = address_mapper def target_addresses_for_source(self, source): result = [] root = get_buildroot() path = source # a top-level source has empty dirname, so do/while instead of straight while loop. while path: path = os.path.dirname(path) candidate = self._address_mapper.from_cache(root_dir=root, relpath=path, must_exist=False) if candidate.file_exists(): result.extend(list(self._find_targets_for_source(source, candidate.family()))) if self._stop_after_match and len(result) > 0: break return result def _find_targets_for_source(self, source, build_files): for build_file in build_files: address_map = self._address_mapper._address_map_from_spec_path(build_file.spec_path) for address, addressable in address_map.values(): self._build_graph.inject_address_closure(address) target = self._build_graph._target_addressable_to_target(address, addressable) sources = target.payload.get_field('sources') if sources and not isinstance(sources, DeferredSourcesField) and sources.matches(source): yield address if address.build_file.relpath == source: yield address if target.has_resources: for resource in target.resources: """ :type resource: pants.backend.core.targets.resources.Resources """ if resource.payload.sources.matches(source): yield address class LazySourceMapper(SourceMapper): """ This attempts to avoid loading more than needed by lazily searching for and loading BUILD files adjacent to or in parent directories (up to the buildroot) of a source to construct a (partial) mapping of sources to owning targets. If in stop-after-match mode, a search will not traverse into parent directories once an owner is identified. THIS MAY FAIL TO FIND ADDITIONAL OWNERS in parent directories, or only find them when other sources are also mapped first, which cause those owners to be loaded. Some repositories may be able to use this to avoid expensive walks, but others may need to prefer correctness. A LazySourceMapper reuses computed mappings and only searches a given path once as populating the BuildGraph is expensive, so in general there should only be one instance of it. """ def __init__(self, address_mapper, build_graph, stop_after_match=False): """Initialize LazySourceMapper. :param AddressMapper address_mapper: An address mapper that can be used to populate the `build_graph` with targets source mappings are needed for. :param BuildGraph build_graph: The build graph to map sources from. :param bool stop_after_match: If `True` a search will not traverse into parent directories once an owner is identified. """ self._stop_after_match = stop_after_match self._build_graph = build_graph self._address_mapper = address_mapper self._source_to_address = defaultdict(set) self._mapped_paths = set() self._searched_sources = set() def _find_owners(self, source): """Searches for BUILD files adjacent or above a source in the file hierarchy. - Walks up the directory tree until it reaches a previously searched path. - Stops after looking in the buildroot. If self._stop_after_match is set, stops searching once a source is mapped, even if the parent has yet to be searched. See class docstring for discussion. :param str source: The source at which to start the search. """ # Bail instantly if a source has already been searched if source in self._searched_sources: return self._searched_sources.add(source) root = get_buildroot() path = os.path.dirname(source) # a top-level source has empty dirname, so do/while instead of straight while loop. walking = True while walking: # It is possible if path not in self._mapped_paths: candidate = self._address_mapper.from_cache(root_dir=root, relpath=path, must_exist=False) if candidate.file_exists(): self._map_sources_from_family(candidate.family()) self._mapped_paths.add(path) elif not self._stop_after_match: # If not in stop-after-match mode, once a path is seen visited, all parents can be assumed. return # See class docstring if self._stop_after_match and source in self._source_to_address: return walking = bool(path) path = os.path.dirname(path) def _map_sources_from_family(self, build_files): """Populate mapping of source to owning addresses with targets from given BUILD files. :param iterable<BuildFile> build_files: a family of BUILD files from which to map sources. """ for build_file in build_files: address_map = self._address_mapper._address_map_from_spec_path(build_file.spec_path) for address, addressable in address_map.values(): self._build_graph.inject_address_closure(address) target = self._build_graph._target_addressable_to_target(address, addressable) if target.has_resources: for resource in target.resources: for item in resource.sources_relative_to_buildroot(): self._source_to_address[item].add(target.address) for target_source in target.sources_relative_to_buildroot(): self._source_to_address[target_source].add(target.address) if not target.is_synthetic: self._source_to_address[target.address.build_file.relpath].add(target.address) def target_addresses_for_source(self, source): """Attempt to find targets which own a source by searching up directory structure to buildroot. :param string source: The source to look up. """ self._find_owners(source) return self._source_to_address[source]
apache-2.0