code
stringlengths
3
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.05M
# =============================================================================== # Copyright 2011 Jake Ross # # 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. # =============================================== ================================ # ========== standard library imports ========== import time # ========== local library imports ============= from pychron.hardware.actuators import get_switch_address from pychron.hardware.actuators.ascii_gp_actuator import ASCIIGPActuator class NGXGPActuator(ASCIIGPActuator): """ """ open_cmd = "OpenValve" close_cmd = "CloseValve" affirmative = "E00" controller = None def ask(self, *args, **kw): if self.controller: return self.controller.ask(*args, **kw) def initialize(self, *args, **kw): service = "pychron.hardware.isotopx_spectrometer_controller.NGXController" s = self.application.get_service(service) if s is not None: self.controller = s return True def actuate(self, *args, **kw): self.ask("StopAcq") self.controller.canceled = True time.sleep(1) return super(NGXGPActuator, self).actuate(*args, **kw) def get_channel_state(self, obj, delay=False, verbose=False, **kw): """ """ if delay: if not isinstance(delay, (float, int)): delay = 0.25 if delay: time.sleep(delay) # with self._lock: # self.debug(f'acquired lock {self._lock}') r = self._get_channel_state(obj, verbose=True, **kw) # self.debug(f'lock released') return r def _get_channel_state(self, obj, verbose=False, **kw): cmd = "GetValveStatus {}".format(get_switch_address(obj)) s = self.ask(cmd, verbose=verbose) if s is not None: for si in s.split("\r\n"): if si.strip() == self.affirmative: # time.sleep(0.2) # recursively call get_channel_state return self._get_channel_state(obj, verbose=verbose, **kw) for si in s.split("\r\n"): if si.strip() == "OPEN": return True else: return False else: return False # ============= EOF =====================================
USGSDenverPychron/pychron
pychron/hardware/actuators/ngx_gp_actuator.py
Python
apache-2.0
2,845
class ConsoleCommandFailed(Exception): pass class ConvergeFailed(Exception): pass
risuoku/wataru
wataru/exceptions.py
Python
mit
91
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError from liljeson.models import * class Command(BaseCommand): help = 'Regenerate global sequence numbers for cards' def handle(self, *args, **options): self.stdout.write('Resequencing cards') catalog_boxes = Box.objects.all().order_by('sequence_number') catalog_sequence_number = 1 for box in catalog_boxes: for card in box.cards.all().order_by('sequence_number'): card.catalog_sequence_number = catalog_sequence_number card.save() catalog_sequence_number += 1 self.stdout.write(self.style.SUCCESS('Done. Last sequence number was %s.' % catalog_sequence_number))
Kungbib/CIPAC
webapp/kortkatalogen/liljeson/management/commands/resequence_liljeson.py
Python
apache-2.0
764
# Copyright 2013 OpenStack Foundation # Copyright (C) 2013 Yahoo! Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import mock import testtools from glanceclient.common import utils from glanceclient.v2 import shell as test_shell class ShellV2Test(testtools.TestCase): def setUp(self): super(ShellV2Test, self).setUp() self._mock_utils() self.gc = self._mock_glance_client() def _make_args(self, args): #NOTE(venkatesh): this conversion from a dict to an object # is required because the test_shell.do_xxx(gc, args) methods # expects the args to be attributes of an object. If passed as # dict directly, it throws an AttributeError. class Args(): def __init__(self, entries): self.__dict__.update(entries) return Args(args) def _mock_glance_client(self): my_mocked_gc = mock.Mock() my_mocked_gc.schemas.return_value = 'test' my_mocked_gc.get.return_value = {} return my_mocked_gc def _mock_utils(self): utils.print_list = mock.Mock() utils.print_dict = mock.Mock() utils.save_image = mock.Mock() def assert_exits_with_msg(self, func, func_args, err_msg): with mock.patch.object(utils, 'exit') as mocked_utils_exit: mocked_utils_exit.return_value = '%s' % err_msg func(self.gc, func_args) mocked_utils_exit.assert_called_once_with(err_msg) def test_do_image_list(self): input = { 'page_size': 18, 'visibility': True, 'member_status': 'Fake', 'owner': 'test', 'checksum': 'fake_checksum', 'tag': 'fake tag' } args = self._make_args(input) with mock.patch.object(self.gc.images, 'list') as mocked_list: mocked_list.return_value = {} test_shell.do_image_list(self.gc, args) exp_img_filters = { 'owner': 'test', 'member_status': 'Fake', 'visibility': True, 'checksum': 'fake_checksum', 'tag': 'fake tag' } mocked_list.assert_called_once_with(page_size=18, filters=exp_img_filters) utils.print_list.assert_called_once_with({}, ['ID', 'Name']) def test_do_image_show(self): args = self._make_args({'id': 'pass', 'page_size': 18, 'max_column_width': 120}) with mock.patch.object(self.gc.images, 'get') as mocked_list: ignore_fields = ['self', 'access', 'file', 'schema'] expect_image = dict([(field, field) for field in ignore_fields]) expect_image['id'] = 'pass' mocked_list.return_value = expect_image test_shell.do_image_show(self.gc, args) mocked_list.assert_called_once_with('pass') utils.print_dict.assert_called_once_with({'id': 'pass'}, max_column_width=120) def test_do_image_create_no_user_props(self): args = self._make_args({'name': 'IMG-01', 'disk_format': 'vhd', 'container_format': 'bare'}) with mock.patch.object(self.gc.images, 'create') as mocked_create: ignore_fields = ['self', 'access', 'file', 'schema'] expect_image = dict([(field, field) for field in ignore_fields]) expect_image['id'] = 'pass' expect_image['name'] = 'IMG-01' expect_image['disk_format'] = 'vhd' expect_image['container_format'] = 'bare' mocked_create.return_value = expect_image test_shell.do_image_create(self.gc, args) mocked_create.assert_called_once_with(name='IMG-01', disk_format='vhd', container_format='bare') utils.print_dict.assert_called_once_with({ 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd', 'container_format': 'bare'}) def test_do_image_create_with_user_props(self): args = self._make_args({'name': 'IMG-01', 'property': ['myprop=myval']}) with mock.patch.object(self.gc.images, 'create') as mocked_create: ignore_fields = ['self', 'access', 'file', 'schema'] expect_image = dict([(field, field) for field in ignore_fields]) expect_image['id'] = 'pass' expect_image['name'] = 'IMG-01' expect_image['myprop'] = 'myval' mocked_create.return_value = expect_image test_shell.do_image_create(self.gc, args) mocked_create.assert_called_once_with(name='IMG-01', myprop='myval') utils.print_dict.assert_called_once_with({ 'id': 'pass', 'name': 'IMG-01', 'myprop': 'myval'}) def test_do_image_update_no_user_props(self): args = self._make_args({'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd', 'container_format': 'bare'}) with mock.patch.object(self.gc.images, 'update') as mocked_update: ignore_fields = ['self', 'access', 'file', 'schema'] expect_image = dict([(field, field) for field in ignore_fields]) expect_image['id'] = 'pass' expect_image['name'] = 'IMG-01' expect_image['disk_format'] = 'vhd' expect_image['container_format'] = 'bare' mocked_update.return_value = expect_image test_shell.do_image_update(self.gc, args) mocked_update.assert_called_once_with('pass', None, name='IMG-01', disk_format='vhd', container_format='bare') utils.print_dict.assert_called_once_with({ 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd', 'container_format': 'bare'}) def test_do_image_update_with_user_props(self): args = self._make_args({'id': 'pass', 'name': 'IMG-01', 'property': ['myprop=myval']}) with mock.patch.object(self.gc.images, 'update') as mocked_update: ignore_fields = ['self', 'access', 'file', 'schema'] expect_image = dict([(field, field) for field in ignore_fields]) expect_image['id'] = 'pass' expect_image['name'] = 'IMG-01' expect_image['myprop'] = 'myval' mocked_update.return_value = expect_image test_shell.do_image_update(self.gc, args) mocked_update.assert_called_once_with('pass', None, name='IMG-01', myprop='myval') utils.print_dict.assert_called_once_with({ 'id': 'pass', 'name': 'IMG-01', 'myprop': 'myval'}) def test_do_image_update_with_remove_props(self): args = self._make_args({'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd', 'remove-property': ['container_format']}) with mock.patch.object(self.gc.images, 'update') as mocked_update: ignore_fields = ['self', 'access', 'file', 'schema'] expect_image = dict([(field, field) for field in ignore_fields]) expect_image['id'] = 'pass' expect_image['name'] = 'IMG-01' expect_image['disk_format'] = 'vhd' mocked_update.return_value = expect_image test_shell.do_image_update(self.gc, args) mocked_update.assert_called_once_with('pass', ['container_format'], name='IMG-01', disk_format='vhd') utils.print_dict.assert_called_once_with({ 'id': 'pass', 'name': 'IMG-01', 'disk_format': 'vhd'}) def test_do_explain(self): input = { 'page_size': 18, 'id': 'pass', 'schemas': 'test', 'model': 'test', } args = self._make_args(input) with mock.patch.object(utils, 'print_list'): test_shell.do_explain(self.gc, args) self.gc.schemas.get.assert_called_once_with('test') def test_do_location_add(self): gc = self.gc loc = {'url': 'http://foo.com/', 'metadata': {'foo': 'bar'}} args = self._make_args({'id': 'pass', 'url': loc['url'], 'metadata': json.dumps(loc['metadata'])}) with mock.patch.object(gc.images, 'add_location') as mocked_addloc: expect_image = {'id': 'pass', 'locations': [loc]} mocked_addloc.return_value = expect_image test_shell.do_location_add(self.gc, args) mocked_addloc.assert_called_once_with('pass', loc['url'], loc['metadata']) utils.print_dict.assert_called_once_with(expect_image) def test_do_location_delete(self): gc = self.gc loc_set = set(['http://foo/bar', 'http://spam/ham']) args = self._make_args({'id': 'pass', 'url': loc_set}) with mock.patch.object(gc.images, 'delete_locations') as mocked_rmloc: test_shell.do_location_delete(self.gc, args) mocked_rmloc.assert_called_once_with('pass', loc_set) def test_do_location_update(self): gc = self.gc loc = {'url': 'http://foo.com/', 'metadata': {'foo': 'bar'}} args = self._make_args({'id': 'pass', 'url': loc['url'], 'metadata': json.dumps(loc['metadata'])}) with mock.patch.object(gc.images, 'update_location') as mocked_modloc: expect_image = {'id': 'pass', 'locations': [loc]} mocked_modloc.return_value = expect_image test_shell.do_location_update(self.gc, args) mocked_modloc.assert_called_once_with('pass', loc['url'], loc['metadata']) utils.print_dict.assert_called_once_with(expect_image) def test_image_upload(self): args = self._make_args( {'id': 'IMG-01', 'file': 'test', 'size': 1024, 'progress': False}) with mock.patch.object(self.gc.images, 'upload') as mocked_upload: utils.get_data_file = mock.Mock(return_value='testfile') mocked_upload.return_value = None test_shell.do_image_upload(self.gc, args) mocked_upload.assert_called_once_with('IMG-01', 'testfile', 1024) def test_do_image_delete(self): args = self._make_args({'id': 'pass', 'file': 'test'}) with mock.patch.object(self.gc.images, 'delete') as mocked_delete: mocked_delete.return_value = 0 test_shell.do_image_delete(self.gc, args) mocked_delete.assert_called_once_with('pass') def test_do_member_list(self): args = self._make_args({'image_id': 'IMG-01'}) with mock.patch.object(self.gc.image_members, 'list') as mocked_list: mocked_list.return_value = {} test_shell.do_member_list(self.gc, args) mocked_list.assert_called_once_with('IMG-01') columns = ['Image ID', 'Member ID', 'Status'] utils.print_list.assert_called_once_with({}, columns) def test_do_member_create(self): args = self._make_args({'image_id': 'IMG-01', 'member_id': 'MEM-01'}) with mock.patch.object(self.gc.image_members, 'create') as mock_create: mock_create.return_value = {} test_shell.do_member_create(self.gc, args) mock_create.assert_called_once_with('IMG-01', 'MEM-01') columns = ['Image ID', 'Member ID', 'Status'] utils.print_list.assert_called_once_with([{}], columns) def test_do_member_create_with_few_arguments(self): args = self._make_args({'image_id': None, 'member_id': 'MEM-01'}) msg = 'Unable to create member. Specify image_id and member_id' self.assert_exits_with_msg(func=test_shell.do_member_create, func_args=args, err_msg=msg) def test_do_member_update(self): input = { 'image_id': 'IMG-01', 'member_id': 'MEM-01', 'member_status': 'status', } args = self._make_args(input) with mock.patch.object(self.gc.image_members, 'update') as mock_update: mock_update.return_value = {} test_shell.do_member_update(self.gc, args) mock_update.assert_called_once_with('IMG-01', 'MEM-01', 'status') columns = ['Image ID', 'Member ID', 'Status'] utils.print_list.assert_called_once_with([{}], columns) def test_do_member_update_with_few_arguments(self): input = { 'image_id': 'IMG-01', 'member_id': 'MEM-01', 'member_status': None, } args = self._make_args(input) msg = 'Unable to update member. Specify image_id, member_id' \ ' and member_status' self.assert_exits_with_msg(func=test_shell.do_member_update, func_args=args, err_msg=msg) def test_do_member_delete(self): args = self._make_args({'image_id': 'IMG-01', 'member_id': 'MEM-01'}) with mock.patch.object(self.gc.image_members, 'delete') as mock_delete: test_shell.do_member_delete(self.gc, args) mock_delete.assert_called_once_with('IMG-01', 'MEM-01') def test_do_member_delete_with_few_arguments(self): args = self._make_args({'image_id': None, 'member_id': 'MEM-01'}) msg = 'Unable to delete member. Specify image_id and member_id' self.assert_exits_with_msg(func=test_shell.do_member_delete, func_args=args, err_msg=msg) def test_image_tag_update(self): args = self._make_args({'image_id': 'IMG-01', 'tag_value': 'tag01'}) with mock.patch.object(self.gc.image_tags, 'update') as mocked_update: self.gc.images.get = mock.Mock(return_value={}) mocked_update.return_value = None test_shell.do_image_tag_update(self.gc, args) mocked_update.assert_called_once_with('IMG-01', 'tag01') def test_image_tag_update_with_few_arguments(self): args = self._make_args({'image_id': None, 'tag_value': 'tag01'}) msg = 'Unable to update tag. Specify image_id and tag_value' self.assert_exits_with_msg(func=test_shell.do_image_tag_update, func_args=args, err_msg=msg) def test_image_tag_delete(self): args = self._make_args({'image_id': 'IMG-01', 'tag_value': 'tag01'}) with mock.patch.object(self.gc.image_tags, 'delete') as mocked_delete: mocked_delete.return_value = None test_shell.do_image_tag_delete(self.gc, args) mocked_delete.assert_called_once_with('IMG-01', 'tag01') def test_image_tag_delete_with_few_arguments(self): args = self._make_args({'image_id': 'IMG-01', 'tag_value': None}) msg = 'Unable to delete tag. Specify image_id and tag_value' self.assert_exits_with_msg(func=test_shell.do_image_tag_delete, func_args=args, err_msg=msg) def test_do_md_namespace_create(self): args = self._make_args({'namespace': 'MyNamespace', 'protected': True}) with mock.patch.object(self.gc.metadefs_namespace, 'create') as mocked_create: expect_namespace = {} expect_namespace['namespace'] = 'MyNamespace' expect_namespace['protected'] = True mocked_create.return_value = expect_namespace test_shell.do_md_namespace_create(self.gc, args) mocked_create.assert_called_once_with(namespace='MyNamespace', protected=True) utils.print_dict.assert_called_once_with(expect_namespace) def test_do_md_namespace_import(self): args = self._make_args({'file': 'test'}) expect_namespace = {} expect_namespace['namespace'] = 'MyNamespace' expect_namespace['protected'] = True with mock.patch.object(self.gc.metadefs_namespace, 'create') as mocked_create: mock_read = mock.Mock(return_value=json.dumps(expect_namespace)) mock_file = mock.Mock(read=mock_read) utils.get_data_file = mock.Mock(return_value=mock_file) mocked_create.return_value = expect_namespace test_shell.do_md_namespace_import(self.gc, args) mocked_create.assert_called_once_with(**expect_namespace) utils.print_dict.assert_called_once_with(expect_namespace) def test_do_md_namespace_import_invalid_json(self): args = self._make_args({'file': 'test'}) mock_read = mock.Mock(return_value='Invalid') mock_file = mock.Mock(read=mock_read) utils.get_data_file = mock.Mock(return_value=mock_file) self.assertRaises(SystemExit, test_shell.do_md_namespace_import, self.gc, args) def test_do_md_namespace_import_no_input(self): args = self._make_args({'file': None}) utils.get_data_file = mock.Mock(return_value=None) self.assertRaises(SystemExit, test_shell.do_md_namespace_import, self.gc, args) def test_do_md_namespace_update(self): args = self._make_args({'id': 'MyNamespace', 'protected': True}) with mock.patch.object(self.gc.metadefs_namespace, 'update') as mocked_update: expect_namespace = {} expect_namespace['namespace'] = 'MyNamespace' expect_namespace['protected'] = True mocked_update.return_value = expect_namespace test_shell.do_md_namespace_update(self.gc, args) mocked_update.assert_called_once_with('MyNamespace', id='MyNamespace', protected=True) utils.print_dict.assert_called_once_with(expect_namespace) def test_do_md_namespace_show(self): args = self._make_args({'namespace': 'MyNamespace', 'max_column_width': 80, 'resource_type': None}) with mock.patch.object(self.gc.metadefs_namespace, 'get') as mocked_get: expect_namespace = {} expect_namespace['namespace'] = 'MyNamespace' mocked_get.return_value = expect_namespace test_shell.do_md_namespace_show(self.gc, args) mocked_get.assert_called_once_with('MyNamespace') utils.print_dict.assert_called_once_with(expect_namespace, 80) def test_do_md_namespace_show_resource_type(self): args = self._make_args({'namespace': 'MyNamespace', 'max_column_width': 80, 'resource_type': 'RESOURCE'}) with mock.patch.object(self.gc.metadefs_namespace, 'get') as mocked_get: expect_namespace = {} expect_namespace['namespace'] = 'MyNamespace' mocked_get.return_value = expect_namespace test_shell.do_md_namespace_show(self.gc, args) mocked_get.assert_called_once_with('MyNamespace', resource_type='RESOURCE') utils.print_dict.assert_called_once_with(expect_namespace, 80) def test_do_md_namespace_list(self): args = self._make_args({'resource_type': None, 'visibility': None, 'page_size': None}) with mock.patch.object(self.gc.metadefs_namespace, 'list') as mocked_list: expect_namespaces = [{'namespace': 'MyNamespace'}] mocked_list.return_value = expect_namespaces test_shell.do_md_namespace_list(self.gc, args) mocked_list.assert_called_once_with(filters={}) utils.print_list.assert_called_once_with(expect_namespaces, ['namespace']) def test_do_md_namespace_list_page_size(self): args = self._make_args({'resource_type': None, 'visibility': None, 'page_size': 2}) with mock.patch.object(self.gc.metadefs_namespace, 'list') as mocked_list: expect_namespaces = [{'namespace': 'MyNamespace'}] mocked_list.return_value = expect_namespaces test_shell.do_md_namespace_list(self.gc, args) mocked_list.assert_called_once_with(filters={}, page_size=2) utils.print_list.assert_called_once_with(expect_namespaces, ['namespace']) def test_do_md_namespace_list_one_filter(self): args = self._make_args({'resource_types': ['OS::Compute::Aggregate'], 'visibility': None, 'page_size': None}) with mock.patch.object(self.gc.metadefs_namespace, 'list') as \ mocked_list: expect_namespaces = [{'namespace': 'MyNamespace'}] mocked_list.return_value = expect_namespaces test_shell.do_md_namespace_list(self.gc, args) mocked_list.assert_called_once_with(filters={ 'resource_types': ['OS::Compute::Aggregate']}) utils.print_list.assert_called_once_with(expect_namespaces, ['namespace']) def test_do_md_namespace_list_all_filters(self): args = self._make_args({'resource_types': ['OS::Compute::Aggregate'], 'visibility': 'public', 'page_size': None}) with mock.patch.object(self.gc.metadefs_namespace, 'list') as mocked_list: expect_namespaces = [{'namespace': 'MyNamespace'}] mocked_list.return_value = expect_namespaces test_shell.do_md_namespace_list(self.gc, args) mocked_list.assert_called_once_with(filters={ 'resource_types': ['OS::Compute::Aggregate'], 'visibility': 'public'}) utils.print_list.assert_called_once_with(expect_namespaces, ['namespace']) def test_do_md_namespace_list_unknown_filter(self): args = self._make_args({'resource_type': None, 'visibility': None, 'some_arg': 'some_value', 'page_size': None}) with mock.patch.object(self.gc.metadefs_namespace, 'list') as mocked_list: expect_namespaces = [{'namespace': 'MyNamespace'}] mocked_list.return_value = expect_namespaces test_shell.do_md_namespace_list(self.gc, args) mocked_list.assert_called_once_with(filters={}) utils.print_list.assert_called_once_with(expect_namespaces, ['namespace']) def test_do_md_namespace_delete(self): args = self._make_args({'namespace': 'MyNamespace', 'content': False}) with mock.patch.object(self.gc.metadefs_namespace, 'delete') as \ mocked_delete: test_shell.do_md_namespace_delete(self.gc, args) mocked_delete.assert_called_once_with('MyNamespace') def test_do_md_resource_type_associate(self): args = self._make_args({'namespace': 'MyNamespace', 'name': 'MyResourceType', 'prefix': 'PREFIX:'}) with mock.patch.object(self.gc.metadefs_resource_type, 'associate') as mocked_associate: expect_rt = {} expect_rt['namespace'] = 'MyNamespace' expect_rt['name'] = 'MyResourceType' expect_rt['prefix'] = 'PREFIX:' mocked_associate.return_value = expect_rt test_shell.do_md_resource_type_associate(self.gc, args) mocked_associate.assert_called_once_with('MyNamespace', **expect_rt) utils.print_dict.assert_called_once_with(expect_rt) def test_do_md_resource_type_deassociate(self): args = self._make_args({'namespace': 'MyNamespace', 'resource_type': 'MyResourceType'}) with mock.patch.object(self.gc.metadefs_resource_type, 'deassociate') as mocked_deassociate: test_shell.do_md_resource_type_deassociate(self.gc, args) mocked_deassociate.assert_called_once_with('MyNamespace', 'MyResourceType') def test_do_md_resource_type_list(self): args = self._make_args({}) with mock.patch.object(self.gc.metadefs_resource_type, 'list') as mocked_list: expect_objects = ['MyResourceType1', 'MyResourceType2'] mocked_list.return_value = expect_objects test_shell.do_md_resource_type_list(self.gc, args) mocked_list.assert_called_once() def test_do_md_namespace_resource_type_list(self): args = self._make_args({'namespace': 'MyNamespace'}) with mock.patch.object(self.gc.metadefs_resource_type, 'get') as mocked_get: expect_objects = [{'namespace': 'MyNamespace', 'object': 'MyObject'}] mocked_get.return_value = expect_objects test_shell.do_md_namespace_resource_type_list(self.gc, args) mocked_get.assert_called_once_with('MyNamespace') utils.print_list.assert_called_once_with(expect_objects, ['name', 'prefix', 'properties_target']) def test_do_md_property_create(self): args = self._make_args({'namespace': 'MyNamespace', 'name': "MyProperty", 'title': "Title", 'schema': '{}'}) with mock.patch.object(self.gc.metadefs_property, 'create') as mocked_create: expect_property = {} expect_property['namespace'] = 'MyNamespace' expect_property['name'] = 'MyProperty' expect_property['title'] = 'Title' mocked_create.return_value = expect_property test_shell.do_md_property_create(self.gc, args) mocked_create.assert_called_once_with('MyNamespace', name='MyProperty', title='Title') utils.print_dict.assert_called_once_with(expect_property) def test_do_md_property_create_invalid_schema(self): args = self._make_args({'namespace': 'MyNamespace', 'name': "MyProperty", 'title': "Title", 'schema': 'Invalid'}) self.assertRaises(SystemExit, test_shell.do_md_property_create, self.gc, args) def test_do_md_property_update(self): args = self._make_args({'namespace': 'MyNamespace', 'property': 'MyProperty', 'name': 'NewName', 'title': "Title", 'schema': '{}'}) with mock.patch.object(self.gc.metadefs_property, 'update') as mocked_update: expect_property = {} expect_property['namespace'] = 'MyNamespace' expect_property['name'] = 'MyProperty' expect_property['title'] = 'Title' mocked_update.return_value = expect_property test_shell.do_md_property_update(self.gc, args) mocked_update.assert_called_once_with('MyNamespace', 'MyProperty', name='NewName', title='Title') utils.print_dict.assert_called_once_with(expect_property) def test_do_md_property_update_invalid_schema(self): args = self._make_args({'namespace': 'MyNamespace', 'property': 'MyProperty', 'name': "MyObject", 'title': "Title", 'schema': 'Invalid'}) self.assertRaises(SystemExit, test_shell.do_md_property_update, self.gc, args) def test_do_md_property_show(self): args = self._make_args({'namespace': 'MyNamespace', 'property': 'MyProperty', 'max_column_width': 80}) with mock.patch.object(self.gc.metadefs_property, 'get') as mocked_get: expect_property = {} expect_property['namespace'] = 'MyNamespace' expect_property['property'] = 'MyProperty' expect_property['title'] = 'Title' mocked_get.return_value = expect_property test_shell.do_md_property_show(self.gc, args) mocked_get.assert_called_once_with('MyNamespace', 'MyProperty') utils.print_dict.assert_called_once_with(expect_property, 80) def test_do_md_property_delete(self): args = self._make_args({'namespace': 'MyNamespace', 'property': 'MyProperty'}) with mock.patch.object(self.gc.metadefs_property, 'delete') as mocked_delete: test_shell.do_md_property_delete(self.gc, args) mocked_delete.assert_called_once_with('MyNamespace', 'MyProperty') def test_do_md_namespace_property_delete(self): args = self._make_args({'namespace': 'MyNamespace'}) with mock.patch.object(self.gc.metadefs_property, 'delete_all') as mocked_delete_all: test_shell.do_md_namespace_properties_delete(self.gc, args) mocked_delete_all.assert_called_once_with('MyNamespace') def test_do_md_property_list(self): args = self._make_args({'namespace': 'MyNamespace'}) with mock.patch.object(self.gc.metadefs_property, 'list') as mocked_list: expect_objects = [{'namespace': 'MyNamespace', 'property': 'MyProperty', 'title': 'MyTitle'}] mocked_list.return_value = expect_objects test_shell.do_md_property_list(self.gc, args) mocked_list.assert_called_once_with('MyNamespace') utils.print_list.assert_called_once_with(expect_objects, ['name', 'title', 'type']) def test_do_md_object_create(self): args = self._make_args({'namespace': 'MyNamespace', 'name': "MyObject", 'schema': '{}'}) with mock.patch.object(self.gc.metadefs_object, 'create') as mocked_create: expect_object = {} expect_object['namespace'] = 'MyNamespace' expect_object['name'] = 'MyObject' mocked_create.return_value = expect_object test_shell.do_md_object_create(self.gc, args) mocked_create.assert_called_once_with('MyNamespace', name='MyObject') utils.print_dict.assert_called_once_with(expect_object) def test_do_md_object_create_invalid_schema(self): args = self._make_args({'namespace': 'MyNamespace', 'name': "MyObject", 'schema': 'Invalid'}) self.assertRaises(SystemExit, test_shell.do_md_object_create, self.gc, args) def test_do_md_object_update(self): args = self._make_args({'namespace': 'MyNamespace', 'object': 'MyObject', 'name': 'NewName', 'schema': '{}'}) with mock.patch.object(self.gc.metadefs_object, 'update') as mocked_update: expect_object = {} expect_object['namespace'] = 'MyNamespace' expect_object['name'] = 'MyObject' mocked_update.return_value = expect_object test_shell.do_md_object_update(self.gc, args) mocked_update.assert_called_once_with('MyNamespace', 'MyObject', name='NewName') utils.print_dict.assert_called_once_with(expect_object) def test_do_md_object_update_invalid_schema(self): args = self._make_args({'namespace': 'MyNamespace', 'object': 'MyObject', 'name': "MyObject", 'schema': 'Invalid'}) self.assertRaises(SystemExit, test_shell.do_md_object_update, self.gc, args) def test_do_md_object_show(self): args = self._make_args({'namespace': 'MyNamespace', 'object': 'MyObject', 'max_column_width': 80}) with mock.patch.object(self.gc.metadefs_object, 'get') as mocked_get: expect_object = {} expect_object['namespace'] = 'MyNamespace' expect_object['object'] = 'MyObject' mocked_get.return_value = expect_object test_shell.do_md_object_show(self.gc, args) mocked_get.assert_called_once_with('MyNamespace', 'MyObject') utils.print_dict.assert_called_once_with(expect_object, 80) def test_do_md_object_property_show(self): args = self._make_args({'namespace': 'MyNamespace', 'object': 'MyObject', 'property': 'MyProperty', 'max_column_width': 80}) with mock.patch.object(self.gc.metadefs_object, 'get') as mocked_get: expect_object = {'name': 'MyObject', 'properties': { 'MyProperty': {'type': 'string'} }} mocked_get.return_value = expect_object test_shell.do_md_object_property_show(self.gc, args) mocked_get.assert_called_once_with('MyNamespace', 'MyObject') utils.print_dict.assert_called_once_with({'type': 'string', 'name': 'MyProperty'}, 80) def test_do_md_object_property_show_non_existing(self): args = self._make_args({'namespace': 'MyNamespace', 'object': 'MyObject', 'property': 'MyProperty', 'max_column_width': 80}) with mock.patch.object(self.gc.metadefs_object, 'get') as mocked_get: expect_object = {'name': 'MyObject', 'properties': {}} mocked_get.return_value = expect_object self.assertRaises(SystemExit, test_shell.do_md_object_property_show, self.gc, args) mocked_get.assert_called_once_with('MyNamespace', 'MyObject') def test_do_md_object_delete(self): args = self._make_args({'namespace': 'MyNamespace', 'object': 'MyObject'}) with mock.patch.object(self.gc.metadefs_object, 'delete') as mocked_delete: test_shell.do_md_object_delete(self.gc, args) mocked_delete.assert_called_once_with('MyNamespace', 'MyObject') def test_do_md_namespace_objects_delete(self): args = self._make_args({'namespace': 'MyNamespace'}) with mock.patch.object(self.gc.metadefs_object, 'delete_all') as mocked_delete_all: test_shell.do_md_namespace_objects_delete(self.gc, args) mocked_delete_all.assert_called_once_with('MyNamespace') def test_do_md_object_list(self): args = self._make_args({'namespace': 'MyNamespace'}) with mock.patch.object(self.gc.metadefs_object, 'list') as mocked_list: expect_objects = [{'namespace': 'MyNamespace', 'object': 'MyObject'}] mocked_list.return_value = expect_objects test_shell.do_md_object_list(self.gc, args) mocked_list.assert_called_once_with('MyNamespace') utils.print_list.assert_called_once_with( expect_objects, ['name', 'description'], field_settings={ 'description': {'align': 'l', 'max_width': 50}})
varunarya10/python-glanceclient
tests/v2/test_shell_v2.py
Python
apache-2.0
39,153
# -*- coding: utf-8 -*- # # dcolumn/dcolumns/tests/test_dcolumns_choice.py # # WARNING: These unittests can only be run from within the original test # framework from https://github.com/cnobile2012/dcolumn. # from django.core.exceptions import ObjectDoesNotExist from django.test import TestCase from dcolumn.dcolumns.manager import DynamicColumnManager from .test_dcolumns_manager import Country class TestChoices(TestCase): def __init__(self, name): super(TestChoices, self).__init__(name) def test_model_objects(self): """ Test that Choice objects get created properly. """ #self.skipTest("Temporarily skipped") values = Country.objects.VALUES modal_objects = Country.objects.model_objects() msg = "modal_objects: {}, values: {}".format(modal_objects, values) self.assertEqual(len(modal_objects), len(values), msg) for model in modal_objects: self.assertTrue(model.name in dict(values), msg) def test_get_pk(self): """ Test that the get method returns the correct object. """ #self.skipTest("Temporarily skipped") values = Country.objects.VALUES obj = Country.objects.get(pk=3) msg = "get: {}, values: {}".format(obj, values) self.assertEqual(obj.language, dict(values).get('Brazil'), msg) def test_get_name(self): """ Test that the get method returns the correct object. """ #self.skipTest("Temporarily skipped") name = 'Brazil' values = Country.objects.VALUES obj = Country.objects.get(name=name) msg = "get: {}, values: {}".format(obj, values) self.assertEqual(obj.language, dict(values).get(name), msg) def test_get_DoesNotExist(self): """ Test that the get method returns the correct object. """ #self.skipTest("Temporarily skipped") name = 'XzXzXz' values = Country.objects.VALUES with self.assertRaises(ObjectDoesNotExist) as cm: obj = Country.objects.get(name=name) msg = "Country matching query does not exist." self.assertTrue(msg in str(cm.exception)) def test_get_value_by_pk(self): """ Test that the proper field is returned with the proper pk. """ #self.skipTest("Temporarily skipped") values = Country.objects.VALUES objs = Country.objects.model_objects() for obj in objs: value = Country.objects.get_value_by_pk(obj.pk, 'name') msg = "value: {}, values: {}".format(value, values) self.assertEqual(value, obj.name, msg) for obj in objs: value = Country.objects.get_value_by_pk(obj.pk, 'language') msg = "value: {}, values: {}".format(value, values) self.assertEqual(value, obj.language, msg) def test_get_choices(self): """ Test that the HTML select option values are returned properly. """ #self.skipTest("Temporarily skipped") objs = Country.objects.model_objects() choices = Country.objects.get_choices('name') msg = "choices: {}, objs: {}".format(choices, objs) # Test that an HTML select option header is in the choices. self.assertTrue(0 in dict(choices), msg) # Test that all the objects are in the choices. for obj in objs: self.assertEqual(obj.name, dict(choices).get(obj.pk), msg) # Test that no HTML select option header is in the choices. choices = Country.objects.get_choices('name', comment=False) msg = "choices: {}, objs: {}".format(choices, objs) self.assertFalse(0 in dict(choices), msg) # Test that the language is in the choices instead of the country # name. choices = Country.objects.get_choices('language') msg = "choices: {}, objs: {}".format(choices, objs) # Test that all the objects are in the choices. for obj in objs: self.assertEqual(obj.language, dict(choices).get(obj.pk), msg)
cnobile2012/dcolumn
dcolumn/dcolumns/tests/test_dcolumns_choice.py
Python
mit
4,126
# Copyright 2011 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 webob.exc from trove.common import exception from trove.common import pagination from trove.common import wsgi from trove.common.utils import correct_id_with_req from trove.extensions.mysql.common import populate_validated_databases from trove.extensions.mysql.common import populate_users from trove.extensions.mysql.common import unquote_user_host from trove.extensions.mysql import models from trove.extensions.mysql import views from trove.guestagent.db import models as guest_models from trove.openstack.common import log as logging from trove.openstack.common.gettextutils import _ import trove.common.apischema as apischema LOG = logging.getLogger(__name__) class RootController(wsgi.Controller): """Controller for instance functionality.""" def index(self, req, tenant_id, instance_id): """Returns True if root is enabled for the given instance; False otherwise. """ LOG.info(_("Getting root enabled for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] is_root_enabled = models.Root.load(context, instance_id) return wsgi.Result(views.RootEnabledView(is_root_enabled).data(), 200) def create(self, req, tenant_id, instance_id): """Enable the root user for the db instance.""" LOG.info(_("Enabling root for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] user_name = context.user root = models.Root.create(context, instance_id, user_name) return wsgi.Result(views.RootCreatedView(root).data(), 200) class UserController(wsgi.Controller): """Controller for instance functionality.""" schemas = apischema.user @classmethod def get_schema(cls, action, body): action_schema = super(UserController, cls).get_schema(action, body) if 'update_all' == action: update_type = body.keys()[0] action_schema = action_schema.get(update_type, {}) return action_schema def index(self, req, tenant_id, instance_id): """Return all users.""" LOG.info(_("Listing users for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] users, next_marker = models.Users.load(context, instance_id) view = views.UsersView(users) paged = pagination.SimplePaginatedDataView(req.url, 'users', view, next_marker) return wsgi.Result(paged.data(), 200) def create(self, req, body, tenant_id, instance_id): """Creates a set of users.""" LOG.info(_("Creating users for instance '%s'") % instance_id) LOG.info(logging.mask_password(_("req : '%s'\n\n") % req)) LOG.info(logging.mask_password(_("body : '%s'\n\n") % body)) context = req.environ[wsgi.CONTEXT_KEY] users = body['users'] try: model_users = populate_users(users) models.User.create(context, instance_id, model_users) except (ValueError, AttributeError) as e: raise exception.BadRequest(msg=str(e)) return wsgi.Result(None, 202) def delete(self, req, tenant_id, instance_id, id): LOG.info(_("Deleting user for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] id = correct_id_with_req(id, req) username, host = unquote_user_host(id) user = None try: user = guest_models.MySQLUser() user.name = username user.host = host found_user = models.User.load(context, instance_id, username, host) if not found_user: user = None except (ValueError, AttributeError) as e: raise exception.BadRequest(msg=str(e)) if not user: raise exception.UserNotFound(uuid=id) models.User.delete(context, instance_id, user.serialize()) return wsgi.Result(None, 202) def show(self, req, tenant_id, instance_id, id): """Return a single user.""" LOG.info(_("Showing a user for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] id = correct_id_with_req(id, req) username, host = unquote_user_host(id) user = None try: user = models.User.load(context, instance_id, username, host) except (ValueError, AttributeError) as e: raise exception.BadRequest(msg=str(e)) if not user: raise exception.UserNotFound(uuid=id) view = views.UserView(user) return wsgi.Result(view.data(), 200) def update(self, req, body, tenant_id, instance_id, id): """Change attributes for one user.""" LOG.info(_("Updating user attributes for instance '%s'") % instance_id) LOG.info(logging.mask_password(_("req : '%s'\n\n") % req)) context = req.environ[wsgi.CONTEXT_KEY] id = correct_id_with_req(id, req) username, hostname = unquote_user_host(id) user = None user_attrs = body['user'] try: user = models.User.load(context, instance_id, username, hostname) except (ValueError, AttributeError) as e: raise exception.BadRequest(msg=str(e)) if not user: raise exception.UserNotFound(uuid=id) try: models.User.update_attributes(context, instance_id, username, hostname, user_attrs) except (ValueError, AttributeError) as e: raise exception.BadRequest(msg=str(e)) return wsgi.Result(None, 202) def update_all(self, req, body, tenant_id, instance_id): """Change the password of one or more users.""" LOG.info(_("Updating user passwords for instance '%s'") % instance_id) LOG.info(logging.mask_password(_("req : '%s'\n\n") % req)) context = req.environ[wsgi.CONTEXT_KEY] users = body['users'] model_users = [] for user in users: try: mu = guest_models.MySQLUser() mu.name = user['name'] mu.host = user.get('host') mu.password = user['password'] found_user = models.User.load(context, instance_id, mu.name, mu.host) if not found_user: user_and_host = mu.name if mu.host: user_and_host += '@' + mu.host raise exception.UserNotFound(uuid=user_and_host) model_users.append(mu) except (ValueError, AttributeError) as e: raise exception.BadRequest(msg=str(e)) models.User.change_password(context, instance_id, model_users) return wsgi.Result(None, 202) class UserAccessController(wsgi.Controller): """Controller for adding and removing database access for a user.""" schemas = apischema.user @classmethod def get_schema(cls, action, body): schema = {} if 'update_all' == action: schema = cls.schemas.get(action).get('databases') return schema def _get_user(self, context, instance_id, user_id): username, hostname = unquote_user_host(user_id) try: user = models.User.load(context, instance_id, username, hostname) except (ValueError, AttributeError) as e: raise exception.BadRequest(msg=str(e)) if not user: raise exception.UserNotFound(uuid=user_id) return user def index(self, req, tenant_id, instance_id, user_id): """Show permissions for the given user.""" LOG.info(_("Showing user access for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] # Make sure this user exists. user_id = correct_id_with_req(user_id, req) user = self._get_user(context, instance_id, user_id) if not user: LOG.error(_("No such user: %(user)s ") % {'user': user}) raise exception.UserNotFound(uuid=user) username, hostname = unquote_user_host(user_id) access = models.User.access(context, instance_id, username, hostname) view = views.UserAccessView(access.databases) return wsgi.Result(view.data(), 200) def update(self, req, body, tenant_id, instance_id, user_id): """Grant access for a user to one or more databases.""" LOG.info(_("Granting user access for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] user_id = correct_id_with_req(user_id, req) user = self._get_user(context, instance_id, user_id) if not user: LOG.error(_("No such user: %(user)s ") % {'user': user}) raise exception.UserNotFound(uuid=user) username, hostname = unquote_user_host(user_id) databases = [db['name'] for db in body['databases']] models.User.grant(context, instance_id, username, hostname, databases) return wsgi.Result(None, 202) def delete(self, req, tenant_id, instance_id, user_id, id): """Revoke access for a user.""" LOG.info(_("Revoking user access for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] user_id = correct_id_with_req(user_id, req) user = self._get_user(context, instance_id, user_id) if not user: LOG.error(_("No such user: %(user)s ") % {'user': user}) raise exception.UserNotFound(uuid=user) username, hostname = unquote_user_host(user_id) access = models.User.access(context, instance_id, username, hostname) databases = [db.name for db in access.databases] if id not in databases: raise exception.DatabaseNotFound(uuid=id) models.User.revoke(context, instance_id, username, hostname, id) return wsgi.Result(None, 202) class SchemaController(wsgi.Controller): """Controller for instance functionality.""" schemas = apischema.dbschema def index(self, req, tenant_id, instance_id): """Return all schemas.""" LOG.info(_("Listing schemas for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] schemas, next_marker = models.Schemas.load(context, instance_id) view = views.SchemasView(schemas) paged = pagination.SimplePaginatedDataView(req.url, 'databases', view, next_marker) return wsgi.Result(paged.data(), 200) def create(self, req, body, tenant_id, instance_id): """Creates a set of schemas.""" LOG.info(_("Creating schema for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) LOG.info(_("body : '%s'\n\n") % body) context = req.environ[wsgi.CONTEXT_KEY] schemas = body['databases'] model_schemas = populate_validated_databases(schemas) models.Schema.create(context, instance_id, model_schemas) return wsgi.Result(None, 202) def delete(self, req, tenant_id, instance_id, id): LOG.info(_("Deleting schema for instance '%s'") % instance_id) LOG.info(_("req : '%s'\n\n") % req) context = req.environ[wsgi.CONTEXT_KEY] try: schema = guest_models.ValidatedMySQLDatabase() schema.name = id models.Schema.delete(context, instance_id, schema.serialize()) except (ValueError, AttributeError) as e: raise exception.BadRequest(msg=str(e)) return wsgi.Result(None, 202) def show(self, req, tenant_id, instance_id, id): raise webob.exc.HTTPNotImplemented()
changsimon/trove
trove/extensions/mysql/service.py
Python
apache-2.0
12,809
import logging from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.db import models, IntegrityError from django.dispatch import receiver from common.utils import get_sentinel_user log = logging.getLogger("apps") try: from django.contrib.contenttypes.generic import GenericForeignKey except ImportError: from django.contrib.contenttypes.fields import GenericForeignKey class TogglePropertyManager(models.Manager): def toggleproperties_for_user(self, property_type, user): return self.get_queryset().filter(user=user, property_type=property_type) def toggleproperties_for_model(self, property_type, model, user=None): content_type = ContentType.objects.get_for_model(model) qs = self.get_queryset().filter(content_type=content_type, property_type=property_type) if user: qs = qs.filter(user=user) return qs def toggleproperties_for_object(self, property_type, obj, user=None): content_type = ContentType.objects.get_for_model(type(obj)) qs = self.get_queryset().filter(content_type=content_type, property_type=property_type, object_id=obj.pk) if user: qs = qs.filter(user=user) return qs def toggleproperties_for_objects(self, property_type, object_list, user=None): object_ids = [o.pk for o in object_list] if not object_ids: return {} content_type = ContentType.objects.get_for_model(object_list[0]) qs = self.get_queryset().filter(content_type=content_type, property_type=property_type, object_id__in=object_ids) counters = qs.values('object_id').annotate(count=models.Count('object_id')) results = {} for c in counters: results.setdefault(c['object_id'], {})['count'] = c['count'] results.setdefault(c['object_id'], {})['is_toggled'] = False results.setdefault(c['object_id'], {})['content_type_id'] = content_type.id if user and user.is_authenticated: qs = qs.filter(user=user) for f in qs: results.setdefault(f.object_id, {})['is_toggled'] = True return results def toggleproperty_for_user(self, property_type, obj, user): content_type = ContentType.objects.get_for_model(type(obj)) return self.get_queryset().get(content_type=content_type, property_type=property_type, user=user, object_id=obj.pk) def create_toggleproperty(self, property_type, content_object, user): content_type = ContentType.objects.get_for_model(type(content_object)) try: tp = self.toggleproperty_for_user(property_type, content_object, user) except ToggleProperty.DoesNotExist: tp = ToggleProperty( user=user, property_type=property_type, content_type=content_type, object_id=content_object.pk, content_object=content_object ) try: tp.save() except IntegrityError as e: log.warning("Integrity error while trying to save ToggleProperty: %s" % str(e)) pass return tp class ToggleProperty(models.Model): property_type = models.CharField(max_length=64) user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user)) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.TextField() content_object = GenericForeignKey('content_type', 'object_id') created_on = models.DateTimeField(auto_now_add=True) objects = TogglePropertyManager() class Meta: verbose_name = "Toggle property" verbose_name_plural = "Toggle properties" unique_together = (('property_type', 'user', 'content_type', 'object_id'),) ordering = ('-created_on',) def __str__(self): return u"%s (%s) %s" % (self.user, self.property_type, self.content_object) @receiver(models.signals.post_delete) def remove_toggleproperty(sender, **kwargs): instance = kwargs.get('instance') if hasattr(instance, 'id'): content_type = ContentType.objects.get_for_model(ToggleProperty) ToggleProperty.objects.filter(content_type=content_type, object_id=instance.id).delete()
astrobin/astrobin
toggleproperties/models.py
Python
agpl-3.0
4,588
import pytest from formulaic.utils.layered_mapping import LayeredMapping def test_layered_context(): layer1 = {"a": 1, "b": 2, "c": 3} layer2 = {"a": 2, "d": 4} layered = LayeredMapping(layer1, layer2) assert layered["a"] == 1 assert layered["b"] == 2 assert layered["c"] == 3 assert layered["d"] == 4 with pytest.raises(KeyError): layered["e"] assert len(layered) == 4 assert set(layered) == {"a", "b", "c", "d"} layered2 = layered.with_layers({"e": 0, "f": 1, "g": 2}, {"h": 1}) assert set(layered2) == {"a", "b", "c", "d", "e", "f", "g", "h"} layered.with_layers({"e": 2}, inplace=True) assert set(layered) == {"a", "b", "c", "d", "e"} assert layered.with_layers() is layered # Test mutations layered["f"] = 10 assert layered.mutations == {"f": 10} del layered["f"] assert layered.mutations == {} with pytest.raises(KeyError): del layered["a"]
matthewwardrop/formulaic
tests/utils/test_layered_mapping.py
Python
mit
961
from yanntricks import * def CercleImplicite(): pspict,fig = SinglePicture("CercleImplicite") x=var('x') R=2 C=Circle(Point(0,0),R) P=C.get_point(45) Pp=C.get_point(-45) Q=C.get_point(180) X=P.projection(pspict.axes.single_axeX) X.put_mark(0.3,180+45,"\( x\)",pspict=pspict) P.put_mark(0.3,P.advised_mark_angle(pspict),"$P$",pspict=pspict) Pp.put_mark(0.3,Pp.advised_mark_angle(pspict),"\( P'\)",pspict=pspict) Q.put_mark(0.3,180-45,"\( Q\)",pspict=pspict) vert=Segment(P,Pp) vert.parameters.style="dotted" vert.parameters.color="red" pspict.axes.no_graduation() pspict.DrawGraphs(C,P,Pp,Q,X,vert) pspict.DrawDefaultAxes() fig.conclude() fig.write_the_file()
LaurentClaessens/mazhe
src_yanntricks/yanntricksCercleImplicite.py
Python
gpl-3.0
746
def test_nginx_package(Package): package = Package('nginx') assert package.is_installed def test_nginx_working(Command): response = Command('curl http://127.0.0.1/') assert 'Automation for the People' in response.stdout def test_nginx_service(Service, Socket): service = Service('nginx') socket = Socket('tcp://0.0.0.0:80') assert service.is_running assert service.is_enabled assert socket.is_listening def test_index_html(File): index = File('/usr/share/nginx/html/index.html') assert index.content.strip() == 'Automation for the People'
dbryant4/stelligent
tests/test_default.py
Python
mit
590
print "Saving plot to 'reversionPoint.png'" figure.savefig('reversionPoint.png')
Unofficial-Extend-Project-Mirror/openfoam-extend-swak4Foam-dev
Examples/PythonIntegration/findPointPitzDaily/endFindPoint.py
Python
gpl-2.0
82
# 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 six import sqlalchemy as sa from nova.db.sqlalchemy import api as db_api from nova.db.sqlalchemy import api_models as models from nova.objects import fields _RC_TBL = models.ResourceClass.__table__ def raise_if_custom_resource_class_pre_v1_1(rc): """Raises ValueError if the supplied resource class identifier is *not* in the set of standard resource classes as of Inventory/Allocation object version 1.1 param rc: Integer or string identifier for a resource class """ if isinstance(rc, six.string_types): if rc not in fields.ResourceClass.V1_0: raise ValueError else: try: fields.ResourceClass.V1_0[rc] except IndexError: raise ValueError @db_api.api_context_manager.reader def _refresh_from_db(ctx, cache): """Grabs all custom resource classes from the DB table and populates the supplied cache object's internal integer and string identifier dicts. :param cache: ResourceClassCache object to refresh. """ with ctx.session.connection() as conn: sel = sa.select([_RC_TBL.c.id, _RC_TBL.c.name]) res = conn.execute(sel).fetchall() cache.id_cache = {r[1]: r[0] for r in res} cache.str_cache = {r[0]: r[1] for r in res} class ResourceClassCache(object): """A cache of integer and string lookup values for resource classes.""" def __init__(self, ctx): """Initialize the cache of resource class identifiers. :param ctx: `nova.context.RequestContext` from which we can grab a `SQLAlchemy.Connection` object to use for any DB lookups. """ self.ctx = ctx self.id_cache = {} self.str_cache = {} def id_from_string(self, rc_str): """Given a string representation of a resource class -- e.g. "DISK_GB" or "IRON_SILVER" -- return the integer code for the resource class. For standard resource classes, this integer code will match the list of resource classes on the fields.ResourceClass field type. Other custom resource classes will cause a DB lookup into the resource_classes table, however the results of these DB lookups are cached since the lookups are so frequent. :param rc_str: The string representation of the resource class to look up a numeric identifier for. :returns integer identifier for the resource class, or None, if no such resource class was found in the list of standard resource classes or the resource_classes database table. """ if rc_str in self.id_cache: return self.id_cache[rc_str] # First check the standard resource classes if rc_str in fields.ResourceClass.STANDARD: return fields.ResourceClass.STANDARD.index(rc_str) else: # Otherwise, check the database table _refresh_from_db(self.ctx, self) return self.id_cache.get(rc_str) def string_from_id(self, rc_id): """The reverse of the id_from_string() method. Given a supplied numeric identifier for a resource class, we look up the corresponding string representation, either in the list of standard resource classes or via a DB lookup. The results of these DB lookups are cached since the lookups are so frequent. :param rc_id: The numeric representation of the resource class to look up a string identifier for. :returns string identifier for the resource class, or None, if no such resource class was found in the list of standard resource classes or the resource_classes database table. """ if rc_id in self.str_cache: return self.str_cache[rc_id] # First check the fields.ResourceClass.STANDARD values try: return fields.ResourceClass.STANDARD[rc_id] except IndexError: # Otherwise, check the database table _refresh_from_db(self.ctx, self) return self.str_cache.get(rc_id)
sebrandon1/nova
nova/db/sqlalchemy/resource_class_cache.py
Python
apache-2.0
4,711
# Copyright 2020 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 TPU Embeddings mid level API utils on TPU.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized from tensorflow.python.compat import v2_compat from tensorflow.python.platform import test from tensorflow.python.tpu import tpu_embedding_v2_utils class TPUEmbeddingOptimizerTest(parameterized.TestCase, test.TestCase): @parameterized.parameters(tpu_embedding_v2_utils.Adagrad, tpu_embedding_v2_utils.Adam) def test_grad_clip_with_accumulation_off(self, optimizer): with self.assertRaisesRegex(ValueError, 'accumulation'): optimizer(use_gradient_accumulation=False, clipvalue=0.) with self.assertRaisesRegex(ValueError, 'accumulation'): optimizer(use_gradient_accumulation=False, clipvalue=(None, 1.)) @parameterized.parameters(tpu_embedding_v2_utils.SGD, tpu_embedding_v2_utils.Adagrad, tpu_embedding_v2_utils.Adam) def test_grad_clip_with_tuple(self, optimizer): opt = optimizer(clipvalue=(-1., 1.)) self.assertEqual(-1., opt.clip_gradient_min) self.assertEqual(1., opt.clip_gradient_max) @parameterized.parameters(tpu_embedding_v2_utils.SGD, tpu_embedding_v2_utils.Adagrad, tpu_embedding_v2_utils.Adam) def test_grad_clip_with_single_value(self, optimizer): opt = optimizer(clipvalue=1.) self.assertEqual(-1., opt.clip_gradient_min) self.assertEqual(1., opt.clip_gradient_max) @parameterized.parameters(tpu_embedding_v2_utils.SGD, tpu_embedding_v2_utils.Adagrad, tpu_embedding_v2_utils.Adam) def test_grad_clip_with_tuple_and_none(self, optimizer): opt = optimizer(clipvalue=(None, 1)) self.assertIsNone(opt.clip_gradient_min) self.assertEqual(1., opt.clip_gradient_max) class ConfigTest(test.TestCase): def test_table_config_repr(self): table = tpu_embedding_v2_utils.TableConfig( vocabulary_size=2, dim=4, initializer=None, combiner='sum', name='table') self.assertEqual( repr(table), 'TableConfig(vocabulary_size=2, dim=4, initializer=None, ' 'optimizer=None, combiner=\'sum\', name=\'table\')') def test_feature_config_repr(self): table = tpu_embedding_v2_utils.TableConfig( vocabulary_size=2, dim=4, initializer=None, combiner='sum', name='table') feature_config = tpu_embedding_v2_utils.FeatureConfig( table=table, name='feature') self.assertEqual( repr(feature_config), 'FeatureConfig(table=TableConfig(vocabulary_size=2, dim=4, ' 'initializer=None, optimizer=None, combiner=\'sum\', name=\'table\'), ' 'max_sequence_length=0, name=\'feature\')' ) if __name__ == '__main__': v2_compat.enable_v2_behavior() test.main()
karllessard/tensorflow
tensorflow/python/tpu/tpu_embedding_v2_utils_test.py
Python
apache-2.0
3,638
from core import * from roles import * from org import * from hrm import * from inv import * from asset import * from project import * from smoke import * from member import *
mrGeen/eden
modules/tests/__init__.py
Python
mit
176
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2004-2019 University of Tromsø, Norway # # This file is part of Cerebrum. # # Cerebrum is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ Process accounts for SITO employees. This should run after importing employee data from SITO. """ from __future__ import absolute_import, print_function import argparse import logging import os import sys import xml.etree.ElementTree import datetime import cereconf import Cerebrum.logutils import Cerebrum.logutils.options from Cerebrum import Entity from Cerebrum.Utils import Factory from Cerebrum.modules import PosixUser from Cerebrum.modules.no.uit.Account import UsernamePolicy from Cerebrum.modules.no.uit import POSIX_GROUP_NAME from Cerebrum.utils.argutils import add_commit_args from Cerebrum.utils.date_compat import get_datetime_naive logger = logging.getLogger(__name__) class ExistingAccount(object): def __init__(self, fnr, uname, expire_date): self._affs = list() self._new_affs = list() self._expire_date = expire_date self._fnr = fnr self._owner_id = None self._uid = None self._home = dict() self._quarantines = list() self._spreads = list() self._traits = list() self._email = None self._uname = uname self._gecos = None def append_affiliation(self, affiliation, ou_id, priority): self._affs.append((affiliation, ou_id, priority)) def append_new_affiliations(self, affiliation, ou_id): self._new_affs.append((affiliation, ou_id, None)) def append_quarantine(self, q): self._quarantines.append(q) def append_spread(self, spread): self._spreads.append(spread) def append_trait(self, trait_code, trait_str): self._traits.append((trait_code, trait_str)) def get_affiliations(self): return self._affs def get_new_affiliations(self): return self._new_affs def get_email(self): return self._email def get_expire_date(self): return self._expire_date def get_fnr(self): return self._fnr def get_gecos(self): return self._gecos def get_posix(self): return self._uid def get_home(self, spread): return self._home.get(spread, (None, None)) def get_home_spreads(self): return self._home.keys() def get_quarantines(self): return self._quarantines def get_spreads(self): return self._spreads def get_traits(self): return self._traits def get_uname(self): return self._uname def has_affiliation(self, aff_cand): return aff_cand in [aff for aff, ou in self._affs] def has_homes(self): return len(self._home) > 0 def set_email(self, email): self._email = email def set_posix(self, uid): self._uid = uid def set_gecos(self, gecos): self._gecos = gecos def set_home(self, spread, home, homedir_id): self._home[spread] = (homedir_id, home) class ExistingPerson(object): def __init__(self, person_id=None): self._affs = list() self._groups = list() self._spreads = list() self._accounts = list() self._primary_accountid = None self._personid = person_id self._fullname = None self._deceased_date = None def append_account(self, acc_id): self._accounts.append(acc_id) def append_affiliation(self, affiliation, ou_id, status): self._affs.append((affiliation, ou_id, status)) def append_group(self, group_id): self._groups.append(group_id) def append_spread(self, spread): self._spreads.append(spread) def get_affiliations(self): return self._affs def get_new_affiliations(self): return self._new_affs def get_fullnanme(self): return self._full_name def get_groups(self): return self._groups def get_personid(self): return self._personid def get_primary_account(self): if self._primary_accountid: return self._primary_accountid[0] else: return self.get_account() def get_spreads(self): return self._spreads def has_account(self): return len(self._accounts) > 0 def get_account(self): return self._accounts[0] def set_primary_account(self, ac_id, priority): if self._primary_accountid: old_id, old_pri = self._primary_accountid if priority < old_pri: self._primary_accountid = (ac_id, priority) else: self._primary_accountid = (ac_id, priority) def set_personid(self, id): self._personid = id def set_fullname(self, full_name): self._fullname = full_name def set_deceased_date(self, deceased_date): self._deceased_date = deceased_date def get_deceased_date(self): return self._deceased_date def get_existing_accounts(db): """ Get caches of SITO data. :rtype: tuple :return: Returns two dict mappings: - fnr to ExistingPerson object - account_id to ExistingAccount object """ co = Factory.get('Constants')(db) pe = Factory.get('Person')(db) ac = Factory.get('Account')(db) pu = PosixUser.PosixUser(db) logger.info("Loading persons...") person_cache = {} account_cache = {} pid2fnr = {} # getting deceased persons deceased = pe.list_deceased() for row in pe.search_external_ids(id_type=co.externalid_fodselsnr, source_system=co.system_sito, fetchall=False): p_id = int(row['entity_id']) if p_id not in pid2fnr: pid2fnr[p_id] = row['external_id'] person_cache[row['external_id']] = ExistingPerson(person_id=p_id) if p_id in deceased: person_cache[row['external_id']].set_deceased_date(deceased[p_id]) del p_id logger.info("Loading person affiliations...") for row in pe.list_affiliations(source_system=co.system_sito, fetchall=False): p_id = int(row['person_id']) if p_id in pid2fnr: person_cache[pid2fnr[p_id]].append_affiliation( int(row['affiliation']), int(row['ou_id']), int(row['status'])) del p_id logger.info("Loading accounts...") for row in ac.search(expire_start=None): a_id = int(row['account_id']) if not row['owner_id'] or int(row['owner_id']) not in pid2fnr: continue account_cache[a_id] = ExistingAccount( pid2fnr[int(row['owner_id'])], row['name'], row['expire_date']) del a_id # Posixusers logger.info("Loading posixinfo...") for row in pu.list_posix_users(): a_obj = account_cache.get(int(row['account_id']), None) if a_obj is not None: a_obj.set_posix(int(row['posix_uid'])) del a_obj # quarantines logger.info("Loading account quarantines...") for row in ac.list_entity_quarantines( entity_types=co.entity_account): a_obj = account_cache.get(int(row['entity_id']), None) if a_obj is not None: a_obj.append_quarantine(int(row['quarantine_type'])) del a_obj # Spreads logger.info("Loading spreads... %r", cereconf.SITO_EMPLOYEE_DEFAULT_SPREADS) spread_list = [int(co.Spread(x)) for x in cereconf.SITO_EMPLOYEE_DEFAULT_SPREADS] for spread_id in spread_list: is_account_spread = is_person_spread = False spread = co.Spread(spread_id) if spread.entity_type == co.entity_account: is_account_spread = True elif spread.entity_type == co.entity_person: is_person_spread = True else: logger.warn("Unknown spread type (%r)", spread) continue for row in ac.list_all_with_spread(spread_id): e_id = int(row['entity_id']) if is_account_spread and e_id in account_cache: account_cache[e_id].append_spread(int(spread)) elif is_person_spread and e_id in pid2fnr: account_cache[pid2fnr[e_id]].append_spread(int(spread)) del e_id # Account homes logger.info("Loading account homes...") for row in ac.list_account_home(): a_id = int(row['account_id']) if a_id in account_cache: account_cache[a_id].set_home(int(row['home_spread']), row['home'], int(row['homedir_id'])) del a_id # Account Affiliations logger.info("Loading account affs...") for row in ac.list_accounts_by_type(filter_expired=False, primary_only=False, fetchall=False): a_id = int(row['account_id']) if a_id in account_cache: account_cache[a_id].append_affiliation( int(row['affiliation']), int(row['ou_id']), int(row['priority'])) del a_id # persons accounts.... for a_id, a_obj in account_cache.items(): fnr = account_cache[a_id].get_fnr() person_cache[fnr].append_account(a_id) for aff in a_obj.get_affiliations(): aff, ou_id, pri = aff person_cache[fnr].set_primary_account(a_id, pri) logger.info("Found %d persons and %d accounts", len(person_cache), len(account_cache)) return person_cache, account_cache def parse_person(person): """ Parse a Person xml element. :param person: A //Persons/Person element :rtype: dict :return: A dictionary with normalized values. """ employee_id = None def get(xpath, default=None): elem = person.find(xpath) if elem is None or not elem.text: logger.warning('Missing element %r for employee_id=%r', xpath, employee_id) return default else: return (elem.text or '').strip() # Mandatory params employee_id = get('EmploymentInfo/Employee/EmployeeNumber') person_dict = { 'employee_id': employee_id, 'ssn': get('SocialSecurityNumber'), 'is_deactivated': get('IsDeactivated') != 'false', } pos_pct = 0.0 for employment in person.findall('EmploymentInfo/Employee/' 'Employment/Employment'): pct_elem = employment.find('EmploymentDistributionList/' 'EmploymentDistribution/PositionPercent') if pct_elem is not None and pct_elem.text: pos_pct = max(pos_pct, float(pct_elem.text)) logger.debug('Position percentage for employee_id=%r: %f', employee_id, pos_pct) person_dict['position_percentage'] = pos_pct return person_dict def generate_persons(filename): """ Find and parse employee data from an xml file. """ if not os.path.isfile(filename): raise OSError('No file %r' % (filename, )) tree = xml.etree.ElementTree.parse(filename) root = tree.getroot() stats = {'ok': 0, 'skipped': 0, 'failed': 0} for i, person in enumerate(root.findall(".//Persons/Person"), 1): try: person_dict = parse_person(person) except Exception: stats['failed'] += 1 logger.error('Skipping person #%d (element=%r), invalid data', i, person, exc_info=True) continue if person_dict['is_deactivated']: logger.info('Skipping person #%d (employee_id=%r), deactivated', i, person_dict['employee_id']) stats['skipped'] += 1 continue if not person_dict['employee_id']: logger.warning('Skipping person #%d (employee_id=%r), missing ' ' employee_id', i, person_dict['employee_id']) stats['skipped'] += 1 continue if not person_dict['ssn']: # TODO: Should use employee_id as identifier... logger.warning('Skipping person #%d (employee_id=%r), missing ssn', i, person_dict['employee_id']) stats['skipped'] += 1 continue stats['ok'] += 1 yield person_dict logger.info("Parsed %d persons (%d ok)", sum(stats.values()), stats['ok']) class SkipPerson(Exception): """Skip processing a person.""" pass class NotFound(Exception): """Missing required info.""" pass class Build(object): """ Account builder """ def __init__(self, db, persons=None, accounts=None): self.db = db self.co = Factory.get('Constants')(db) self.persons = persons or {} self.accounts = accounts or {} def process(self, person_data): """ Process a list of persons from the sito import data. :param person_data: An iterable with dicts from py:func:`parse_person` """ stats = {'ok': 0, 'skipped': 0, 'failed': 0} for person_dict in person_data: try: self.process_person(person_dict) except SkipPerson as e: logger.warning('Skipping employee_id=%r: %s', person_dict['employee_id'], e) stats['skipped'] += 1 except Exception: logger.error('Skipping employee_id=%r: unhandled error', person_dict['employee_id'], exc_info=True) stats['failed'] += 1 continue else: stats['ok'] += 1 logger.info("Processed %d persons (%d ok)", sum(stats.values()), stats['ok']) def _calculate_spreads(self, acc_affs, new_affs): default_spreads = [int(self.co.Spread(x)) for x in cereconf.SITO_EMPLOYEE_DEFAULT_SPREADS] all_affs = acc_affs + new_affs # need at least one aff to give exchange spread if set(all_affs): default_spreads.append(int(self.co.Spread('exchange_mailbox'))) return default_spreads def process_person(self, person_dict): """ Process a given person: :param person_data: A dict from py:func:`parse_person` """ employee_id = person_dict['employee_id'] logger.info("Process employee_id=%r", employee_id) fnr = person_dict['ssn'] if not fnr: raise SkipPerson('missing ssn') if fnr not in self.persons: raise SkipPerson('unknown person') p_obj = self.persons[fnr] changes = [] account = Factory.get('Account')(self.db) if not p_obj.has_account(): # person does not have an account. Create a sito account acc_id = self.create_sito_account(p_obj, fnr) else: # person has account(s) sito_account = 0 acc_id = 0 try: acc_id = self.get_sito_account(p_obj) except NotFound: acc_id = self.create_sito_account(p_obj, fnr) # we now have correct account object. Add missing account data. acc_obj = self.accounts[acc_id] # Check if account is a posix account if not acc_obj.get_posix(): changes.append(('promote_posix', True)) # Update expire if needed current_expire = acc_obj.get_expire_date() new_expire = get_expire_date() # expire account if person is deceased new_deceased = False if p_obj.get_deceased_date() is not None: new_expire = p_obj.get_deceased_date() if current_expire != new_expire: logger.warn("Account owner deceased: %s", acc_obj.get_uname()) new_deceased = True logger.debug("Current expire %s, new expire %s", current_expire, new_expire) if new_expire > current_expire or new_deceased: changes.append(('expire_date', str(new_expire))) # check account affiliation and status changes.extend(self._populate_account_affiliations(acc_id, p_obj)) # make sure user has correct spreads if p_obj.get_affiliations(): # if person has affiliations, add spreads default_spreads = self._calculate_spreads( acc_obj.get_affiliations(), acc_obj.get_new_affiliations()) logger.debug("old affs:%s, new affs:%s", acc_obj.get_affiliations(), acc_obj.get_new_affiliations()) def_spreads = set(default_spreads) cb_spreads = set(acc_obj.get_spreads()) to_add = def_spreads - cb_spreads if to_add: changes.append(('spreads_add', to_add)) # Set spread expire date # Always use new expire to avoid SITO specific spreads to be # extended because of mixed student / employee accounts # TBD: 3 personer fra SITO har i dag bare 1 tilhørighet til rot-noden. # Disse må få enda en tilhørighet. Hvis det ikke skjer, vil disse 3 # ikke få konto. if 'def_spreads' in locals(): for ds in def_spreads: account.set_spread_expire(spread=ds, expire_date=new_expire, entity_id=acc_id) else: logger.debug("person %s has no active sito affiliation", p_obj.get_personid()) # check quarantines for qt in acc_obj.get_quarantines(): # employees should not have tilbud quarantine. if qt == self.co.quarantine_tilbud: changes.append(('quarantine_del', qt)) if changes: logger.info("Changes for account_id=%r: %s", acc_id, repr(changes)) _handle_changes(self.db, acc_id, changes) def create_sito_account(self, existing_person, fnr): """ Create a sito account for a given person. """ p_obj = Factory.get('Person')(self.db) p_obj.find(existing_person.get_personid()) first_name = p_obj.get_name(self.co.system_cached, self.co.name_first) last_name = p_obj.get_name(self.co.system_cached, self.co.name_last) full_name = "%s %s" % (first_name, last_name) name_gen = UsernamePolicy(self.db) uname = name_gen.get_sito_uname(fnr, full_name) acc_obj = Factory.get('Account')(self.db) acc_obj.populate( uname, self.co.entity_person, p_obj.entity_id, None, get_creator_id(self.db), get_expire_date()) try: acc_obj.write_db() except Exception as m: logger.error("Failed create for %s, uname=%s, reason: %s", fnr, uname, m) else: password = acc_obj.make_passwd(uname) acc_obj.set_password(password) acc_obj.write_db() # register new account obj in existing accounts list self.accounts[acc_obj.entity_id] = ExistingAccount(fnr, uname, None) logger.info("Created sito account_id=%r (%s) for person_id=%r", acc_obj.entity_id, uname, existing_person.get_personid()) return acc_obj.entity_id def get_sito_account(self, existing_person): account = Factory.get('Account')(self.db) person_id = existing_person.get_personid() sito_account = None for acc in existing_person._accounts: account.clear() account.find(acc) for acc_type in account.get_account_types(): if self.co.affiliation_ansatt_sito in acc_type: sito_account = account.entity_id logger.info("Found sito account_id=%r (%s) for " "person_id=%r (from acc_type)", sito_account, account.account_name, person_id) break if sito_account is None: # An account may have its account type not set. # in these cases, the only way to check if an acocunt is a sito # account is to check the last 2 letters in the account name. # if they are'-s', then its a sito account. for acc in existing_person._accounts: account.clear() account.find(acc) # Account did not have a sito type (only set on active # accounts). we will have to check account name in case we # have to reopen an inactive account. if UsernamePolicy.is_valid_sito_name(account.account_name): sito_account = account.entity_id logger.info("Found sito account_id=%r (%s) for " "person_id=%r (from username)", sito_account, account.account_name, person_id) break if sito_account is None: raise NotFound("No sito account for %r", existing_person) else: return sito_account def _populate_account_affiliations(self, account_id, existing_person): """ Generate changes to account affs from person affs. """ changes = [] tmp_affs = self.accounts[account_id].get_affiliations() account_affs = list() logger.debug('generate aff list for account_id:%s', account_id) for aff, ou, pri in tmp_affs: account_affs.append((aff, ou)) p_id = existing_person.get_personid() p_affs = existing_person.get_affiliations() logger.debug("person_id=%r has affs=%r", p_id, p_affs) logger.debug("account_id=%s has account affs=%r", account_id, account_affs) for aff, ou, status in p_affs: if (aff, ou) not in account_affs: changes.append(('set_ac_type', (ou, aff))) self.accounts[account_id].append_new_affiliations(aff, ou) return changes def get_expire_date(): """ calculate a default expire date. Take into consideration that we do not want an expiredate in the general holiday time in Norway. """ today = datetime.datetime.today() ff_start = datetime.datetime(today.year, 6, 15) ff_slutt = datetime.datetime(today.year, 8, 15) nextmonth = today + datetime.timedelta(30) # ikke sett default expire til en dato i fellesferien if nextmonth > ff_start and nextmonth < ff_slutt: # fellesferien. Bruk 1 sept istedet. return get_datetime_naive(datetime.datetime(today.year, 9, 1)) else: return get_datetime_naive(nextmonth) def _handle_changes(db, account_id, changes): do_promote_posix = False ac = Factory.get('Account')(db) ac.find(account_id) for chg in changes: ccode, cdata = chg if ccode == 'spreads_add': for s in cdata: ac.add_spread(s) ac.set_home_dir(s) elif ccode == 'quarantine_add': ac.add_entity_quarantine(cdata, get_creator_id(db)) elif ccode == 'quarantine_del': ac.delete_entity_quarantine(cdata) elif ccode == 'set_ac_type': ac.set_account_type(cdata[0], cdata[1]) elif ccode == 'gecos': ac.gecos = cdata elif ccode == 'expire_date': ac.expire_date = cdata elif ccode == 'promote_posix': do_promote_posix = True # TODO: no update_email? # elif ccode == 'update_mail': # update_email(account_id, cdata) else: logger.error("Invalid change for account_id=%r change=%r (%r)", account_id, ccode, cdata) continue ac.write_db() if do_promote_posix: _promote_posix(db, ac) logger.info("All changes written for account_id=%r", account_id) def _promote_posix(db, acc_obj): co = Factory.get('Constants')(db) group = Factory.get('Group')(db) pu = PosixUser.PosixUser(db) uid = pu.get_free_uid() shell = co.posix_shell_bash group.find_by_name(POSIX_GROUP_NAME) try: pu.populate(uid, group.entity_id, None, shell, parent=acc_obj) pu.write_db() except Exception as msg: logger.error("Error during promote_posix. Error was: %s", msg) return False # only gets here if posix user created successfully logger.info("%s promoted to posixaccount (uidnumber=%s)", acc_obj.account_name, uid) return True def get_creator_id(db): co = Factory.get('Constants')(db) entity_name = Entity.EntityName(db) entity_name.find_by_name(cereconf.INITIAL_ACCOUNTNAME, co.account_namespace) return entity_name.entity_id default_person_file = os.path.join(sys.prefix, 'var/cache/sito/Sito-Persons.xml') def main(inargs=None): parser = argparse.ArgumentParser( description="Process accounts for SITO employees") parser.add_argument( '-p', '--person-file', default=default_person_file, help='Process persons from %(metavar)s', metavar='xml-file', ) add_commit_args(parser) Cerebrum.logutils.options.install_subparser(parser) args = parser.parse_args(inargs) Cerebrum.logutils.autoconf('cronjob', args) logger.info('Start of %s', parser.prog) logger.debug('args: %r', args) db = Factory.get('Database')() db.cl_init(change_program='process_sito') builder = Build(db) logger.info('Fetching cerebrum data') builder.persons, builder.accounts = get_existing_accounts(db) logger.info('Reading persons from %r', args.person_file) source_data = generate_persons(args.person_file) logger.info('Processing persons') builder.process(source_data) if args.commit: logger.info('Commiting changes') db.commit() else: db.rollback() logger.info('Rolling back changes') logger.info('Done %s', parser.prog) if __name__ == '__main__': main()
unioslo/cerebrum
contrib/no/uit/process_sito.py
Python
gpl-2.0
27,213
# -*- coding: utf-8 -*- __author__ = 'amaier1' from temis import extract_entities
axelspringer/semaeval
semaeval/engine/temis/__init__.py
Python
mit
83
#!/usr/bin/env python # Simple debugger # See instructions around line 36 import sys import readline # Our buggy program def remove_html_markup(s): tag = False quote = False out = "" for c in s: if c == '<' and not quote: tag = True elif c == '>' and not quote: tag = False elif c == '"' or c == "'" and tag: quote = not quote elif not tag: out = out + c return out # main program that runs the buggy program def main(): print remove_html_markup('xyz') print remove_html_markup('"<b>foo</b>"') print remove_html_markup("'<b>foo</b>'") # globals breakpoints = {14: True} watchpoints = {'c': True} stepping = False """ Our debug function Improve and expand the debug function to accept a watchpoint command 'w <var name>'. Add the variable name to the watchpoints dictionary or print 'You must supply a variable name' if 'w' is not followed by a string. """ def debug(command, my_locals): global stepping global breakpoints #global watchpoints if command.find(' ') > 0: arg = command.split(' ')[1] else: arg = None if command.startswith('s'): # step stepping = True return True elif command.startswith('c'): # continue stepping = False return True elif command.startswith('p'): # print # FIRST ASSIGNMENT CODE pass elif command.startswith('b'): # breakpoint # SECOND ASSIGNMENT CODE pass elif command.startswith('w'): # watch variable # YOUR CODE HERE if arg == None: print "You must supply a variable name" else: watchpoints[arg] = True return True elif command.startswith('q'): # quit print "Exiting my-spyder..." sys.exit(0) else: print "No such command", repr(command) return False commands = ["w out", "c", "c", "c", "c", "c", "c", "q"] def input_command(): #command = raw_input("(my-spyder) ") global commands command = commands.pop(0) return command def traceit(frame, event, trace_arg): global stepping if event == 'line': if stepping or breakpoints.has_key(frame.f_lineno): resume = False while not resume: print event, frame.f_lineno, frame.f_code.co_name, frame.f_locals command = input_command() resume = debug(command, frame.f_locals) return traceit # Using the tracer #sys.settrace(traceit) #main() #sys.settrace(None) #Simple test print watchpoints debug("w s", {'s': 'xyz', 'tag': False}) print watchpoints #>>> {'c': True} #>>> {'c': True, 's': True}
juangm/Udacity
Software_Debugging/Problem_1/Debugger_Part3.py
Python
unlicense
2,771
""" byceps.services.user_badge.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from dataclasses import dataclass from datetime import datetime from typing import NewType from uuid import UUID from ....typing import BrandID, UserID BadgeID = NewType('BadgeID', UUID) @dataclass(frozen=True) class Badge: id: BadgeID slug: str label: str description: str image_filename: str image_url_path: str brand_id: BrandID featured: bool @dataclass(frozen=True) class BadgeAwarding: id: UUID badge_id: BadgeID user_id: UserID awarded_at: datetime @dataclass(frozen=True) class QuantifiedBadgeAwarding: badge_id: BadgeID user_id: UserID quantity: int
homeworkprod/byceps
byceps/services/user_badge/transfer/models.py
Python
bsd-3-clause
822
# coding: utf8 import requests import json import reactor headers = {'content-type': 'application/json'} def _request(data): # print id(reactor), reactor.APPLICATION_ID, id(reactor.APPLICATION_ID) data['data'].update({'application_id': reactor.APPLICATION_ID}) return requests.post( reactor.REACTOR_URL, headers=headers, data=json.dumps(data, sort_keys=reactor.JSON_SORT_KEYS) ) def collect(data): return _request({ 'type': 'collect', 'data': data }) def event(event_name, data): # this could overwrite users data data.update({'type': event_name}) return _request({ 'type': 'event', 'data': data, })
Pexeso/reactor-python
reactor/common.py
Python
gpl-2.0
631
''' forest data structure ''' import itertools import weakref from p2pool.util import skiplist, variable class TrackerSkipList(skiplist.SkipList): def __init__(self, tracker): skiplist.SkipList.__init__(self) self.tracker = tracker self_ref = weakref.ref(self, lambda _: tracker.removed.unwatch(watch_id)) watch_id = self.tracker.removed.watch(lambda share: self_ref().forget_item(share.hash)) def previous(self, element): return self.tracker.delta_type.from_element(self.tracker.shares[element]).tail class DistanceSkipList(TrackerSkipList): def get_delta(self, element): return element, 1, self.previous(element) def combine_deltas(self, (from_hash1, dist1, to_hash1), (from_hash2, dist2, to_hash2)): if to_hash1 != from_hash2: raise AssertionError() return from_hash1, dist1 + dist2, to_hash2 def initial_solution(self, start, (n,)): return 0, start def apply_delta(self, (dist1, to_hash1), (from_hash2, dist2, to_hash2), (n,)): if to_hash1 != from_hash2: raise AssertionError() return dist1 + dist2, to_hash2 def judge(self, (dist, hash), (n,)): if dist > n: return 1 elif dist == n: return 0 else: return -1 def finalize(self, (dist, hash), (n,)): assert dist == n return hash def get_attributedelta_type(attrs): # attrs: {name: func} class ProtoAttributeDelta(object): __slots__ = ['head', 'tail'] + attrs.keys() @classmethod def get_none(cls, element_id): return cls(element_id, element_id, **dict((k, 0) for k in attrs)) @classmethod def from_element(cls, share): return cls(share.hash, share.previous_hash, **dict((k, v(share)) for k, v in attrs.iteritems())) def __init__(self, head, tail, **kwargs): self.head, self.tail = head, tail for k, v in kwargs.iteritems(): setattr(self, k, v) def __add__(self, other): assert self.tail == other.head return self.__class__(self.head, other.tail, **dict((k, getattr(self, k) + getattr(other, k)) for k in attrs)) def __sub__(self, other): if self.head == other.head: return self.__class__(other.tail, self.tail, **dict((k, getattr(self, k) - getattr(other, k)) for k in attrs)) elif self.tail == other.tail: return self.__class__(self.head, other.head, **dict((k, getattr(self, k) - getattr(other, k)) for k in attrs)) else: raise AssertionError() def __repr__(self): return '%s(%r, %r%s)' % (self.__class__, self.head, self.tail, ''.join(', %s=%r' % (k, getattr(self, k)) for k in attrs)) ProtoAttributeDelta.attrs = attrs return ProtoAttributeDelta AttributeDelta = get_attributedelta_type(dict( height=lambda item: 1, )) class Tracker(object): def __init__(self, shares=[], delta_type=AttributeDelta): self.shares = {} # hash -> share self.reverse_shares = {} # delta.tail -> set of share_hashes self.heads = {} # head hash -> tail_hash self.tails = {} # tail hash -> set of head hashes self.deltas = {} # share_hash -> delta, ref self.reverse_deltas = {} # ref -> set of share_hashes self.ref_generator = itertools.count() self.delta_refs = {} # ref -> delta self.reverse_delta_refs = {} # delta.tail -> ref self.added = variable.Event() self.removed = variable.Event() self.get_nth_parent_hash = DistanceSkipList(self) self.delta_type = delta_type for share in shares: self.add(share) def add(self, share): assert not isinstance(share, (int, long, type(None))) delta = self.delta_type.from_element(share) if delta.head in self.shares: raise ValueError('share already present') if delta.head in self.tails: heads = self.tails.pop(delta.head) else: heads = set([delta.head]) if delta.tail in self.heads: tail = self.heads.pop(delta.tail) else: tail = self.get_last(delta.tail) self.shares[delta.head] = share self.reverse_shares.setdefault(delta.tail, set()).add(delta.head) self.tails.setdefault(tail, set()).update(heads) if delta.tail in self.tails[tail]: self.tails[tail].remove(delta.tail) for head in heads: self.heads[head] = tail self.added.happened(share) def remove(self, share_hash): assert isinstance(share_hash, (int, long, type(None))) if share_hash not in self.shares: raise KeyError() share = self.shares[share_hash] del share_hash delta = self.delta_type.from_element(share) children = self.reverse_shares.get(delta.head, set()) if delta.head in self.heads and delta.tail in self.tails: tail = self.heads.pop(delta.head) self.tails[tail].remove(delta.head) if not self.tails[delta.tail]: self.tails.pop(delta.tail) elif delta.head in self.heads: tail = self.heads.pop(delta.head) self.tails[tail].remove(delta.head) if self.reverse_shares[delta.tail] != set([delta.head]): pass # has sibling else: self.tails[tail].add(delta.tail) self.heads[delta.tail] = tail elif delta.tail in self.tails and len(self.reverse_shares[delta.tail]) <= 1: # move delta refs referencing children down to this, so they can be moved up in one step if delta.tail in self.reverse_delta_refs: for x in list(self.reverse_deltas.get(self.reverse_delta_refs.get(delta.head, object()), set())): self.get_last(x) assert delta.head not in self.reverse_delta_refs, list(self.reverse_deltas.get(self.reverse_delta_refs.get(delta.head, None), set())) heads = self.tails.pop(delta.tail) for head in heads: self.heads[head] = delta.head self.tails[delta.head] = set(heads) # move ref pointing to this up if delta.tail in self.reverse_delta_refs: assert delta.head not in self.reverse_delta_refs, list(self.reverse_deltas.get(self.reverse_delta_refs.get(delta.head, object()), set())) ref = self.reverse_delta_refs[delta.tail] cur_delta = self.delta_refs[ref] assert cur_delta.tail == delta.tail self.delta_refs[ref] = cur_delta - self.delta_type.from_element(share) assert self.delta_refs[ref].tail == delta.head del self.reverse_delta_refs[delta.tail] self.reverse_delta_refs[delta.head] = ref else: raise NotImplementedError() # delete delta entry and ref if it is empty if delta.head in self.deltas: delta1, ref = self.deltas.pop(delta.head) self.reverse_deltas[ref].remove(delta.head) if not self.reverse_deltas[ref]: del self.reverse_deltas[ref] delta2 = self.delta_refs.pop(ref) del self.reverse_delta_refs[delta2.tail] self.shares.pop(delta.head) self.reverse_shares[delta.tail].remove(delta.head) if not self.reverse_shares[delta.tail]: self.reverse_shares.pop(delta.tail) self.removed.happened(share) def get_height(self, share_hash): return self.get_delta(share_hash).height def get_work(self, share_hash): return self.get_delta(share_hash).work def get_last(self, share_hash): return self.get_delta(share_hash).tail def get_height_and_last(self, share_hash): delta = self.get_delta(share_hash) return delta.height, delta.tail def get_height_work_and_last(self, share_hash): delta = self.get_delta(share_hash) return delta.height, delta.work, delta.tail def _get_delta(self, share_hash): if share_hash in self.deltas: delta1, ref = self.deltas[share_hash] delta2 = self.delta_refs[ref] res = delta1 + delta2 else: res = self.delta_type.from_element(self.shares[share_hash]) assert res.head == share_hash return res def _set_delta(self, share_hash, delta): other_share_hash = delta.tail if other_share_hash not in self.reverse_delta_refs: ref = self.ref_generator.next() assert ref not in self.delta_refs self.delta_refs[ref] = self.delta_type.get_none(other_share_hash) self.reverse_delta_refs[other_share_hash] = ref del ref ref = self.reverse_delta_refs[other_share_hash] ref_delta = self.delta_refs[ref] assert ref_delta.tail == other_share_hash if share_hash in self.deltas: prev_ref = self.deltas[share_hash][1] self.reverse_deltas[prev_ref].remove(share_hash) if not self.reverse_deltas[prev_ref] and prev_ref != ref: self.reverse_deltas.pop(prev_ref) x = self.delta_refs.pop(prev_ref) self.reverse_delta_refs.pop(x.tail) self.deltas[share_hash] = delta - ref_delta, ref self.reverse_deltas.setdefault(ref, set()).add(share_hash) def get_delta(self, share_hash): assert isinstance(share_hash, (int, long, type(None))) delta = self.delta_type.get_none(share_hash) updates = [] while delta.tail in self.shares: updates.append((delta.tail, delta)) this_delta = self._get_delta(delta.tail) delta += this_delta for update_hash, delta_then in updates: self._set_delta(update_hash, delta - delta_then) return delta def get_chain(self, start_hash, length): assert length <= self.get_height(start_hash) for i in xrange(length): yield self.shares[start_hash] start_hash = self.delta_type.from_element(self.shares[start_hash]).tail def is_child_of(self, share_hash, possible_child_hash): height, last = self.get_height_and_last(share_hash) child_height, child_last = self.get_height_and_last(possible_child_hash) if child_last != last: return None # not connected, so can't be determined height_up = child_height - height return height_up >= 0 and self.get_nth_parent_hash(possible_child_hash, height_up) == share_hash
goblin/p2pool
p2pool/util/forest.py
Python
gpl-3.0
11,137
from django.apps import AppConfig class LandingConfig(AppConfig): name = 'landing' verbose_name = 'Django Landing'
joshmarlow/crowdpact
crowdpact/apps/landing/app.py
Python
mit
125
# -*- coding: utf-8 -*- # # SymPy documentation build configuration file, created by # sphinx-quickstart.py on Sat Mar 22 19:34:32 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import sys import sympy # If your extensions are in another directory, add it here. sys.path = ['../sympy', 'ext'] + sys.path # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.addons.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.mathjax', 'numpydoc', 'sympylive', 'sphinx.ext.graphviz', ] # Use this to use pngmath instead #extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.pngmath', ] # MathJax file, which is free to use. See http://www.mathjax.org/docs/2.0/start.html mathjax_path = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full' # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General substitutions. project = 'SymPy' copyright = '2016 SymPy Development Team' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = sympy.__version__ # The full version, including alpha/beta/rc tags. release = version # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' html_logo = '_static/sympylogo.png' html_favicon = '../_build/logo/sympy-notailtext-favicon.ico' # See http://sphinx-doc.org/theming.html#builtin-themes. # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Content template for the index page. #html_index = '' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True html_domain_indices = ['py-modindex'] # If true, the reST sources are included in the HTML build as _sources/<name>. #html_copy_source = True # Output file base name for HTML help builder. htmlhelp_basename = 'SymPydoc' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual], toctree_only). # toctree_only is set to True so that the start file document itself is not included in the # output, only the documents referenced by it via TOC trees. The extra stuff in the master # document is intended to show up in the HTML, but doesn't really belong in the LaTeX output. latex_documents = [('index', 'sympy-%s.tex' % release, 'SymPy Documentation', 'SymPy Development Team', 'manual', True)] # Additional stuff for the LaTeX preamble. # Tweaked to work with XeTeX. latex_elements = { 'babel': '', 'fontenc': r''' \usepackage{bm} \usepackage{amssymb} \usepackage{fontspec} \usepackage[english]{babel} \defaultfontfeatures{Mapping=tex-text} \setmainfont{DejaVu Serif} \setsansfont{DejaVu Sans} \setmonofont{DejaVu Sans Mono} ''', 'fontpkg': '', 'inputenc': '', 'utf8extra': '', 'preamble': r''' % redefine \LaTeX to be usable in math mode \expandafter\def\expandafter\LaTeX\expandafter{\expandafter\text\expandafter{\LaTeX}} ''' } # SymPy logo on title page html_logo = '_static/sympylogo.png' latex_logo = '_static/sympylogo_big.png' # Documents to append as an appendix to all manuals. #latex_appendices = [] # Show page numbers next to internal references latex_show_pagerefs = True # We use False otherwise the module index gets generated twice. latex_use_modindex = False default_role = 'math' pngmath_divpng_args = ['-gamma 1.5', '-D 110'] # Note, this is ignored by the mathjax extension # Any \newcommand should be defined in the file pngmath_latex_preamble = '\\usepackage{amsmath}\n' \ '\\usepackage{bm}\n' \ '\\usepackage{amsfonts}\n' \ '\\usepackage{amssymb}\n' \ '\\setlength{\\parindent}{0pt}\n' texinfo_documents = [ (master_doc, 'sympy', 'SymPy Documentation', 'SymPy Development Team', 'SymPy', 'Computer algebra system (CAS) in Python', 'Programming', 1), ] # Use svg for graphviz graphviz_output_format = 'svg'
antepsis/anteplahmacun
doc/src/conf.py
Python
bsd-3-clause
6,371
#------------------------------------------------------------------------------- # Copyright (c) 2011 Anton Golubkov. # All rights reserved. This program and the accompanying materials # are made available under the terms of the GNU Lesser Public License v2.1 # which accompanies this distribution, and is available at # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html # # Contributors: # Anton Golubkov - initial API and implementation #------------------------------------------------------------------------------- #!/usr/bin/python # -*- coding: utf-8 -*- import unittest import cv import PIL from PySide import QtGui import os, sys cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__))) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) import gui.image_convert class TestImageConvert(unittest.TestCase): def setUp(self): self.iplimage = cv.LoadImage("files/test.png") self.pilimage = PIL.Image.open("files/test.png") self.qimage = QtGui.QImage("files/test.png") self.gray_iplimage = cv.LoadImage("files/test.png", 0) self.zero_iplimage = cv.CreateImage( (0, 0), cv.IPL_DEPTH_8U, 3) self.zero_pilimage = PIL.Image.Image() self.zero_qimage = QtGui.QImage() def images_equal(self, filename1, filename2): i1 = cv.LoadImage(filename1) i2 = cv.LoadImage(filename2) return i1.tostring() == i2.tostring() def test_ipl_to_pil(self): result_pil = gui.image_convert.iplimage_to_pilimage(self.iplimage) result_pil.save("files/test_ipl_pil.png", "PNG") self.assertTrue(self.images_equal("files/test.png", "files/test_ipl_pil.png")) def test_pil_to_ipl(self): result_ipl = gui.image_convert.pilimage_to_iplimage(self.pilimage) cv.SaveImage("files/test_pil_ipl.png", result_ipl) self.assertTrue(self.images_equal("files/test.png", "files/test_pil_ipl.png")) def test_qimage_to_ipl(self): result_ipl = gui.image_convert.qimage_to_iplimage(self.qimage) cv.SaveImage("files/test_qimage_ipl.png", result_ipl) self.assertTrue(self.images_equal("files/test.png", "files/test_qimage_ipl.png")) def test_pil_to_qimage(self): result_qimage = gui.image_convert.pilimage_to_qimage(self.pilimage) result_qimage.save("files/test_pil_qimage.png") self.assertTrue(self.images_equal("files/test.png", "files/test_pil_qimage.png")) def test_qimage_to_pil(self): result_pil = gui.image_convert.qimage_to_pilimage(self.qimage) result_pil.save("files/test_qimage_pil.png") self.assertTrue(self.images_equal("files/test.png", "files/test_qimage_pil.png")) def test_ipl_to_qimage(self): result_qimage = gui.image_convert.iplimage_to_qimage(self.iplimage) result_qimage.save("files/test_ipl_qimage.png") self.assertTrue(self.images_equal("files/test.png", "files/test_ipl_qimage.png")) def test_zero_ipl_to_pil(self): result_pil = gui.image_convert.iplimage_to_pilimage(self.zero_iplimage) self.assertEqual(result_pil.size, (0, 0)) def test_zero_pil_to_ipl(self): result_ipl = gui.image_convert.pilimage_to_iplimage(self.zero_pilimage) self.assertEqual(cv.GetSize(result_ipl), (0, 0)) def test_zero_ipl_to_q(self): result_q = gui.image_convert.iplimage_to_qimage(self.zero_iplimage) self.assertEqual(result_q, self.zero_qimage) def test_zero_q_to_ipl(self): result_ipl = gui.image_convert.qimage_to_iplimage(self.zero_qimage) self.assertEqual(cv.GetSize(result_ipl), (0, 0)) def test_zero_pil_to_q(self): result_q = gui.image_convert.pilimage_to_qimage(self.zero_pilimage) self.assertEqual(result_q, self.zero_qimage) def test_zero_q_to_pil(self): result_pil = gui.image_convert.qimage_to_pilimage(self.zero_qimage) self.assertEqual(result_pil.size, (0, 0)) def test_gray_ipl_to_pil(self): result_pil = gui.image_convert.iplimage_to_pilimage(self.gray_iplimage) result_pil.save("files/test_gray_ipl_pil.png", "PNG") self.assertTrue(self.images_equal("files/test_gray_pil.png", "files/test_gray_ipl_pil.png")) if __name__ == '__main__': unittest.main()
anton-golubkov/Garland
src/test/test_image_convert.py
Python
lgpl-2.1
4,530
#!/usr/bin/env python # # Copyright (C) 2009-2011 Wander Lairson Costa # # The following terms apply to all files associated # with the software unless explicitly disclaimed in individual files. # # The authors hereby grant permission to use, copy, modify, distribute, # and license this software and its documentation for any purpose, provided # that existing copyright notices are retained in all copies and that this # notice is included verbatim in any distributions. No written agreement, # license, or royalty fee is required for any of the authorized uses. # Modifications to this software may be copyrighted by their authors # and need not follow the licensing terms described here, provided that # the new terms are clearly indicated on the first page of each file where # they apply. # # IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY # FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES # ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY # DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE # IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE # NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR # MODIFICATIONS. from distutils.core import setup setup( name='pyusb', version='1.0.0a2', description='Python USB access module', author='Wander Lairson Costa', author_email='wander.lairson@gmail.com', license = 'BSD', url='http://pyusb.sourceforge.net', packages=['usb', 'usb.backend'], long_description = """ PyUSB offers easy USB devices communication in Python. It should work without additional code in any environment with Python >= 2.4, ctypes and an pre-built usb backend library (currently, libusb 0.1.x, libusb 1.x, and OpenUSB). """ )
StephenForrest/pyUSB
setup.py
Python
bsd-3-clause
2,062
# This file is part of project Sverchok. It's copyrighted by the contributors # recorded in the version control history of the file, available from # its original location https://github.com/nortikin/sverchok/commit/master # # SPDX-License-Identifier: GPL3 # License-Filename: LICENSE import numpy as np import bpy from bpy.props import BoolProperty, EnumProperty, FloatProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import (zip_long_repeat, ensure_nesting_level, updateNode, get_data_nesting_level) from sverchok.utils.geom import PlaneEquation, LineEquation, linear_approximation from sverchok.utils.dummy_nodes import add_dummy from sverchok.dependencies import FreeCAD if FreeCAD is None: add_dummy('SvSelectSolidNode', 'Select Solid Elements', 'FreeCAD') else: import FreeCAD import Part from FreeCAD import Base from sverchok.utils.solid import SvSolidTopology class SvSelectSolidNode(bpy.types.Node, SverchCustomTreeNode): """ Triggers: Select Solid Elements Tooltip: Select Vertexes, Edges or Faces of Solid object by location """ bl_idname = 'SvSelectSolidNode' bl_label = 'Select Solid Elements' bl_icon = 'UV_SYNC_SELECT' solid_catergory = "Operators" element_types = [ ('VERTS', "Vertices", "Select vertices first, and then select adjacent edges and faces", 'VERTEXSEL', 0), ('EDGES', "Edges", "Select edges first, and then select adjacent vertices and faces", "EDGESEL", 1), ('FACES', "Faces", "Select faces first, and then select adjacent vertices and edges", 'FACESEL', 2) ] criteria_types = [ ('SIDE', "By Side", "By Side", 0), ('NORMAL', "By Normal", "By Normal direction", 1), ('SPHERE', "By Center and Radius", "By center and radius", 2), ('PLANE', "By Plane", "By plane defined by point and normal", 3), ('CYLINDER', "By Cylinder", "By cylinder defined by point, direction vector and radius", 4), ('DIRECTION', "By Direction", "By direction", 5), ('SOLID_DISTANCE', "By Distance to Solid", "By Distance to Solid", 6), ('SOLID_INSIDE', "Inside Solid", "Select elements that are inside given solid", 7), ('NORMAL_OUTSIDE', "Normal pointing outside", "Select faces, normals of which point outside the body", 8), ('NORMAL_INSIDE', "Normal pointing inside", "Select faces, normals of which point inside the body", 9), #('BBOX', "By Bounding Box", "By bounding box", 6) ] known_criteria = { 'VERTS': {'SIDE', 'SPHERE', 'PLANE', 'CYLINDER', 'SOLID_DISTANCE', 'SOLID_INSIDE'}, 'EDGES': {'SIDE', 'SPHERE', 'PLANE', 'CYLINDER', 'DIRECTION', 'SOLID_DISTANCE', 'SOLID_INSIDE'}, 'FACES': {'SIDE', 'NORMAL', 'SPHERE', 'PLANE', 'CYLINDER', 'SOLID_DISTANCE', 'SOLID_INSIDE', 'NORMAL_INSIDE', 'NORMAL_OUTSIDE'} } def update_type(self, context): criteria = self.criteria_type available = SvSelectSolidNode.known_criteria[self.element_type] if criteria not in available: self.criteria_type = available[0] else: self.update_sockets(context) updateNode(self, context) element_type : EnumProperty( name = "Select", description = "What kind of Solid elements to select first", items = element_types, default = 'VERTS', update = updateNode) def get_available_criteria(self, context): result = [] for item in SvSelectSolidNode.criteria_types: if item[0] in SvSelectSolidNode.known_criteria[self.element_type]: result.append(item) return result def update_sockets(self, context): self.inputs['Direction'].hide_safe = self.criteria_type not in {'SIDE', 'NORMAL', 'PLANE', 'CYLINDER', 'DIRECTION'} self.inputs['Center'].hide_safe = self.criteria_type not in {'SPHERE', 'PLANE', 'CYLINDER'} self.inputs['Percent'].hide_safe = self.criteria_type not in {'SIDE', 'NORMAL', 'DIRECTION', 'NORMAL_INSIDE', 'NORMAL_OUTSIDE'} self.inputs['Radius'].hide_safe = self.criteria_type not in {'SPHERE', 'PLANE', 'CYLINDER', 'SOLID_DISTANCE'} self.inputs['Tool'].hide_safe = self.criteria_type not in {'SOLID_DISTANCE', 'SOLID_INSIDE'} self.inputs['Precision'].hide_safe = self.element_type == 'VERTS' or self.criteria_type in {'SOLID_DISTANCE'} updateNode(self, context) criteria_type : EnumProperty( name = "Criteria", description = "Type of criteria to select by", items = get_available_criteria, update = update_sockets) include_partial: BoolProperty(name="Include partial selection", description="Include partially selected edges/faces - for primary selection", default=False, update=updateNode) include_partial_other: BoolProperty(name="Include partial selection", description="Include partially selected vertices/edges/faces - for secondary selection", default=False, update=updateNode) percent: FloatProperty(name="Percent", default=1.0, min=0.0, max=100.0, update=updateNode) radius: FloatProperty(name="Radius", default=1.0, min=0.0, update=updateNode) precision: FloatProperty( name="Precision", default=0.01, precision=4, update=updateNode) tolerance : FloatProperty( name = "Tolerance", default = 0.01, precision = 4, update=updateNode) include_shell : BoolProperty( name = "Including shell", description = "indicates if the point lying directly on a face is considered to be inside or not", default = False, update=updateNode) def draw_buttons(self, context, layout): layout.prop(self, 'element_type') layout.prop(self, 'criteria_type', text='') if self.element_type in {'EDGES', 'FACES'} and self.criteria_type not in {'SOLID_DISTANCE'}: if self.element_type == 'EDGES': text = "1. Partially selected edges" else: text = "1. Partially selected faces" layout.prop(self, 'include_partial', text=text) if self.element_type == 'VERTS': text = "2. Partially selected edges, faces" layout.prop(self, 'include_partial_other', text=text) elif self.element_type == 'EDGES': text = "2. Partially selected faces" layout.prop(self, 'include_partial_other', text=text) if self.criteria_type == 'SOLID_INSIDE': layout.prop(self, 'tolerance') layout.prop(self, 'include_shell') def sv_init(self, context): self.inputs.new('SvSolidSocket', "Solid") self.inputs.new('SvSolidSocket', "Tool") d = self.inputs.new('SvVerticesSocket', "Direction") d.use_prop = True d.prop = (0.0, 0.0, 1.0) c = self.inputs.new('SvVerticesSocket', "Center") c.use_prop = True c.prop = (0.0, 0.0, 0.0) self.inputs.new('SvStringsSocket', 'Percent').prop_name = 'percent' self.inputs.new('SvStringsSocket', 'Radius').prop_name = 'radius' self.inputs.new('SvStringsSocket', 'Precision').prop_name = 'precision' self.outputs.new('SvStringsSocket', 'VerticesMask') self.outputs.new('SvStringsSocket', 'EdgesMask') self.outputs.new('SvStringsSocket', 'FacesMask') self.update_sockets(context) def map_percent(self, values, percent): maxv = max(values) minv = min(values) if maxv <= minv: return maxv return maxv - percent * (maxv - minv) * 0.01 def _by_side(self, points, direction, percent): direction = direction / np.linalg.norm(direction) values = points.dot(direction) threshold = self.map_percent(values, percent) return values > threshold # VERTS def _verts_by_side(self, topo, direction, percent): verts = [(v.X ,v.Y, v.Z) for v in topo.solid.Vertexes] verts = np.array(verts) direction = np.array(direction) mask = self._by_side(verts, direction, percent) return mask.tolist() def _verts_by_sphere(self, topo, center, radius): return topo.get_vertices_within_range_mask(center, radius) def _verts_by_plane(self, topo, center, direction, radius): plane = PlaneEquation.from_normal_and_point(direction, center) condition = lambda v: plane.distance_to_point(v) < radius return topo.get_vertices_by_location_mask(condition) def _verts_by_cylinder(self, topo, center, direction, radius): line = LineEquation.from_direction_and_point(direction, center) condition = lambda v: line.distance_to_point(v) < radius return topo.get_vertices_by_location_mask(condition) def _verts_by_solid_distance(self, topo, tool, radius): condition = lambda v: v.distToShape(tool)[0] < radius mask = [condition(v) for v in topo.solid.Vertexes] return mask def _verts_by_solid_inside(self, topo, tool): condition = lambda v: tool.isInside(v.Point, self.tolerance, self.include_shell) mask = [condition(v) for v in topo.solid.Vertexes] return mask # EDGES def _edges_by_side(self, topo, direction, percent): direction = np.array(direction) all_values = [] values_per_edge = dict() for edge in topo.solid.Edges: points = np.array(topo.get_points_by_edge(edge)) values = points.dot(direction) all_values.extend(values.tolist()) values_per_edge[SvSolidTopology.Item(edge)] = values threshold = self.map_percent(all_values, percent) check = any if self.include_partial else all mask = [] for edge in topo.solid.Edges: values = values_per_edge[SvSolidTopology.Item(edge)] test = check(values > threshold) mask.append(test) return mask def _edges_by_sphere(self, topo, center, radius): center = np.array(center) def condition(points): dvs = points - center distances = (dvs * dvs).sum(axis=1) return distances < radius*radius return topo.get_edges_by_location_mask(condition, self.include_partial) def _edges_by_plane(self, topo, center, direction, radius): plane = PlaneEquation.from_normal_and_point(direction, center) def condition(points): distances = plane.distance_to_points(points) return distances < radius return topo.get_edges_by_location_mask(condition, self.include_partial) def _edges_by_cylinder(self, topo, center, direction, radius): line = LineEquation.from_direction_and_point(direction, center) def condition(points): distances = line.distance_to_points(points) return distances < radius return topo.get_edges_by_location_mask(condition, self.include_partial) def _edges_by_direction(self, topo, direction, percent): direction = np.array(direction) def calc_value(points): approx = linear_approximation(points) line = approx.most_similar_line() line_direction = np.array(line.direction) return abs(direction.dot(line_direction)) values = np.array([calc_value(topo.get_points_by_edge(edge)) for edge in topo.solid.Edges]) threshold = self.map_percent(values, percent) return (values > threshold).tolist() def _edges_by_solid_distance(self, topo, tool, radius): condition = lambda e: e.distToShape(tool)[0] < radius mask = [condition(e) for e in topo.solid.Edges] return mask def _edges_by_solid_inside(self, topo, tool): def condition(points): good = [tool.isInside(Base.Vector(*p), self.tolerance, self.include_shell) for p in points] return np.array(good) return topo.get_edges_by_location_mask(condition, self.include_partial) # FACES def _faces_by_side(self, topo, direction, percent): direction = np.array(direction) all_values = [] values_per_face = dict() for face in topo.solid.Faces: points = np.array(topo.get_points_by_face(face)) values = points.dot(direction) all_values.extend(values.tolist()) values_per_face[SvSolidTopology.Item(face)] = values threshold = self.map_percent(all_values, percent) check = any if self.include_partial else all mask = [] for face in topo.solid.Faces: values = values_per_face[SvSolidTopology.Item(face)] test = check(values > threshold) mask.append(test) return mask def _faces_by_normal(self, topo, direction, percent): direction = np.array(direction) def calc_value(normal): return direction.dot(normal) values = np.array([calc_value(topo.get_normal_by_face(face)) for face in topo.solid.Faces]) threshold = self.map_percent(values, percent) return (values > threshold).tolist() def _faces_by_normal_outside(self, solid, topo, percent): c = solid.BoundBox.Center body_center = np.array([c.x, c.y, c.z]) def calc_value(face): to_center = body_center - topo.get_center_by_face(face) to_center /= np.linalg.norm(to_center) normal = topo.get_normal_by_face(face) return - normal.dot(to_center) values = np.array([calc_value(face) for face in topo.solid.Faces]) threshold = self.map_percent(values, percent) return (values > threshold).tolist() def _faces_by_normal_inside(self, solid, topo, percent): c = solid.BoundBox.Center body_center = np.array([c.x, c.y, c.z]) def calc_value(face): to_center = body_center - topo.get_center_by_face(face) to_center /= np.linalg.norm(to_center) normal = topo.get_normal_by_face(face) return normal.dot(to_center) values = np.array([calc_value(face) for face in topo.solid.Faces]) threshold = self.map_percent(values, percent) return (values > threshold).tolist() def _faces_by_sphere(self, topo, center, radius): center = np.array(center) def condition(points): dvs = points - center distances = (dvs * dvs).sum(axis=1) return distances < radius*radius return topo.get_faces_by_location_mask(condition, self.include_partial) def _faces_by_plane(self, topo, center, direction, radius): plane = PlaneEquation.from_normal_and_point(direction, center) def condition(points): distances = plane.distance_to_points(points) return distances < radius return topo.get_faces_by_location_mask(condition, self.include_partial) def _faces_by_cylinder(self, topo, center, direction, radius): line = LineEquation.from_direction_and_point(direction, center) def condition(points): distances = line.distance_to_points(points) return distances < radius return topo.get_faces_by_location_mask(condition, self.include_partial) def _faces_by_solid_distance(self, topo, tool, radius): condition = lambda f: f.distToShape(tool)[0] < radius mask = [condition(f) for f in topo.solid.Faces] return mask def _faces_by_solid_inside(self, topo, tool): def condition(points): good = [tool.isInside(Base.Vector(*p), self.tolerance, self.include_shell) for p in points] return np.array(good) return topo.get_faces_by_location_mask(condition, self.include_partial) # SWITCH def calc_mask(self, solid, tool, precision, direction, center, percent, radius): topo = SvSolidTopology(solid) if self.element_type == 'VERTS': if self.criteria_type == 'SIDE': vertex_mask = self._verts_by_side(topo, direction, percent) elif self.criteria_type == 'SPHERE': vertex_mask = self._verts_by_sphere(topo, center, radius) elif self.criteria_type == 'PLANE': vertex_mask = self._verts_by_plane(topo, center, direction, radius) elif self.criteria_type == 'CYLINDER': vertex_mask = self._verts_by_cylinder(topo, center, direction, radius) elif self.criteria_type == 'SOLID_DISTANCE': vertex_mask = self._verts_by_solid_distance(topo, tool, radius) elif self.criteria_type == 'SOLID_INSIDE': vertex_mask = self._verts_by_solid_inside(topo, tool) else: raise Exception("Unknown criteria for vertices") verts = [v for c, v in zip(vertex_mask, solid.Vertexes) if c] edge_mask = topo.get_edges_by_vertices_mask(verts, self.include_partial_other) face_mask = topo.get_faces_by_vertices_mask(verts, self.include_partial_other) elif self.element_type == 'EDGES': topo.tessellate(precision) if self.criteria_type == 'SIDE': edge_mask = self._edges_by_side(topo, direction, percent) elif self.criteria_type == 'SPHERE': edge_mask = self._edges_by_sphere(topo, center, radius) elif self.criteria_type == 'PLANE': edge_mask = self._edges_by_plane(topo, center, direction, radius) elif self.criteria_type == 'CYLINDER': edge_mask = self._edges_by_cylinder(topo, center, direction, radius) elif self.criteria_type == 'DIRECTION': edge_mask = self._edges_by_direction(topo, direction, percent) elif self.criteria_type == 'SOLID_DISTANCE': edge_mask = self._edges_by_solid_distance(topo, tool, radius) elif self.criteria_type == 'SOLID_INSIDE': edge_mask = self._edges_by_solid_inside(topo, tool) else: raise Exception("Unknown criteria for edges") edges = [e for c, e in zip(edge_mask, solid.Edges) if c] vertex_mask = topo.get_vertices_by_edges_mask(edges) face_mask = topo.get_faces_by_edges_mask(edges, self.include_partial_other) else: # FACES topo.tessellate(precision) if self.criteria_type == 'SIDE': face_mask = self._faces_by_side(topo, direction, percent) elif self.criteria_type == 'NORMAL': topo.calc_normals() face_mask = self._faces_by_normal(topo, direction, percent) elif self.criteria_type == 'NORMAL_INSIDE': topo.calc_normals() topo.calc_face_centers() face_mask = self._faces_by_normal_inside(solid, topo, percent) elif self.criteria_type == 'NORMAL_OUTSIDE': topo.calc_normals() topo.calc_face_centers() face_mask = self._faces_by_normal_outside(solid, topo, percent) elif self.criteria_type == 'SPHERE': face_mask = self._faces_by_sphere(topo, center, radius) elif self.criteria_type == 'PLANE': face_mask = self._faces_by_plane(topo, center, direction, radius) elif self.criteria_type == 'CYLINDER': face_mask = self._faces_by_cylinder(topo, center, direction, radius) elif self.criteria_type == 'SOLID_DISTANCE': face_mask = self._faces_by_solid_distance(topo, tool, radius) elif self.criteria_type == 'SOLID_INSIDE': face_mask = self._faces_by_solid_inside(topo, tool) else: raise Exception("Unknown criteria type for faces") faces = [f for c, f in zip(face_mask, solid.Faces) if c] vertex_mask = topo.get_vertices_by_faces_mask(faces) edge_mask = topo.get_edges_by_faces_mask(faces) return vertex_mask, edge_mask, face_mask def process(self): if not any(output.is_linked for output in self.outputs): return solid_s = self.inputs['Solid'].sv_get() if self.criteria_type in {'SOLID_DISTANCE', 'SOLID_INSIDE'}: tool_s = self.inputs['Tool'].sv_get() tool_s = ensure_nesting_level(tool_s, 2, data_types=(Part.Shape,)) else: tool_s = [[None]] direction_s = self.inputs['Direction'].sv_get() center_s = self.inputs['Center'].sv_get() percent_s = self.inputs['Percent'].sv_get() radius_s = self.inputs['Radius'].sv_get() precision_s = self.inputs['Precision'].sv_get() input_level = get_data_nesting_level(solid_s, data_types=(Part.Shape,)) solid_s = ensure_nesting_level(solid_s, 2, data_types=(Part.Shape,)) direction_s = ensure_nesting_level(direction_s, 3) center_s = ensure_nesting_level(center_s, 3) percent_s = ensure_nesting_level(percent_s, 2) radius_s = ensure_nesting_level(radius_s, 2) precision_s = ensure_nesting_level(precision_s, 2) vertex_mask_out = [] edge_mask_out = [] face_mask_out = [] for objects in zip_long_repeat(solid_s, tool_s, direction_s, center_s, percent_s, radius_s, precision_s): vertex_mask_new = [] edge_mask_new = [] face_mask_new = [] for solid, tool, direction, center, percent, radius, precision in zip_long_repeat(*objects): vertex_mask, edge_mask, face_mask = self.calc_mask(solid, tool, precision, direction, center, percent, radius) vertex_mask_new.append(vertex_mask) edge_mask_new.append(edge_mask) face_mask_new.append(face_mask) if input_level == 2: vertex_mask_out.append(vertex_mask_new) edge_mask_out.append(edge_mask_new) face_mask_out.append(face_mask_new) else: vertex_mask_out.extend(vertex_mask_new) edge_mask_out.extend(edge_mask_new) face_mask_out.extend(face_mask_new) self.outputs['VerticesMask'].sv_set(vertex_mask_out) self.outputs['EdgesMask'].sv_set(edge_mask_out) self.outputs['FacesMask'].sv_set(face_mask_out) def register(): if FreeCAD is not None: bpy.utils.register_class(SvSelectSolidNode) def unregister(): if FreeCAD is not None: bpy.utils.unregister_class(SvSelectSolidNode)
DolphinDream/sverchok
nodes/solid/solid_select.py
Python
gpl-3.0
22,887
"""Support for Acmeda Roller Blind Batteries.""" from __future__ import annotations from homeassistant.components.sensor import SensorDeviceClass, SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import PERCENTAGE from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from .base import AcmedaBase from .const import ACMEDA_HUB_UPDATE, DOMAIN from .helpers import async_add_acmeda_entities async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the Acmeda Rollers from a config entry.""" hub = hass.data[DOMAIN][config_entry.entry_id] current: set[int] = set() @callback def async_add_acmeda_sensors(): async_add_acmeda_entities( hass, AcmedaBattery, config_entry, current, async_add_entities ) hub.cleanup_callbacks.append( async_dispatcher_connect( hass, ACMEDA_HUB_UPDATE.format(config_entry.entry_id), async_add_acmeda_sensors, ) ) class AcmedaBattery(AcmedaBase, SensorEntity): """Representation of a Acmeda cover device.""" device_class = SensorDeviceClass.BATTERY _attr_native_unit_of_measurement = PERCENTAGE @property def name(self): """Return the name of roller.""" return f"{super().name} Battery" @property def native_value(self): """Return the state of the device.""" return self.roller.battery
mezz64/home-assistant
homeassistant/components/acmeda/sensor.py
Python
apache-2.0
1,666
#!/usr/bin/env python3 from setuptools import setup, find_packages setup(name='grossi16', version='0.0.2', description='An open-source easy to use classroom clicker system', author='Gabriel Queiroz', author_email='gabrieljvnq@gmail.com', license='MIT', package_dir={'gorssi16': 'grossi16'}, package_data={'grossi.web': ['static/*.css', 'static/*.js', 'static/*.woff2', 'templates/*.html']}, packages=['grossi16.web', 'grossi16.cli'], zip_safe=True, include_package_data=True, install_requires=[ 'flask>=0.11.1', 'click>=6.6', 'CommonMark>=0.7.2', 'FilterHTML>=0.5.0', 'netifaces>=0.10.5' ], entry_points={ 'console_scripts': [ 'grossi16-cli=grossi16.cli:main' ], 'setuptools.installation': [ 'eggsecutable=grossi16.cli:main' ], })
gjvnq/grossi16
setup.py
Python
mit
924
# -*- coding: utf-8 -*- # # Copyright (C) 2005-2009 Edgewall Software # Copyright (C) 2005-2006 Christian Boos <cboos@edgewall.org> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.org/wiki/TracLicense. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://trac.edgewall.org/log/. # # Author: Christian Boos <cboos@edgewall.org> import re from genshi.builder import tag from trac.cache import cached from trac.config import ConfigSection from trac.core import * from trac.util.translation import _, N_ from trac.wiki.api import IWikiChangeListener, IWikiMacroProvider from trac.wiki.parser import WikiParser from trac.wiki.formatter import split_url_into_path_query_fragment class InterWikiMap(Component): """InterWiki map manager.""" implements(IWikiChangeListener, IWikiMacroProvider) interwiki_section = ConfigSection('interwiki', """Every option in the `[interwiki]` section defines one InterWiki prefix. The option name defines the prefix. The option value defines the URL, optionally followed by a description separated from the URL by whitespace. Parametric URLs are supported as well. '''Example:''' {{{ [interwiki] MeatBall = http://www.usemod.com/cgi-bin/mb.pl? PEP = http://www.python.org/peps/pep-$1.html Python Enhancement Proposal $1 tsvn = tsvn: Interact with TortoiseSvn }}} """) _page_name = 'InterMapTxt' _interwiki_re = re.compile(r"(%s)[ \t]+([^ \t]+)(?:[ \t]+#(.*))?" % WikiParser.LINK_SCHEME, re.UNICODE) _argspec_re = re.compile(r"\$\d") # The component itself behaves as a read-only map def __contains__(self, ns): return ns.upper() in self.interwiki_map def __getitem__(self, ns): return self.interwiki_map[ns.upper()] def keys(self): return self.interwiki_map.keys() # Expansion of positional arguments ($1, $2, ...) in URL and title def _expand(self, txt, args): """Replace "$1" by the first args, "$2" by the second, etc.""" def setarg(match): num = int(match.group()[1:]) return args[num - 1] if 0 < num <= len(args) else '' return re.sub(InterWikiMap._argspec_re, setarg, txt) def _expand_or_append(self, txt, args): """Like expand, but also append first arg if there's no "$".""" if not args: return txt expanded = self._expand(txt, args) return txt + args[0] if expanded == txt else expanded def url(self, ns, target): """Return `(url, title)` for the given InterWiki `ns`. Expand the colon-separated `target` arguments. """ ns, url, title = self[ns] maxargnum = max([0] + [int(a[1:]) for a in re.findall(InterWikiMap._argspec_re, url)]) target, query, fragment = split_url_into_path_query_fragment(target) if maxargnum > 0: args = target.split(':', (maxargnum - 1)) else: args = [target] url = self._expand_or_append(url, args) ntarget, nquery, nfragment = split_url_into_path_query_fragment(url) if query and nquery: nquery = '%s&%s' % (nquery, query[1:]) else: nquery = nquery or query nfragment = fragment or nfragment # user provided takes precedence expanded_url = ntarget + nquery + nfragment expanded_title = self._expand(title, args) if expanded_title == title: expanded_title = _("%(target)s in %(name)s", target=target, name=title) return expanded_url, expanded_title # IWikiChangeListener methods def wiki_page_added(self, page): if page.name == InterWikiMap._page_name: del self.interwiki_map def wiki_page_changed(self, page, version, t, comment, author, ipnr): if page.name == InterWikiMap._page_name: del self.interwiki_map def wiki_page_deleted(self, page): if page.name == InterWikiMap._page_name: del self.interwiki_map def wiki_page_version_deleted(self, page): if page.name == InterWikiMap._page_name: del self.interwiki_map @cached def interwiki_map(self, db): """Map from upper-cased namespaces to (namespace, prefix, title) values. """ from trac.wiki.model import WikiPage map = {} content = WikiPage(self.env, InterWikiMap._page_name, db=db).text in_map = False for line in content.split('\n'): if in_map: if line.startswith('----'): in_map = False else: m = re.match(InterWikiMap._interwiki_re, line) if m: prefix, url, title = m.groups() url = url.strip() title = title.strip() if title else prefix map[prefix.upper()] = (prefix, url, title) elif line.startswith('----'): in_map = True for prefix, value in self.interwiki_section.options(): value = value.split(None, 1) if value: url = value[0].strip() title = value[1].strip() if len(value) > 1 else prefix map[prefix.upper()] = (prefix, url, title) return map # IWikiMacroProvider methods def get_macros(self): yield 'InterWiki' def get_macro_description(self, name): return 'messages', \ N_("Provide a description list for the known InterWiki " "prefixes.") def expand_macro(self, formatter, name, content): interwikis = [] for k in sorted(self.keys()): prefix, url, title = self[k] interwikis.append({ 'prefix': prefix, 'url': url, 'title': title, 'rc_url': self._expand_or_append(url, ['RecentChanges']), 'description': url if title == prefix else title}) return tag.table(tag.tr(tag.th(tag.em(_("Prefix"))), tag.th(tag.em(_("Site")))), [tag.tr(tag.td(tag.a(w['prefix'], href=w['rc_url'])), tag.td(tag.a(w['description'], href=w['url']))) for w in interwikis ], class_="wiki interwiki")
jun66j5/trac-ja
trac/wiki/interwiki.py
Python
bsd-3-clause
6,799
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.mobile.home import Home class TestMobileLoginLogout: @pytest.mark.nondestructive def test_login(self, base_url, selenium, variables): user = variables['users']['default'] home_page = Home(base_url, selenium).open() home_page.log_in(user['username'], user['password']) assert home_page.is_user_logged_in, 'User not shown to be logged in' @pytest.mark.nondestructive def test_logout(self, base_url, selenium, variables): user = variables['users']['default'] home_page = Home(base_url, selenium).open() home_page.log_in(user['username'], user['password']) assert home_page.is_user_logged_in, 'User is not shown to be logged in' # sign out home_page.log_out() home_page.is_the_current_page assert not home_page.is_user_logged_in
mythmon/kitsune
tests/functional/mobile/test_login_logout.py
Python
bsd-3-clause
1,070
# Copyright 2011 James McCauley # Copyright 2008 (C) Nicira, Inc. # # This file is part of POX. # # POX 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. # # POX 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 POX. If not, see <http://www.gnu.org/licenses/>. # This file is derived from the packet library in NOX, which was # developed by Nicira, Inc. #====================================================================== # # MPLS tag format # # 0 1 2 3 4 # 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | LABEL | TC |S| TTL | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # #====================================================================== import struct from packet_base import packet_base from ethernet import ethernet from packet_utils import * class mpls(packet_base): "mpls header" MIN_LEN = 4 def __init__(self, raw=None, prev=None, **kw): packet_base.__init__(self) self.prev = prev self.next = None self.label = 0 self.tc = 0 self.s = 0 self.ttl = 0 if raw is not None: self.parse(raw) self._init(kw) def __str__(self): s = "[MPLS label={0} tc={1} s={2} ttl={3}]".format(self.label, self.tc, self.s, self.ttl) return s def parse(self, raw): assert isinstance(raw, bytes) self.raw = raw dlen = len(raw) if dlen < mpls.MIN_LEN: self.msg('(mpls parse) warning MPLS packet data too short to ' + 'parse header: data len %u' % (dlen,)) return (label_high, label_low_tc_s, self.ttl) = struct.unpack("!HBB", raw[:mpls.MIN_LEN]) self.s = label_low_tc_s & 0x1 self.tc = ((label_low_tc_s & 0xf) >> 1) self.label = (label_high << 4) | (label_low_tc_s >> 4) self.parsed = True self.next = raw[mpls.MIN_LEN:] def hdr(self, payload): label = self.label & 0xfffff tc = self.tc & 0x7 s = self.s & 0x1 ttl = self.ttl & 0xff label_high = label >> 4 label_low_tc_s = ((label & 0xf) << 4) | (tc << 1) | s buf = struct.pack('!HBB', label_high, label_low_tc_s, ttl) return buf
0xdyu/RouteFlow-Exodus
pox/pox/lib/packet/mpls.py
Python
apache-2.0
2,901
""" Django admin page for grades models """ from config_models.admin import ConfigurationModelAdmin, KeyedConfigurationModelAdmin from django.contrib import admin from lms.djangoapps.grades.config.forms import CoursePersistentGradesAdminForm from lms.djangoapps.grades.config.models import ( ComputeGradesSetting, CoursePersistentGradesFlag, PersistentGradesEnabledFlag ) class CoursePersistentGradesAdmin(KeyedConfigurationModelAdmin): """ Admin for enabling subsection grades on a course-by-course basis. Allows searching by course id. """ form = CoursePersistentGradesAdminForm search_fields = ['course_id'] fieldsets = ( (None, { 'fields': ('course_id', 'enabled'), 'description': 'Enter a valid course id. If it is invalid, an error message will display.' }), ) admin.site.register(CoursePersistentGradesFlag, CoursePersistentGradesAdmin) admin.site.register(PersistentGradesEnabledFlag, ConfigurationModelAdmin) admin.site.register(ComputeGradesSetting, ConfigurationModelAdmin)
edx/edx-platform
lms/djangoapps/grades/admin.py
Python
agpl-3.0
1,075
# -*- coding: utf-8 -*- """Top-level package for MountainProject API.""" from .mountainproject import Api __author__ = """Christopher J. Woodall""" __email__ = 'chris.j.woodall@gmail.com' __version__ = '0.3.2'
cwoodall/mountainproject-py
mountainproject/__init__.py
Python
mit
213
from irc.bot import IRCBot import irc.events import irc.loops from irc.protocol import log import time from datetime import timedelta, datetime import sqlite3 import nplstatus ip = 'irc.quakenet.org' port = 6667 nick = 'TSBot' channel = '#teamspeak' start_time = time.time() db = sqlite3.connect('bar.db') db_cursor = db.cursor() db_cursor.execute('CREATE TABLE IF NOT EXISTS bar (trigger text, answer text)') db_cursor.execute('CREATE TABLE IF NOT EXISTS lowscore (username text, lines text, time int)') db.commit() global last_status last_status = nplstatus.get() # functions for the bar-functionality def add_to_bar(trigger, answer): db_cursor.execute('INSERT INTO bar VALUES (?, ?)', (str(trigger.lower()), str(answer))) db.commit() def remove_from_bar(trigger): db_cursor.execute('DELETE FROM bar WHERE trigger=?', (trigger.lower(),)) db.commit() def get_triggers(): r = [] for trigger in db_cursor.execute('SELECT trigger FROM bar'): r.append(trigger[0]) return r def get_text(trigger): db_cursor.execute('SELECT answer FROM bar WHERE trigger=?', (trigger,)) return db_cursor.fetchone()[0] # variables for lowscore-functionality lowscore_last_messages = {} # functions for the lowscore-functionality def add_lowscore(username, lines, time): db_cursor.execute('INSERT INTO lowscore VALUES (?,?,?)', (str(username), str(lines), int(time))) db.commit() def get_lowscores(amount): r = [] for lowscore in db_cursor.execute('SELECT * from lowscore ORDER BY time ASC LIMIT '+str(amount)): r.append({'username': lowscore[0], 'lines': lowscore[1], 'time': lowscore[2]}) return r @irc.loops.min5 def check_status(bot): global last_status status = nplstatus.get() if status != last_status: last_status = status if status: bot.privmsg('NPL-Registrations are now open! http://npl.teamspeakusa.com/ts3npl.php') else: bot.privmsg('NPL-Registrations are now closed!') @irc.events.channel_msg def lowscore_message(bot, host, target, msg): user = lowscore_last_messages.get(host, None) if user is not None: user['lines'].append(msg) if msg.startswith('_lowscore'): lowscores = get_lowscores(3) answer = 'TOP 3: ' for l in lowscores: answer += l['username'] + ' [T: ' + str(l['time']) + ' seconds] ' bot.privmsg(answer) @irc.events.user_join def lowscore_user_join(bot, host): global lowscore_last_messages lowscore_last_messages[host] = {'lines': [], 'join': time.time()} @irc.events.user_part def lowscore_user_part(bot, host): user = lowscore_last_messages.get(host, None) if user is not None: join_time = user['join'] cur_time = time.time() if (cur_time - join_time) < 10*60 and len(user['lines']) > 0: add_lowscore(host.split('!')[0], user['lines'], cur_time-join_time) lowscore_last_messages.pop(host, None) @irc.loops.min5 def lowscore_cleanup(bot): global lowscore_last_messages cur_time = time.time() to_del = [] for key in lowscore_last_messages: if (cur_time - lowscore_last_messages[key]['join']) > 10*60: to_del.append(key) for key in to_del: lowscore_last_messages.pop(key, None) @irc.events.channel_msg def info(bot, host, target, msg): msg = msg.lower() if nick.lower() in msg: if 'who are you' in msg or 'who is' in msg or 'what are you doing' in msg: bot.privmsg('I\'m a bot fetching the status of NPL-Registrations every 5 minutes! You can check it manually with "!nplstatus".') elif 'how are you' in msg: sec = timedelta(seconds=(time.time() - start_time)) d = datetime(1, 1, 1) + sec days = d.day - 1 hours = d.hour minutes = d.minute seconds = d.second bot.privmsg('I\'m fine and running for {} days, {} hours, {} minutes and {} seconds!'.format(days, hours, minutes, seconds)) @irc.events.channel_msg def commands(bot, host, target, msg): nick = host.split('!')[0] msg_ = msg msg = msg.lower() if msg.startswith('!'): cmd = msg[1:].strip() cmd_ = msg_[1:].strip() if cmd == 'register': bot.notice(add_register(nick), nick) elif cmd == 'unregister': bot.notice(remove_register(nick), nick) elif cmd == 'nplstatus': if last_status: bot.privmsg('NPL-Registrations are open! You can register one here: http://npl.teamspeakusa.com/ts3npl.php') else: bot.privmsg('NPL-Registrations are closed!') elif cmd == 'bar': triggers = get_triggers() if len(triggers) >= 1: bot.privmsg(', '.join(triggers)) else: bot.privmsg('No items in bar!') elif cmd.split()[0] == 'addtobar': cmd_split = cmd_.split() if len(cmd_split) < 3: bot.privmsg('Too less arguments! Try "!addtobar <trigger> <message>"') else: if cmd_split[1].lower() not in get_triggers(): add_to_bar(cmd_split[1].lower(), ' '.join(cmd_split[2:])) bot.privmsg('Successfully added {} to bar!'.format(cmd_split[1].lower())) else: bot.privmsg('Item already in bar!') elif cmd.split()[0] == 'removefrombar': cmd_split = cmd_.split() if len(cmd_split) < 2: bot.privmsg('Too less arguments! Try "!removefrombar <trigger>"') else: if cmd_split[1].lower() in get_triggers(): remove_from_bar(cmd_split[1].lower()) bot.privmsg('Successfully removed {} from bar!'.format(cmd_split[1].lower())) else: bot.privmsg('Item not in bar!') @irc.events.channel_msg def bar(bot, host, target, msg): if msg.startswith('!'): msg = msg.lower()[1:] triggers = get_triggers() if msg in triggers: bot.privmsg(get_text(msg)) @irc.events.connected def join_channels(bot): bot.join(channel) bot = IRCBot(ip, port, nick) bot.start()
ohaz/TeamspeakIRC
ts3npl_bot.py
Python
mit
6,279
# Generated by Django 2.2.7 on 2019-12-29 22:12 import os from django.db import migrations, models import localized_fields.fields.text_field DIR = os.path.dirname(os.path.realpath(__file__)) WELCOME = os.path.join(DIR, 'welcome_message.html') def create_welcome(apps, schema_editor): with open(WELCOME, 'r') as f: content = f.read() db = schema_editor.connection.alias Chunk = apps.get_model('chunks', 'Chunk') Chunk.objects.using(db).create( slug="welcome", content=content, ) class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Chunk', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('slug', models.SlugField(unique=True, verbose_name='slug')), ('content', localized_fields.fields.text_field.LocalizedTextField(required=[], verbose_name='content')), ], options={ 'verbose_name': 'Chunk', 'verbose_name_plural': 'Chunks', 'ordering': ['slug'], }, ), migrations.RunPython(create_welcome), ]
GISAElkartea/tresna-kutxa
tk/chunks/migrations/0001_initial.py
Python
agpl-3.0
1,269
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Vaucher, Guewen Baconnier # Copyright 2012 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, orm class AccountAccountLine(orm.Model): _inherit = 'account.move.line' # By convention added columns stats with gl_. _columns = { 'gl_foreign_balance': fields.float('Aggregated Amount curency'), 'gl_balance': fields.float('Aggregated Amount'), 'gl_revaluated_balance': fields.float('Revaluated Amount'), 'gl_currency_rate': fields.float('Currency rate')} class AccountAccount(orm.Model): _inherit = 'account.account' _columns = { 'currency_revaluation': fields.boolean( "Allow Currency revaluation") } _defaults = {'currency_revaluation': False} _sql_mapping = { 'balance': "COALESCE(SUM(l.debit),0) - COALESCE(SUM(l.credit), 0) as " "balance", 'debit': "COALESCE(SUM(l.debit), 0) as debit", 'credit': "COALESCE(SUM(l.credit), 0) as credit", 'foreign_balance': "COALESCE(SUM(l.amount_currency), 0) as foreign_" "balance", } def _revaluation_query(self, cr, uid, ids, revaluation_date, context=None): lines_where_clause = self.pool.get('account.move.line').\ _query_get(cr, uid, context=context) query = ("SELECT l.account_id as id, l.partner_id, l.currency_id, " + ', '.join(self._sql_mapping.values()) + " FROM account_move_line l " " WHERE l.account_id IN %(account_ids)s AND " " l.date <= %(revaluation_date)s AND " " l.currency_id IS NOT NULL AND " " l.reconcile_id IS NULL AND " + lines_where_clause + " GROUP BY l.account_id, l.currency_id, l.partner_id") params = {'revaluation_date': revaluation_date, 'account_ids': tuple(ids)} return query, params def compute_revaluations( self, cr, uid, ids, period_ids, revaluation_date, context=None): if context is None: context = {} accounts = {} # compute for each account the balance/debit/credit from the move lines ctx_query = context.copy() ctx_query['periods'] = period_ids query, params = self._revaluation_query( cr, uid, ids, revaluation_date, context=ctx_query) cr.execute(query, params) lines = cr.dictfetchall() for line in lines: # generate a tree # - account_id # -- currency_id # --- partner_id # ----- balances account_id, currency_id, partner_id = \ line['id'], line['currency_id'], line['partner_id'] accounts.setdefault(account_id, {}) accounts[account_id].setdefault(currency_id, {}) accounts[account_id][currency_id].\ setdefault(partner_id, {}) accounts[account_id][currency_id][partner_id] = line return accounts
rschnapka/account-closing
account_multicurrency_revaluation/account.py
Python
agpl-3.0
4,018
# encoding: utf-8 # module samba.dcerpc.srvsvc # from /usr/lib/python2.7/dist-packages/samba/dcerpc/srvsvc.so # by generator 1.135 """ srvsvc DCE/RPC """ # imports import dcerpc as __dcerpc import talloc as __talloc class Statistics(__talloc.Object): # no doc def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass avresponse = property(lambda self: object(), lambda self, v: None, lambda self: None) # default bigbufneed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default bytesrcvd_high = property(lambda self: object(), lambda self, v: None, lambda self: None) # default bytesrcvd_low = property(lambda self: object(), lambda self, v: None, lambda self: None) # default bytessent_high = property(lambda self: object(), lambda self, v: None, lambda self: None) # default bytessent_low = property(lambda self: object(), lambda self, v: None, lambda self: None) # default devopens = property(lambda self: object(), lambda self, v: None, lambda self: None) # default fopens = property(lambda self: object(), lambda self, v: None, lambda self: None) # default jobsqueued = property(lambda self: object(), lambda self, v: None, lambda self: None) # default permerrors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default pwerrors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default reqbufneed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default serrorout = property(lambda self: object(), lambda self, v: None, lambda self: None) # default sopens = property(lambda self: object(), lambda self, v: None, lambda self: None) # default start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default stimeouts = property(lambda self: object(), lambda self, v: None, lambda self: None) # default syserrors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/srvsvc/Statistics.py
Python
gpl-2.0
2,286
from django.db import models from django.contrib.auth.models import User from django.core.urlresolvers import reverse class ThirdParty(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name def get_absolute_url(self): return reverse('expense-list') class PaymentMode(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name def get_absolute_url(self): return reverse('expense-list') class Expense(models.Model): date_expense = models.DateField() third_party = models.ForeignKey(ThirdParty, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=6, decimal_places=2) notes = models.TextField(max_length=255,blank=True) payment_mode = models.ForeignKey(PaymentMode, on_delete=models.CASCADE) property_of = models.ForeignKey(User, on_delete=models.CASCADE, related_name='simplecost_owner') shared_with = models.ManyToManyField(User, blank=True, related_name='simplecost_user') def __str__(self): return str(self.date_expense) + '_' + str(self.third_party) + '_' + str(self.amount) def get_absolute_url(self): return reverse('expense-list')
Humch/nxt-simplecost
simplecost/models.py
Python
mit
1,269
"""Tasks for updating this site.""" import re import os import json import redis from os.path import abspath from celery import shared_task from celery import chain from subprocess import call, Popen, PIPE from django.conf import settings from .. import now, apps, get_git_root def updatelog(sha1, msg=None, clear=False): key = 'updatelog_'+sha1 r = redis.StrictRedis(host=settings.SESSION_REDIS_HOST, port=6379, db=0) if clear: s = "" r.set(key, s, ex=3600*24*30) else: s = r.get(key) if s is None: s = "" else: s = s.decode() if msg is None: return s s += msg r.set(key, s, ex=3600*24*30) return s # def supervisor(jobname, cmd): @shared_task def supervisor(*args): pass # return call(['sudo', 'supervisorctl', cmd, jobname]) # return Popen(['sudo', 'supervisorctl', cmd, jobname]) # kill -HUP $pid # {{repo}}/tmp/celery.pid # from django.conf import settings # Popen([ # 'sudo', # 'kill', # "-HUP", # os.path.join(settings.GIT_PATH, "tmp", "celery.pid") # ]) # return "ok" @shared_task def restart_celery(*args): pidfile = os.path.join(settings.GIT_PATH, "tmp", "celery.pid") pid = '' with open(pidfile) as f: pid = f.read().strip() Popen(['sudo', 'kill', "-HUP", pid]) return "ok" @shared_task def build_css(sha1, *args): """Find scss files and compile them to css""" # find . -type f -name "*.scss" -not -name "_*" \ # -not -path "./node_modules/*" -not -path "./static/*" -print \ # | parallel --no-notice sass --cache-location /tmp/sass \ # --style compressed {} {.}.css # find scss: # find all .scss files, but not starting with "_" symbol, # and not under /node_modules/, /static/ folders try: cmd1 = [ "find", settings.GIT_PATH, "-type", "f", "-name", '"*.scss"', '-not', '-name', '"_*"', '-not', '-path', '"./node_modules/*"', '-not', '-path', '"./static/*"', '-print' ] # compile css cmd2 = [ "parallel", "--no-notice", "sass", '--cache-location', '/tmp/sass', '--style', 'compressed', '{}', '{.}.css' ] p1 = Popen(cmd1, stdout=PIPE) p2 = Popen(cmd2, stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output, err = p2.communicate() updatelog(sha1, "\nCompile CSS...\n{}\n".format(output)) except Exception as e: updatelog(sha1, "\nERROR compiling CSS...\n{}\n".format(str(e))) return sha1 @shared_task def migrate(sha1, *args): cmd = [ settings.VEPYTHON, os.path.join(settings.GIT_PATH, 'src', 'manage.py'), 'migrate' ] updatelog(sha1, "\nMigrate...\n") call(cmd) return sha1 @shared_task def collect_static(sha1, *args): # tmp/ve/bin/python ./src/manage.py collectstatic --noinput # -i *.scss -i *.sass -i *.less -i *.coffee -i *.map -i *.md cmd = [ settings.VEPYTHON, os.path.join(settings.GIT_PATH, "src", "manage.py"), 'collectstatic', '--noinput', '-i', '*.scss', '-i', '*.sass', '-i', '*.less', '-i', '*.coffee', '-i', '*.map', '-i', '*.md' ] p = Popen(cmd, stdout=PIPE) output, err = p.communicate() updatelog(sha1, "\nCollect static...\n{}\n".format(output)) return sha1 # @task_postrun.connect() # @task_postrun.connect(sender=restart_celery) # def task_postrun(signal=None, sender=None, task_id=None, task=None, # args=None, kwargs=None, retval=None, state=None): # # note that this hook runs even when there has been an exception # # thrown by the task # # print "post run {0} ".format(task) # from django.conf import settings # Popen([ # 'sudo', # 'kill', # "-HUP", # os.path.join(settings.GIT_PATH, "tmp", "celery.pid") # ]) @shared_task def get_project_at_commit(sha1): """Clone a repo and place it near current working project. If current project is in /var/www/prj, a new one will be in /var/www/ef49782e...4c09a305 for example. """ updatelog(sha1, "\nCloning...\n") dst = os.path.join( os.path.dirname(settings.REPO_PATH), # parent path of current project sha1 # use SHA1 as folder name ) if os.path.isdir(dst): updatelog( sha1, "Path {} already exists. Skipping.\n".format(dst) ) return sha1 # git clone... cmd = [ 'git', 'clone', '--depth=1', 'https://github.com/pashinin-com/pashinin.com.git', dst ] p = Popen(cmd, stdout=PIPE) output, err = p.communicate() updatelog(sha1, "{}\n{}\n".format(" ".join(cmd), output)) return sha1 @shared_task def project_update(sha1): """This task runs when Travis build is finished succesfully. Runs in core/hooks/views.py: Travis class """ updatelog(sha1, clear=True) # clear log in case we've already run this job chain( get_project_at_commit.s(sha1), build_css.s(), collect_static.s(), migrate.s(), # chain( # supervisor.s("worker-"+settings.DOMAIN, "restart"), # restart_celery.s() # ), update_finish.s() )() # get() waits for all subtasks # supervisor.delay("worker-"+settings.DOMAIN, "restart") # restart_celery.delay() @shared_task def update_finish(sha1, *args): from core.models import SiteUpdate upd, created = SiteUpdate.objects.get_or_create(sha1=sha1) upd.log = updatelog(sha1) upd.finished = now() upd.save() return sha1 @shared_task def render_jinja_file(filename, data=None, outdir=None): """ Output filename is the same without .ext part: settings.py.jinja -> settings.py """ if data is None: data = get_variables() full = os.path.abspath(filename) d = os.path.dirname(full) base, ext = os.path.splitext(os.path.basename(full)) output = os.path.join(d, base) if outdir is not None: output = os.path.join(outdir, base) input = open(full, 'r').read() from jinja2 import Environment with open(output, 'w') as f: try: f.write(Environment().from_string(input).render(**data)) except Exception: print('FAILED rendering: ', filename) raise def get_variables(): """Return configs/tmp/conf.json variables as a dict.""" conf = os.path.join( get_git_root(abspath(__file__)), "configs", "tmp", "conf.json" ) return json.load(open(conf, 'r')) @shared_task def render_configs(): """""" path = os.path.join( get_git_root(abspath(__file__)), "configs" ) templates = [os.path.join(path, f) for f in os.listdir(path) if re.match(r'.*\.jinja', f)] for template in templates: print(template) render_jinja_file(template, outdir=os.path.join(path, 'tmp')) @shared_task def generate_settings(): """Scans all apps and (re)generates settings.py files. It looks for 'settings*.jinja' files and runs render_jinja_file to render a file. """ for app, path in apps(): templates = [os.path.join(path, f) for f in os.listdir(path) if re.match(r'settings.*\.jinja', f)] for template in templates: print(template) render_jinja_file(template)
pashinin-com/pashinin.com
src/core/tasks/update.py
Python
gpl-3.0
7,593
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module implements classes and methods for processing LAMMPS output files (log and dump). """ import glob import re from io import StringIO import numpy as np import pandas as pd from monty.io import zopen from monty.json import MSONable from pymatgen.io.lammps.data import LammpsBox __author__ = "Kiran Mathew, Zhi Deng" __copyright__ = "Copyright 2018, The Materials Virtual Lab" __version__ = "1.0" __maintainer__ = "Zhi Deng" __email__ = "z4deng@eng.ucsd.edu" __date__ = "Aug 1, 2018" class LammpsDump(MSONable): """ Object for representing dump data for a single snapshot. """ def __init__(self, timestep, natoms, box, data): """ Base constructor. Args: timestep (int): Current timestep. natoms (int): Total number of atoms in the box. box (LammpsBox): Simulation box. data (pd.DataFrame): Dumped atomic data. """ self.timestep = timestep self.natoms = natoms self.box = box self.data = data @classmethod def from_string(cls, string): """ Constructor from string parsing. Args: string (str): Input string. """ lines = string.split("\n") timestep = int(lines[1]) natoms = int(lines[3]) box_arr = np.loadtxt(StringIO("\n".join(lines[5:8]))) bounds = box_arr[:, :2] tilt = None if "xy xz yz" in lines[4]: tilt = box_arr[:, 2] x = (0, tilt[0], tilt[1], tilt[0] + tilt[1]) y = (0, tilt[2]) bounds -= np.array([[min(x), max(x)], [min(y), max(y)], [0, 0]]) box = LammpsBox(bounds, tilt) data_head = lines[8].replace("ITEM: ATOMS", "").split() data = pd.read_csv(StringIO("\n".join(lines[9:])), names=data_head, delim_whitespace=True) return cls(timestep, natoms, box, data) @classmethod def from_dict(cls, d): """ Args: d (dict): Dict representation Returns: LammpsDump """ items = {"timestep": d["timestep"], "natoms": d["natoms"]} items["box"] = LammpsBox.from_dict(d["box"]) items["data"] = pd.read_json(d["data"], orient="split") return cls(**items) def as_dict(self): """ Returns: MSONable dict """ d = dict() d["@module"] = self.__class__.__module__ d["@class"] = self.__class__.__name__ d["timestep"] = self.timestep d["natoms"] = self.natoms d["box"] = self.box.as_dict() d["data"] = self.data.to_json(orient="split") return d def parse_lammps_dumps(file_pattern): """ Generator that parses dump file(s). Args: file_pattern (str): Filename to parse. The timestep wildcard (e.g., dump.atom.'*') is supported and the files are parsed in the sequence of timestep. Yields: LammpsDump for each available snapshot. """ files = glob.glob(file_pattern) if len(files) > 1: pattern = r"%s" % file_pattern.replace("*", "([0-9]+)") pattern = pattern.replace("\\", "\\\\") files = sorted(files, key=lambda f: int(re.match(pattern, f).group(1))) for fname in files: with zopen(fname, "rt") as f: dump_cache = [] for line in f: if line.startswith("ITEM: TIMESTEP"): if len(dump_cache) > 0: yield LammpsDump.from_string("".join(dump_cache)) dump_cache = [line] else: dump_cache.append(line) yield LammpsDump.from_string("".join(dump_cache)) def parse_lammps_log(filename="log.lammps"): """ Parses log file with focus on thermo data. Both one and multi line formats are supported. Any incomplete runs (no "Loop time" marker) will not be parsed. Notes: SHAKE stats printed with thermo data are not supported yet. They are ignored in multi line format, while they may cause issues with dataframe parsing in one line format. Args: filename (str): Filename to parse. Returns: [pd.DataFrame] containing thermo data for each completed run. """ with zopen(filename, "rt") as f: lines = f.readlines() begin_flag = ( "Memory usage per processor =", "Per MPI rank memory allocation (min/avg/max) =", ) end_flag = "Loop time of" begins, ends = [], [] for i, l in enumerate(lines): if l.startswith(begin_flag): begins.append(i) elif l.startswith(end_flag): ends.append(i) def _parse_thermo(lines): multi_pattern = r"-+\s+Step\s+([0-9]+)\s+-+" # multi line thermo data if re.match(multi_pattern, lines[0]): timestep_marks = [i for i, l in enumerate(lines) if re.match(multi_pattern, l)] timesteps = np.split(lines, timestep_marks)[1:] dicts = [] kv_pattern = r"([0-9A-Za-z_\[\]]+)\s+=\s+([0-9eE\.+-]+)" for ts in timesteps: data = {} data["Step"] = int(re.match(multi_pattern, ts[0]).group(1)) data.update({k: float(v) for k, v in re.findall(kv_pattern, "".join(ts[1:]))}) dicts.append(data) df = pd.DataFrame(dicts) # rearrange the sequence of columns columns = ["Step"] + [k for k, v in re.findall(kv_pattern, "".join(timesteps[0][1:]))] df = df[columns] # one line thermo data else: df = pd.read_csv(StringIO("".join(lines)), delim_whitespace=True) return df runs = [] for b, e in zip(begins, ends): runs.append(_parse_thermo(lines[b + 1 : e])) return runs
gmatteo/pymatgen
pymatgen/io/lammps/outputs.py
Python
mit
5,960
# 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. # -------------------------------------------------------------------------- import functools from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.polling import LROPoller, NoPolling, PollingMethod from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.arm_polling import ARMPolling from msrest import Serializer from .. import models as _models from .._vendor import _convert_request, _format_url_section T = TypeVar('T') JSONType = Any ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_check_availability_request( subscription_id: str, *, json: JSONType = None, content: Any = None, **kwargs: Any ) -> HttpRequest: content_type = kwargs.pop('content_type', None) # type: Optional[str] api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/checkNamespaceAvailability') path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="POST", url=url, params=query_parameters, headers=header_parameters, json=json, content=content, **kwargs ) def build_create_or_update_request( resource_group_name: str, namespace_name: str, subscription_id: str, *, json: JSONType = None, content: Any = None, **kwargs: Any ) -> HttpRequest: content_type = kwargs.pop('content_type', None) # type: Optional[str] api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="PUT", url=url, params=query_parameters, headers=header_parameters, json=json, content=content, **kwargs ) def build_patch_request( resource_group_name: str, namespace_name: str, subscription_id: str, *, json: JSONType = None, content: Any = None, **kwargs: Any ) -> HttpRequest: content_type = kwargs.pop('content_type', None) # type: Optional[str] api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="PATCH", url=url, params=query_parameters, headers=header_parameters, json=json, content=content, **kwargs ) def build_delete_request_initial( resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2017-04-01" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') return HttpRequest( method="DELETE", url=url, params=query_parameters, **kwargs ) def build_get_request( resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="GET", url=url, params=query_parameters, headers=header_parameters, **kwargs ) def build_create_or_update_authorization_rule_request( resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, *, json: JSONType = None, content: Any = None, **kwargs: Any ) -> HttpRequest: content_type = kwargs.pop('content_type', None) # type: Optional[str] api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "authorizationRuleName": _SERIALIZER.url("authorization_rule_name", authorization_rule_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="PUT", url=url, params=query_parameters, headers=header_parameters, json=json, content=content, **kwargs ) def build_delete_authorization_rule_request( resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2017-04-01" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "authorizationRuleName": _SERIALIZER.url("authorization_rule_name", authorization_rule_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') return HttpRequest( method="DELETE", url=url, params=query_parameters, **kwargs ) def build_get_authorization_rule_request( resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "authorizationRuleName": _SERIALIZER.url("authorization_rule_name", authorization_rule_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="GET", url=url, params=query_parameters, headers=header_parameters, **kwargs ) def build_list_request( resource_group_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="GET", url=url, params=query_parameters, headers=header_parameters, **kwargs ) def build_list_all_request( subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/namespaces') path_format_arguments = { "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="GET", url=url, params=query_parameters, headers=header_parameters, **kwargs ) def build_list_authorization_rules_request( resource_group_name: str, namespace_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="GET", url=url, params=query_parameters, headers=header_parameters, **kwargs ) def build_list_keys_request( resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/listKeys') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "authorizationRuleName": _SERIALIZER.url("authorization_rule_name", authorization_rule_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="POST", url=url, params=query_parameters, headers=header_parameters, **kwargs ) def build_regenerate_keys_request( resource_group_name: str, namespace_name: str, authorization_rule_name: str, subscription_id: str, *, json: JSONType = None, content: Any = None, **kwargs: Any ) -> HttpRequest: content_type = kwargs.pop('content_type', None) # type: Optional[str] api_version = "2017-04-01" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "namespaceName": _SERIALIZER.url("namespace_name", namespace_name, 'str'), "authorizationRuleName": _SERIALIZER.url("authorization_rule_name", authorization_rule_name, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="POST", url=url, params=query_parameters, headers=header_parameters, json=json, content=content, **kwargs ) class NamespacesOperations(object): """NamespacesOperations 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.notificationhubs.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): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config @distributed_trace def check_availability( self, parameters: "_models.CheckAvailabilityParameters", **kwargs: Any ) -> "_models.CheckAvailabilityResult": """Checks the availability of the given service namespace across all Azure subscriptions. This is useful because the domain name is created based on the service namespace name. :param parameters: The namespace name. :type parameters: ~azure.mgmt.notificationhubs.models.CheckAvailabilityParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: CheckAvailabilityResult, or the result of cls(response) :rtype: ~azure.mgmt.notificationhubs.models.CheckAvailabilityResult :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.CheckAvailabilityResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] _json = self._serialize.body(parameters, 'CheckAvailabilityParameters') request = build_check_availability_request( subscription_id=self._config.subscription_id, content_type=content_type, json=_json, template_url=self.check_availability.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = 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('CheckAvailabilityResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized check_availability.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/checkNamespaceAvailability'} # type: ignore @distributed_trace def create_or_update( self, resource_group_name: str, namespace_name: str, parameters: "_models.NamespaceCreateOrUpdateParameters", **kwargs: Any ) -> "_models.NamespaceResource": """Creates/Updates a service namespace. Once created, this namespace's resource manifest is immutable. This operation is idempotent. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :param parameters: Parameters supplied to create a Namespace Resource. :type parameters: ~azure.mgmt.notificationhubs.models.NamespaceCreateOrUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: NamespaceResource, or the result of cls(response) :rtype: ~azure.mgmt.notificationhubs.models.NamespaceResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NamespaceResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] _json = self._serialize.body(parameters, 'NamespaceCreateOrUpdateParameters') request = build_create_or_update_request( resource_group_name=resource_group_name, namespace_name=namespace_name, subscription_id=self._config.subscription_id, content_type=content_type, json=_json, template_url=self.create_or_update.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = 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('NamespaceResource', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('NamespaceResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}'} # type: ignore @distributed_trace def patch( self, resource_group_name: str, namespace_name: str, parameters: "_models.NamespacePatchParameters", **kwargs: Any ) -> "_models.NamespaceResource": """Patches the existing namespace. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :param parameters: Parameters supplied to patch a Namespace Resource. :type parameters: ~azure.mgmt.notificationhubs.models.NamespacePatchParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: NamespaceResource, or the result of cls(response) :rtype: ~azure.mgmt.notificationhubs.models.NamespaceResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NamespaceResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] _json = self._serialize.body(parameters, 'NamespacePatchParameters') request = build_patch_request( resource_group_name=resource_group_name, namespace_name=namespace_name, subscription_id=self._config.subscription_id, content_type=content_type, json=_json, template_url=self.patch.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = 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('NamespaceResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized patch.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}'} # type: ignore def _delete_initial( self, resource_group_name: str, namespace_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) request = build_delete_request_initial( resource_group_name=resource_group_name, namespace_name=namespace_name, subscription_id=self._config.subscription_id, template_url=self._delete_initial.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = 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.NotificationHubs/namespaces/{namespaceName}'} # type: ignore @distributed_trace def begin_delete( self, resource_group_name: str, namespace_name: str, **kwargs: Any ) -> LROPoller[None]: """Deletes an existing namespace. This operation also removes all associated notificationHubs under the namespace. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_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: By default, your polling method will be ARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of LROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.LROPoller[None] :raises: ~azure.core.exceptions.HttpResponseError """ polling = kwargs.pop('polling', True) # type: Union[bool, azure.core.polling.PollingMethod] 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 = self._delete_initial( resource_group_name=resource_group_name, namespace_name=namespace_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) if polling is True: polling_method = ARMPolling(lro_delay, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: return LROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return LROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}'} # type: ignore @distributed_trace def get( self, resource_group_name: str, namespace_name: str, **kwargs: Any ) -> "_models.NamespaceResource": """Returns the description for the specified namespace. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: NamespaceResource, or the result of cls(response) :rtype: ~azure.mgmt.notificationhubs.models.NamespaceResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NamespaceResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) request = build_get_request( resource_group_name=resource_group_name, namespace_name=namespace_name, subscription_id=self._config.subscription_id, template_url=self.get.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = 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('NamespaceResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}'} # type: ignore @distributed_trace def create_or_update_authorization_rule( self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, parameters: "_models.SharedAccessAuthorizationRuleCreateOrUpdateParameters", **kwargs: Any ) -> "_models.SharedAccessAuthorizationRuleResource": """Creates an authorization rule for a namespace. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :param authorization_rule_name: Authorization Rule Name. :type authorization_rule_name: str :param parameters: The shared access authorization rule. :type parameters: ~azure.mgmt.notificationhubs.models.SharedAccessAuthorizationRuleCreateOrUpdateParameters :keyword callable cls: A custom type or function that will be passed the direct response :return: SharedAccessAuthorizationRuleResource, or the result of cls(response) :rtype: ~azure.mgmt.notificationhubs.models.SharedAccessAuthorizationRuleResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedAccessAuthorizationRuleResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] _json = self._serialize.body(parameters, 'SharedAccessAuthorizationRuleCreateOrUpdateParameters') request = build_create_or_update_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, content_type=content_type, json=_json, template_url=self.create_or_update_authorization_rule.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = 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('SharedAccessAuthorizationRuleResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update_authorization_rule.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}'} # type: ignore @distributed_trace def delete_authorization_rule( self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any ) -> None: """Deletes a namespace authorization rule. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :param authorization_rule_name: Authorization Rule Name. :type authorization_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) request = build_delete_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, template_url=self.delete_authorization_rule.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 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_authorization_rule.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}'} # type: ignore @distributed_trace def get_authorization_rule( self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any ) -> "_models.SharedAccessAuthorizationRuleResource": """Gets an authorization rule for a namespace by name. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :param authorization_rule_name: Authorization rule name. :type authorization_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: SharedAccessAuthorizationRuleResource, or the result of cls(response) :rtype: ~azure.mgmt.notificationhubs.models.SharedAccessAuthorizationRuleResource :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedAccessAuthorizationRuleResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) request = build_get_authorization_rule_request( resource_group_name=resource_group_name, namespace_name=namespace_name, authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, template_url=self.get_authorization_rule.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = 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('SharedAccessAuthorizationRuleResource', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_authorization_rule.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}'} # type: ignore @distributed_trace def list( self, resource_group_name: str, **kwargs: Any ) -> Iterable["_models.NamespaceListResult"]: """Lists the available namespaces within a resourceGroup. :param resource_group_name: The name of the resource group. If resourceGroupName value is null the method lists all the namespaces within subscription. :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 NamespaceListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.notificationhubs.models.NamespaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NamespaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if not next_link: request = build_list_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, template_url=self.list.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = build_list_request( resource_group_name=resource_group_name, subscription_id=self._config.subscription_id, template_url=next_link, ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("NamespaceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = 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 ItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces'} # type: ignore @distributed_trace def list_all( self, **kwargs: Any ) -> Iterable["_models.NamespaceListResult"]: """Lists all the available namespaces within the subscription irrespective of the resourceGroups. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either NamespaceListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.notificationhubs.models.NamespaceListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.NamespaceListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if not next_link: request = build_list_all_request( subscription_id=self._config.subscription_id, template_url=self.list_all.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = build_list_all_request( subscription_id=self._config.subscription_id, template_url=next_link, ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("NamespaceListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = 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 ItemPaged( get_next, extract_data ) list_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/namespaces'} # type: ignore @distributed_trace def list_authorization_rules( self, resource_group_name: str, namespace_name: str, **kwargs: Any ) -> Iterable["_models.SharedAccessAuthorizationRuleListResult"]: """Gets the authorization rules for a namespace. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SharedAccessAuthorizationRuleListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.notificationhubs.models.SharedAccessAuthorizationRuleListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.SharedAccessAuthorizationRuleListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if not next_link: request = build_list_authorization_rules_request( resource_group_name=resource_group_name, namespace_name=namespace_name, subscription_id=self._config.subscription_id, template_url=self.list_authorization_rules.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = build_list_authorization_rules_request( resource_group_name=resource_group_name, namespace_name=namespace_name, subscription_id=self._config.subscription_id, template_url=next_link, ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("SharedAccessAuthorizationRuleListResult", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = 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 ItemPaged( get_next, extract_data ) list_authorization_rules.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules'} # type: ignore @distributed_trace def list_keys( self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, **kwargs: Any ) -> "_models.ResourceListKeys": """Gets the Primary and Secondary ConnectionStrings to the namespace. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :param authorization_rule_name: The connection string of the namespace for the specified authorizationRule. :type authorization_rule_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ResourceListKeys, or the result of cls(response) :rtype: ~azure.mgmt.notificationhubs.models.ResourceListKeys :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceListKeys"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) request = build_list_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, template_url=self.list_keys.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = 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('ResourceListKeys', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized list_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/listKeys'} # type: ignore @distributed_trace def regenerate_keys( self, resource_group_name: str, namespace_name: str, authorization_rule_name: str, parameters: "_models.PolicykeyResource", **kwargs: Any ) -> "_models.ResourceListKeys": """Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param namespace_name: The namespace name. :type namespace_name: str :param authorization_rule_name: The connection string of the namespace for the specified authorizationRule. :type authorization_rule_name: str :param parameters: Parameters supplied to regenerate the Namespace Authorization Rule Key. :type parameters: ~azure.mgmt.notificationhubs.models.PolicykeyResource :keyword callable cls: A custom type or function that will be passed the direct response :return: ResourceListKeys, or the result of cls(response) :rtype: ~azure.mgmt.notificationhubs.models.ResourceListKeys :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ResourceListKeys"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] _json = self._serialize.body(parameters, 'PolicykeyResource') request = build_regenerate_keys_request( resource_group_name=resource_group_name, namespace_name=namespace_name, authorization_rule_name=authorization_rule_name, subscription_id=self._config.subscription_id, content_type=content_type, json=_json, template_url=self.regenerate_keys.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = 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('ResourceListKeys', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized regenerate_keys.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys'} # type: ignore
Azure/azure-sdk-for-python
sdk/notificationhubs/azure-mgmt-notificationhubs/azure/mgmt/notificationhubs/operations/_namespaces_operations.py
Python
mit
57,092
from func import * logger = logging.getLogger('neuromodulation') startbuild = datetime.datetime.now() nest.ResetKernel() nest.SetKernelStatus({'overwrite_files': True, 'local_num_threads': 4, 'resolution': 0.1}) generate_neurons(3000) # parameters of synapse models nest.CopyModel('stdp_synapse', glu_synapse, STDP_synparams_Glu) nest.CopyModel('stdp_synapse', gaba_synapse, STDP_synparams_GABA) logger.debug("* * * Start connection initialisation") ''' spike out of thalamus ******************************************************* ''' #to 1 collumn connect(thalamus[thalamus_Glu], l6[l6_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l5[l5_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l4[l4_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l4[l4_Glu0], syn_type=Glu) connect(thalamus[thalamus_Glu], l4[l4_Gaba0], syn_type=Glu) connect(thalamus[thalamus_Glu], l3[l3_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l3[l3_Gaba1], syn_type=Glu) #to 2 collumn connect(thalamus[thalamus_Glu], l6c2[l6c2_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l5c2[l5c2_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c2[l4c2_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c2[l4c2_Glu0], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c2[l4c2_Gaba0], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c2[l3c2_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c2[l3c2_Gaba1], syn_type=Glu) #to 3 collumn connect(thalamus[thalamus_Glu], l6c3[l6c3_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l5c3[l5c3_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c3[l4c3_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c3[l4c3_Glu0], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c3[l4c3_Gaba0], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c3[l3c3_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c3[l3c3_Gaba1], syn_type=Glu) #to 4 collumn connect(thalamus[thalamus_Glu], l6c4[l6c4_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l5c4[l5c4_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c4[l4c4_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c4[l4c4_Glu0], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c4[l4c4_Gaba0], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c4[l3c4_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c4[l3c4_Gaba1], syn_type=Glu) #to 5 collumn connect(thalamus[thalamus_Glu], l6c5[l6c5_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l5c5[l5c5_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c5[l4c5_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c5[l4c5_Glu0], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c5[l4c5_Gaba0], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c5[l3c5_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c5[l3c5_Gaba1], syn_type=Glu) #to 6 collumn connect(thalamus[thalamus_Glu], l6c6[l6c6_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l5c6[l5c6_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c6[l4c6_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c6[l4c6_Glu0], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c6[l4c6_Gaba0], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c6[l3c6_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c6[l3c6_Gaba1], syn_type=Glu) #to 7 collumn connect(thalamus[thalamus_Glu], l6c7[l6c7_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l5c7[l5c7_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c7[l4c7_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c7[l4c7_Glu0], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c7[l4c7_Gaba0], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c7[l3c7_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c7[l3c7_Gaba1], syn_type=Glu) #to 8 collumn connect(thalamus[thalamus_Glu], l6c8[l6c8_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l5c8[l5c8_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c8[l4c8_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c8[l4c8_Glu0], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c8[l4c8_Gaba0], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c8[l3c8_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c8[l3c8_Gaba1], syn_type=Glu) #to 9 collumn connect(thalamus[thalamus_Glu], l6c9[l6c9_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l5c9[l5c9_Glu], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c9[l4c9_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c9[l4c9_Glu0], syn_type=Glu) connect(thalamus[thalamus_Glu], l4c9[l4c9_Gaba0], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c9[l3c9_Glu1], syn_type=Glu) connect(thalamus[thalamus_Glu], l3c9[l3c9_Gaba1], syn_type=Glu) ''' connect layers gaba,glu into collumns ******************************************* ''' # connect into collumn num. 1 ********************** connect(l2[l2_Gaba0], l4[l4_Glu0], syn_type=GABA, weight_coef=0.000005) connect(l3[l3_Gaba0], l3[l3_Glu1], syn_type=GABA, weight_coef=0.00005) connect(l3[l3_Gaba1], l3[l3_Glu1], syn_type=GABA, weight_coef=0.0001) connect(l3[l3_Glu1], thalamus[thalamus_Glu], syn_type=GABA, weight_coef=0.00005) connect(l4[l4_Glu0], l3[l3_Glu1], syn_type=Glu) connect(l4[l4_Glu0], l2[l2_Gaba1], syn_type=Glu) connect(l4[l4_Glu1], l3[l3_Glu1], syn_type=Glu) connect(l4[l4_Gaba0], l2[l2_Gaba0], syn_type=GABA, weight_coef=0.00005) connect(l5[l5_Glu], l3[l3_Glu1], syn_type=Glu) connect(l5[l5_Glu], l3[l3_Gaba1], syn_type=Glu) connect(l5[l5_Glu], l3[l3_Gaba0], syn_type=Glu) connect(l5[l5_Glu], l2[l2_Gaba0], syn_type=Glu) connect(l6[l6_Glu], l4[l4_Glu1], syn_type=Glu) # connect into collumn num. 2 ********************** connect(l2c2[l2c2_Gaba0], l4c2[l4c2_Glu0], syn_type=GABA, weight_coef=0.000005) connect(l3c2[l3c2_Gaba0], l3c2[l3c2_Glu1], syn_type=GABA, weight_coef=0.00005) connect(l3c2[l3c2_Gaba1], l3c2[l3c2_Glu1], syn_type=GABA, weight_coef=0.0001) connect(l3c2[l3c2_Glu1], thalamus[thalamus_Glu], syn_type=GABA, weight_coef=0.00005) connect(l4c2[l4c2_Glu0], l3c2[l3c2_Glu1], syn_type=Glu) connect(l4c2[l4c2_Glu0], l2c2[l2c2_Gaba1], syn_type=Glu) connect(l4c2[l4c2_Glu1], l3c2[l3c2_Glu1], syn_type=Glu) connect(l4c2[l4c2_Gaba0], l2c2[l2c2_Gaba0], syn_type=GABA, weight_coef=0.00005) connect(l5c2[l5c2_Glu], l3c2[l3c2_Glu1], syn_type=Glu) connect(l5c2[l5c2_Glu], l3c2[l3c2_Gaba1], syn_type=Glu) connect(l5c2[l5c2_Glu], l3c2[l3c2_Gaba0], syn_type=Glu) connect(l5c2[l5c2_Glu], l2c2[l2c2_Gaba0], syn_type=Glu) connect(l6c2[l6c2_Glu], l4c2[l4c2_Glu1], syn_type=Glu) # connect into collumn num. 3 ********************** connect(l2c3[l2c3_Gaba0], l4c3[l4c3_Glu0], syn_type=GABA, weight_coef=0.000005) connect(l3c3[l3c3_Gaba0], l3c3[l3c3_Glu1], syn_type=GABA, weight_coef=0.00005) connect(l3c3[l3c3_Gaba1], l3c3[l3c3_Glu1], syn_type=GABA, weight_coef=0.0001) connect(l3c3[l3c3_Glu1], thalamus[thalamus_Glu], syn_type=GABA, weight_coef=0.00005) connect(l4c3[l4c3_Glu0], l3c3[l3c3_Glu1], syn_type=Glu) connect(l4c3[l4c3_Glu0], l2c3[l2c3_Gaba1], syn_type=Glu) connect(l4c3[l4c3_Glu1], l3c3[l3c3_Glu1], syn_type=Glu) connect(l4c3[l4c3_Gaba0], l2c3[l2c3_Gaba0], syn_type=GABA, weight_coef=0.00005) connect(l5c3[l5c3_Glu], l3c3[l3c3_Glu1], syn_type=Glu) connect(l5c3[l5c3_Glu], l3c3[l3c3_Gaba1], syn_type=Glu) connect(l5c3[l5c3_Glu], l3c3[l3c3_Gaba0], syn_type=Glu) connect(l5c3[l5c3_Glu], l2c3[l2c3_Gaba0], syn_type=Glu) connect(l6c3[l6c3_Glu], l4c3[l4c3_Glu1], syn_type=Glu) # connect into collumn num. 4 ********************** connect(l2c4[l2c4_Gaba0], l4c4[l4c4_Glu0], syn_type=GABA, weight_coef=0.000005) connect(l3c4[l3c4_Gaba0], l3c4[l3c4_Glu1], syn_type=GABA, weight_coef=0.00005) connect(l3c4[l3c4_Gaba1], l3c4[l3c4_Glu1], syn_type=GABA, weight_coef=0.0001) connect(l3c4[l3c4_Glu1], thalamus[thalamus_Glu], syn_type=GABA, weight_coef=0.00005) connect(l4c4[l4c4_Glu0], l3c4[l3c4_Glu1], syn_type=Glu) connect(l4c4[l4c4_Glu0], l2c4[l2c4_Gaba1], syn_type=Glu) connect(l4c4[l4c4_Glu1], l3c4[l3c4_Glu1], syn_type=Glu) connect(l4c4[l4c4_Gaba0], l2c4[l2c4_Gaba0], syn_type=GABA, weight_coef=0.00005) connect(l5c4[l5c4_Glu], l3c4[l3c4_Glu1], syn_type=Glu) connect(l5c4[l5c4_Glu], l3c4[l3c4_Gaba1], syn_type=Glu) connect(l5c4[l5c4_Glu], l3c4[l3c4_Gaba0], syn_type=Glu) connect(l5c4[l5c4_Glu], l2c4[l2c4_Gaba0], syn_type=Glu) connect(l6c4[l6c4_Glu], l4c4[l4c4_Glu1], syn_type=Glu) # connect into collumn num. 5 ********************** connect(l2c5[l2c5_Gaba0], l4c5[l4c5_Glu0], syn_type=GABA, weight_coef=0.000005) connect(l3c5[l3c5_Gaba0], l3c5[l3c5_Glu1], syn_type=GABA, weight_coef=0.00005) connect(l3c5[l3c5_Gaba1], l3c5[l3c5_Glu1], syn_type=GABA, weight_coef=0.0001) connect(l3c5[l3c5_Glu1], thalamus[thalamus_Glu], syn_type=GABA, weight_coef=0.00005) connect(l4c5[l4c5_Glu0], l3c5[l3c5_Glu1], syn_type=Glu) connect(l4c5[l4c5_Glu0], l2c5[l2c5_Gaba1], syn_type=Glu) connect(l4c5[l4c5_Glu1], l3c5[l3c5_Glu1], syn_type=Glu) connect(l4c5[l4c5_Gaba0], l2c5[l2c5_Gaba0], syn_type=GABA, weight_coef=0.00005) connect(l5c5[l5c5_Glu], l3c5[l3c5_Glu1], syn_type=Glu) connect(l5c5[l5c5_Glu], l3c5[l3c5_Gaba1], syn_type=Glu) connect(l5c5[l5c5_Glu], l3c5[l3c5_Gaba0], syn_type=Glu) connect(l5c5[l5c5_Glu], l2c5[l2c5_Gaba0], syn_type=Glu) connect(l6c5[l6c5_Glu], l4c5[l4c5_Glu1], syn_type=Glu) # connect into collumn num. 6 ********************** connect(l2c6[l2c6_Gaba0], l4c6[l4c6_Glu0], syn_type=GABA, weight_coef=0.000005) connect(l3c6[l3c6_Gaba0], l3c6[l3c6_Glu1], syn_type=GABA, weight_coef=0.00005) connect(l3c6[l3c6_Gaba1], l3c6[l3c6_Glu1], syn_type=GABA, weight_coef=0.0001) connect(l3c6[l3c6_Glu1], thalamus[thalamus_Glu], syn_type=GABA, weight_coef=0.00005) connect(l4c6[l4c6_Glu0], l3c6[l3c6_Glu1], syn_type=Glu) connect(l4c6[l4c6_Glu0], l2c6[l2c6_Gaba1], syn_type=Glu) connect(l4c6[l4c6_Glu1], l3c6[l3c6_Glu1], syn_type=Glu) connect(l4c6[l4c6_Gaba0], l2c6[l2c6_Gaba0], syn_type=GABA, weight_coef=0.00005) connect(l5c6[l5c6_Glu], l3c6[l3c6_Glu1], syn_type=Glu) connect(l5c6[l5c6_Glu], l3c6[l3c6_Gaba1], syn_type=Glu) connect(l5c6[l5c6_Glu], l3c6[l3c6_Gaba0], syn_type=Glu) connect(l5c6[l5c6_Glu], l2c6[l2c6_Gaba0], syn_type=Glu) connect(l6c6[l6c6_Glu], l4c6[l4c6_Glu1], syn_type=Glu) # connect into collumn num. 7 ********************** connect(l2c7[l2c7_Gaba0], l4c7[l4c7_Glu0], syn_type=GABA, weight_coef=0.000005) connect(l3c7[l3c7_Gaba0], l3c7[l3c7_Glu1], syn_type=GABA, weight_coef=0.00005) connect(l3c7[l3c7_Gaba1], l3c7[l3c7_Glu1], syn_type=GABA, weight_coef=0.0001) connect(l3c7[l3c7_Glu1], thalamus[thalamus_Glu], syn_type=GABA, weight_coef=0.00005) connect(l4c7[l4c7_Glu0], l3c7[l3c7_Glu1], syn_type=Glu) connect(l4c7[l4c7_Glu0], l2c7[l2c7_Gaba1], syn_type=Glu) connect(l4c7[l4c7_Glu1], l3c7[l3c7_Glu1], syn_type=Glu) connect(l4c7[l4c7_Gaba0], l2c7[l2c7_Gaba0], syn_type=GABA, weight_coef=0.00005) connect(l5c7[l5c7_Glu], l3c7[l3c7_Glu1], syn_type=Glu) connect(l5c7[l5c7_Glu], l3c7[l3c7_Gaba1], syn_type=Glu) connect(l5c7[l5c7_Glu], l3c7[l3c7_Gaba0], syn_type=Glu) connect(l5c7[l5c7_Glu], l2c7[l2c7_Gaba0], syn_type=Glu) connect(l6c7[l6c7_Glu], l4c7[l4c7_Glu1], syn_type=Glu) # connect into collumn num. 8 ********************** connect(l2c8[l2c8_Gaba0], l4c8[l4c8_Glu0], syn_type=GABA, weight_coef=0.000005) connect(l3c8[l3c8_Gaba0], l3c8[l3c8_Glu1], syn_type=GABA, weight_coef=0.00005) connect(l3c8[l3c8_Gaba1], l3c8[l3c8_Glu1], syn_type=GABA, weight_coef=0.0001) connect(l3c8[l3c8_Glu1], thalamus[thalamus_Glu], syn_type=GABA, weight_coef=0.00005) connect(l4c8[l4c8_Glu0], l3c8[l3c8_Glu1], syn_type=Glu) connect(l4c8[l4c8_Glu0], l2c8[l2c8_Gaba1], syn_type=Glu) connect(l4c8[l4c8_Glu1], l3c8[l3c8_Glu1], syn_type=Glu) connect(l4c8[l4c8_Gaba0], l2c8[l2c8_Gaba0], syn_type=GABA, weight_coef=0.00005) connect(l5c8[l5c8_Glu], l3c8[l3c8_Glu1], syn_type=Glu) connect(l5c8[l5c8_Glu], l3c8[l3c8_Gaba1], syn_type=Glu) connect(l5c8[l5c8_Glu], l3c8[l3c8_Gaba0], syn_type=Glu) connect(l5c8[l5c8_Glu], l2c8[l2c8_Gaba0], syn_type=Glu) connect(l6c8[l6c8_Glu], l4c8[l4c8_Glu1], syn_type=Glu) # connect into collumn num. 9 ********************** connect(l2c9[l2c9_Gaba0], l4c9[l4c9_Glu0], syn_type=GABA, weight_coef=0.000005) connect(l3c9[l3c9_Gaba0], l3c9[l3c9_Glu1], syn_type=GABA, weight_coef=0.00005) connect(l3c9[l3c9_Gaba1], l3c9[l3c9_Glu1], syn_type=GABA, weight_coef=0.0001) connect(l3c9[l3c9_Glu1], thalamus[thalamus_Glu], syn_type=GABA, weight_coef=0.00005) connect(l4c9[l4c9_Glu0], l3c9[l3c9_Glu1], syn_type=Glu) connect(l4c9[l4c9_Glu0], l2c9[l2c9_Gaba1], syn_type=Glu) connect(l4c9[l4c9_Glu1], l3c9[l3c9_Glu1], syn_type=Glu) connect(l4c9[l4c9_Gaba0], l2c9[l2c9_Gaba0], syn_type=GABA, weight_coef=0.00005) connect(l5c9[l5c9_Glu], l3c9[l3c9_Glu1], syn_type=Glu) connect(l5c9[l5c9_Glu], l3c9[l3c9_Gaba1], syn_type=Glu) connect(l5c9[l5c9_Glu], l3c9[l3c9_Gaba0], syn_type=Glu) connect(l5c9[l5c9_Glu], l2c9[l2c9_Gaba0], syn_type=Glu) connect(l6c9[l6c9_Glu], l4c9[l4c9_Glu1], syn_type=Glu) ''' connect collumn with other collumn**************************************************** ''' ''' 1 | 2 | 3 4 | 5 | 6 7 | 8 | 9 ''' #collumn num.1 connect(l2[l2_Gaba1], l2c2[l2c2_Gaba1], syn_type=GABA) connect(l2[l2_Gaba1], l2c4[l2c4_Gaba1], syn_type=GABA) connect(l2[l2_Gaba1], l2c5[l2c5_Gaba1], syn_type=GABA) #collumn num.2 connect(l2c2[l2c2_Gaba1], l2[l2_Gaba1], syn_type=GABA) connect(l2c2[l2c2_Gaba1], l2c3[l2c3_Gaba1], syn_type=GABA) connect(l2c2[l2c2_Gaba1], l2c4[l2c4_Gaba1], syn_type=GABA) connect(l2c2[l2c2_Gaba1], l2c5[l2c5_Gaba1], syn_type=GABA) connect(l2c2[l2c2_Gaba1], l2c6[l2c6_Gaba1], syn_type=GABA) #collumn num.3 connect(l2c3[l2c3_Gaba1], l2c2[l2c2_Gaba1], syn_type=GABA) connect(l2c3[l2c3_Gaba1], l2c5[l2c5_Gaba1], syn_type=GABA) connect(l2c3[l2c3_Gaba1], l2c6[l2c6_Gaba1], syn_type=GABA) #collumn num.4 connect(l2c4[l2c4_Gaba1], l2[l2_Gaba1], syn_type=GABA) connect(l2c4[l2c4_Gaba1], l2c2[l2c2_Gaba1], syn_type=GABA) connect(l2c4[l2c4_Gaba1], l2c7[l2c7_Gaba1], syn_type=GABA) connect(l2c4[l2c4_Gaba1], l2c5[l2c5_Gaba1], syn_type=GABA) connect(l2c4[l2c4_Gaba1], l2c8[l2c8_Gaba1], syn_type=GABA) #collumn num.5 connect(l2c5[l2c5_Gaba1], l2[l2_Gaba1], syn_type=GABA) connect(l2c5[l2c5_Gaba1], l2c2[l2c2_Gaba1], syn_type=GABA) connect(l2c5[l2c5_Gaba1], l2c3[l2c3_Gaba1], syn_type=GABA) connect(l2c5[l2c5_Gaba1], l2c4[l2c4_Gaba1], syn_type=GABA) connect(l2c5[l2c5_Gaba1], l2c6[l2c6_Gaba1], syn_type=GABA) connect(l2c5[l2c5_Gaba1], l2c7[l2c7_Gaba1], syn_type=GABA) connect(l2c5[l2c5_Gaba1], l2c8[l2c8_Gaba1], syn_type=GABA) connect(l2c5[l2c5_Gaba1], l2c9[l2c9_Gaba1], syn_type=GABA) #collumn num.6 connect(l2c6[l2c6_Gaba1], l2c2[l2c2_Gaba1], syn_type=GABA) connect(l2c6[l2c6_Gaba1], l2c3[l2c3_Gaba1], syn_type=GABA) connect(l2c6[l2c6_Gaba1], l2c5[l2c5_Gaba1], syn_type=GABA) connect(l2c6[l2c6_Gaba1], l2c8[l2c8_Gaba1], syn_type=GABA) connect(l2c6[l2c6_Gaba1], l2c9[l2c9_Gaba1], syn_type=GABA) #collumn num.7 connect(l2c7[l2c7_Gaba1], l2c4[l2c4_Gaba1], syn_type=GABA) connect(l2c7[l2c7_Gaba1], l2c5[l2c5_Gaba1], syn_type=GABA) connect(l2c7[l2c7_Gaba1], l2c8[l2c8_Gaba1], syn_type=GABA) #collumn num.8 connect(l2c8[l2c8_Gaba1], l2c4[l2c4_Gaba1], syn_type=GABA) connect(l2c8[l2c8_Gaba1], l2c5[l2c5_Gaba1], syn_type=GABA) connect(l2c8[l2c8_Gaba1], l2c6[l2c6_Gaba1], syn_type=GABA) connect(l2c8[l2c8_Gaba1], l2c8[l2c8_Gaba1], syn_type=GABA) connect(l2c8[l2c8_Gaba1], l2c7[l2c7_Gaba1], syn_type=GABA) #collumn num.9 connect(l2c9[l2c9_Gaba1], l2c5[l2c5_Gaba1], syn_type=GABA) connect(l2c9[l2c9_Gaba1], l2c6[l2c6_Gaba1], syn_type=GABA) connect(l2c9[l2c9_Gaba1], l2c8[l2c8_Gaba1], syn_type=GABA) logger.debug("* * * Creating spike generators...") if generator_flag: connect_generator(thalamus[thalamus_Glu], rate=100, coef_part=1) logger.debug("* * * Attaching spikes detector") for part in getAllParts(): connect_detector(part) del generate_neurons, connect, connect_generator, connect_detector endbuild = datetime.datetime.now() simulate() get_log(startbuild, endbuild) save(GUI=status_gui)
vitaliykomarov/NEUCOGAR
nest/visual/V4/scripts/neuromodulation.py
Python
gpl-2.0
15,870
""" QUESTION: Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If nums = [1,2,2], a solution is: [ [2], [1], [1,2,2], [2,2], [1,2], [] ] ANSWER: The idea is bitwise. For each number from 0 to 2^n, the set bits corresponding to the choose element of set. One more tricky to deal with duplicate """ class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() cand = [] for x in xrange(2**len(nums)): sel = True for i in xrange(1,len(nums)): if nums[i] == nums[i-1] and (x>>(i-1))&3==1: sel = False break if sel: cand.append(x) return [[nums[i] for i in xrange(len(nums)) if (x>>i)&1] for x in cand] if __name__ == '__main__': for s in Solution().subsetsWithDup([2,3,2,5,4,5,9]): print s
tktrungna/leetcode
Python/subsets-ii.py
Python
mit
1,124
#!/usr/bin/env python3 from __future__ import print_function import ast import base64 import logging from pprint import pprint from email.mime.text import MIMEText import httplib2 from fluent import sender, event from googleapiclient.discovery import Resource from googleapiclient.discovery import build from googleapiclient.errors import HttpError from oauth2client.service_account import ServiceAccountCredentials from retrying import retry from . import alg_utils CREDENTIALS = { 'drive': { 'key': alg_utils.get_secret('gsuite', 'drive_robot_keyfile'), 'scopes': ['https://www.googleapis.com/auth/drive'] }, 'gmail': { 'key': alg_utils.get_secret('gsuite', 'gmail_robot_keyfile'), 'scopes': ['https://www.googleapis.com/auth/gmail.modify'] }, 'admin': { 'key': alg_utils.get_secret('gsuite', 'admin_robot_keyfile'), 'scopes': ['https://www.googleapis.com/auth/admin'] } } logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR) server_email = alg_utils.get_config('gsuite', 'server_account') discovery_url = 'https://www.googleapis.com/discovery' drive_discovery_url = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest' sender.setup( host=alg_utils.get_config('fluent', 'host'), port=alg_utils.get_config('fluent', 'port'), tag='alg.worker.pickles') def fire_batch_value_clear(email: str, spreadsheet_id: str, ranges: list): http = get_authorized_http('drive', email=email) body = {'ranges': ranges} return build('sheets', 'v4', http=http) \ .spreadsheets() \ .values() \ .batchClear(spreadsheetId=spreadsheet_id, body=body) \ .execute() @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000, stop_max_attempt_number=25) def fire_batch_values_change(email: str, spreadsheet_id: str, changes: list({str: object})): http = get_authorized_http('drive', email=email) body = { 'valueInputOption': 'USER_ENTERED', 'data': changes} pprint(body) build('sheets', 'v4', http=http) \ .spreadsheets()\ .values()\ .batchUpdate(spreadsheetId=spreadsheet_id, body=body) \ .execute() @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000, stop_max_attempt_number=25) def fire_batch_spreadsheet_change(email: str, spreadsheet_id: str, changes: dict({str: object})): http = get_authorized_http('drive', email=email) body = {'requests': changes} service = build('sheets', 'v4', http=http)\ .spreadsheets()\ .batchUpdate(spreadsheetId=spreadsheet_id, body=body) service.execute() @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000, stop_max_attempt_number=25) def fire_spreadsheet_copy(email: str,src_workbook_id: str, dst_workbook_id: str, sheet_id: str): http = get_authorized_http('drive', email=email) body = {'destinationSpreadsheetId': dst_workbook_id} service = build('sheets', 'v4', http=http) \ .spreadsheets()\ .sheets()\ .copyTo(spreadsheetId=src_workbook_id, sheetId=sheet_id, body=body) return service.execute() def get_email_request(email): http = get_authorized_http('gmail', email) service = build('gmail', 'v1', http=http) return service def refresh_data_sheet(email, book_id, sheet_name, values): sheet_metadata = get_sheet_metadata(book_id, email, sheet_name) while not sheet_metadata: create_sheet(email, book_id, sheet_name) sheet_metadata = get_sheet_metadata(book_id, email, sheet_name) clear_sheet(email, book_id, sheet_metadata['sheetId']) write_values(email, book_id, sheet_name, values) def clear_sheet(email, book_id, sheet_id): body = { 'requests': [ { 'deleteRange': { 'range': { 'sheetId': sheet_id }, 'shiftDimension': "ROWS" } } ] } service = build("sheets", "v4", http=get_authorized_http('drive', email)). \ spreadsheets(). \ batchUpdate(spreadsheetId=book_id, body=body) service.execute() def get_file_by_name(email, file_name): files = get_all_files(email) possibles = [] for file in files: name = file['name'] if name == file_name: possibles.append(file) if not possibles or len(possibles) > 1: return None else: return possibles[0] def get_all_files(email): http = get_authorized_http('drive', email) service = build('drive', 'v3', http=http) files = service.files().list().execute() return files['files'] def get_authorized_http(credential_type, email=server_email): credentials = get_credentials(credential_type) delegated_credentials = credentials.create_delegated(email) http = httplib2.Http() return delegated_credentials.authorize(http) def get_gsuite_group_info(): http = get_authorized_http('admin') service = build("admin", "directory_v1", http=http) return service.groups().list(domain='mbihs.com').execute() def get_emp_group(user_email): """ Return list of groups user belongs to :param user_email: string :return: [string, string2, ...] """ group_email = [] http = get_authorized_http('admin') service = build("admin", "directory_v1", http=http) group_dict = service.groups().list(userKey=user_email).execute() if 'groups' in group_dict: group_list = group_dict['groups'] for dictionary in group_list: email = dictionary['email'] group_email.append(email) return group_email def add_google_group_user(user_email, team_email, is_admin): """Match user to google group based on team, as a member """ body = { "role": "MEMBER", # Role of member "email": user_email, # Email of member (Read-only) } http = get_authorized_http('admin') service = build("admin", "directory_v1", http=http) if is_admin == 'true': body['role'] = "OWNER" service.members().insert(groupKey=team_email, body=body).execute() def get_group_name_map(): test = get_gsuite_group_info() test_dict = test['groups'] gsuite_map = {} for group in test_dict: email = group['email'] team_name = group['name'] gsuite_map[team_name] = email return gsuite_map def check_user(user_email): http = get_authorized_http('admin') service = build("admin", "directory_v1", http=http) try: service.users().get(userKey=user_email).execute() return True except HttpError: return False def get_all_emails(): http = get_authorized_http('gmail') service = build("admin", "directory_v1", http=http) return service.users().list(domain='mbihs.com', maxResults=500, pageToken=None).execute() def send_email_to_multiple(users, subject, text): for user in users: send_email(server_email, user, subject, text) def send_email(from_user, to_user, subject, text, from_user_decorated=None): if not from_user_decorated: from_user_decorated = from_user message = MIMEText(text) message['to'] = to_user message['from'] = from_user_decorated message['subject'] = subject raw = base64.urlsafe_b64encode(message.as_bytes()) raw = raw.decode() body = {'raw': raw} http = get_authorized_http('gmail', from_user) service = build('gmail', 'v1', http=http) service.users().messages().send(userId=from_user, body=body).execute() def copy_sheet(email, master_sheet_id, master_workbook_id, target_workbook_id): body = { 'destinationSpreadsheetId': target_workbook_id } http = get_authorized_http('drive', email) service = build("sheets", "v4", http=http, discoveryServiceUrl=discovery_url) service.spreadsheets().sheets().copyTo( spreadsheetId=master_workbook_id, sheetId=master_sheet_id, body=body, ).execute() def delete_first_sheet_id(email, workbook_id): event.Event('event', { 'gsuite_task': 'started the deletion of the first workbook sheet', 'workbook_id': str(workbook_id), 'email': str(email) }) delete_sheet(email, workbook_id, 0) event.Event('event', { 'gsuite_task': 'completed the deletion of the first workbook sheet', 'workbook_id': str(workbook_id), 'email': str(email) }) def delete_sheet(email, workbook_id, sheet_id): body = { 'requests': [ { 'deleteSheet': { 'sheet_id': sheet_id } }, ] } http = get_authorized_http('drive', email) service = build("sheets", "v4", http=http, discoveryServiceUrl=discovery_url) service.spreadsheets().batchUpdate( spreadsheetId=workbook_id, body=body, ).execute() def request_add_sheet_create(request_body, sheet_name): request_body['requests'].append( { 'addSheet': { 'properties': { 'title': sheet_name } } } ) return request_body def request_add_sheet_delete(request_body, sheet_id): request_body['requests'].append( { 'deleteSheet': { 'sheet_id': sheet_id } } ) return request_body def create_sheet(email, workbook_id, sheet_name): event.Event('event', { 'gsuite_task': 'started the creation of a workbook sheet', 'workbook_id': str(workbook_id), 'email': str(email), 'sheet_name': str(sheet_name) }) body = { 'requests': [ { 'addSheet': { 'properties': { 'title': sheet_name } } }, ] } http = get_authorized_http('drive', email) service = build("sheets", "v4", http=http, discoveryServiceUrl=discovery_url) test = service.spreadsheets().batchUpdate( spreadsheetId=workbook_id, body=body, ).execute() sheet_id = test['replies'][0]['addSheet']['properties']['sheetId'] event.Event('event', { 'gsuite_task': 'finished the creation of a workbook sheet', 'workbook_id': str(workbook_id), 'email': str(email), 'sheet_name': str(sheet_name), 'written sheet id': str(sheet_id) }) return sheet_id def write_values(email, workbook_id, sheet_name, sheet_data): event.Event('event', { 'gsuite_task': 'started writing values to a workbook sheet', 'workbook_id': str(workbook_id), 'email': str(email), 'sheet_name': str(sheet_name), 'sheet_data': str(sheet_data) }) body = { 'valueInputOption': 'USER_ENTERED', 'data': { 'range': sheet_name, 'values': sheet_data } } http = get_authorized_http('drive', email) service = build("sheets", "v4", http=http, discoveryServiceUrl=discovery_url) test = service.spreadsheets().values().batchUpdate( spreadsheetId=workbook_id, body=body, ).execute() event.Event('event', { 'gsuite_task': 'finished writing values to a workbook sheet', 'workbook_id': str(workbook_id), 'email': str(email), 'sheet_name': str(sheet_name), 'sheet_data': str(sheet_data), 'write return': str(test) }) def create_workbook(email, workbook_name): event.Event('event', { 'task': 'gsuite_tasks', 'info': { 'message': 'started creating a workbook', 'email': str(email), 'workbook_name': str(workbook_name) } }) body = { 'mimeType': 'application/vnd.google-apps.spreadsheet', 'name': workbook_name, } http = get_authorized_http('drive', email) service = build("drive", "v3", http=http, discoveryServiceUrl=drive_discovery_url) response = service.files().create(body=body).execute() workbook_id = response['id'] event.Event('event', { 'task': 'gsuite_tasks', 'info': { 'message': 'finished creating a workbook', 'email': str(email), 'workbook_name': str(workbook_name), 'new_workbook_id': str(workbook_id) } }) return workbook_id def get_sheets(spreadsheet_id: str, email: str) -> dict({str: Resource}): sheets = {} sheet_names = [] spreadsheet = get_spreadsheet(spreadsheet_id, email=email) for sheet in spreadsheet['sheets']: sheet_name = sheet['properties']['title'] sheets[sheet_name] = {'properties': sheet} sheet_names.append(sheet_name) values = get_spreadsheet_values(spreadsheet_id, email, sheet_names) for sheet in values['valueRanges']: title = sheet['range'].split('!')[0].replace("'", '') sheets[title]['values'] = sheet return sheets def get_spreadsheet_values(spreadsheet_id, email, ranges): http = get_authorized_http('drive', email) service = build("sheets", "v4", http=http).spreadsheets()\ .values()\ .batchGet(spreadsheetId=spreadsheet_id, ranges=ranges) return service.execute() def get_sheet_update(email): http = get_authorized_http('drive', email) service = build("sheets", "v4", http=http).batchUpdate() return service def get_spreadsheet(spreadsheet_id, email): http = get_authorized_http('drive', email) service = build("sheets", "v4", http=http).spreadsheets().get(spreadsheetId=spreadsheet_id) spreadsheet = service.execute() return spreadsheet def get_sheet_metadata(spreadsheet_id, email, sheet_name): spreadsheet = get_spreadsheet(spreadsheet_id, email) sheets = spreadsheet['sheets'] for sheet in sheets: sheet_properties = sheet['properties'] if sheet_properties['title'] == sheet_name: return sheet_properties return None def get_sheet_values(email, workbook_id, sheet_name): event.Event('event', { 'gsuite_task': 'started the extraction of workbook data', 'workbook_id': str(workbook_id), 'email': str(email), 'sheet name': str(sheet_name) }) http = get_authorized_http('drive', email) service = build("sheets", "v4", http=http, discoveryServiceUrl=discovery_url) response = service.spreadsheets().values().get( spreadsheetId=workbook_id, range=str(sheet_name), ).execute() values = response['values'] event.Event('event', { 'gsuite_task': 'completed the extraction of workbook data', 'workbook_id': str(workbook_id), 'email': str(email), 'sheet name': str(sheet_name) }) return values # noinspection PyTypeChecker def get_credentials(credential_type): scopes = CREDENTIALS[credential_type]['scopes'] key_path = CREDENTIALS[credential_type]['key'] keyfile_string = open(key_path).read() keyfile_dict = ast.literal_eval(keyfile_string) credentials = ServiceAccountCredentials.from_json_keyfile_dict(keyfile_dict, scopes) return credentials
jkcubeta/algernon
src/overwatch/src/overwatch/alg_tasks/gsuite_tasks.py
Python
apache-2.0
15,666
import sys import os.path from pyquery import PyQuery as pq import time import common def getValues(url): print("getValues()") url = "https://{0}".format(url) print("Get URL: " + url) d = pq(url=url) list = d(".logostatam") obj = {} obj['site_id'] = common.getSiteId(url) if obj['site_id'] == None: obj['site_id'] = -1 obj['total_account'] = list[1].text_content() obj['active_account'] = 0 obj['total_deposit'] = list[2].text_content().replace("$ ", "") obj['total_withdraw'] = list[3].text_content().replace("$ ", "") obj['time'] = long(time.time()) * 1000 print("{0} - {1} - {2} {3}".format(obj['total_account'], obj['active_account'], obj['total_deposit'], obj['total_withdraw'], obj['time'])) common.insertSiteStat(obj) def run(): print "\n========== RUN vertexasset_com.run() ============" try : getValues("vertexasset.com") except Exception: pass
vietdh85/vh-utility
script/stat/vertexasset_com.py
Python
gpl-3.0
898
"""Backup methods and utilities""" import couchdb import logging import os import re import sys import shutil import subprocess as sp import time from datetime import datetime from taca.utils.config import CONFIG from taca.utils import filesystem, misc logger = logging.getLogger(__name__) class run_vars(object): """A simple variable storage class""" def __init__(self, run): self.abs_path = os.path.abspath(run) self.path, self.name = os.path.split(self.abs_path) self.name = self.name.split('.', 1)[0] self.zip = "{}.tar.gz".format(self.name) self.key = "{}.key".format(self.name) self.key_encrypted = "{}.key.gpg".format(self.name) self.zip_encrypted = "{}.tar.gz.gpg".format(self.name) class backup_utils(object): """A class object with main utility methods related to backing up""" def __init__(self, run=None): self.run = run self.fetch_config_info() self.host_name = os.getenv('HOSTNAME', os.uname()[1]).split('.', 1)[0] def fetch_config_info(self): """Try to fecth required info from the config file. Log and exit if any neccesary info is missing""" try: self.data_dirs = CONFIG['backup']['data_dirs'] self.archive_dirs = CONFIG['backup']['archive_dirs'] self.keys_path = CONFIG['backup']['keys_path'] self.gpg_receiver = CONFIG['backup']['gpg_receiver'] self.mail_recipients = CONFIG['mail']['recipients'] self.check_demux = CONFIG.get('backup', {}).get('check_demux', False) self.couch_info = CONFIG.get('statusdb') except KeyError as e: logger.error("Config file is missing the key {}, make sure it have all required information".format(str(e))) raise SystemExit def collect_runs(self, ext=None, filter_by_ext=False): """Collect runs from archive directories""" self.runs = [] if self.run: run = run_vars(self.run) if not re.match(filesystem.RUN_RE, run.name): logger.error("Given run {} did not match a FC pattern".format(self.run)) raise SystemExit self.runs.append(run) else: for adir in self.archive_dirs.values(): if not os.path.isdir(adir): logger.warn("Path {} does not exist or it is not a directory".format(adir)) return self.runs for item in os.listdir(adir): if filter_by_ext and not item.endswith(ext): continue elif item.endswith(ext): item = item.replace(ext, '') elif not os.path.isdir(item): continue if re.match(filesystem.RUN_RE, item) and item not in self.runs: self.runs.append(run_vars(os.path.join(adir, item))) def avail_disk_space(self, path, run): """Check the space on file system based on parent directory of the run""" # not able to fetch runtype use the max size as precaution, size units in GB illumina_run_sizes = {'hiseq' : 500, 'hiseqx' : 900, 'miseq' : 20} required_size = illumina_run_sizes.get(self._get_run_type(run), 900) * 2 # check for any ongoing runs and add up the required size accrdingly for ddir in self.data_dirs.values(): for item in os.listdir(ddir): if not re.match(filesystem.RUN_RE, item): continue if not os.path.exists(os.path.join(ddir, item, "RTAComplete.txt")): required_size += illumina_run_sizes.get(self._get_run_type(run), 900) # get available free space from the file system try: df_proc = sp.Popen(['df', path], stdout=sp.PIPE, stderr=sp.PIPE) df_out, df_err = df_proc.communicate() available_size = int(df_out.strip().split('\n')[-1].strip().split()[2])/1024/1024 except Exception, e: logger.error("Evaluation of disk space failed with error {}".format(e)) raise SystemExit if available_size < required_size: e_msg = "Required space for encryption is {}GB, but only {}GB available".format(required_size, available_size) subjt = "Low space for encryption - {}".format(self.host_name) logger.error(e_msg) misc.send_mail(subjt, e_msg, self.mail_recipients) raise SystemExit def file_in_pdc(self, src_file, silent=True): """Check if the given files exist in PDC""" # dsmc will return zero/True only when file exists, it returns # non-zero/False though cmd is execudted but file not found src_file_abs = os.path.abspath(src_file) try: sp.check_call(['dsmc', 'query', 'archive', src_file_abs], stdout=sp.PIPE, stderr=sp.PIPE) value = True except sp.CalledProcessError: value = False if not silent: msg = "File {} {} in PDC".format(src_file_abs, "exist" if value else "do not exist") logger.info(msg) return value def _get_run_type(self, run): """Returns run type based on the flowcell name""" run_type = '' try: if "ST-" in run: run_type = "hiseqx" elif "-" in run.split('_')[-1]: run_type = "miseq" else: run_type = "hiseq" except: logger.warn("Could not fetch run type for run {}".format(run)) return run_type def _call_commands(self, cmd1, cmd2=None, out_file=None, return_out=False, mail_failed=False, tmp_files=[]): """Call an external command(s) with atmost two commands per function call. Given 'out_file' is always used for the later cmd and also stdout can be return for the later cmd. In case of failure, the 'tmp_files' are removed""" if out_file: if not cmd2: stdout1 = open(out_file, 'w') else: stdout1 = sp.PIPE stdout2 = open(out_file, 'w') else: stdout1 = sp.PIPE stdout2 = sp.PIPE # calling the commands try: cmd1 = cmd1.split() p1 = sp.Popen(cmd1, stdout=stdout1, stderr=sp.PIPE) if cmd2: cmd2 = cmd2.split() p2 = sp.Popen(cmd2, stdin=p1.stdout, stdout=stdout2, stderr=sp.PIPE) p2_stat = p2.wait() p2_out, p2_err = p2.communicate() if not self._check_status(cmd2, p2_stat, p2_err, mail_failed, tmp_files): return (False, p2_err) if return_out else False p1_stat = p1.wait() p1_out, p1_err = p1.communicate() if not self._check_status(cmd1, p1_stat, p1_err, mail_failed, tmp_files): return (False, p1_err) if return_out else False if return_out: return (True, p2_out) if cmd2 else (True, p1_out) return True except Exception, e: raise e finally: if out_file: if not cmd2: stdout1.close() else: stdout2.close() def _check_status(self, cmd, status, err_msg, mail_failed, files_to_remove=[]): """Check if a subprocess status is success and log error if failed""" if status != 0: self._clean_tmp_files(files_to_remove) if mail_failed: subjt = "Command call failed - {}".format(self.host_name) e_msg = "Called cmd: {}\n\nError msg: {}".format(" ".join(cmd), err_msg) misc.send_mail(subjt, e_msg, self.mail_recipients) logger.error("Command '{}' failed with the error '{}'".format(" ".join(cmd),err_msg)) return False return True def _clean_tmp_files(self, files): """Remove the file is exist""" for fl in files: if os.path.exists(fl): os.remove(fl) def _log_pdc_statusdb(self, run): """Log the time stamp in statusDB if a file is succussfully sent to PDC""" try: run_vals = run.split('_') run_fc = "{}_{}".format(run_vals[0],run_vals[-1]) server = "http://{username}:{password}@{url}:{port}".format(url=self.couch_info['url'],username=self.couch_info['username'], password=self.couch_info['password'],port=self.couch_info['port']) couch = couchdb.Server(server) db = couch[self.couch_info['db']] fc_names = {e.key:e.id for e in db.view("names/name", reduce=False)} d_id = fc_names[run_fc] doc = db.get(d_id) doc['pdc_archived'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') db.save(doc) logger.info("Logged 'pdc_archived' timestamp for fc {} in statusdb doc '{}'".format(run, d_id)) except: logger.warn("Not able to log 'pdc_archived' timestamp for run {}".format(run)) @classmethod def encrypt_runs(cls, run, force): """Encrypt the runs that have been collected""" bk = cls(run) bk.collect_runs(ext=".tar.gz") logger.info("In total, found {} run(s) to be encrypted".format(len(bk.runs))) for run in bk.runs: run.flag = "{}.encrypting".format(run.name) run.dst_key_encrypted = os.path.join(bk.keys_path, run.key_encrypted) tmp_files = [run.zip_encrypted, run.key_encrypted, run.key, run.flag] logger.info("Encryption of run {} is now started".format(run.name)) # Check if there is enough space and exit if not bk.avail_disk_space(run.path, run.name) # Check if the run in demultiplexed if not force and bk.check_demux: if not misc.run_is_demuxed(run.name, bk.couch_info): logger.warn("Run {} is not demultiplexed yet, so skipping it".format(run.name)) continue logger.info("Run {} is demultiplexed and proceeding with encryption".format(run.name)) with filesystem.chdir(run.path): # skip run if already ongoing if os.path.exists(run.flag): logger.warn("Run {} is already being encrypted, so skipping now".format(run.name)) continue flag = open(run.flag, 'w').close() # zip the run directory if os.path.exists(run.zip): if os.path.isdir(run.name): logger.warn("Both run source and zipped archive exist for run {}, skipping run as precaution".format(run.name)) bk._clean_tmp_files([run.flag]) continue logger.info("Zipped archive already exist for run {}, so using it for encryption".format(run.name)) else: logger.info("Creating zipped archive for run {}".format(run.name)) if bk._call_commands(cmd1="tar -cf - {}".format(run.name), cmd2="pigz --fast -c -", out_file=run.zip, mail_failed=True, tmp_files=[run.zip, run.flag]): logger.info("Run {} was successfully compressed, so removing the run source directory".format(run.name)) shutil.rmtree(run.name) else: logger.warn("Skipping run {} and moving on".format(run.name)) continue # Remove encrypted file if already exists if os.path.exists(run.zip_encrypted): logger.warn(("Removing already existing encrypted file for run {}, this is a precaution " "to make sure the file was encrypted with correct key file".format(run.name))) bk._clean_tmp_files([run.zip_encrypted, run.key, run.key_encrypted, run.dst_key_encrypted]) # Generate random key to use as pasphrase if not bk._call_commands(cmd1="gpg --gen-random 1 256", out_file=run.key, tmp_files=tmp_files): logger.warn("Skipping run {} and moving on".format(run.name)) continue logger.info("Generated randon phrase key for run {}".format(run.name)) # Calculate md5 sum pre encryption if not force: logger.info("Calculating md5sum before encryption") md5_call, md5_out = bk._call_commands(cmd1="md5sum {}".format(run.zip), return_out=True, tmp_files=tmp_files) if not md5_call: logger.warn("Skipping run {} and moving on".format(run.name)) continue md5_pre_encrypt = md5_out.split()[0] # Encrypt the zipped run file logger.info("Encrypting the zipped run file") if not bk._call_commands(cmd1=("gpg --symmetric --cipher-algo aes256 --passphrase-file {} --batch --compress-algo " "none -o {} {}".format(run.key, run.zip_encrypted, run.zip)), tmp_files=tmp_files): logger.warn("Skipping run {} and moving on".format(run.name)) continue # Decrypt and check for md5 if not force: logger.info("Calculating md5sum after encryption") md5_call, md5_out = bk._call_commands(cmd1="gpg --decrypt --cipher-algo aes256 --passphrase-file {} --batch {}".format(run.key, run.zip_encrypted), cmd2="md5sum", return_out=True, tmp_files=tmp_files) if not md5_call: logger.warn("Skipping run {} and moving on".format(run.name)) continue md5_post_encrypt = md5_out.split()[0] if md5_pre_encrypt != md5_post_encrypt: logger.error(("md5sum did not match before {} and after {} encryption. Will remove temp files and " "move on".format(md5_pre_encrypt, md5_post_encrypt))) bk._clean_tmp_files(tmp_files) continue logger.info("Md5sum is macthing before and after encryption") # Encrypt and move the key file if bk._call_commands(cmd1="gpg -e -r {} -o {} {}".format(bk.gpg_receiver, run.key_encrypted, run.key), tmp_files=tmp_files): shutil.move(run.key_encrypted, run.dst_key_encrypted) else: logger.error("Encrption of key file failed, skipping run") continue bk._clean_tmp_files([run.zip, run.key, run.flag]) logger.info("Encryption of run {} is successfully done, removing zipped run file".format(run.name)) @classmethod def pdc_put(cls, run): """Archive the collected runs to PDC""" bk = cls(run) bk.collect_runs(ext=".tar.gz.gpg", filter_by_ext=True) logger.info("In total, found {} run(s) to send PDC".format(len(bk.runs))) for run in bk.runs: run.flag = "{}.archiving".format(run.name) run.dst_key_encrypted = os.path.join(bk.keys_path, run.key_encrypted) if run.path not in bk.archive_dirs.values(): logger.error(("Given run is not in one of the archive directories {}. Kindly move the run {} to appropriate " "archive dir before sending it to PDC".format(",".join(bk.archive_dirs.values()), run.name))) continue if not os.path.exists(run.dst_key_encrypted): logger.error("Encrypted key file {} is not found for file {}, skipping it".format(run.dst_key_encrypted, run.zip_encrypted)) continue #skip run if being encrypted if os.path.exists("{}.encrypting".format(run.name)): logger.warn("Run {} is currently being encrypted, so skipping now".format(run.name)) continue # skip run if already ongoing if os.path.exists(run.flag): logger.warn("Run {} is already being archived, so skipping now".format(run.name)) continue flag = open(run.flag, 'w').close() with filesystem.chdir(run.path): if bk.file_in_pdc(run.zip_encrypted, silent=False) or bk.file_in_pdc(run.dst_key_encrypted, silent=False): logger.warn("Seems like files realted to run {} already exist in PDC, check and cleanup".format(run.name)) bk._clean_tmp_files([run.flag]) continue logger.info("Sending file {} to PDC".format(run.zip_encrypted)) if bk._call_commands(cmd1="dsmc archive {}".format(run.zip_encrypted), tmp_files=[run.flag]): time.sleep(15) # give some time just in case 'dsmc' needs to settle if bk._call_commands(cmd1="dsmc archive {}".format(run.dst_key_encrypted), tmp_files=[run.flag]): time.sleep(5) # give some time just in case 'dsmc' needs to settle if bk.file_in_pdc(run.zip_encrypted) and bk.file_in_pdc(run.dst_key_encrypted): logger.info("Successfully sent file {} to PDC, removing file locally from {}".format(run.zip_encrypted, run.path)) if bk.couch_info: bk._log_pdc_statusdb(run.name) bk._clean_tmp_files([run.zip_encrypted, run.dst_key_encrypted, run.flag]) continue logger.warn("Sending file {} to PDC failed".format(run.zip_encrypted))
kate-v-stepanova/TACA
taca/backup/backup.py
Python
mit
18,146
# Django Rest Framework Imports from rest_framework import routers # Local Imports import messages import participants import misc import visits # Make Django Rest Framework Router router = routers.DefaultRouter() router.register(r'participants', participants.ParticipantViewSet,'participant') router.register(r'messages', messages.MessageViewSet,'message') router.register(r'visits', visits.VisitViewSet,'visit') router.register(r'scheduled-calls', misc.PendingCallViewSet,'pending-call') router.register(r'pending',misc.PendingViewSet,'pending')
tperrier/mwachx
contacts/serializers/__init__.py
Python
apache-2.0
550
import abc import os import six if six.PY3: import io file_types = (io.TextIOWrapper,) else: import abc file_types = (abc.types.FileType,) class Patch(object): def __init__(self, file, new_suffix=".new", backup_suffix=".old", read_mode="r", write_mode="w", auto_begin=True): if not isinstance(file, six.string_types + file_types): raise TypeError("file must be string or file object") self.file = file self.new_suffix = new_suffix self.backup_suffix = backup_suffix self.read_mode = read_mode self.write_mode = write_mode if auto_begin: self.begin() def begin(self): if isinstance(self.file, six.string_types): self.infile = open(self.file, self.read_mode) elif isinstance(self.file, file_types): self.infile = self.file self.write_mode = self.file.mode.replace("r", "w") else: raise TypeError("file must be string or file object") if self.backup_suffix: self.backupfile_name = self.infile.name+self.backup_suffix if os.path.isfile(self.backupfile_name): os.rename(self.backupfile_name, self.infile.name) newfile_name = self.infile.name + self.new_suffix self.newfile = open(newfile_name, self.write_mode) def __enter__(self): return self def __iter__(self): return self.infile.__iter__() def read(self, n=None): if n is None: return self.infile.read() else: return self.infile.read(n) def readline(self): return self.infile.readline() def readlines(self): return self.infile.readlines() def write(self, data): return self.newfile.write(data) def writelines(self, lines): return self.newfile.writelines(lines) def _close_all(self): try: self.infile.close() except IOError: pass try: self.newfile.close() except IOError: pass def close(self): self.commit() def commit(self): self._close_all() # if backup is set, make a backup if self.backup_suffix: os.rename(self.infile.name, self.backupfile_name) # move the new file to the orig # this should be atomic on POSIX os.rename(self.newfile.name, self.infile.name) def rollback(self): self._close_all() os.unlink(self.newfile.name) def __exit__(self, exc_type, exc_value, traceback): if exc_type: # exception was raised, ignore the new file self.rollback() else: # no exception, commit self.commit()
csernazs/patchwork
lib/patchwork/patch.py
Python
mit
2,846
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ 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. # # ESPResSo++ 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/>. """ ********************************* **espresso.FixedTripleAngleList** ********************************* """ from espresso import pmi import _espresso #import espresso from espresso.esutil import cxxinit class FixedTripleAngleListLocal(_espresso.FixedTripleAngleList): 'The (local) fixed triple list.' def __init__(self, storage): 'Local construction of a fixed triple list' #if pmi.workerIsActive(): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): cxxinit(self, _espresso.FixedTripleAngleList, storage) def add(self, pid1, pid2, pid3): 'add triple to fixed triple list' if pmi.workerIsActive(): return self.cxxclass.add(self, pid1, pid2, pid3) def addTriples(self, triplelist): """ Each processor takes the broadcasted triplelist and adds those triples whose first particle is owned by this processor. """ if pmi.workerIsActive(): for triple in triplelist: pid1, pid2, pid3 = triple self.cxxclass.add(self, pid1, pid2, pid3) def size(self): 'count number of Triples in GlobalTripleList, involves global reduction' if pmi.workerIsActive(): return self.cxxclass.size(self) def getTriples(self): 'return the triples of the GlobalTripleList' if pmi.workerIsActive(): triples = self.cxxclass.getTriples(self) return triples 'returns the list of (pid1, pid2, pid3, angle(123))' def getTriplesAngles(self): 'return the triples of the GlobalTripleList' if pmi.workerIsActive(): triples_angles = self.cxxclass.getTriplesAngles(self) return triples_angles def getAngle(self, pid1, pid2, pid3): if pmi.workerIsActive(): return self.cxxclass.getAngle(self, pid1, pid2, pid3) if pmi.isController: class FixedTripleAngleList(object): __metaclass__ = pmi.Proxy pmiproxydefs = dict( cls = 'espresso.FixedTripleAngleListLocal', localcall = [ "add" ], pmicall = [ "addTriples" ], pmiinvoke = ["getTriples", "getTriplesAngles", "size"] ) def getAngle(self, pid1, pid2, pid3 ): angles = pmi.invoke(self.pmiobject, 'getAngle', pid1, pid2, pid3 ) for i in angles: if( i != -1 ): return i
BackupTheBerlios/espressopp
src/FixedTripleAngleList.py
Python
gpl-3.0
3,321
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import tempfile import numpy as np import tensorflow as tf from tensorflow import flags from tensorflow.examples.tutorials.mnist import input_data from tensorflow.lite.python.op_hint import convert_op_hints_to_stubs from tensorflow.python.framework import test_util from tensorflow.python.platform import test from tensorflow.python.tools import optimize_for_inference_lib FLAGS = flags.FLAGS # Number of steps to train model. TRAIN_STEPS = 1 CONFIG = tf.ConfigProto(device_count={"GPU": 0}) class UnidirectionalSequenceRnnTest(test_util.TensorFlowTestCase): def __init__(self, *args, **kwargs): super(UnidirectionalSequenceRnnTest, self).__init__(*args, **kwargs) # Define constants # Unrolled through 28 time steps self.time_steps = 28 # Rows of 28 pixels self.n_input = 28 # Learning rate for Adam optimizer self.learning_rate = 0.001 # MNIST is meant to be classified in 10 classes(0-9). self.n_classes = 10 # Batch size self.batch_size = 16 # Rnn Units. self.num_units = 16 def setUp(self): super(UnidirectionalSequenceRnnTest, self).setUp() # Import MNIST dataset data_dir = tempfile.mkdtemp(dir=FLAGS.test_tmpdir) self.mnist = input_data.read_data_sets(data_dir, one_hot=True) def buildRnnLayer(self): return tf.keras.layers.StackedRNNCells([ tf.lite.experimental.nn.TfLiteRNNCell(self.num_units, name="rnn1"), tf.lite.experimental.nn.TfLiteRNNCell(self.num_units, name="rnn2") ]) def buildModel(self, rnn_layer, is_dynamic_rnn): # Weights and biases for output softmax layer. out_weights = tf.Variable( tf.random_normal([self.num_units, self.n_classes])) out_bias = tf.Variable(tf.random_normal([self.n_classes])) # input image placeholder x = tf.placeholder( "float", [None, self.time_steps, self.n_input], name="INPUT_IMAGE") # x is shaped [batch_size,time_steps,num_inputs] if is_dynamic_rnn: rnn_input = tf.transpose(x, perm=[1, 0, 2]) outputs, _ = tf.lite.experimental.nn.dynamic_rnn( rnn_layer, rnn_input, dtype="float32") outputs = tf.unstack(outputs, axis=0) else: rnn_input = tf.unstack(x, self.time_steps, 1) outputs, _ = tf.nn.static_rnn(rnn_layer, rnn_input, dtype="float32") # Compute logits by multiplying outputs[-1] of shape [batch_size,num_units] # by the softmax layer's out_weight of shape [num_units,n_classes] # plus out_bias prediction = tf.matmul(outputs[-1], out_weights) + out_bias output_class = tf.nn.softmax(prediction, name="OUTPUT_CLASS") return x, prediction, output_class def trainModel(self, x, prediction, output_class, sess): # input label placeholder y = tf.placeholder("float", [None, self.n_classes]) # Loss function loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y)) # Optimization opt = tf.train.AdamOptimizer( learning_rate=self.learning_rate).minimize(loss) # Initialize variables sess.run(tf.global_variables_initializer()) for _ in range(TRAIN_STEPS): batch_x, batch_y = self.mnist.train.next_batch( batch_size=self.batch_size, shuffle=False) batch_x = batch_x.reshape((self.batch_size, self.time_steps, self.n_input)) sess.run(opt, feed_dict={x: batch_x, y: batch_y}) def saveAndRestoreModel(self, rnn_layer, sess, saver, is_dynamic_rnn): """Saves and restores the model to mimic the most common use case. Args: rnn_layer: The rnn layer either a single rnn cell or a multi rnn cell. sess: Old session. saver: saver created by tf.train.Saver() is_dynamic_rnn: use dynamic_rnn or not. Returns: A tuple containing: - Input tensor of the restored model. - Prediction tensor of the restored model. - Output tensor, which is the softwmax result of the prediction tensor. - new session of the restored model. """ model_dir = tempfile.mkdtemp(dir=FLAGS.test_tmpdir) saver.save(sess, model_dir) # Reset the graph. tf.reset_default_graph() x, prediction, output_class = self.buildModel(rnn_layer, is_dynamic_rnn) new_sess = tf.Session(config=CONFIG) saver = tf.train.Saver() saver.restore(new_sess, model_dir) return x, prediction, output_class, new_sess def getInferenceResult(self, x, output_class, sess): b1, _ = self.mnist.train.next_batch(batch_size=1) sample_input = np.reshape(b1, (1, self.time_steps, self.n_input)) expected_output = sess.run(output_class, feed_dict={x: sample_input}) frozen_graph = tf.graph_util.convert_variables_to_constants( sess, sess.graph_def, [output_class.op.name]) return sample_input, expected_output, frozen_graph def tfliteInvoke(self, graph, test_inputs, outputs): tf.reset_default_graph() # Turn the input into placeholder of shape 1 tflite_input = tf.placeholder( "float", [1, self.time_steps, self.n_input], name="INPUT_IMAGE_LITE") tf.import_graph_def(graph, name="", input_map={"INPUT_IMAGE": tflite_input}) with tf.Session() as sess: curr = sess.graph_def curr = convert_op_hints_to_stubs(graph_def=curr) curr = optimize_for_inference_lib.optimize_for_inference( curr, ["INPUT_IMAGE_LITE"], ["OUTPUT_CLASS"], [tf.float32.as_datatype_enum]) converter = tf.lite.TFLiteConverter(curr, [tflite_input], [outputs]) tflite = converter.convert() interpreter = tf.lite.Interpreter(model_content=tflite) interpreter.allocate_tensors() input_index = interpreter.get_input_details()[0]["index"] interpreter.set_tensor(input_index, test_inputs) interpreter.invoke() output_index = interpreter.get_output_details()[0]["index"] result = interpreter.get_tensor(output_index) # Reset all variables so it will not pollute other inferences. interpreter.reset_all_variables() return result def testStaticRnnMultiRnnCell(self): sess = tf.Session(config=CONFIG) x, prediction, output_class = self.buildModel( self.buildRnnLayer(), is_dynamic_rnn=False) self.trainModel(x, prediction, output_class, sess) saver = tf.train.Saver() x, prediction, output_class, new_sess = self.saveAndRestoreModel( self.buildRnnLayer(), sess, saver, is_dynamic_rnn=False) test_inputs, expected_output, frozen_graph = self.getInferenceResult( x, output_class, new_sess) result = self.tfliteInvoke(frozen_graph, test_inputs, output_class) self.assertTrue(np.allclose(expected_output, result, rtol=1e-6, atol=1e-2)) @test_util.enable_control_flow_v2 def testDynamicRnnMultiRnnCell(self): sess = tf.Session(config=CONFIG) x, prediction, output_class = self.buildModel( self.buildRnnLayer(), is_dynamic_rnn=True) self.trainModel(x, prediction, output_class, sess) saver = tf.train.Saver() x, prediction, output_class, new_sess = self.saveAndRestoreModel( self.buildRnnLayer(), sess, saver, is_dynamic_rnn=True) test_inputs, expected_output, frozen_graph = self.getInferenceResult( x, output_class, new_sess) result = self.tfliteInvoke(frozen_graph, test_inputs, output_class) self.assertTrue(np.allclose(expected_output, result, rtol=1e-6, atol=1e-2)) if __name__ == "__main__": test.main()
ageron/tensorflow
tensorflow/lite/experimental/examples/lstm/unidirectional_sequence_rnn_test.py
Python
apache-2.0
8,216
# -*- coding: utf-8 -*- """The Viper analysis plugin CLI arguments helper.""" from plaso.analysis import viper from plaso.cli.helpers import interface from plaso.cli.helpers import manager from plaso.lib import errors class ViperAnalysisArgumentsHelper(interface.ArgumentsHelper): """Viper analysis plugin CLI arguments helper.""" NAME = 'viper' CATEGORY = 'analysis' DESCRIPTION = 'Argument helper for the Viper analysis plugin.' _DEFAULT_HASH = 'sha256' _DEFAULT_HOST = 'localhost' _DEFAULT_PORT = 8080 _DEFAULT_PROTOCOL = 'http' @classmethod def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group. """ argument_group.add_argument( '--viper-hash', '--viper_hash', dest='viper_hash', type=str, action='store', choices=viper.ViperAnalyzer.SUPPORTED_HASHES, default=cls._DEFAULT_HASH, metavar='HASH', help=( 'Type of hash to use to query the Viper server, the default is: ' '{0:s}. Supported options: {1:s}').format( cls._DEFAULT_HASH, ', '.join( viper.ViperAnalyzer.SUPPORTED_HASHES))) argument_group.add_argument( '--viper-host', '--viper_host', dest='viper_host', type=str, action='store', default=cls._DEFAULT_HOST, metavar='HOST', help=( 'Hostname of the Viper server to query, the default is: ' '{0:s}'.format(cls._DEFAULT_HOST))) argument_group.add_argument( '--viper-port', '--viper_port', dest='viper_port', type=int, action='store', default=cls._DEFAULT_PORT, metavar='PORT', help=( 'Port of the Viper server to query, the default is: {0:d}.'.format( cls._DEFAULT_PORT))) argument_group.add_argument( '--viper-protocol', '--viper_protocol', dest='viper_protocol', type=str, choices=viper.ViperAnalyzer.SUPPORTED_PROTOCOLS, action='store', default=cls._DEFAULT_PROTOCOL, metavar='PROTOCOL', help=( 'Protocol to use to query Viper, the default is: {0:s}. ' 'Supported options: {1:s}').format( cls._DEFAULT_PROTOCOL, ', '.join( viper.ViperAnalyzer.SUPPORTED_PROTOCOLS))) # pylint: disable=arguments-differ @classmethod # pylint: disable=arguments-differ def ParseOptions(cls, options, analysis_plugin): """Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. BadConfigOption: when unable to connect to Viper instance. """ if not isinstance(analysis_plugin, viper.ViperAnalysisPlugin): raise errors.BadConfigObject( 'Analysis plugin is not an instance of ViperAnalysisPlugin') lookup_hash = cls._ParseStringOption( options, 'viper_hash', default_value=cls._DEFAULT_HASH) analysis_plugin.SetLookupHash(lookup_hash) host = cls._ParseStringOption( options, 'viper_host', default_value=cls._DEFAULT_HOST) analysis_plugin.SetHost(host) port = cls._ParseNumericOption( options, 'viper_port', default_value=cls._DEFAULT_PORT) analysis_plugin.SetPort(port) protocol = cls._ParseStringOption( options, 'viper_protocol', default_value=cls._DEFAULT_PROTOCOL) protocol = protocol.lower().strip() analysis_plugin.SetProtocol(protocol) if not analysis_plugin.TestConnection(): raise errors.BadConfigOption( 'Unable to connect to Viper {0:s}:{1:d}'.format(host, port)) manager.ArgumentHelperManager.RegisterHelper(ViperAnalysisArgumentsHelper)
Onager/plaso
plaso/cli/helpers/viper_analysis.py
Python
apache-2.0
4,005
#!/usr/bin/env python ''' Count frequency of each n-gram and save to Pickle file. The n-gram frequencies are held in an in-memory dict, so this script can only be used if the vocab is small (e.g. POS tags). For unigrams, see also: BillionWordImputation/build/Release/count_unigrams ''' import sys, argparse from util import ngram_frequencies def opts(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-n', '--order', type=int, required=True, help='Order of model to count') return parser if __name__ == "__main__": args = opts().parse_args() counts = ngram_frequencies(sys.stdin, args.order) for ngram, freq in counts.iteritems(): print '%s\t%s' % (' '.join(ngram), freq)
timpalpant/KaggleBillionWordImputation
scripts/count_ngrams.py
Python
gpl-3.0
744
# vim:set ts=8 sw=2 sts=2 et: """A command line interface for the wavemaker module.""" import argparse import wavemaker from wavemaker import signals def parse_command_line_arguments(): """Parse command line arguments. Returns: An argparse.Namespace object """ parser = argparse.ArgumentParser( description='Generate WAVE files.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'output_path', help='The path to the resulting WAVE file') parser.add_argument( '--waveform', choices=signals.SignalFactory.WAVEFORMS, default='sine', help='The shape of the signal being generated') parser.add_argument( '--frequency', type=float, default=440.0, help='The oscillating rate of the wave. A non-negative float, in Hz') parser.add_argument( '--amplitude', type=float, default=1.0, help='The amplitude of the wave. A float between 0.0 and 1.0') parser.add_argument( '--duration', type=float, default=1.0, help='The time duration of the signal. A non-negative float, in seconds') parser.add_argument( '--sample_rate', type=int, default=44100, help='The number of samples per second. A non-negative int, in Hz') parser.add_argument( '--sample_size', type=int, choices=[16], default=16, help='The number of bits used to store each sample') return parser.parse_args() def main(): """The command line entry point for wavemaker.""" args = parse_command_line_arguments() wavemaker.write_wave_file(args.output_path, args.waveform, args.frequency, args.amplitude, args.duration, args.sample_rate, args.sample_size)
serban/wavemaker
wavemaker/cli.py
Python
mit
1,766
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class RAgdex(RPackage): """A tool to evaluate agreement of differential expression for cross-species genomics.""" homepage = "http://bioconductor.org/packages/AGDEX/" url = "https://git.bioconductor.org/packages/AGDEX" version('1.24.0', git='https://git.bioconductor.org/packages/AGDEX', commit='29c6bcfa6919a5c6d8bcb36b44e75145a60ce7b5') depends_on('r@3.4.0:3.4.9', when='@1.24.0') depends_on('r-biobase', type=('build', 'run')) depends_on('r-gseabase', type=('build', 'run'))
skosukhin/spack
var/spack/repos/builtin/packages/r-agdex/package.py
Python
lgpl-2.1
1,775
# Copyright 2014 Cloudera 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 unittest import pytest import ibis import ibis.expr.types as ir from ibis.tests.expr.mocks import MockBackend from ibis.tests.util import assert_equal def test_warns_on_deprecated_import(): with pytest.warns(FutureWarning, match=r"ibis\.expr\.analytics"): import ibis.expr.analytics # noqa: F401 class TestAnalytics(unittest.TestCase): def setUp(self): self.con = MockBackend() self.alltypes = self.con.table('functional_alltypes') def test_category_project(self): t = self.alltypes tier = t.double_col.bucket([0, 50, 100]).name('tier') expr = t[tier, t] assert isinstance(expr.tier, ir.CategoryColumn) def test_bucket(self): d = self.alltypes.double_col bins = [0, 10, 50, 100] expr = d.bucket(bins) assert isinstance(expr, ir.CategoryColumn) assert expr.op().nbuckets == 3 expr = d.bucket(bins, include_over=True) assert expr.op().nbuckets == 4 expr = d.bucket(bins, include_over=True, include_under=True) assert expr.op().nbuckets == 5 def test_bucket_error_cases(self): d = self.alltypes.double_col self.assertRaises(ValueError, d.bucket, []) self.assertRaises(ValueError, d.bucket, [1, 2], closed='foo') # it works! d.bucket([10], include_under=True, include_over=True) self.assertRaises(ValueError, d.bucket, [10]) self.assertRaises(ValueError, d.bucket, [10], include_under=True) self.assertRaises(ValueError, d.bucket, [10], include_over=True) def test_histogram(self): d = self.alltypes.double_col self.assertRaises(ValueError, d.histogram, nbins=10, binwidth=5) self.assertRaises(ValueError, d.histogram) self.assertRaises(ValueError, d.histogram, 10, closed='foo') def test_topk_analysis_bug(self): # GH #398 airlines = ibis.table( [('dest', 'string'), ('origin', 'string'), ('arrdelay', 'int32')], 'airlines', ) dests = ['ORD', 'JFK', 'SFO'] t = airlines[airlines.dest.isin(dests)] delay_filter = t.origin.topk(10, by=t.arrdelay.mean()) filtered = t.filter([delay_filter]) post_pred = filtered.op().predicates[0] assert delay_filter.to_filter().equals(post_pred) def test_topk_function_late_bind(self): # GH #520 airlines = ibis.table( [('dest', 'string'), ('origin', 'string'), ('arrdelay', 'int32')], 'airlines', ) expr1 = airlines.dest.topk(5, by=lambda x: x.arrdelay.mean()) expr2 = airlines.dest.topk(5, by=airlines.arrdelay.mean()) assert_equal(expr1.to_aggregation(), expr2.to_aggregation())
cloudera/ibis
ibis/tests/expr/test_analytics.py
Python
apache-2.0
3,341
#!/usr/bin/env python3 # # Randomize the (X,Y) position of each X-ray photon events according # to a Gaussian distribution of given sigma. # # References: # [1] G. Scheellenberger, T.H. Reiprich, L. Lovisari, J. Nevalainen & L. David # 2015, A&A, 575, A30 # # # Aaron LI # Created: 2016-03-24 # Updated: 2016-03-24 # from astropy.io import fits import numpy as np import os import sys import datetime import argparse CHANDRA_ARCSEC_PER_PIXEL = 0.492 def randomize_events(infile, outfile, sigma, clobber=False): """ Randomize the position (X,Y) of each X-ray event according to a specified size/sigma Gaussian distribution. """ sigma_pix = sigma / CHANDRA_ARCSEC_PER_PIXEL evt_fits = fits.open(infile) evt_table = evt_fits[1].data # (X,Y) physical coordinate evt_x = evt_table["x"] evt_y = evt_table["y"] rand_x = np.random.normal(scale=sigma_pix, size=evt_x.shape)\ .astype(evt_x.dtype) rand_y = np.random.normal(scale=sigma_pix, size=evt_y.shape)\ .astype(evt_y.dtype) evt_x += rand_x evt_y += rand_y # Add history to FITS header evt_hdr = evt_fits[1].header evt_hdr.add_history("TOOL: %s @ %s" % ( os.path.basename(sys.argv[0]), datetime.datetime.utcnow().isoformat())) evt_hdr.add_history("COMMAND: %s" % " ".join(sys.argv)) evt_fits.writeto(outfile, clobber=clobber, checksum=True) def main(): parser = argparse.ArgumentParser( description="Randomize the (X,Y) of each X-ray event") parser.add_argument("infile", help="input event file") parser.add_argument("outfile", help="output randomized event file") parser.add_argument("-s", "--sigma", dest="sigma", required=True, type=float, help="sigma/size of the Gaussian distribution used" + \ "to randomize the position of events (unit: arcsec)") parser.add_argument("-C", "--clobber", dest="clobber", action="store_true", help="overwrite output file if exists") args = parser.parse_args() randomize_events(args.infile, args.outfile, sigma=args.sigma, clobber=args.clobber) if __name__ == "__main__": main()
liweitianux/atoolbox
astro/chandra/randomize_events.py
Python
mit
2,207
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( clean_html, int_or_none, js_to_json, parse_iso8601, ) class NetzkinoIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?netzkino\.de/\#!/(?P<category>[^/]+)/(?P<id>[^/]+)' _TEST = { 'url': 'http://www.netzkino.de/#!/scifikino/rakete-zum-mond', 'md5': '92a3f8b76f8d7220acce5377ea5d4873', 'info_dict': { 'id': 'rakete-zum-mond', 'ext': 'mp4', 'title': 'Rakete zum Mond (Endstation Mond, Destination Moon)', 'comments': 'mincount:3', 'description': 'md5:1eddeacc7e62d5a25a2d1a7290c64a28', 'upload_date': '20120813', 'thumbnail': 're:https?://.*\.jpg$', 'timestamp': 1344858571, 'age_limit': 12, }, } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) category_id = mobj.group('category') video_id = mobj.group('id') api_url = 'http://api.netzkino.de.simplecache.net/capi-2.0a/categories/%s.json?d=www' % category_id api_info = self._download_json(api_url, video_id) info = next( p for p in api_info['posts'] if p['slug'] == video_id) custom_fields = info['custom_fields'] production_js = self._download_webpage( 'http://www.netzkino.de/beta/dist/production.min.js', video_id, note='Downloading player code') avo_js = self._search_regex( r'window\.avoCore\s*=.*?urlTemplate:\s*(\{.*?"\})', production_js, 'URL templates') templates = self._parse_json( avo_js, video_id, transform_source=js_to_json) suffix = { 'hds': '.mp4/manifest.f4m', 'hls': '.mp4/master.m3u8', 'pmd': '.mp4', } film_fn = custom_fields['Streaming'][0] formats = [{ 'format_id': key, 'ext': 'mp4', 'url': tpl.replace('{}', film_fn) + suffix[key], } for key, tpl in templates.items()] self._sort_formats(formats) comments = [{ 'timestamp': parse_iso8601(c.get('date'), delimiter=' '), 'id': c['id'], 'author': c['name'], 'html': c['content'], 'parent': 'root' if c.get('parent', 0) == 0 else c['parent'], } for c in info.get('comments', [])] return { 'id': video_id, 'formats': formats, 'comments': comments, 'title': info['title'], 'age_limit': int_or_none(custom_fields.get('FSK')[0]), 'timestamp': parse_iso8601(info.get('date'), delimiter=' '), 'description': clean_html(info.get('content')), 'thumbnail': info.get('thumbnail'), 'playlist_title': api_info.get('title'), 'playlist_id': category_id, }
HyShai/youtube-dl
youtube_dl/extractor/netzkino.py
Python
unlicense
2,975
"""Dependency tracking for checkpointable objects.""" # 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. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.eager import def_function from tensorflow.python.eager import function as defun from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.training.checkpointable import base from tensorflow.python.training.checkpointable import data_structures from tensorflow.python.util import tf_contextlib # global _RESOURCE_TRACKER_STACK _RESOURCE_TRACKER_STACK = [] class NotCheckpointable(object): """Marks instances of child classes as unsaveable using an object-based API. Useful for marking objects which would otherwise look checkpointable because of inheritance (e.g. through `Layer`) as not checkpointable. Inheriting from `NotCheckpointable` does not prevent an object from being assigned to any attributes, but will throw an error on save/restore. """ pass class AutoCheckpointable(base.Checkpointable): """Manages dependencies on other objects. `Checkpointable` objects may have dependencies: other `Checkpointable` objects which should be saved if the object declaring the dependency is saved. A correctly saveable program has a dependency graph such that if changing a global variable affects an object (e.g. changes the behavior of any of its methods) then there is a chain of dependencies from the influenced object to the variable. Dependency edges have names, and are created implicitly when a `Checkpointable` object is assigned to an attribute of another `Checkpointable` object. For example: ``` obj = Checkpointable() obj.v = ResourceVariable(0.) ``` The `Checkpointable` object `obj` now has a dependency named "v" on a variable. `Checkpointable` objects may specify `Tensor`s to be saved and restored directly (e.g. a `Variable` indicating how to save itself) rather than through dependencies on other objects. See `Checkpointable._gather_saveables_for_checkpoint` for details. """ def __setattr__(self, name, value): """Support self.foo = checkpointable syntax.""" if getattr(self, "_setattr_tracking", True): value = data_structures.sticky_attribute_assignment( checkpointable=self, value=value, name=name) super(AutoCheckpointable, self).__setattr__(name, value) def __delattr__(self, name): self._maybe_initialize_checkpointable() if name in self._unconditional_dependency_names: del self._unconditional_dependency_names[name] for index, (dep_name, _) in enumerate( self._unconditional_checkpoint_dependencies): if dep_name == name: del self._unconditional_checkpoint_dependencies[index] break super(AutoCheckpointable, self).__delattr__(name) def _no_dependency(self, value): """Override to allow CheckpointableBase to disable dependency tracking.""" return data_structures.NoDependency(value) def _list_functions_for_serialization(self): """Return a dict of `Function`s of a checkpointable.""" functions = dict() for attribute_name in dir(self): try: attribute_value = getattr(self, attribute_name, None) except Exception: # pylint: disable=broad-except # We really don't want to throw an exception just because some object's # attribute accessor is broken. attribute_value = None if isinstance(attribute_value, (def_function.Function, defun.ConcreteFunction)): functions[attribute_name] = attribute_value return functions class ResourceTracker(object): """An object that tracks a list of resources.""" def __init__(self): self._resources = [] @property def resources(self): return self._resources def add_resource(self, resource): self._resources.append(resource) @tf_contextlib.contextmanager def resource_tracker_scope(resource_tracker): """A context to manage resource trackers. Use this in order to collect up all resources created within a block of code. Example usage: ```python resource_tracker = ResourceTracker() with resource_tracker_scope(resource_tracker): resource = TrackableResource() assert resource_tracker.resources == [resource] Args: resource_tracker: The passed in ResourceTracker object Yields: A scope in which the resource_tracker is active. """ global _RESOURCE_TRACKER_STACK old = list(_RESOURCE_TRACKER_STACK) _RESOURCE_TRACKER_STACK.append(resource_tracker) try: yield finally: _RESOURCE_TRACKER_STACK = old class TrackableResource(base.Checkpointable): """Base class for all resources that need to be tracked.""" def __init__(self): global _RESOURCE_TRACKER_STACK for resource_tracker in _RESOURCE_TRACKER_STACK: resource_tracker.add_resource(self) self._resource_handle = None def create_resource(self): """A function that creates a resource handle.""" raise NotImplementedError("TrackableResource.create_resource not " "implemented.") def initialize(self): """A function that initializes the resource. Optional.""" pass @property def resource_handle(self): """Returns the resource handle associated with this Resource.""" if self._resource_handle is None: self._resource_handle = self.create_resource() return self._resource_handle class TrackableAsset(base.Checkpointable): """Base class for asset files which need to be tracked.""" def __init__(self, path): """Record the full path to the asset.""" # The init_scope prevents functions from capturing `path` in an # initialization graph, since it is transient and should not end up in a # serialized function body. with ops.init_scope(): self._path = ops.internal_convert_to_tensor(path, dtype=dtypes.string, name="asset_path") @property def asset_path(self): """Fetch the current asset path.""" return self._path ops.register_tensor_conversion_function( TrackableAsset, lambda asset, **kw: ops.internal_convert_to_tensor(asset.asset_path, **kw))
jendap/tensorflow
tensorflow/python/training/checkpointable/tracking.py
Python
apache-2.0
6,960
# Network Security Spring 2015 Assignment 1 # Programming problem # Roberto Amorim - rja2139 import argparse import socket import os.path # Here I take care of the command line arguments parser = argparse.ArgumentParser(description='Server that holds encrypted data until client requests it.', add_help=True) parser.add_argument('--port1', dest = 'cl1Port', required = True, help = 'Port for client 1') parser.add_argument('--port2', dest = 'cl2Port', required = True, help = 'Port for client 2') parser.add_argument('--mode', dest = 'mode', required = True, help = 'Server mode (t or u)') args = parser.parse_args() # Here I validate the client ports if args.cl1Port.isdigit(): port1 = int(args.cl1Port) if port1 > 65535: print "ERROR: Client 1 port number is outside the acceptable range! (0-65535)" exit(1) else: print "ERROR: Client 1 port must be a number!" exit (1) if args.cl2Port.isdigit(): port2 = int(args.cl2Port) if port2 > 65535: print "ERROR: Client 2 port number is outside the acceptable range! (0-65535)" exit(1) else: print "ERROR: Client 2 port must be a number!" exit (1) if port1 == port2: print "ERROR: The client ports must be different!" exit (1) #And now I validate the mode if args.mode != "t" and args.mode != "u": print "ERROR: the only acceptable values for mode are t and u" exit (1) ## All input validated, I can start working! # First I receive the signature and encrypted file from client 1 sock = socket.socket() try: sock.bind(("localhost", port1)) except: print "Error binding to the requested port " + str(port1) + ". Do you have permission to bind to it?" exit(1) sock.listen(5) # The first connection contains the signature client1sock, client1addr = sock.accept() print "Client 1 connected from " + client1addr[0] signature = client1sock.recv(1024) print "Signature received from client 1" client1sock.close() client1sock, client1addr = sock.accept() try: file = open("ServerTempFile", 'wb') except IOError: print "Could not write encrypted file to current folder. Please run the script from a folder you have write access to." exit (1) while True: data = client1sock.recv(1024) # We get 1kb at a time if not data: # Until data stops arriving print "Encrypted file arrived from client 1" break file.write(data) client1sock.close() sock.close() file.close() # I now have the encrypted file and the signature, so I send both to client 2 ## Remember I have to send the actual file or a fake file depending on the server mode if args.mode == "t": sending = "ServerTempFile" else: sending = "serverdata" sock = socket.socket() try: sock.bind(("localhost", port2)) except: print "Error binding to the requested port " + str(port2) + ". Do you have permission to bind to it?" os.remove("ServerTempFile") #cleanup exit(1) sock.listen(5) # First I send the signature client2sock, client2addr = sock.accept() print "Client 2 connected from " + client2addr[0] client2sock.send(signature) client2sock.close() # Then I send the file - the encrypted one, or the fake one client2sock, client2addr = sock.accept() file = open(sending, 'rb') while True: data = file.read(1024) #I read/send the file 1024 bytes at a time if not data: break # EOF client2sock.send(data) print "File " + sending + " sent to client 2" file.close() os.remove("ServerTempFile") client2sock.close() sock.close() print "Server completed all its tasks successfully. Exiting..." exit()
rjamorim/netsec-hw1
server.py
Python
unlicense
3,585
""" Chat service """ from smserver import event from smserver import messaging def send_message_token(token, message, source=None): """ Send a chat message to the given target :param str token: target of the message (token of the connection) :param str message: Message to send :param str source: token which have send the event """ msg = event.Event( kind=event.EventKind.chat_message, data={ "source": source, "message": message, "target": {"type": "token", "value": token}, "type": "chat" }, token=source, ) messaging.send(msg) def send_message_room(room_id, message, source=None): """ Send a chat message to the given target :param room: room target of the message :type room: smserver.models.room.Room :param str message: Message to send :param str source: token which have send the event """ msg = event.Event( kind=event.EventKind.chat_message, data={ "source": source, "message": message, "target": {"type": "room", "value": room_id}, "type": "chat" }, room_id=room_id, token=source, ) messaging.send(msg)
ningirsu/stepmania-server
smserver/services/chat.py
Python
mit
1,301
#!/usr/bin/python import sys, os, urllib, argparse, base64, time, threading, re from gi.repository import Gtk, WebKit, Notify webView = None def refresh(widget, event): global webView webView.reload() window_title = '' def HandleTitleChanged(webview, title): global window_title window_title = title parent = webview while parent.get_parent() != None: parent = webview.get_parent() parent.set_title(title) return True def HandleCreateWebView(webview, frame): info = Gtk.Window() info.set_default_size(1000, 700) child = WebKit.WebView() child.connect('create-web-view', HandleCreateWebView) child.connect('close-web-view', HandleCloseWebView) child.connect('navigation-policy-decision-requested', HandleNavigationRequested) #child.connect('notify::title', HandleTitleChanged) info.set_title('') info.add(child) info.show_all() return child def HandleCloseWebView(webview): parent = webview while parent.get_parent() != None: parent = webview.get_parent() parent.destroy() def HandleNewWindowPolicyDecisionRequested(webview, frame, request, navigation_action, policy_decision): if '&URL=' in request.get_uri(): os.system('xdg-open "%s"' % urllib.unquote(request.get_uri().split('&URL=')[1]).decode('utf8')) def HandleNavigationRequested(webview, frame, request, navigation_action, policy_decision): if '&URL=' in request.get_uri(): HandleCloseWebView(webview) return 1 prefills = {} submit = False ignore_submit = [] def prefill_password(webview, frame): global prefills, submit should_ignore_submit = False dom = webview.get_dom_document() forms = dom.get_forms() for i in range(0, forms.get_length()): form = forms.item(i) elements = form.get_elements() is_form_modified = False for j in range(0, elements.get_length()): element = elements.item(j) element_name = element.get_name() if element_name in ignore_submit: should_ignore_submit = True for key in prefills.keys(): if element_name == key: if prefills[key].lower() == 'true': element.set_checked(True) is_form_modified = True else: element.set_value(prefills[key]) is_form_modified = True if is_form_modified and submit and not should_ignore_submit: form.submit() def HandleMimeType(webview, frame, request, mimetype, policy_decision): print 'Requested decision for mimetype:', mimetype return True stop_threads = False search_notifys = [] def SearchNotify(webview): global stop_threads global window_title global search_notifys while True: if stop_threads: break dom = webview.get_dom_document() if not dom: continue body = dom.get_body() if not body: continue body_html = body.get_inner_html() if not body_html: continue for notice in search_notifys: msgs = list(set(re.findall(notice, body_html))) if len(msgs) > 0: for msg in msgs: Notify.init(window_title) msg_notify = Notify.Notification.new(window_title, msg, "dialog-information") msg_notify.show() time.sleep(2) # Don't duplicate the notification time.sleep(2) if __name__ == "__main__": parser_epilog = ("Example:\n\n" "./simple_browse.py https://owa.example.com --useragent=\"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0\" --stylesheet=~/simple_browse/sample_styles/owa_style.css --username=<webmail username> --b64pass=\"<base64 encoded password>\" --forminput=trusted:true --submit --notify=PHNwYW4gY2xhc3M9Im53SXRtVHh0U2JqIj4oW1x3IF0rKTwvc3Bhbj4=\n\n" "This command will open Outlook Web Access, set the user agent to allow it to \nload using pipelight (for silverlight support), login to webmail, then apply a \ncustom css style to make webmail look like a desktop app. When new emails\narrive, notification will be sent to gnome-shell.\n") parser = argparse.ArgumentParser(description="Simple Browser: A simple webkit browser written in Python", epilog=parser_epilog, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("url") parser.add_argument("--useragent", help="An optional user agent to apply to the main page") parser.add_argument("--stylesheet", help="An optional stylesheet to apply to the main page") parser.add_argument("--username", help="A username we'll try to use to sign in") parser.add_argument("--password", help="A password for signing in") parser.add_argument("--b64pass", help="An alternative b64 encoded password for sign on") parser.add_argument("--forminput", help="A form field name and value to prefill (seperated by a colon). Only one value for each key is allowed.", action='append') parser.add_argument("--submit", help="Submit the filled form when we've finished entering values", action="store_true") parser.add_argument("--ignore-submit", help="Ignore the submit if the form contains this key", action='append') parser.add_argument("--title", help="Title for the window") parser.add_argument("--notify", help="A regex search string, base64 encoded, which will display a notification when found, example: <span class=\"nwItmTxtSbj\">([\w ]+)</span>", action='append') args = parser.parse_args() url = args.url user_agent = None if args.useragent: user_agent = args.useragent stylesheet = None if args.stylesheet: stylesheet = 'file://localhost%s' % os.path.abspath(args.stylesheet) if args.username: prefills['username'] = args.username if args.b64pass: prefills['password'] = base64.b64decode(args.b64pass) elif args.password: prefills['password'] = args.password if args.submit: submit = True if args.forminput: for field in args.forminput: key, value = field.split(':') if key in prefills: parser.print_help() exit(1) prefills[key] = value if args.ignore_submit: ignore_submit.extend(args.ignore_submit) if args.notify: for notice in args.notify: search_notifys.append(base64.b64decode(notice)) win = Gtk.Window() scrolled = Gtk.ScrolledWindow() win.set_default_size(1500, 900) webView = WebKit.WebView() webView.load_uri(url) overlay = Gtk.Overlay() overlay.add(webView) # Apply Settings settings = WebKit.WebSettings() if user_agent: settings.set_property('user-agent', user_agent) settings.set_property('enable-spell-checking', True) if stylesheet: settings.set_property('user-stylesheet-uri', stylesheet) webView.set_settings(settings) # Add Signal handlers to the webview webView.connect('create-web-view', HandleCreateWebView) webView.connect('close-web-view', HandleCloseWebView) webView.connect('new-window-policy-decision-requested', HandleNewWindowPolicyDecisionRequested) webView.connect('navigation-policy-decision-requested', HandleNavigationRequested) #webView.connect('notify::title', HandleTitleChanged) webView.connect('mime-type-policy-decision-requested', HandleMimeType) webView.connect('load-finished', prefill_password) win.set_title('') # Add the Refresh button fixed = Gtk.Fixed() fixed.set_halign(Gtk.Align.START) fixed.set_valign(Gtk.Align.START) overlay.add_overlay(fixed) fixed.show() image = Gtk.Image() image.set_from_pixbuf(Gtk.IconTheme().load_icon('gtk-refresh', 10, 0)) imgevent = Gtk.EventBox() imgevent.add(image) imgevent.connect('button-press-event', refresh) fixed.put(imgevent, 10, 10) win.add(scrolled) scrolled.add(overlay) win.show_all() win.connect('destroy', Gtk.main_quit) if args.title: window_title = args.title win.set_title(args.title) if search_notifys: t = threading.Thread(target=SearchNotify, args=(webView,)) t.start() Gtk.main() stop_threads = True
DavidMulder/simple_browse
simple_browse.py
Python
gpl-2.0
8,391
import json, requests, time, hmac, hashlib, math, socket, os, datetime from subprocess import Popen, PIPE import subprocess import socket import sys import time import random import base64 import platform if platform.system() == "Windows": PYTHON_PATH = "D:\Python27\Python.exe" else: PYTHON_PATH = "/usr/bin/python" class DomeController: """DomeLights Controller class""" def __init__(self, master_url, controller_name, controller_key): """ Initialize """ import socket self._master_url = master_url self._controller_name = controller_name self._controller_key = controller_key self._authenticated = False self._active = False self._httpClient = requests.Session() self._running = True self._state = None self._runningFile = None self._subprocess = None self._script_name = None Debug("Sending STOP signal to residual processes") self._runningFile = open('running', 'w') self._runningFile.write("STOP") self._runningFile.close() time.sleep(5) Debug("Clearing STOP signal") self._runningFile = open('running', 'w') self._runningFile.write("") self._runningFile.close() def api_call(self, remote_method, data): message_hash = self._controller_name + str(int(time.time())) + self._controller_key data['controller_name'] = self._controller_name data['timestamp'] = int(time.time()) data['hash'] = hmac.new(self._controller_key, message_hash, hashlib.sha256).hexdigest() request_url = self._master_url + remote_method s = self._httpClient try: r = s.post(request_url, data) except requests.exceptions.ConnectionError as e: r = s.post(request_url, data) pass Debug('api_call:'+str(r.text)) return r.json() def GetControllerState(self): data = {} request_result = self.api_call('GetControllerState', data) self._fallback_script_name = request_result['script_name'] return request_result['mode'] def GetControllerTask(self): data = {} request_result = self.api_call('GetControllerTask', data) return request_result def SetAnimationPlayed(self, animation_id ): data = {} data['animation_id'] = animation_id request_result = self.api_call('SetAnimationPlayed', data) return request_result def stopScript(self): if not self._subprocess: return Debug("Signalling STOP") self._runningFile = open('running', 'w') self._runningFile.write("STOP") self._runningFile.close() Debug("Waiting for subprocess to stop...") self._subprocess.wait() Debug("Killed!") # Send black screen update self.sendBlackScreen() # Reset subprocess handle self._subprocess = None def sendBlackScreen(self): self.runScript( 'blackscreen.py' ) def run(self): while True: Debug("Loop...") controller_state = self.GetControllerState() Debug( "Controller State: " + str( controller_state ) ) if self._state != None and controller_state != self._state: Debug( "Changing states from " + self._state + " to " + controller_state ) self.stopScript() self._state = controller_state sleep = 1 Debug("Subprocess: " + str(self._subprocess)) if controller_state == '0': Debug("Player is set down, sleeping for 60 seconds") sleep = 60 elif controller_state == '1': # Fetch next animation task_info = self.GetControllerTask() if task_info['mode'] == '0': Debug( "Scheduled down time, sleeping for 60 seconds" ) sleep = 60 elif task_info['mode'] == '1': script_name = task_info['script_name'] # If we have a valid animation, send a stop signal and start playback if script_name == 'domeplayer.py': self._script_name = script_name if self._subprocess != None and self._subprocess.poll() == None: Debug("Animation player already running") # Send stop self.stopScript() try: fp = open( 'LightData.dat', 'w' ) fp.write( base64.b64decode( task_info['data'] ) ) fp.close() finally: # Run animation self.runAnimation() # Set animation as played self.SetAnimationPlayed( task_info['id'] ) Debug( "Done!" ) sleep = 0 elif self._script_name != script_name: # Send stop self.stopScript() Debug("Spawning script player") self.runScript( script_name ) sleep = 5 elif self._subprocess != None and self._subprocess.poll() == None: Debug("Animation player already running") sleep = 5 else: Debug("Animation player not running") Debug("Spawning script player") self.runScript( script_name ) sleep = 5 elif controller_state == "2": if self._script_name != self._fallback_script_name: # Send stop self.stopScript() Debug("Spawning script player") self.runScript( self._fallback_script_name ) sleep = 5 elif self._subprocess != None and self._subprocess.poll() == None: Debug("Animation player already running") sleep = 5 else: Debug("Animation player not running") Debug("Spawning script player") self.runScript( self._fallback_script_name ) sleep = 5 Debug( "Sleeping[" + str(sleep) + "]..." ) for per in range(0, sleep): # Debug("Sleeping [" + str(sleep - per) + "]...") time.sleep(1) def runAnimation(self): Debug( "Playing animation" ) self._subprocess = None # Start animation self._subprocess = subprocess.Popen([ PYTHON_PATH, "scripts/domeplayer.py", "LightData.dat" ], stdout=PIPE, stdin=PIPE, stderr=PIPE) # Wait for animation to be done playing self._subprocess.wait() def runScript(self,script_name): self._script_name = script_name script_file = "scripts/" + script_name Debug("Spawning scripted animation: " + script_file) self._subprocess = None self._subprocess = subprocess.Popen([ PYTHON_PATH, script_file ], stdout=PIPE, stdin=PIPE, stderr=PIPE) def Debug(message): if Debug: print datetime.datetime.now(), message
ScienceWorldCA/domelights
backend/domeplayer/domelights.py
Python
apache-2.0
6,424
#-*- coding: utf-8 -*- from __future__ import unicode_literals import aldryn_apphooks_config.fields import app_data.fields import djangocms_text_ckeditor.fields from cms.models import Page from cms.utils.i18n import get_language_list from django.db import models, migrations def forwards(apps, schema_editor): BlogConfig = apps.get_model('djangocms_blog', 'BlogConfig') BlogConfigTranslation = apps.get_model('djangocms_blog', 'BlogConfigTranslation') Post = apps.get_model('djangocms_blog', 'Post') BlogCategory = apps.get_model('djangocms_blog', 'BlogCategory') GenericBlogPlugin = apps.get_model('djangocms_blog', 'GenericBlogPlugin') LatestPostsPlugin = apps.get_model('djangocms_blog', 'LatestPostsPlugin') AuthorEntriesPlugin = apps.get_model('djangocms_blog', 'AuthorEntriesPlugin') config = None for page in Page.objects.drafts().filter(application_urls='BlogApp'): config = BlogConfig.objects.create(namespace=page.application_namespace) for lang in get_language_list(): title = page.get_title(lang) translation = BlogConfigTranslation.objects.create(language_code=lang, master_id=config.pk, app_title=title) if config: for model in (Post, BlogCategory, GenericBlogPlugin, LatestPostsPlugin, AuthorEntriesPlugin): for item in model.objects.all(): item.app_config = config item.save() def backwards(apps, schema_editor): # No need for backward data migration pass class Migration(migrations.Migration): dependencies = [ ('cms', '__latest__'), ('djangocms_blog', '0009_latestpostsplugin_tags_new'), ] operations = [ migrations.CreateModel( name='BlogConfig', fields=[ ('id', models.AutoField(auto_created=True, verbose_name='ID', serialize=False, primary_key=True)), ('type', models.CharField(verbose_name='type', max_length=100)), ('namespace', models.CharField(default=None, verbose_name='instance namespace', unique=True, max_length=100)), ('app_data', app_data.fields.AppDataField(editable=False, default='{}')), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='BlogConfigTranslation', fields=[ ('id', models.AutoField(auto_created=True, verbose_name='ID', serialize=False, primary_key=True)), ('language_code', models.CharField(db_index=True, verbose_name='Language', max_length=15)), ('app_title', models.CharField(verbose_name='application title', max_length=234)), ('master', models.ForeignKey(editable=False, to='djangocms_blog.BlogConfig', related_name='translations', null=True)), ], options={ 'verbose_name': 'blog config Translation', 'db_table': 'djangocms_blog_blogconfig_translation', 'default_permissions': (), 'db_tablespace': '', 'managed': True, }, ), migrations.CreateModel( name='GenericBlogPlugin', fields=[ ('cmsplugin_ptr', models.OneToOneField(parent_link=True, serialize=False, primary_key=True, auto_created=True, to='cms.CMSPlugin')), ('app_config', aldryn_apphooks_config.fields.AppHookConfigField(verbose_name='app. config', blank=True, to='djangocms_blog.BlogConfig', help_text='When selecting a value, the form is reloaded to get the updated default')), ], options={ 'abstract': False, }, bases=('cms.cmsplugin',), ), migrations.AlterField( model_name='posttranslation', name='abstract', field=djangocms_text_ckeditor.fields.HTMLField(default='', verbose_name='abstract', blank=True), ), migrations.AddField( model_name='authorentriesplugin', name='app_config', field=aldryn_apphooks_config.fields.AppHookConfigField(default=None, blank=True, verbose_name='app. config', to='djangocms_blog.BlogConfig', help_text='When selecting a value, the form is reloaded to get the updated default'), preserve_default=False, ), migrations.AddField( model_name='blogcategory', name='app_config', field=aldryn_apphooks_config.fields.AppHookConfigField(default=None, verbose_name='app. config', to='djangocms_blog.BlogConfig', help_text='When selecting a value, the form is reloaded to get the updated default'), preserve_default=False, ), migrations.AddField( model_name='latestpostsplugin', name='app_config', field=aldryn_apphooks_config.fields.AppHookConfigField(default=None, blank=True, verbose_name='app. config', to='djangocms_blog.BlogConfig', help_text='When selecting a value, the form is reloaded to get the updated default'), preserve_default=False, ), migrations.AddField( model_name='post', name='app_config', field=aldryn_apphooks_config.fields.AppHookConfigField(default=None, verbose_name='app. config', to='djangocms_blog.BlogConfig', help_text='When selecting a value, the form is reloaded to get the updated default'), preserve_default=False, ), migrations.AlterUniqueTogether( name='blogconfigtranslation', unique_together=set([('language_code', 'master')]), ), migrations.AlterField( model_name='post', name='sites', field=models.ManyToManyField(to='sites.Site', help_text='Select sites in which to show the post. If none is set it will be visible in all the configured sites.', blank=True, verbose_name='Site(s)'), ), migrations.RunPython(forwards, backwards) ]
Venturi/oldcms
env/lib/python2.7/site-packages/djangocms_blog/migrations/0010_auto_20150923_1151.py
Python
apache-2.0
6,032
import re import pdb def requirement_3(input_string): """ Passwords must contain at least two different, non-overlapping pairs of letters, like aa, bb, or zz. input_string - Input value @returns - True/False depending on pass ability """ return 2 <= len(re.findall('([a-z])\\1', input_string)) def requirement_2(input_string): """ Passwords may not contain the letters i, o, or l, as these letters can be mistaken for other characters and are therefore confusing. input_string - Input value @returns - True/False depending on pass ability """ return 0 == len(re.findall('[iol]', input_string)) def requirement_1(input_string): """ Passwords must include one increasing straight of at least three letters, like abc, bcd, cde, and so on, up to xyz. They cannot skip letters; abd doesn't count. input_string - Input value @returns - True/False depending on pass ability """ for i in range(len(input_string)-2): sub_unit = input_string[i:i+3] if ord(sub_unit[0]) == ord(sub_unit[1]) - 1 == ord(sub_unit[2]) - 2: return True return False def increment_password(input_string): """ To help him remember his new password after the old one expires, Santa has devised a method of coming up with a password based on the previous one. Corporate policy dictates that passwords must be exactly eight lowercase letters (for security reasons), so he finds his new password by incrementing his old password string repeatedly until it is valid. Incrementing is just like counting with numbers: xx, xy, xz, ya, yb, and so on. Increase the rightmost letter one step; if it was z, it wraps around to a, and repeat with the next letter to the left until one doesn't wrap around. """ if input_string[-1] != 'z': input_string = input_string[:-1] + \ chr(ord(input_string[-1])+1) else: back_index = 1 while input_string.endswith('z'*back_index): back_index += 1 pre_partition = -1*(back_index) partition = pre_partition post_count = back_index - 1 input_string = input_string[:pre_partition] + \ chr(ord(input_string[partition])+1) + \ 'a'*(post_count) return input_string def compute_next(input_string): """ Compute Santa's next password input_string - input @returns - Result """ input_string = increment_password(input_string) while not( requirement_3(input_string) and requirement_2(input_string) and requirement_1(input_string) ): input_string = increment_password(input_string) return input_string seed_string = 'hxbxwxba' print compute_next(seed_string) print compute_next(compute_next(seed_string)
hasteur/advent_of_code
2015/puzzle11.py
Python
gpl-2.0
2,869
#!/usr/bin/env python import json from tests.unit import AWSMockServiceTestCase from boto.beanstalk.layer1 import Layer1 # These tests are just checking the basic structure of # the Elastic Beanstalk code, by picking a few calls # and verifying we get the expected results with mocked # responses. The integration tests actually verify the # API calls interact with the service correctly. class TestListAvailableSolutionStacks(AWSMockServiceTestCase): connection_class = Layer1 def default_body(self): return json.dumps( {u'ListAvailableSolutionStacksResponse': {u'ListAvailableSolutionStacksResult': {u'SolutionStackDetails': [ {u'PermittedFileTypes': [u'war', u'zip'], u'SolutionStackName': u'32bit Amazon Linux running Tomcat 7'}, {u'PermittedFileTypes': [u'zip'], u'SolutionStackName': u'32bit Amazon Linux running PHP 5.3'}], u'SolutionStacks': [u'32bit Amazon Linux running Tomcat 7', u'32bit Amazon Linux running PHP 5.3']}, u'ResponseMetadata': {u'RequestId': u'request_id'}}}) def test_list_available_solution_stacks(self): self.set_http_response(status_code=200) api_response = self.service_connection.list_available_solution_stacks() stack_details = api_response['ListAvailableSolutionStacksResponse']\ ['ListAvailableSolutionStacksResult']\ ['SolutionStackDetails'] solution_stacks = api_response['ListAvailableSolutionStacksResponse']\ ['ListAvailableSolutionStacksResult']\ ['SolutionStacks'] self.assertEqual(solution_stacks, [u'32bit Amazon Linux running Tomcat 7', u'32bit Amazon Linux running PHP 5.3']) # These are the parameters that are actually sent to the CloudFormation # service. self.assert_request_parameters({ 'Action': 'ListAvailableSolutionStacks', 'ContentType': 'JSON', 'SignatureMethod': 'HmacSHA256', 'SignatureVersion': 2, 'Version': '2010-12-01', 'AWSAccessKeyId': 'aws_access_key_id', }, ignore_params_values=['Timestamp']) class TestCreateApplicationVersion(AWSMockServiceTestCase): connection_class = Layer1 def default_body(self): return json.dumps({ 'CreateApplicationVersionResponse': {u'CreateApplicationVersionResult': {u'ApplicationVersion': {u'ApplicationName': u'application1', u'DateCreated': 1343067094.342, u'DateUpdated': 1343067094.342, u'Description': None, u'SourceBundle': {u'S3Bucket': u'elasticbeanstalk-us-east-1', u'S3Key': u'resources/elasticbeanstalk-sampleapp.war'}, u'VersionLabel': u'version1'}}}}) def test_create_application_version(self): self.set_http_response(status_code=200) api_response = self.service_connection.create_application_version( 'application1', 'version1', s3_bucket='mybucket', s3_key='mykey', auto_create_application=True) app_version = api_response['CreateApplicationVersionResponse']\ ['CreateApplicationVersionResult']\ ['ApplicationVersion'] self.assert_request_parameters({ 'Action': 'CreateApplicationVersion', 'ContentType': 'JSON', 'SignatureMethod': 'HmacSHA256', 'SignatureVersion': 2, 'Version': '2010-12-01', 'ApplicationName': 'application1', 'AutoCreateApplication': 'true', 'SourceBundle.S3Bucket': 'mybucket', 'SourceBundle.S3Key': 'mykey', 'VersionLabel': 'version1', 'AWSAccessKeyId': 'aws_access_key_id', }, ignore_params_values=['Timestamp']) self.assertEqual(app_version['ApplicationName'], 'application1') self.assertEqual(app_version['VersionLabel'], 'version1') class TestCreateEnvironment(AWSMockServiceTestCase): connection_class = Layer1 def default_body(self): return json.dumps({}) def test_create_environment(self): self.set_http_response(status_code=200) api_response = self.service_connection.create_environment( 'application1', 'environment1', 'version1', '32bit Amazon Linux running Tomcat 7', option_settings=[ ('aws:autoscaling:launchconfiguration', 'Ec2KeyName', 'mykeypair'), ('aws:elasticbeanstalk:application:environment', 'ENVVAR', 'VALUE1')]) self.assert_request_parameters({ 'Action': 'CreateEnvironment', 'ApplicationName': 'application1', 'EnvironmentName': 'environment1', 'TemplateName': '32bit Amazon Linux running Tomcat 7', 'ContentType': 'JSON', 'SignatureMethod': 'HmacSHA256', 'SignatureVersion': 2, 'Version': '2010-12-01', 'VersionLabel': 'version1', 'AWSAccessKeyId': 'aws_access_key_id', 'OptionSettings.member.1.Namespace': 'aws:autoscaling:launchconfiguration', 'OptionSettings.member.1.OptionName': 'Ec2KeyName', 'OptionSettings.member.1.Value': 'mykeypair', 'OptionSettings.member.2.Namespace': 'aws:elasticbeanstalk:application:environment', 'OptionSettings.member.2.OptionName': 'ENVVAR', 'OptionSettings.member.2.Value': 'VALUE1', }, ignore_params_values=['Timestamp'])
palladius/gcloud
packages/gsutil/boto/tests/unit/beanstalk/test_layer1.py
Python
gpl-3.0
5,946
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ Train ab initio gene predictors. """ import os import os.path as op import sys import logging from jcvi.apps.base import OptionParser, ActionDispatcher, mkdir, sh, need_update def main(): actions = ( ("pasa", "extract pasa training models"), ("snap", "train snap model"), ("augustus", "train augustus model"), ("genemark", "train genemark model"), ) p = ActionDispatcher(actions) p.dispatch(globals()) def pasa(args): """ %prog ${pasadb}.assemblies.fasta ${pasadb}.pasa_assemblies.gff3 Wraps `pasa_asmbls_to_training_set.dbi`. """ from jcvi.formats.base import SetFile from jcvi.formats.gff import Gff p = OptionParser(pasa.__doc__) p.set_home("pasa") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) fastafile, gffile = args transcodergff = fastafile + ".transdecoder.gff3" transcodergenomegff = fastafile + ".transdecoder.genome.gff3" if need_update((fastafile, gffile), (transcodergff, transcodergenomegff)): cmd = "{0}/scripts/pasa_asmbls_to_training_set.dbi".format(opts.pasa_home) cmd += " --pasa_transcripts_fasta {0} --pasa_transcripts_gff3 {1}".format( fastafile, gffile ) sh(cmd) completeids = fastafile.rsplit(".", 1)[0] + ".complete.ids" if need_update(transcodergff, completeids): cmd = "grep complete {0} | cut -f1 | sort -u".format(transcodergff) sh(cmd, outfile=completeids) complete = SetFile(completeids) seen = set() completegff = transcodergenomegff.rsplit(".", 1)[0] + ".complete.gff3" fw = open(completegff, "w") gff = Gff(transcodergenomegff) for g in gff: a = g.attributes if "Parent" in a: id = a["Parent"][0] else: id = a["ID"][0] asmbl_id = id.split("|")[0] if asmbl_id not in complete: continue print(g, file=fw) if g.type == "gene": seen.add(id) fw.close() logging.debug( "A total of {0} complete models extracted to `{1}`.".format( len(seen), completegff ) ) def genemark(args): """ %prog genemark species fastafile Train GENEMARK model given fastafile. GENEMARK self-trains so no trainig model gff file is needed. """ p = OptionParser(genemark.__doc__) p.add_option("--junctions", help="Path to `junctions.bed` from Tophat2") p.set_home("gmes") p.set_cpus(cpus=32) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) species, fastafile = args junctions = opts.junctions mhome = opts.gmes_home license = op.expanduser("~/.gm_key") assert op.exists(license), "License key ({0}) not found!".format(license) cmd = "{0}/gmes_petap.pl --sequence {1}".format(mhome, fastafile) cmd += " --cores {0}".format(opts.cpus) if junctions: intronsgff = "introns.gff" if need_update(junctions, intronsgff): jcmd = "{0}/bet_to_gff.pl".format(mhome) jcmd += " --bed {0} --gff {1} --label Tophat2".format(junctions, intronsgff) sh(jcmd) cmd += " --ET {0} --et_score 10".format(intronsgff) else: cmd += " --ES" sh(cmd) logging.debug("GENEMARK matrix written to `output/gmhmm.mod") def snap(args): """ %prog snap species gffile fastafile Train SNAP model given gffile and fastafile. Whole procedure taken from: <http://gmod.org/wiki/MAKER_Tutorial_2012> """ p = OptionParser(snap.__doc__) p.set_home("maker") opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) species, gffile, fastafile = args gffile = os.path.abspath(gffile) fastafile = os.path.abspath(fastafile) mhome = opts.maker_home snapdir = "snap" mkdir(snapdir) cwd = os.getcwd() os.chdir(snapdir) newgffile = "training.gff3" logging.debug("Construct GFF file combined with sequence ...") sh("cat {0} > {1}".format(gffile, newgffile)) sh('echo "##FASTA" >> {0}'.format(newgffile)) sh("cat {0} >> {1}".format(fastafile, newgffile)) logging.debug("Make models ...") sh("{0}/src/bin/maker2zff training.gff3".format(mhome)) sh("{0}/exe/snap/fathom -categorize 1000 genome.ann genome.dna".format(mhome)) sh("{0}/exe/snap/fathom -export 1000 -plus uni.ann uni.dna".format(mhome)) sh("{0}/exe/snap/forge export.ann export.dna".format(mhome)) sh("{0}/exe/snap/hmm-assembler.pl {1} . > {1}.hmm".format(mhome, species)) os.chdir(cwd) logging.debug("SNAP matrix written to `{0}/{1}.hmm`".format(snapdir, species)) def augustus(args): """ %prog augustus species gffile fastafile Train AUGUSTUS model given gffile and fastafile. Whole procedure taken from: <http://www.molecularevolution.org/molevolfiles/exercises/augustus/training.html> """ p = OptionParser(augustus.__doc__) p.add_option( "--autotrain", default=False, action="store_true", help="Run autoAugTrain.pl to iteratively train AUGUSTUS", ) p.set_home("augustus") opts, args = p.parse_args(args) if len(args) != 3: sys.exit(not p.print_help()) species, gffile, fastafile = args gffile = os.path.abspath(gffile) fastafile = os.path.abspath(fastafile) mhome = opts.augustus_home augdir = "augustus" cwd = os.getcwd() mkdir(augdir) os.chdir(augdir) target = "{0}/config/species/{1}".format(mhome, species) if op.exists(target): logging.debug("Removing existing target `{0}`".format(target)) sh("rm -rf {0}".format(target)) config_path = "{0}/config".format(mhome) sh( "{0}/scripts/new_species.pl --species={1} --AUGUSTUS_CONFIG_PATH={2}".format( mhome, species, config_path ) ) sh( "{0}/scripts/gff2gbSmallDNA.pl {1} {2} 1000 raw.gb".format( mhome, gffile, fastafile ) ) sh("{0}/bin/etraining --species={1} raw.gb 2> train.err".format(mhome, species)) sh(r"cat train.err | perl -pe 's/.*in sequence (\S+): .*/$1/' > badgenes.lst") sh("{0}/scripts/filterGenes.pl badgenes.lst raw.gb > training.gb".format(mhome)) sh("grep -c LOCUS raw.gb training.gb") # autoAugTrain failed to execute, disable for now if opts.autotrain: sh("rm -rf {0}".format(target)) sh( "{0}/scripts/autoAugTrain.pl --trainingset=training.gb --species={1}".format( mhome, species ) ) os.chdir(cwd) sh("cp -r {0} augustus/".format(target)) if __name__ == "__main__": main()
tanghaibao/jcvi
jcvi/annotation/train.py
Python
bsd-2-clause
6,793
from google.appengine.ext import vendor # Add any libraries installed in the "lib" folder. vendor.add('lib')
nelango/ViralityAnalysis
model/appengine_config.py
Python
mit
109
""" Unit tests for getting the list of courses and the course outline. """ import datetime import json import ddt import lxml import mock import pytz from django.conf import settings from django.core.exceptions import PermissionDenied from django.utils.translation import ugettext as _ from opaque_keys.edx.locator import CourseLocator from search.api import perform_search from contentstore.courseware_index import CoursewareSearchIndexer, SearchIndexingError from contentstore.tests.utils import CourseTestCase from contentstore.utils import add_instructor, reverse_course_url, reverse_library_url, reverse_usage_url from contentstore.views.course import ( _deprecated_blocks_info, course_outline_initial_state, reindex_course_and_check_access ) from contentstore.views.item import VisibilityState, create_xblock_info from course_action_state.managers import CourseRerunUIStateManager from course_action_state.models import CourseRerunState from student.auth import has_course_author_access from student.roles import LibraryUserRole from student.tests.factories import UserFactory from util.date_utils import get_default_time_display from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, LibraryFactory class TestCourseIndex(CourseTestCase): """ Unit tests for getting the list of courses and the course outline. """ def setUp(self): """ Add a course with odd characters in the fields """ super(TestCourseIndex, self).setUp() # had a problem where index showed course but has_access failed to retrieve it for non-staff self.odd_course = CourseFactory.create( org='test.org_1-2', number='test-2.3_course', display_name='dotted.course.name-2', ) def check_index_and_outline(self, authed_client): """ Test getting the list of courses and then pulling up their outlines """ index_url = '/home/' index_response = authed_client.get(index_url, {}, HTTP_ACCEPT='text/html') parsed_html = lxml.html.fromstring(index_response.content) course_link_eles = parsed_html.find_class('course-link') self.assertGreaterEqual(len(course_link_eles), 2) for link in course_link_eles: self.assertRegexpMatches( link.get("href"), 'course/{}'.format(settings.COURSE_KEY_PATTERN) ) # now test that url outline_response = authed_client.get(link.get("href"), {}, HTTP_ACCEPT='text/html') # ensure it has the expected 2 self referential links outline_parsed = lxml.html.fromstring(outline_response.content) outline_link = outline_parsed.find_class('course-link')[0] self.assertEqual(outline_link.get("href"), link.get("href")) course_menu_link = outline_parsed.find_class('nav-course-courseware-outline')[0] self.assertEqual(course_menu_link.find("a").get("href"), link.get("href")) def test_libraries_on_course_index(self): """ Test getting the list of libraries from the course listing page """ def _assert_library_link_present(response, library): """ Asserts there's a valid library link on libraries tab. """ parsed_html = lxml.html.fromstring(response.content) library_link_elements = parsed_html.find_class('library-link') self.assertEqual(len(library_link_elements), 1) link = library_link_elements[0] self.assertEqual( link.get("href"), reverse_library_url('library_handler', library.location.library_key), ) # now test that url outline_response = self.client.get(link.get("href"), {}, HTTP_ACCEPT='text/html') self.assertEqual(outline_response.status_code, 200) # Add a library: lib1 = LibraryFactory.create() index_url = '/home/' index_response = self.client.get(index_url, {}, HTTP_ACCEPT='text/html') _assert_library_link_present(index_response, lib1) # Make sure libraries are visible to non-staff users too self.client.logout() non_staff_user, non_staff_userpassword = self.create_non_staff_user() lib2 = LibraryFactory.create(user_id=non_staff_user.id) LibraryUserRole(lib2.location.library_key).add_users(non_staff_user) self.client.login(username=non_staff_user.username, password=non_staff_userpassword) index_response = self.client.get(index_url, {}, HTTP_ACCEPT='text/html') _assert_library_link_present(index_response, lib2) def test_is_staff_access(self): """ Test that people with is_staff see the courses and can navigate into them """ self.check_index_and_outline(self.client) def test_negative_conditions(self): """ Test the error conditions for the access """ outline_url = reverse_course_url('course_handler', self.course.id) # register a non-staff member and try to delete the course branch non_staff_client, _ = self.create_non_staff_authed_user_client() response = non_staff_client.delete(outline_url, {}, HTTP_ACCEPT='application/json') self.assertEqual(response.status_code, 403) def test_course_staff_access(self): """ Make and register course_staff and ensure they can access the courses """ course_staff_client, course_staff = self.create_non_staff_authed_user_client() for course in [self.course, self.odd_course]: permission_url = reverse_course_url('course_team_handler', course.id, kwargs={'email': course_staff.email}) self.client.post( permission_url, data=json.dumps({"role": "staff"}), content_type="application/json", HTTP_ACCEPT="application/json", ) # test access self.check_index_and_outline(course_staff_client) def test_json_responses(self): outline_url = reverse_course_url('course_handler', self.course.id) chapter = ItemFactory.create(parent_location=self.course.location, category='chapter', display_name="Week 1") lesson = ItemFactory.create(parent_location=chapter.location, category='sequential', display_name="Lesson 1") subsection = ItemFactory.create( parent_location=lesson.location, category='vertical', display_name='Subsection 1' ) ItemFactory.create(parent_location=subsection.location, category="video", display_name="My Video") resp = self.client.get(outline_url, HTTP_ACCEPT='application/json') json_response = json.loads(resp.content) # First spot check some values in the root response self.assertEqual(json_response['category'], 'course') self.assertEqual(json_response['id'], unicode(self.course.location)) self.assertEqual(json_response['display_name'], self.course.display_name) self.assertTrue(json_response['published']) self.assertIsNone(json_response['visibility_state']) # Now verify the first child children = json_response['child_info']['children'] self.assertGreater(len(children), 0) first_child_response = children[0] self.assertEqual(first_child_response['category'], 'chapter') self.assertEqual(first_child_response['id'], unicode(chapter.location)) self.assertEqual(first_child_response['display_name'], 'Week 1') self.assertTrue(json_response['published']) self.assertEqual(first_child_response['visibility_state'], VisibilityState.unscheduled) self.assertGreater(len(first_child_response['child_info']['children']), 0) # Finally, validate the entire response for consistency self.assert_correct_json_response(json_response) def test_notifications_handler_get(self): state = CourseRerunUIStateManager.State.FAILED action = CourseRerunUIStateManager.ACTION should_display = True # try when no notification exists notification_url = reverse_course_url('course_notifications_handler', self.course.id, kwargs={ 'action_state_id': 1, }) resp = self.client.get(notification_url, HTTP_ACCEPT='application/json') # verify that we get an empty dict out self.assertEquals(resp.status_code, 400) # create a test notification rerun_state = CourseRerunState.objects.update_state( course_key=self.course.id, new_state=state, allow_not_found=True ) CourseRerunState.objects.update_should_display( entry_id=rerun_state.id, user=UserFactory(), should_display=should_display ) # try to get information on this notification notification_url = reverse_course_url('course_notifications_handler', self.course.id, kwargs={ 'action_state_id': rerun_state.id, }) resp = self.client.get(notification_url, HTTP_ACCEPT='application/json') json_response = json.loads(resp.content) self.assertEquals(json_response['state'], state) self.assertEquals(json_response['action'], action) self.assertEquals(json_response['should_display'], should_display) def test_notifications_handler_dismiss(self): state = CourseRerunUIStateManager.State.FAILED should_display = True rerun_course_key = CourseLocator(org='testx', course='test_course', run='test_run') # add an instructor to this course user2 = UserFactory() add_instructor(rerun_course_key, self.user, user2) # create a test notification rerun_state = CourseRerunState.objects.update_state( course_key=rerun_course_key, new_state=state, allow_not_found=True ) CourseRerunState.objects.update_should_display( entry_id=rerun_state.id, user=user2, should_display=should_display ) # try to get information on this notification notification_dismiss_url = reverse_course_url('course_notifications_handler', self.course.id, kwargs={ 'action_state_id': rerun_state.id, }) resp = self.client.delete(notification_dismiss_url) self.assertEquals(resp.status_code, 200) with self.assertRaises(CourseRerunState.DoesNotExist): # delete nofications that are dismissed CourseRerunState.objects.get(id=rerun_state.id) self.assertFalse(has_course_author_access(user2, rerun_course_key)) def assert_correct_json_response(self, json_response): """ Asserts that the JSON response is syntactically consistent """ self.assertIsNotNone(json_response['display_name']) self.assertIsNotNone(json_response['id']) self.assertIsNotNone(json_response['category']) self.assertTrue(json_response['published']) if json_response.get('child_info', None): for child_response in json_response['child_info']['children']: self.assert_correct_json_response(child_response) def test_course_updates_invalid_url(self): """ Tests the error conditions for the invalid course updates URL. """ # Testing the response code by passing slash separated course id whose format is valid but no course # having this id exists. invalid_course_key = '{}_blah_blah_blah'.format(self.course.id) course_updates_url = reverse_course_url('course_info_handler', invalid_course_key) response = self.client.get(course_updates_url) self.assertEqual(response.status_code, 404) # Testing the response code by passing split course id whose format is valid but no course # having this id exists. split_course_key = CourseLocator(org='orgASD', course='course_01213', run='Run_0_hhh_hhh_hhh') course_updates_url_split = reverse_course_url('course_info_handler', split_course_key) response = self.client.get(course_updates_url_split) self.assertEqual(response.status_code, 404) # Testing the response by passing split course id whose format is invalid. invalid_course_id = 'invalid.course.key/{}'.format(split_course_key) course_updates_url_split = reverse_course_url('course_info_handler', invalid_course_id) response = self.client.get(course_updates_url_split) self.assertEqual(response.status_code, 404) def test_course_index_invalid_url(self): """ Tests the error conditions for the invalid course index URL. """ # Testing the response code by passing slash separated course key, no course # having this key exists. invalid_course_key = '{}_some_invalid_run'.format(self.course.id) course_outline_url = reverse_course_url('course_handler', invalid_course_key) response = self.client.get_html(course_outline_url) self.assertEqual(response.status_code, 404) # Testing the response code by passing split course key, no course # having this key exists. split_course_key = CourseLocator(org='invalid_org', course='course_01111', run='Run_0_invalid') course_outline_url_split = reverse_course_url('course_handler', split_course_key) response = self.client.get_html(course_outline_url_split) self.assertEqual(response.status_code, 404) def test_course_outline_with_display_course_number_as_none(self): """ Tests course outline when 'display_coursenumber' field is none. """ # Change 'display_coursenumber' field to None and update the course. self.course.display_coursenumber = None updated_course = self.update_course(self.course, self.user.id) # Assert that 'display_coursenumber' field has been changed successfully. self.assertEqual(updated_course.display_coursenumber, None) # Perform GET request on course outline url with the course id. course_outline_url = reverse_course_url('course_handler', updated_course.id) response = self.client.get_html(course_outline_url) # Assert that response code is 200. self.assertEqual(response.status_code, 200) # Assert that 'display_course_number' is being set to "" (as display_coursenumber was None). self.assertIn('display_course_number: ""', response.content) @ddt.ddt class TestCourseOutline(CourseTestCase): """ Unit tests for the course outline. """ ENABLED_SIGNALS = ['course_published'] def setUp(self): """ Set up the for the course outline tests. """ super(TestCourseOutline, self).setUp() self.chapter = ItemFactory.create( parent_location=self.course.location, category='chapter', display_name="Week 1" ) self.sequential = ItemFactory.create( parent_location=self.chapter.location, category='sequential', display_name="Lesson 1" ) self.vertical = ItemFactory.create( parent_location=self.sequential.location, category='vertical', display_name='Subsection 1' ) self.video = ItemFactory.create( parent_location=self.vertical.location, category="video", display_name="My Video" ) @ddt.data(True, False) def test_json_responses(self, is_concise): """ Verify the JSON responses returned for the course. Arguments: is_concise (Boolean) : If True, fetch concise version of course outline. """ outline_url = reverse_course_url('course_handler', self.course.id) outline_url = outline_url + '?format=concise' if is_concise else outline_url resp = self.client.get(outline_url, HTTP_ACCEPT='application/json') json_response = json.loads(resp.content) # First spot check some values in the root response self.assertEqual(json_response['category'], 'course') self.assertEqual(json_response['id'], unicode(self.course.location)) self.assertEqual(json_response['display_name'], self.course.display_name) self.assertNotEqual(json_response.get('published', False), is_concise) self.assertIsNone(json_response.get('visibility_state')) # Now verify the first child children = json_response['child_info']['children'] self.assertGreater(len(children), 0) first_child_response = children[0] self.assertEqual(first_child_response['category'], 'chapter') self.assertEqual(first_child_response['id'], unicode(self.chapter.location)) self.assertEqual(first_child_response['display_name'], 'Week 1') self.assertNotEqual(json_response.get('published', False), is_concise) if not is_concise: self.assertEqual(first_child_response['visibility_state'], VisibilityState.unscheduled) self.assertGreater(len(first_child_response['child_info']['children']), 0) # Finally, validate the entire response for consistency self.assert_correct_json_response(json_response, is_concise) def assert_correct_json_response(self, json_response, is_concise=False): """ Asserts that the JSON response is syntactically consistent """ self.assertIsNotNone(json_response['display_name']) self.assertIsNotNone(json_response['id']) self.assertIsNotNone(json_response['category']) self.assertNotEqual(json_response.get('published', False), is_concise) if json_response.get('child_info', None): for child_response in json_response['child_info']['children']: self.assert_correct_json_response(child_response, is_concise) def test_course_outline_initial_state(self): course_module = modulestore().get_item(self.course.location) course_structure = create_xblock_info( course_module, include_child_info=True, include_children_predicate=lambda xblock: not xblock.category == 'vertical' ) # Verify that None is returned for a non-existent locator self.assertIsNone(course_outline_initial_state('no-such-locator', course_structure)) # Verify that the correct initial state is returned for the test chapter chapter_locator = unicode(self.chapter.location) initial_state = course_outline_initial_state(chapter_locator, course_structure) self.assertEqual(initial_state['locator_to_show'], chapter_locator) expanded_locators = initial_state['expanded_locators'] self.assertIn(unicode(self.sequential.location), expanded_locators) self.assertIn(unicode(self.vertical.location), expanded_locators) def test_start_date_on_page(self): """ Verify that the course start date is included on the course outline page. """ def _get_release_date(response): """Return the release date from the course page""" parsed_html = lxml.html.fromstring(response.content) return parsed_html.find_class('course-status')[0].find_class('status-release-value')[0].text_content() def _assert_settings_link_present(response): """ Asserts there's a course settings link on the course page by the course release date. """ parsed_html = lxml.html.fromstring(response.content) settings_link = parsed_html.find_class('course-status')[0].find_class('action-edit')[0].find('a') self.assertIsNotNone(settings_link) self.assertEqual(settings_link.get('href'), reverse_course_url('settings_handler', self.course.id)) outline_url = reverse_course_url('course_handler', self.course.id) response = self.client.get(outline_url, {}, HTTP_ACCEPT='text/html') # A course with the default release date should display as "Unscheduled" self.assertEqual(_get_release_date(response), 'Unscheduled') _assert_settings_link_present(response) self.course.start = datetime.datetime(2014, 1, 1, tzinfo=pytz.utc) modulestore().update_item(self.course, ModuleStoreEnum.UserID.test) response = self.client.get(outline_url, {}, HTTP_ACCEPT='text/html') self.assertEqual(_get_release_date(response), get_default_time_display(self.course.start)) _assert_settings_link_present(response) def _create_test_data(self, course_module, create_blocks=False, publish=True, block_types=None): """ Create data for test. """ if create_blocks: for block_type in block_types: ItemFactory.create( parent_location=self.vertical.location, category=block_type, display_name='{} Problem'.format(block_type) ) if not publish: self.store.unpublish(self.vertical.location, self.user.id) course_module.advanced_modules.extend(block_types) def _verify_deprecated_info(self, course_id, advanced_modules, info, deprecated_block_types): """ Verify deprecated info. """ expected_blocks = [] for block_type in deprecated_block_types: expected_blocks.append( [ reverse_usage_url('container_handler', self.vertical.location), '{} Problem'.format(block_type) ] ) self.assertEqual( info['deprecated_enabled_block_types'], [component for component in advanced_modules if component in deprecated_block_types] ) self.assertItemsEqual(info['blocks'], expected_blocks) self.assertEqual( info['advance_settings_url'], reverse_course_url('advanced_settings_handler', course_id) ) @ddt.data( [{'publish': True}, ['notes']], [{'publish': False}, ['notes']], [{'publish': True}, ['notes', 'lti']] ) @ddt.unpack def test_verify_deprecated_warning_message(self, publish, block_types): """ Verify deprecated warning info. """ course_module = modulestore().get_item(self.course.location) self._create_test_data(course_module, create_blocks=True, block_types=block_types, publish=publish) info = _deprecated_blocks_info(course_module, block_types) self._verify_deprecated_info( course_module.id, course_module.advanced_modules, info, block_types ) @ddt.data( (["a", "b", "c"], ["a", "b", "c"]), (["a", "b", "c"], ["a", "b", "d"]), (["a", "b", "c"], ["a", "d", "e"]), (["a", "b", "c"], ["d", "e", "f"]) ) @ddt.unpack def test_verify_warn_only_on_enabled_modules(self, enabled_block_types, deprecated_block_types): """ Verify that we only warn about block_types that are both deprecated and enabled. """ expected_block_types = list(set(enabled_block_types) & set(deprecated_block_types)) course_module = modulestore().get_item(self.course.location) self._create_test_data(course_module, create_blocks=True, block_types=enabled_block_types) info = _deprecated_blocks_info(course_module, deprecated_block_types) self._verify_deprecated_info( course_module.id, course_module.advanced_modules, info, expected_block_types ) @ddt.data( {'delete_vertical': True}, {'delete_vertical': False}, ) @ddt.unpack def test_deprecated_blocks_list_updated_correctly(self, delete_vertical): """ Verify that deprecated blocks list shown on banner is updated correctly. Here is the scenario: This list of deprecated blocks shown on banner contains published and un-published blocks. That list should be updated when we delete un-published block(s). This behavior should be same if we delete unpublished vertical or problem. """ block_types = ['notes'] course_module = modulestore().get_item(self.course.location) vertical1 = ItemFactory.create( parent_location=self.sequential.location, category='vertical', display_name='Vert1 Subsection1' ) problem1 = ItemFactory.create( parent_location=vertical1.location, category='notes', display_name='notes problem in vert1', publish_item=False ) info = _deprecated_blocks_info(course_module, block_types) # info['blocks'] should be empty here because there is nothing # published or un-published present self.assertEqual(info['blocks'], []) vertical2 = ItemFactory.create( parent_location=self.sequential.location, category='vertical', display_name='Vert2 Subsection1' ) ItemFactory.create( parent_location=vertical2.location, category='notes', display_name='notes problem in vert2', pubish_item=True ) # At this point CourseStructure will contain both the above # published and un-published verticals info = _deprecated_blocks_info(course_module, block_types) self.assertItemsEqual( info['blocks'], [ [reverse_usage_url('container_handler', vertical1.location), 'notes problem in vert1'], [reverse_usage_url('container_handler', vertical2.location), 'notes problem in vert2'] ] ) # Delete the un-published vertical or problem so that CourseStructure updates its data if delete_vertical: self.store.delete_item(vertical1.location, self.user.id) else: self.store.delete_item(problem1.location, self.user.id) info = _deprecated_blocks_info(course_module, block_types) # info['blocks'] should only contain the info about vertical2 which is published. # There shouldn't be any info present about un-published vertical1 self.assertEqual( info['blocks'], [[reverse_usage_url('container_handler', vertical2.location), 'notes problem in vert2']] ) class TestCourseReIndex(CourseTestCase): """ Unit tests for the course outline. """ SUCCESSFUL_RESPONSE = _("Course has been successfully reindexed.") ENABLED_SIGNALS = ['course_published'] def setUp(self): """ Set up the for the course outline tests. """ super(TestCourseReIndex, self).setUp() self.course.start = datetime.datetime(2014, 1, 1, tzinfo=pytz.utc) modulestore().update_item(self.course, self.user.id) self.chapter = ItemFactory.create( parent_location=self.course.location, category='chapter', display_name="Week 1" ) self.sequential = ItemFactory.create( parent_location=self.chapter.location, category='sequential', display_name="Lesson 1" ) self.vertical = ItemFactory.create( parent_location=self.sequential.location, category='vertical', display_name='Subsection 1' ) self.video = ItemFactory.create( parent_location=self.vertical.location, category="video", display_name="My Video" ) self.html = ItemFactory.create( parent_location=self.vertical.location, category="html", display_name="My HTML", data="<div>This is my unique HTML content</div>", ) def test_reindex_course(self): """ Verify that course gets reindexed. """ index_url = reverse_course_url('course_search_index_handler', self.course.id) response = self.client.get(index_url, {}, HTTP_ACCEPT='application/json') # A course with the default release date should display as "Unscheduled" self.assertIn(self.SUCCESSFUL_RESPONSE, response.content) self.assertEqual(response.status_code, 200) response = self.client.post(index_url, {}, HTTP_ACCEPT='application/json') self.assertEqual(response.content, '') self.assertEqual(response.status_code, 405) self.client.logout() response = self.client.get(index_url, {}, HTTP_ACCEPT='application/json') self.assertEqual(response.status_code, 302) def test_negative_conditions(self): """ Test the error conditions for the access """ index_url = reverse_course_url('course_search_index_handler', self.course.id) # register a non-staff member and try to delete the course branch non_staff_client, _ = self.create_non_staff_authed_user_client() response = non_staff_client.get(index_url, {}, HTTP_ACCEPT='application/json') self.assertEqual(response.status_code, 403) def test_empty_content_type(self): """ Test json content type is set if '' is selected """ index_url = reverse_course_url('course_search_index_handler', self.course.id) response = self.client.get(index_url, {}, CONTENT_TYPE='') # A course with the default release date should display as "Unscheduled" self.assertIn(self.SUCCESSFUL_RESPONSE, response.content) self.assertEqual(response.status_code, 200) @mock.patch('xmodule.html_module.HtmlDescriptor.index_dictionary') def test_reindex_course_search_index_error(self, mock_index_dictionary): """ Test json response with mocked error data for html """ # set mocked exception response err = SearchIndexingError mock_index_dictionary.return_value = err index_url = reverse_course_url('course_search_index_handler', self.course.id) # Start manual reindex and check error in response response = self.client.get(index_url, {}, HTTP_ACCEPT='application/json') self.assertEqual(response.status_code, 500) def test_reindex_json_responses(self): """ Test json response with real data """ # results are indexed because they are published from ItemFactory response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) # Start manual reindex reindex_course_and_check_access(self.course.id, self.user) # Check results remain the same response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) @mock.patch('xmodule.video_module.VideoDescriptor.index_dictionary') def test_reindex_video_error_json_responses(self, mock_index_dictionary): """ Test json response with mocked error data for video """ # results are indexed because they are published from ItemFactory response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) # set mocked exception response err = SearchIndexingError mock_index_dictionary.return_value = err # Start manual reindex and check error in response with self.assertRaises(SearchIndexingError): reindex_course_and_check_access(self.course.id, self.user) @mock.patch('xmodule.html_module.HtmlDescriptor.index_dictionary') def test_reindex_html_error_json_responses(self, mock_index_dictionary): """ Test json response with mocked error data for html """ # results are indexed because they are published from ItemFactory response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) # set mocked exception response err = SearchIndexingError mock_index_dictionary.return_value = err # Start manual reindex and check error in response with self.assertRaises(SearchIndexingError): reindex_course_and_check_access(self.course.id, self.user) @mock.patch('xmodule.seq_module.SequenceDescriptor.index_dictionary') def test_reindex_seq_error_json_responses(self, mock_index_dictionary): """ Test json response with mocked error data for sequence """ # results are indexed because they are published from ItemFactory response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) # set mocked exception response err = Exception mock_index_dictionary.return_value = err # Start manual reindex and check error in response with self.assertRaises(SearchIndexingError): reindex_course_and_check_access(self.course.id, self.user) @mock.patch('xmodule.modulestore.mongo.base.MongoModuleStore.get_course') def test_reindex_no_item(self, mock_get_course): """ Test system logs an error if no item found. """ # set mocked exception response err = ItemNotFoundError mock_get_course.return_value = err # Start manual reindex and check error in response with self.assertRaises(SearchIndexingError): reindex_course_and_check_access(self.course.id, self.user) def test_reindex_no_permissions(self): # register a non-staff member and try to delete the course branch user2 = UserFactory() with self.assertRaises(PermissionDenied): reindex_course_and_check_access(self.course.id, user2) def test_indexing_responses(self): """ Test do_course_reindex response with real data """ # results are indexed because they are published from ItemFactory response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) # Start manual reindex CoursewareSearchIndexer.do_course_reindex(modulestore(), self.course.id) # Check results are the same following reindex response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) @mock.patch('xmodule.video_module.VideoDescriptor.index_dictionary') def test_indexing_video_error_responses(self, mock_index_dictionary): """ Test do_course_reindex response with mocked error data for video """ # results are indexed because they are published from ItemFactory response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) # set mocked exception response err = Exception mock_index_dictionary.return_value = err # Start manual reindex and check error in response with self.assertRaises(SearchIndexingError): CoursewareSearchIndexer.do_course_reindex(modulestore(), self.course.id) @mock.patch('xmodule.html_module.HtmlDescriptor.index_dictionary') def test_indexing_html_error_responses(self, mock_index_dictionary): """ Test do_course_reindex response with mocked error data for html """ # results are indexed because they are published from ItemFactory response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) # set mocked exception response err = Exception mock_index_dictionary.return_value = err # Start manual reindex and check error in response with self.assertRaises(SearchIndexingError): CoursewareSearchIndexer.do_course_reindex(modulestore(), self.course.id) @mock.patch('xmodule.seq_module.SequenceDescriptor.index_dictionary') def test_indexing_seq_error_responses(self, mock_index_dictionary): """ Test do_course_reindex response with mocked error data for sequence """ # results are indexed because they are published from ItemFactory response = perform_search( "unique", user=self.user, size=10, from_=0, course_id=unicode(self.course.id)) self.assertEqual(response['total'], 1) # set mocked exception response err = Exception mock_index_dictionary.return_value = err # Start manual reindex and check error in response with self.assertRaises(SearchIndexingError): CoursewareSearchIndexer.do_course_reindex(modulestore(), self.course.id) @mock.patch('xmodule.modulestore.mongo.base.MongoModuleStore.get_course') def test_indexing_no_item(self, mock_get_course): """ Test system logs an error if no item found. """ # set mocked exception response err = ItemNotFoundError mock_get_course.return_value = err # Start manual reindex and check error in response with self.assertRaises(SearchIndexingError): CoursewareSearchIndexer.do_course_reindex(modulestore(), self.course.id)
fintech-circle/edx-platform
cms/djangoapps/contentstore/views/tests/test_course_index.py
Python
agpl-3.0
38,422
# Copyright 2014-2016 Maurice van der Pot <griffon26@kfk4ever.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 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 numpy as np import itertools class Square(): def __init__(self, bitmap, position): self.bitmap = bitmap self.position = position def lookslike(self, otherthingwithbitmap): #diff = cv2.norm(self.bitmap, otherthingwithbitmap.bitmap, cv2.NORM_L1) #print 'lookslike calculated diff of ', diff # self.bitmap ~ otherthingwithbitmap.bitmap return False class TaskNote(): def __init__(self, taskid, bitmap, position, state): self.taskid = taskid self.bitmap = bitmap self.position = position self.state = state def to_serializable(self): return { 'bitmap' : self.bitmap.tolist(), 'position' : self.position, 'state' : self.state } def from_serializable(self, data): self.bitmap = np.array(data['bitmap'], dtype=np.uint8) self.state = data['state'] self.position = data['position'] def _setstate(self, newposition, newstate): self.position = newposition self.state = newstate class Scrumboard(): def __init__(self, linepositions=None): self.linepositions = linepositions self.bitmap = np.array([]) self.tasknotes = [] self.states = ['todo', 'busy', 'blocked', 'in review', 'done'] def to_serializable(self): return { 'bitmap' : self.bitmap.tolist(), 'tasknotes' : [tasknote.to_serializable() for tasknote in self.tasknotes] } def from_serializable(self, data): self.bitmap = np.array(data['bitmap'], dtype=np.uint8) self.tasknotes = [] for tasknote_data in data['tasknotes']: tasknote = TaskNote(len(self.tasknotes), None, None, None) tasknote.from_serializable(tasknote_data) self.tasknotes.append(tasknote) def get_state_from_position(self, position): for i, linepos in enumerate(self.linepositions): if position[0] < linepos: return self.states[i] return self.states[-1] def get_position_from_state(self, state): positions = [0] + self.linepositions + [None] stateindex = self.states.index(state) return positions[stateindex], positions[stateindex + 1] def get_bitmap(self): return self.bitmap def set_bitmap(self, image): self.bitmap = image def add_tasknote(self, square): state = self.get_state_from_position(square.position) tasknote = TaskNote(len(self.tasknotes), square.bitmap, square.position, state) self.tasknotes.append(tasknote) return tasknote def move_tasknote(self, tasknote, newposition): newstate = self.get_state_from_position(newposition) self.tasknotes[tasknote.taskid]._setstate(newposition, newstate) return newstate def diff(self, otherboard): differences = {} for i, states in enumerate(itertools.izip_longest((note.state for note in otherboard.tasknotes), (note.state for note in self.tasknotes))): if states[0] != states[1]: differences[i] = states return differences
Griffon26/scrumboardtracker
scrumboardtracker/board.py
Python
gpl-3.0
3,909
# -*- coding: utf-8 -*- # Copyright (C) 2015-16 Red Hat, Inc. # This file is part of the Infinity Note Compiler. # # The Infinity Note Compiler 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. # # The Infinity Note Compiler 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 the Infinity Note Compiler. If not, see # <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from tests import TestCase from i8c.compiler import ParserError, RedefinedIdentError SOURCE = """\ define test::load_slot argument int an_argument extern ptr a_symbol extern func () a_function extern func () other_provider::function_2 load a_symbol load a_function load other_provider::function_2 """ SOURCE_NAMES_SLOTS = (("an_argument", 3), ("a_symbol", 2), ("a_function", 1), ("test::a_function", 1), ("other_provider::function_2", 0)) SOURCE_WITH_NAME = SOURCE + """\ load 23 name 0, a_name """ SWN_NAMES_SLOTS = (("an_argument", 4), ("a_symbol", 3), ("a_function", 2), ("test::a_function", 2), ("other_provider::function_2", 1), ("a_name", 0)) class TestLoadSlot(TestCase): def test_shortname_only(self): """Check that name rejects fullnames.""" source = SOURCE + "name 2 provider::shortname" self.assertRaises(ParserError, self.compile, source) def test_basic(self): """Check externals' names work.""" for name, expect_slot in SOURCE_NAMES_SLOTS: source = SOURCE + "load " + name tree, output = self.compile(source) ops = output.ops self.assertEqual(len(ops), 4) op = ops[-1] if expect_slot == 0: self.assertEqual(op.name, "dup") elif expect_slot == 1: self.assertEqual(op.name, "over") else: self.assertEqual(op.name, "pick") self.assertEqual(op.operand, expect_slot) def test_name_anonymous_slot(self): """Check naming anonymous slots works.""" for name, expect_slot in SWN_NAMES_SLOTS: tree, output = self.compile(SOURCE_WITH_NAME + "load " + name) ops = output.ops self.assertEqual(len(ops), 5) op = ops[-1] if expect_slot == 0: self.assertEqual(op.name, "dup") elif expect_slot == 1: self.assertEqual(op.name, "over") else: self.assertEqual(op.name, "pick") self.assertEqual(op.operand, expect_slot) def test_name_named_slot(self): """Check naming already-named slots works.""" for name, expect_slot in SOURCE_NAMES_SLOTS: names = ["a_name", name] for order in 0, 1: source = SOURCE + "\n".join( ["name %d, a_name" % expect_slot] + ["load %s" % name for name in names]) tree, output = self.compile(source) ops = output.ops self.assertEqual(len(ops), 5) # The first load can pick from anywhere op = ops[-2] if expect_slot == 0: self.assertEqual(op.name, "dup") elif expect_slot == 1: self.assertEqual(op.name, "over") else: self.assertEqual(op.name, "pick") self.assertEqual(op.operand, expect_slot) # The second load should grab the top slot self.assertEqual(ops[-1].name, "dup") names.reverse() def test_shadowing_rename(self): """Check that you cannot shadow slots.""" for name, expect_slot in SWN_NAMES_SLOTS: if name.find("::") >= 0: continue assert expect_slot != 1 source = SOURCE_WITH_NAME + "name 1, %s" % name self.assertRaises(RedefinedIdentError, self.compile, source) def test_existing_name(self): """Check that giving a slot its existing name is ok.""" for name, expect_slot in SWN_NAMES_SLOTS: if name.find("::") >= 0: continue source = SOURCE_WITH_NAME + "\n".join( ["name %d, %s" % (expect_slot, name), "load %s" % name]) tree, output = self.compile(source) ops = output.ops self.assertEqual(len(ops), 5) op = ops[-1] if expect_slot == 0: self.assertEqual(op.name, "dup") elif expect_slot == 1: self.assertEqual(op.name, "over") else: self.assertEqual(op.name, "pick") self.assertEqual(op.operand, expect_slot)
gbenson/i8c
tests/test_load_slot.py
Python
lgpl-2.1
5,461
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2004-2012 Pexego Sistemas Informáticos All Rights Reserved # $Marta Vázquez Rodríguez$ <marta@pexego.es> # # 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 osv import osv, fields class product_category(osv.osv): _inherit = 'product.category' _columns = { 'cost_structure_id': fields.many2one('cost.structure', 'Cost Structure') } product_category()
Comunitea/alimentacion
product_cost_management/product_category.py
Python
agpl-3.0
1,268
# -*- coding: utf-8 -*- class Charset(object): common_name = 'NotoSansHebrew-Regular' native_name = '' def glyphs(self): chars = [] chars.append(0x0000) #null ???? chars.append(0x200C) #uni200C ZERO WIDTH NON-JOINER chars.append(0x000D) #nonmarkingreturn ???? chars.append(0x200E) #uni200E LEFT-TO-RIGHT MARK chars.append(0x200F) #uni200F RIGHT-TO-LEFT MARK chars.append(0x0020) #space SPACE chars.append(0x200D) #uni200D ZERO WIDTH JOINER chars.append(0x00A0) #space NO-BREAK SPACE chars.append(0x20AA) #sheqel NEW SHEQEL SIGN chars.append(0xFEFF) #null ZERO WIDTH NO-BREAK SPACE chars.append(0xFB1D) #uniFB1D HEBREW LETTER YOD WITH HIRIQ chars.append(0xFB1E) #uniFB1E HEBREW POINT JUDEO-SPANISH VARIKA chars.append(0xFB1F) #yodyod_patah HEBREW LIGATURE YIDDISH YOD YOD PATAH chars.append(0xFB20) #alternativeayin HEBREW LETTER ALTERNATIVE AYIN chars.append(0xFB21) #alefwide HEBREW LETTER WIDE ALEF chars.append(0xFB22) #daletwide HEBREW LETTER WIDE DALET chars.append(0xFB23) #hewide HEBREW LETTER WIDE HE chars.append(0xFB24) #kafwide HEBREW LETTER WIDE KAF chars.append(0xFB25) #lamedwide HEBREW LETTER WIDE LAMED chars.append(0xFB26) #finalmemwide HEBREW LETTER WIDE FINAL MEM chars.append(0xFB27) #reshwide HEBREW LETTER WIDE RESH chars.append(0xFB28) #tavwide HEBREW LETTER WIDE TAV chars.append(0xFB29) #alt_plussign HEBREW LETTER ALTERNATIVE PLUS SIGN chars.append(0xFB2A) #shinshindot HEBREW LETTER SHIN WITH SHIN DOT chars.append(0xFB2B) #shinsindot HEBREW LETTER SHIN WITH SIN DOT chars.append(0xFB2C) #shindageshshindot HEBREW LETTER SHIN WITH DAGESH AND SHIN DOT chars.append(0xFB2D) #shindageshsindot HEBREW LETTER SHIN WITH DAGESH AND SIN DOT chars.append(0xFB2E) #alefpatah HEBREW LETTER ALEF WITH PATAH chars.append(0xFB2F) #alefqamats HEBREW LETTER ALEF WITH QAMATS chars.append(0xFB30) #alefmapiq HEBREW LETTER ALEF WITH MAPIQ chars.append(0xFB31) #betdagesh HEBREW LETTER BET WITH DAGESH chars.append(0xFB32) #gimeldagesh HEBREW LETTER GIMEL WITH DAGESH chars.append(0xFB33) #daletdagesh HEBREW LETTER DALET WITH DAGESH chars.append(0xFB34) #hedagesh HEBREW LETTER HE WITH MAPIQ chars.append(0xFB35) #vavdagesh HEBREW LETTER VAV WITH DAGESH chars.append(0xFB36) #zayindagesh HEBREW LETTER ZAYIN WITH DAGESH chars.append(0xFB38) #tetdagesh HEBREW LETTER TET WITH DAGESH chars.append(0xFB39) #yoddagesh HEBREW LETTER YOD WITH DAGESH chars.append(0xFB3A) #finalkafdagesh HEBREW LETTER FINAL KAF WITH DAGESH chars.append(0xFB3B) #kafdagesh HEBREW LETTER KAF WITH DAGESH chars.append(0xFB3C) #lameddagesh HEBREW LETTER LAMED WITH DAGESH chars.append(0xFB3E) #memdagesh HEBREW LETTER MEM WITH DAGESH chars.append(0xFB40) #nundagesh HEBREW LETTER NUN WITH DAGESH chars.append(0xFB41) #samekhdagesh HEBREW LETTER SAMEKH WITH DAGESH chars.append(0xFB43) #finalpedagesh HEBREW LETTER FINAL PE WITH DAGESH chars.append(0xFB44) #pedagesh HEBREW LETTER PE WITH DAGESH chars.append(0xFB46) #tsadidagesh HEBREW LETTER TSADI WITH DAGESH chars.append(0xFB47) #qofdagesh HEBREW LETTER QOF WITH DAGESH chars.append(0xFB48) #reshdagesh HEBREW LETTER RESH WITH DAGESH chars.append(0xFB49) #shindagesh HEBREW LETTER SHIN WITH DAGESH chars.append(0xFB4A) #tavdagesh HEBREW LETTER TAV WITH DAGESH chars.append(0xFB4B) #vavholam HEBREW LETTER VAV WITH HOLAM chars.append(0xFB4C) #betrafe HEBREW LETTER BET WITH RAFE chars.append(0xFB4D) #kafrafe HEBREW LETTER KAF WITH RAFE chars.append(0xFB4E) #perafe HEBREW LETTER PE WITH RAFE chars.append(0xFB4F) #aleflamed HEBREW LIGATURE ALEF LAMED chars.append(0x0591) #uni0591 HEBREW ACCENT ETNAHTA chars.append(0x0592) #uni0592 HEBREW ACCENT SEGOL chars.append(0x0593) #uni0593 HEBREW ACCENT SHALSHELET chars.append(0x0594) #uni0594 HEBREW ACCENT ZAQEF QATAN chars.append(0x0595) #uni0595 HEBREW ACCENT ZAQEF GADOL chars.append(0x0596) #uni0596 HEBREW ACCENT TIPEHA chars.append(0x0597) #uni0597 HEBREW ACCENT REVIA chars.append(0x0598) #uni0598 HEBREW ACCENT ZARQA chars.append(0x0599) #uni0599 HEBREW ACCENT PASHTA chars.append(0x059A) #uni059A HEBREW ACCENT YETIV chars.append(0x059B) #uni059B HEBREW ACCENT TEVIR chars.append(0x059C) #uni059C HEBREW ACCENT GERESH chars.append(0x059D) #uni059D HEBREW ACCENT GERESH MUQDAM chars.append(0x059E) #uni059E HEBREW ACCENT GERSHAYIM chars.append(0x059F) #uni059F HEBREW ACCENT QARNEY PARA chars.append(0x05A0) #uni05A0 HEBREW ACCENT TELISHA GEDOLA chars.append(0x05A1) #uni05A1 HEBREW ACCENT PAZER chars.append(0x05A2) #uni05A2 HEBREW ACCENT ATNAH HAFUKH chars.append(0x05A3) #uni05A3 HEBREW ACCENT MUNAH chars.append(0x05A4) #uni05A4 HEBREW ACCENT MAHAPAKH chars.append(0x05A5) #uni05A5 HEBREW ACCENT MERKHA chars.append(0x05A6) #uni05A6 HEBREW ACCENT MERKHA KEFULA chars.append(0x05A7) #uni05A7 HEBREW ACCENT DARGA chars.append(0x05A8) #uni05A8 HEBREW ACCENT QADMA chars.append(0x05A9) #uni05A9 HEBREW ACCENT TELISHA QETANA chars.append(0x05AA) #uni05AA HEBREW ACCENT YERAH BEN YOMO chars.append(0x05AB) #uni05AB HEBREW ACCENT OLE chars.append(0x05AC) #uni05AC HEBREW ACCENT ILUY chars.append(0x05AD) #uni05AD HEBREW ACCENT DEHI chars.append(0x05AE) #uni05AE HEBREW ACCENT ZINOR chars.append(0x05AF) #uni05AF HEBREW MARK MASORA CIRCLE chars.append(0x05B0) #sheva HEBREW POINT SHEVA chars.append(0x05B1) #hatafsegol HEBREW POINT HATAF SEGOL chars.append(0x05B2) #hatafpatah HEBREW POINT HATAF PATAH chars.append(0x05B3) #hatafqamats HEBREW POINT HATAF QAMATS chars.append(0x05B4) #hiriq HEBREW POINT HIRIQ chars.append(0x05B5) #tsere HEBREW POINT TSERE chars.append(0x05B6) #segol HEBREW POINT SEGOL chars.append(0x05B7) #patah HEBREW POINT PATAH chars.append(0x05B8) #qamats HEBREW POINT QAMATS chars.append(0x05B9) #holam HEBREW POINT HOLAM chars.append(0x05BA) #uni05BA HEBREW POINT HOLAM HASER FOR VAV chars.append(0x05BB) #qubuts HEBREW POINT QUBUTS chars.append(0x05BC) #dagesh HEBREW POINT DAGESH OR MAPIQ chars.append(0x05BD) #meteg HEBREW POINT METEG chars.append(0x05BE) #maqaf HEBREW PUNCTUATION MAQAF chars.append(0x05BF) #rafe HEBREW POINT RAFE chars.append(0x05C0) #paseq HEBREW PUNCTUATION PASEQ chars.append(0x05C1) #shindot HEBREW POINT SHIN DOT chars.append(0x05C2) #sindot HEBREW POINT SIN DOT chars.append(0x05C3) #sofpasuq HEBREW PUNCTUATION SOF PASUQ chars.append(0x05C4) #upper_dot HEBREW MARK UPPER DOT chars.append(0x05C5) #lowerdot HEBREW MARK LOWER DOT chars.append(0x05C6) #uni05C6 HEBREW PUNCTUATION NUN HAFUKHA chars.append(0x05C7) #qamatsqatan HEBREW POINT QAMATS QATAN chars.append(0x25CC) #uni25CC DOTTED CIRCLE chars.append(0x05D0) #alef HEBREW LETTER ALEF chars.append(0x05D1) #bet HEBREW LETTER BET chars.append(0x05D2) #gimel HEBREW LETTER GIMEL chars.append(0x05D3) #dalet HEBREW LETTER DALET chars.append(0x05D4) #he HEBREW LETTER HE chars.append(0x05D5) #vav HEBREW LETTER VAV chars.append(0x05D6) #zayin HEBREW LETTER ZAYIN chars.append(0x05D7) #het HEBREW LETTER HET chars.append(0x05D8) #tet HEBREW LETTER TET chars.append(0x05D9) #yod HEBREW LETTER YOD chars.append(0x05DA) #finalkaf HEBREW LETTER FINAL KAF chars.append(0x05DB) #kaf HEBREW LETTER KAF chars.append(0x05DC) #lamed HEBREW LETTER LAMED chars.append(0x05DD) #finalmem HEBREW LETTER FINAL MEM chars.append(0x05DE) #mem HEBREW LETTER MEM chars.append(0x05DF) #finalnun HEBREW LETTER FINAL NUN chars.append(0x05E0) #nun HEBREW LETTER NUN chars.append(0x05E1) #samekh HEBREW LETTER SAMEKH chars.append(0x05E2) #ayin HEBREW LETTER AYIN chars.append(0x05E3) #finalpe HEBREW LETTER FINAL PE chars.append(0x05E4) #pe HEBREW LETTER PE chars.append(0x05E5) #finaltsadi HEBREW LETTER FINAL TSADI chars.append(0x05E6) #tsadi HEBREW LETTER TSADI chars.append(0x05E7) #qof HEBREW LETTER QOF chars.append(0x05E8) #resh HEBREW LETTER RESH chars.append(0x05E9) #shin HEBREW LETTER SHIN chars.append(0x05EA) #tav HEBREW LETTER TAV chars.append(0x05F0) #vavvav HEBREW LIGATURE YIDDISH DOUBLE VAV chars.append(0x05F1) #vavyod HEBREW LIGATURE YIDDISH VAV YOD chars.append(0x05F2) #yodyod HEBREW LIGATURE YIDDISH DOUBLE YOD chars.append(0x05F3) #geresh HEBREW PUNCTUATION GERESH chars.append(0x05F4) #gershayim HEBREW PUNCTUATION GERSHAYIM return chars
davelab6/pyfontaine
fontaine/charsets/noto_chars/notosanshebrew_regular.py
Python
gpl-3.0
9,355
from .fullscreentoolbox import FullScreenToolBox from .maintoolbox import MainToolBox
umlfri/umlfri2
umlfri2/qtgui/toolbox/__init__.py
Python
gpl-3.0
86
# -*- encoding: utf-8 -*- """ Class for communication with an H2O server. `H2OConnection` is the main class of this module, and it handles the connection itself: hc = H2OConnection.open() : open a new connection hc.request(endpoint, [data|json|filename]) : make a REST API request to the server hc.info() : return information about the current connection hc.close() : close the connection hc.session_id : current session id :copyright: (c) 2016 H2O.ai :license: Apache License Version 2.0 (see LICENSE for details) """ from __future__ import absolute_import, division, print_function, unicode_literals import atexit import os import re import sys import tempfile import time from warnings import warn import requests from requests.auth import AuthBase from h2o.backend import H2OCluster, H2OLocalServer from h2o.exceptions import H2OConnectionError, H2OServerError, H2OResponseError, H2OValueError from h2o.schemas.error import H2OErrorV3, H2OModelBuilderErrorV3 from h2o.two_dim_table import H2OTwoDimTable from h2o.utils.backward_compatibility import backwards_compatible, CallableString from h2o.utils.compatibility import * # NOQA from h2o.utils.shared_utils import stringify_list, print2 from h2o.utils.typechecks import (assert_is_type, assert_matches, assert_satisfies, is_type, numeric) from h2o.model.metrics_base import (H2ORegressionModelMetrics, H2OClusteringModelMetrics, H2OBinomialModelMetrics, H2OMultinomialModelMetrics, H2OOrdinalModelMetrics, H2OAutoEncoderModelMetrics) __all__ = ("H2OConnection", "H2OConnectionConf", ) if tuple(int(x) for x in requests.__version__.split('.')) < (2, 10): print("[WARNING] H2O requires requests module of version 2.10 or newer. You have version %s.\n" "You can upgrade to the newest version of the module running from the command line\n" " $ pip%s install --upgrade requests" % (requests.__version__, sys.version_info[0])) class H2OConnectionConf(object): """ Configuration of connection to H2O. The main goal of this class is to specify location of running H2O instance and properties of connection. The location of running instance is given by schema, ip, port, context_path parameters forming connection URL in the following way: ``schema://ip:port/context_path`` """ def __init__(self, config = None): self._ip = None self._port = None self._https = None self._context_path = '' self._verify_ssl_certificates = True self._proxy = None self._auth = None self._cookies = None self._verbose = True # Fill from config if it is specified if config is not None: self._fill_from_config(config) """List of allowed property names exposed by this class""" allowed_properties = ["ip", "port", "https", "context_path", "verify_ssl_certificates", "proxy", "auth", "cookies", "verbose"] def _fill_from_config(self, config): """ Fill this instance from given dictionary. The method only uses keys which corresponds to properties this class, throws exception on unknown property name. :param conf: dictionary of parameters :return: a new instance of this class filled with values from given dictionary :raises H2OValueError: if input config contains unknown property name. """ for k,v in config.items(): if k in H2OConnectionConf.allowed_properties: setattr(self, k, v) else: raise H2OValueError(message="Unsupported name of property: %s!" % k, var_name="config") @property def ip(self): return self._ip @ip.setter def ip(self, value): assert_is_type(value, str) self._ip = value @property def port(self): return self._port @port.setter def port(self, value): assert_is_type(value, int) self._port = value @property def https(self): return self._https @https.setter def https(self, value): assert_is_type(value, bool) self._https = value @property def context_path(self): return self._context_path @context_path.setter def context_path(self, value): assert_is_type(value, str) self._context_path = value @property def verify_ssl_certificates(self): return self._verify_ssl_certificates @verify_ssl_certificates.setter def verify_ssl_certificates(self, value): assert_is_type(value, bool) self._verify_ssl_certificates = value @property def proxy(self): return self._proxy @proxy.setter def proxy(self, value): assert_is_type(value, str, None) self._proxy = value @property def auth(self): return self._auth @auth.setter def auth(self, value): assert_is_type(value, AuthBase, (str, str), None) self._auth = value @property def cookies(self): return self._cookies @cookies.setter def cookies(self, value): assert_is_type(value, [str], None) self._cookies = value @property def verbose(self): return self._verbose @verbose.setter def verbose(self, value): assert_is_type(value, bool) self._verbose = value @property def url(self): if self.https: schema = "https" else: schema = "http" curl = "{}://{}:{}/{}".format(schema, self.ip, self.port, self.context_path) return curl class H2OConnection(backwards_compatible()): """ Connection handle to an H2O cluster. In a typical scenario you don't need to access this class directly. Instead use :func:`h2o.connect` to establish a connection, and :func:`h2o.api` to make requests to the backend H2O server. However if your use-case is not typical, then read on. Instances of this class may only be created through a static method :meth:`open`:: hc = H2OConnection.open(...) Once opened, the connection remains active until the script exits (or until you explicitly :meth:`close` it). If the script exits with an exception, then the connection will fail to close, and the backend server will keep all the temporary frames and the open session. Alternatively you can use this class as a context manager, which will ensure that the connection gets closed at the end of the ``with ...`` block even if an exception occurs:: with H2OConnection.open() as hc: hc.info().pprint() Once the connection is established, you can send REST API requests to the server using :meth:`request`. """ """ Defines pattern matching URL in the following form ``schema://ip:port/context_path``. """ url_pattern = r"^(https?)://((?:[\w-]+\.)*[\w-]+):(\d+)/?((/[\w-]+)+)?$" @staticmethod def open(server=None, url=None, ip=None, port=None, https=None, auth=None, verify_ssl_certificates=True, proxy=None, cookies=None, verbose=True, _msgs=None): r""" Establish connection to an existing H2O server. The connection is not kept alive, so what this method actually does is it attempts to connect to the specified server, and checks that the server is healthy and responds to REST API requests. If the H2O server cannot be reached, an :class:`H2OConnectionError` will be raised. On success this method returns a new :class:`H2OConnection` object, and it is the only "official" way to create instances of this class. There are 3 ways to specify the target to connect to (these settings are mutually exclusive): * pass a ``server`` option, * pass the full ``url`` for the connection, * provide a triple of parameters ``ip``, ``port``, ``https``. :param H2OLocalServer server: connect to the specified local server instance. There is a slight difference between connecting to a local server by specifying its ip and address, and connecting through an H2OLocalServer instance: if the server becomes unresponsive, then having access to its process handle will allow us to query the server status through OS, and potentially provide snapshot of the server's error log in the exception information. :param url: full url of the server to connect to. :param ip: target server's IP address or hostname (default "localhost"). :param port: H2O server's port (default 54321). :param https: if True then connect using https instead of http (default False). :param verify_ssl_certificates: if False then SSL certificate checking will be disabled (default True). This setting should rarely be disabled, as it makes your connection vulnerable to man-in-the-middle attacks. When used, it will generate a warning from the requests library. Has no effect when ``https`` is False. :param auth: authentication token for connecting to the remote server. This can be either a (username, password) tuple, or an authenticator (AuthBase) object. Please refer to the documentation in the ``requests.auth`` module. :param proxy: url address of a proxy server. If you do not specify the proxy, then the requests module will attempt to use a proxy specified in the environment (in HTTP_PROXY / HTTPS_PROXY variables). We check for the presence of these variables and issue a warning if they are found. In order to suppress that warning and use proxy from the environment, pass ``proxy="(default)"``. :param cookies: Cookie (or list of) to add to requests :param verbose: if True, then connection progress info will be printed to the stdout. :param _msgs: custom messages to display during connection. This is a tuple (initial message, success message, failure message). :returns: A new :class:`H2OConnection` instance. :raises H2OConnectionError: if the server cannot be reached. :raises H2OServerError: if the server is in an unhealthy state (although this might be a recoverable error, the client itself should decide whether it wants to retry or not). """ if server is not None: assert_is_type(server, H2OLocalServer) assert_is_type(ip, None, "`ip` should be None when `server` parameter is supplied") assert_is_type(url, None, "`ip` should be None when `server` parameter is supplied") if not server.is_running(): raise H2OConnectionError("Unable to connect to server because it is not running") ip = server.ip port = server.port scheme = server.scheme context_path = '' elif url is not None: assert_is_type(url, str) assert_is_type(ip, None, "`ip` should be None when `url` parameter is supplied") # We don't allow any Unicode characters in the URL. Maybe some day we will... match = assert_matches(url, H2OConnection.url_pattern) scheme = match.group(1) ip = match.group(2) port = int(match.group(3)) context_path = '' if match.group(4) is None else "%s" % (match.group(4)) else: if ip is None: ip = str("localhost") if port is None: port = 54321 if https is None: https = False if is_type(port, str) and port.isdigit(): port = int(port) assert_is_type(ip, str) assert_is_type(port, int) assert_is_type(https, bool) assert_matches(ip, r"(?:[\w-]+\.)*[\w-]+") assert_satisfies(port, 1 <= port <= 65535) scheme = "https" if https else "http" context_path = '' if verify_ssl_certificates is None: verify_ssl_certificates = True assert_is_type(verify_ssl_certificates, bool) assert_is_type(proxy, str, None) assert_is_type(auth, AuthBase, (str, str), None) assert_is_type(cookies, str, [str], None) assert_is_type(_msgs, None, (str, str, str)) conn = H2OConnection() conn._verbose = bool(verbose) conn._local_server = server conn._base_url = "%s://%s:%d%s" % (scheme, ip, port, context_path) conn._verify_ssl_cert = bool(verify_ssl_certificates) conn._auth = auth conn._cookies = cookies conn._proxies = None if proxy and proxy != "(default)": conn._proxies = {scheme: proxy} elif not proxy: # Give user a warning if there are any "*_proxy" variables in the environment. [PUBDEV-2504] # To suppress the warning pass proxy = "(default)". for name in os.environ: if name.lower() == scheme + "_proxy": warn("Proxy is defined in the environment: %s. " "This may interfere with your H2O Connection." % name) try: retries = 20 if server else 5 conn._stage = 1 conn._timeout = 3.0 conn._cluster = conn._test_connection(retries, messages=_msgs) # If a server is unable to respond within 1s, it should be considered a bug. However we disable this # setting for now, for no good reason other than to ignore all those bugs :( conn._timeout = None # This is a good one! On the surface it registers a callback to be invoked when the script is about # to finish, but it also has a side effect in that the reference to current connection will be held # by the ``atexit`` service till the end -- which means it will never be garbage-collected. atexit.register(lambda: conn.close()) except Exception: # Reset _session_id so that we know the connection was not initialized properly. conn._stage = 0 raise return conn def request(self, endpoint, data=None, json=None, filename=None, save_to=None): """ Perform a REST API request to the backend H2O server. :param endpoint: (str) The endpoint's URL, for example "GET /4/schemas/KeyV4" :param data: data payload for POST (and sometimes GET) requests. This should be a dictionary of simple key/value pairs (values can also be arrays), which will be sent over in x-www-form-encoded format. :param json: also data payload, but it will be sent as a JSON body. Cannot be used together with `data`. :param filename: file to upload to the server. Cannot be used with `data` or `json`. :param save_to: if provided, will write the response to that file (additionally, the response will be streamed, so large files can be downloaded seamlessly). This parameter can be either a file name, or a folder name. If the folder doesn't exist, it will be created automatically. :returns: an H2OResponse object representing the server's response (unless ``save_to`` parameter is provided, in which case the output file's name will be returned). :raises H2OConnectionError: if the H2O server cannot be reached (or connection is not initialized) :raises H2OServerError: if there was a server error (http 500), or server returned malformed JSON :raises H2OResponseError: if the server returned an H2OErrorV3 response (e.g. if the parameters were invalid) """ if self._stage == 0: raise H2OConnectionError("Connection not initialized; run .connect() first.") if self._stage == -1: raise H2OConnectionError("Connection was closed, and can no longer be used.") # Prepare URL assert_is_type(endpoint, str) match = assert_matches(str(endpoint), r"^(GET|POST|PUT|DELETE|PATCH|HEAD) (/.*)$") method = match.group(1) urltail = match.group(2) url = self._base_url + urltail # Prepare data if filename is not None: assert_is_type(filename, str) assert_is_type(json, None, "Argument `json` should be None when `filename` is used.") assert_is_type(data, None, "Argument `data` should be None when `filename` is used.") assert_satisfies(method, method == "POST", "File uploads can only be done via POST method, got %s" % method) elif data is not None: assert_is_type(data, dict) assert_is_type(json, None, "Argument `json` should be None when `data` is used.") elif json is not None: assert_is_type(json, dict) data = self._prepare_data_payload(data) files = self._prepare_file_payload(filename) params = None if method == "GET" and data: params = data data = None stream = False if save_to is not None: assert_is_type(save_to, str) stream = True if self._cookies is not None and isinstance(self._cookies, list): self._cookies = ";".join(self._cookies) # Make the request start_time = time.time() try: self._log_start_transaction(endpoint, data, json, files, params) headers = {"User-Agent": "H2O Python client/" + sys.version.replace("\n", ""), "X-Cluster": self._cluster_id, "Cookie": self._cookies} resp = requests.request(method=method, url=url, data=data, json=json, files=files, params=params, headers=headers, timeout=self._timeout, stream=stream, auth=self._auth, verify=self._verify_ssl_cert, proxies=self._proxies) self._log_end_transaction(start_time, resp) return self._process_response(resp, save_to) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: if self._local_server and not self._local_server.is_running(): self._log_end_exception("Local server has died.") raise H2OConnectionError("Local server has died unexpectedly. RIP.") else: self._log_end_exception(e) raise H2OConnectionError("Unexpected HTTP error: %s" % e) except requests.exceptions.Timeout as e: self._log_end_exception(e) elapsed_time = time.time() - start_time raise H2OConnectionError("Timeout after %.3fs" % elapsed_time) except H2OResponseError as e: err = e.args[0] err.endpoint = endpoint err.payload = (data, json, files, params) raise def close(self): """ Close an existing connection; once closed it cannot be used again. Strictly speaking it is not necessary to close all connection that you opened -- we have several mechanisms in place that will do so automatically (__del__(), __exit__() and atexit() handlers), however there is also no good reason to make this method private. """ if self._session_id: try: # If the server gone bad, we don't want to wait forever... if self._timeout is None: self._timeout = 1 self.request("DELETE /4/sessions/%s" % self._session_id) self._print("H2O session %s closed." % self._session_id) except Exception: pass self._session_id = None self._stage = -1 @property def session_id(self): """ Return the session id of the current connection. The session id is issued (through an API request) the first time it is requested, but no sooner. This is because generating a session id puts it into the DKV on the server, which effectively locks the cloud. Once issued, the session id will stay the same until the connection is closed. """ if self._session_id is None: req = self.request("POST /4/sessions") self._session_id = req.get("session_key") or req.get("session_id") return CallableString(self._session_id) @property def cluster(self): """H2OCluster object describing the underlying cloud.""" return self._cluster @property def base_url(self): """Base URL of the server, without trailing ``"/"``. For example: ``"https://example.com:54321"``.""" return self._base_url @property def proxy(self): """URL of the proxy server used for the connection (or None if there is no proxy).""" if self._proxies is None: return None return self._proxies.values()[0] @property def local_server(self): """Handler to the H2OLocalServer instance (if connected to one).""" return self._local_server @property def requests_count(self): """Total number of request requests made since the connection was opened (used for debug purposes).""" return self._requests_counter @property def timeout_interval(self): """Timeout length for each request, in seconds.""" return self._timeout @timeout_interval.setter def timeout_interval(self, v): assert_is_type(v, numeric, None) self._timeout = v def start_logging(self, dest=None): """ Start logging all API requests to the provided destination. :param dest: Where to write the log: either a filename (str), or an open file handle (file). If not given, then a new temporary file will be created. """ assert_is_type(dest, None, str, type(sys.stdout)) if dest is None: dest = os.path.join(tempfile.mkdtemp(), "h2o-connection.log") self._print("Now logging all API requests to file %r" % dest) self._is_logging = True self._logging_dest = dest def stop_logging(self): """Stop logging API requests.""" if self._is_logging: self._print("Logging stopped.") self._is_logging = False #------------------------------------------------------------------------------------------------------------------- # PRIVATE #------------------------------------------------------------------------------------------------------------------- def __init__(self): """[Private] Please use H2OConnection.connect() to create H2OConnection objects.""" super(H2OConnection, self).__init__() globals()["__H2OCONN__"] = self # for backward-compatibility: __H2OCONN__ is the latest instantiated object self._stage = 0 # 0 = not connected, 1 = connected, -1 = disconnected self._session_id = None # Rapids session id; issued upon request only self._base_url = None # "{scheme}://{ip}:{port}" self._verify_ssl_cert = None self._auth = None # Authentication token self._proxies = None # `proxies` dictionary in the format required by the requests module self._cluster_id = None self._cookies = None self._cluster = None # H2OCluster object self._verbose = None # Print detailed information about connection status self._requests_counter = 0 # how many API requests were made self._timeout = None # timeout for a single request (in seconds) self._is_logging = False # when True, log every request self._logging_dest = None # where the log messages will be written, either filename or open file handle self._local_server = None # H2OLocalServer instance to which we are connected (if known) # self.start_logging(sys.stdout) def _test_connection(self, max_retries=5, messages=None): """ Test that the H2O cluster can be reached, and retrieve basic cloud status info. :param max_retries: Number of times to try to connect to the cloud (with 0.2s intervals). :returns: Cloud information (an H2OCluster object) :raises H2OConnectionError, H2OServerError: """ if messages is None: messages = ("Connecting to H2O server at {url}..", "successful.", "failed.") self._print(messages[0].format(url=self._base_url), end="") cld = None errors = [] for _ in range(max_retries): self._print(".", end="", flush=True) if self._local_server and not self._local_server.is_running(): raise H2OServerError("Local server was unable to start") try: cld = self.request("GET /3/Cloud") if cld.consensus and cld.cloud_healthy: self._print(" " + messages[1]) return cld else: if cld.consensus and not cld.cloud_healthy: msg = "in consensus but not healthy" elif not cld.consensus and cld.cloud_healthy: msg = "not in consensus but healthy" else: msg = "not in consensus and not healthy" errors.append("Cloud is in a bad shape: %s (size = %d, bad nodes = %d)" % (msg, cld.cloud_size, cld.bad_nodes)) except (H2OConnectionError, H2OServerError) as e: message = str(e) if "\n" in message: message = message[:message.index("\n")] errors.append("[%s.%02d] %s: %s" % (time.strftime("%M:%S"), int(time.time() * 100) % 100, e.__class__.__name__, message)) # Cloud too small, or voting in progress, or server is not up yet; sleep then try again time.sleep(0.2) self._print(" " + messages[2]) if cld and not cld.cloud_healthy: raise H2OServerError("Cluster reports unhealthy status") if cld and not cld.consensus: raise H2OServerError("Cluster cannot reach consensus") else: raise H2OConnectionError("Could not establish link to the H2O cloud %s after %d retries\n%s" % (self._base_url, max_retries, "\n".join(errors))) @staticmethod def _prepare_data_payload(data): """ Make a copy of the `data` object, preparing it to be sent to the server. The data will be sent via x-www-form-urlencoded or multipart/form-data mechanisms. Both of them work with plain lists of key/value pairs, so this method converts the data into such format. """ if not data: return None res = {} for key, value in viewitems(data): if value is None: continue # don't send args set to None so backend defaults take precedence if isinstance(value, list): value = stringify_list(value) elif isinstance(value, dict) and "__meta" in value and value["__meta"]["schema_name"].endswith("KeyV3"): value = value["name"] else: value = str(value) res[key] = value return res @staticmethod def _prepare_file_payload(filename): """ Prepare `filename` to be sent to the server. The "preparation" consists of creating a data structure suitable for passing to requests.request(). """ if not filename: return None absfilename = os.path.abspath(filename) if not os.path.exists(absfilename): raise H2OValueError("File %s does not exist" % filename, skip_frames=1) return {os.path.basename(absfilename): open(absfilename, "rb")} def _log_start_transaction(self, endpoint, data, json, files, params): """Log the beginning of an API request.""" # TODO: add information about the caller, i.e. which module + line of code called the .request() method # This can be done by fetching current traceback and then traversing it until we find the request function self._requests_counter += 1 if not self._is_logging: return msg = "\n---- %d --------------------------------------------------------\n" % self._requests_counter msg += "[%s] %s\n" % (time.strftime("%H:%M:%S"), endpoint) if params is not None: msg += " params: {%s}\n" % ", ".join("%s:%s" % item for item in viewitems(params)) if data is not None: msg += " body: {%s}\n" % ", ".join("%s:%s" % item for item in viewitems(data)) if json is not None: import json as j msg += " json: %s\n" % j.dumps(json) if files is not None: msg += " file: %s\n" % ", ".join(f.name for f in viewvalues(files)) self._log_message(msg + "\n") def _log_end_transaction(self, start_time, response): """Log response from an API request.""" if not self._is_logging: return elapsed_time = int((time.time() - start_time) * 1000) msg = "<<< HTTP %d %s (%d ms)\n" % (response.status_code, response.reason, elapsed_time) if "Content-Type" in response.headers: msg += " Content-Type: %s\n" % response.headers["Content-Type"] msg += response.text self._log_message(msg + "\n\n") def _log_end_exception(self, exception): """Log API request that resulted in an exception.""" if not self._is_logging: return self._log_message(">>> %s\n\n" % str(exception)) def _log_message(self, msg): """ Log the message `msg` to the destination `self._logging_dest`. If this destination is a file name, then we append the message to the file and then close the file immediately. If the destination is an open file handle, then we simply write the message there and do not attempt to close it. """ if is_type(self._logging_dest, str): with open(self._logging_dest, "at", encoding="utf-8") as f: f.write(msg) else: self._logging_dest.write(msg) @staticmethod def _process_response(response, save_to): """ Given a response object, prepare it to be handed over to the external caller. Preparation steps include: * detect if the response has error status, and convert it to an appropriate exception; * detect Content-Type, and based on that either parse the response as JSON or return as plain text. """ status_code = response.status_code if status_code == 200 and save_to: if save_to.startswith("~"): save_to = os.path.expanduser(save_to) if os.path.isdir(save_to) or save_to.endswith(os.path.sep): dirname = os.path.abspath(save_to) filename = H2OConnection._find_file_name(response) else: dirname, filename = os.path.split(os.path.abspath(save_to)) fullname = os.path.join(dirname, filename) try: if not os.path.exists(dirname): os.makedirs(dirname) with open(fullname, "wb") as f: for chunk in response.iter_content(chunk_size=65536): if chunk: # Empty chunks may occasionally happen f.write(chunk) except OSError as e: raise H2OValueError("Cannot write to file %s: %s" % (fullname, e)) return fullname content_type = response.headers.get("Content-Type", "") if ";" in content_type: # Remove a ";charset=..." part content_type = content_type[:content_type.index(";")] # Auto-detect response type by its content-type. Decode JSON, all other responses pass as-is. if content_type == "application/json": try: data = response.json(object_pairs_hook=H2OResponse) except (JSONDecodeError, requests.exceptions.ContentDecodingError) as e: raise H2OServerError("Malformed JSON from server (%s):\n%s" % (str(e), response.text)) else: data = response.text # Success (200 = "Ok", 201 = "Created", 202 = "Accepted", 204 = "No Content") if status_code in {200, 201, 202, 204}: return data # Client errors (400 = "Bad Request", 404 = "Not Found", 412 = "Precondition Failed") if status_code in {400, 404, 412} and isinstance(data, (H2OErrorV3, H2OModelBuilderErrorV3)): raise H2OResponseError(data) # Server errors (notably 500 = "Server Error") # Note that it is possible to receive valid H2OErrorV3 object in this case, however it merely means the server # did not provide the correct status code. raise H2OServerError("HTTP %d %s:\n%r" % (status_code, response.reason, data)) @staticmethod def _find_file_name(response): cd = response.headers.get("Content-Disposition", "") mm = re.search(r'filename="(.*)"$', cd) return mm.group(1) if mm else "unknown" def _print(self, msg, flush=False, end="\n"): """Helper function to print connection status messages when in verbose mode.""" if self._verbose: print2(msg, end=end, flush=flush) def __repr__(self): if self._stage == 0: return "<H2OConnection uninitialized>" elif self._stage == 1: sess = "session %s" % self._session_id if self._session_id else "no session" return "<H2OConnection to %s, %s>" % (self._base_url, sess) else: return "<H2OConnection closed>" def __enter__(self): """Called when an H2OConnection object is created within the ``with ...`` statement.""" return self def __exit__(self, *args): """Called at the end of the ``with ...`` statement.""" self.close() assert len(args) == 3 # Avoid warning about unused args... return False # ensure that any exception will be re-raised #------------------------------------------------------------------------------------------------------------------- # DEPRECATED # # Access to any of these vars / methods will produce deprecation warnings. # Consult backwards_compatible.py for the description of these vars. # # These methods are deprecated since July 2016. Please remove them if it's 2017 already... #------------------------------------------------------------------------------------------------------------------- _bcsv = {"__ENCODING__": "utf-8", "__ENCODING_ERROR__": "replace"} _bcsm = { "default": lambda: _deprecated_default(), "jar_paths": lambda: list(getattr(H2OLocalServer, "_jar_paths")()), "rest_version": lambda: 3, "https": lambda: __H2OCONN__.base_url.split(":")[0] == "https", "ip": lambda: __H2OCONN__.base_url.split(":")[1][2:], "port": lambda: __H2OCONN__.base_url.split(":")[2], "username": lambda: _deprecated_username(), "password": lambda: _deprecated_password(), "insecure": lambda: not getattr(__H2OCONN__, "_verify_ssl_cert"), "current_connection": lambda: __H2OCONN__, "check_conn": lambda: _deprecated_check_conn(), "make_url": lambda url_suffix, _rest_version=3: __H2OCONN__.make_url(url_suffix, _rest_version), "get": lambda url_suffix, **kwargs: _deprecated_get(__H2OCONN__, url_suffix, **kwargs), "post": lambda url_suffix, file_upload_info=None, **kwa: _deprecated_post(__H2OCONN__, url_suffix, file_upload_info=file_upload_info, **kwa), "delete": lambda url_suffix, **kwargs: _deprecated_delete(__H2OCONN__, url_suffix, **kwargs), "get_json": lambda url_suffix, **kwargs: _deprecated_get(__H2OCONN__, url_suffix, **kwargs), "post_json": lambda url_suffix, file_upload_info=None, **kwa: _deprecated_post(__H2OCONN__, url_suffix, file_upload_info=file_upload_info, **kwa), "rest_ctr": lambda: __H2OCONN__.requests_count, } _bcim = { "cluster_is_up": lambda self: self.cluster.is_running(), "info": lambda self, refresh=True: self.cluster, "shutdown_server": lambda self, prompt=True: self.cluster.shutdown(prompt), "make_url": lambda self, url_suffix, _rest_version=3: "/".join([self._base_url, str(_rest_version), url_suffix]), "get": lambda *args, **kwargs: _deprecated_get(*args, **kwargs), "post": lambda *args, **kwargs: _deprecated_post(*args, **kwargs), "delete": lambda *args, **kwargs: _deprecated_delete(*args, **kwargs), "get_json": lambda *args, **kwargs: _deprecated_get(*args, **kwargs), "post_json": lambda *args, **kwargs: _deprecated_post(*args, **kwargs), } class H2OResponse(dict): """Temporary...""" def __new__(cls, keyvals): # This method is called by the simplejson.json(object_pairs_hook=<this>) # `keyvals` is a list of (key,value) tuples. For example: # [("schema_version", 3), ("schema_name", "InitIDV3"), ("schema_type", "Iced")] schema = None for k, v in keyvals: if k == "__meta" and isinstance(v, dict): schema = v["schema_name"] break if k == "__schema" and is_type(v, str): schema = v break if schema == "CloudV3": return H2OCluster.from_kvs(keyvals) if schema == "H2OErrorV3": return H2OErrorV3(keyvals) if schema == "H2OModelBuilderErrorV3": return H2OModelBuilderErrorV3(keyvals) if schema == "TwoDimTableV3": return H2OTwoDimTable.make(keyvals) if schema == "ModelMetricsRegressionV3": return H2ORegressionModelMetrics.make(keyvals) if schema == "ModelMetricsClusteringV3": return H2OClusteringModelMetrics.make(keyvals) if schema == "ModelMetricsBinomialV3": return H2OBinomialModelMetrics.make(keyvals) if schema == "ModelMetricsMultinomialV3": return H2OMultinomialModelMetrics.make(keyvals) if schema == "ModelMetricsOrdinalV3": return H2OOrdinalModelMetrics.make(keyvals) if schema == "ModelMetricsAutoEncoderV3": return H2OAutoEncoderModelMetrics.make(keyvals) return super(H2OResponse, cls).__new__(cls, keyvals) # def __getattr__(self, key): # """This gets invoked for any attribute "key" that is NOT yet defined on the object.""" # if key in self: # return self[key] # return None # Find the exception that occurs on invalid JSON input JSONDecodeError, _r = None, None try: _r = requests.Response() _r._content = b"haha" _r.json() except Exception as exc: JSONDecodeError = type(exc) del _r #----------------------------------------------------------------------------------------------------------------------- # Deprecated method implementations #----------------------------------------------------------------------------------------------------------------------- __H2OCONN__ = H2OConnection() # Latest instantiated H2OConnection object. Do not use in any new code! __H2O_REST_API_VERSION__ = 3 # Has no actual meaning def _deprecated_default(): H2OConnection.__ENCODING__ = "utf-8" H2OConnection.__ENCODING_ERROR__ = "replace" def _deprecated_username(): auth = getattr(__H2OCONN__, "_auth") return auth[0] if isinstance(auth, tuple) else None def _deprecated_password(): auth = getattr(__H2OCONN__, "_auth") return auth[1] if isinstance(auth, tuple) else None def _deprecated_check_conn(): if not __H2OCONN__: raise H2OConnectionError("No active connection to an H2O cluster. Try calling `h2o.connect()`") return __H2OCONN__ def _deprecated_get(self, url_suffix, **kwargs): restver = kwargs.pop("_rest_version") if "_rest_version" in kwargs else 3 endpoint = "GET /%d/%s" % (restver, url_suffix) return self.request(endpoint, data=kwargs) def _deprecated_post(self, url_suffix, **kwargs): restver = kwargs.pop("_rest_version") if "_rest_version" in kwargs else 3 endpoint = "POST /%d/%s" % (restver, url_suffix) filename = None if "file_upload_info" in kwargs: filename = next(iter(viewvalues(kwargs.pop("file_upload_info")))) return self.request(endpoint, data=kwargs, filename=filename) def _deprecated_delete(self, url_suffix, **kwargs): restver = kwargs.pop("_rest_version") if "_rest_version" in kwargs else 3 endpoint = "DELETE /%d/%s" % (restver, url_suffix) return self.request(endpoint, data=kwargs) def end_session(): """Deprecated, use connection.close() instead.""" print("Warning: end_session() is deprecated") __H2OCONN__.close()
spennihana/h2o-3
h2o-py/h2o/backend/connection.py
Python
apache-2.0
41,004
from __future__ import print_function from __future__ import division from builtins import range from past.utils import old_div from proteus import Comm, Profiling import numpy as np import numpy.testing as npt import unittest import random from math import cos,sin,cosh,sinh,pi,tanh,log,atan2,asin,acos,radians import sys,os import logging import pytest import cython comm = Comm.init() Profiling.procID = comm.rank() def getpath(): path = sys.path[0]+'/' return path def remove_files(filenames): ''' delete files in filenames list ''' for f in filenames: if os.path.exists(f): try: os.remove(f) except OSError as e: print ("Error: %s - %s" %(e.filename,e.strerror)) else: pass Profiling.logEvent("Testing Bodydynamics") class TestAuxFunctions(unittest.TestCase): def testForwardEler(self): from proteus.mprans.BodyDynamics import forward_euler p0 = 5.0 v0 = 2.0 a = 0.5 dt = 0.01 v = v0 + a*dt p = p0 + v*dt p1, v1 = forward_euler(p0, v0, a, dt) self.assertTrue(p==p1) self.assertTrue(v==v1) def testRungeKutta(self): from proteus.mprans.BodyDynamics import runge_kutta u0 = 5.0 v0 = 2.0 dt = 0.01 substeps = 20 F = 150.0 K = 100000.0 C = 1000.0 m = 50.0 a0 = old_div((F - C*v0 - K*u0), m) velCheck = True # Loop through substeps for i in range(substeps): # 1st step u1 = u0 v1 = v0 a1 = old_div((F - C*v1 - K*u1), m) # 2nd step u2 = u0 + v1*dt/2. v2 = v0 + a1*dt/2. a2 = old_div((F - C*v2 - K*u2), m) # 3rd step u3 = u0 + v2*dt/2. v3 = v0 + a2*dt/2. a3 = old_div((F - C*v3 - K*u3), m) # 4th step u4 = u0 + v3*dt v4 = v0 + a3*dt a4 = old_div((F - C*v4 - K*u4), m) # Final step u = u0 + dt/6.*(v1+2*v2+2*v3+v4) v = v0 + dt/6.*(a1+2*a2+2*a3+a4) a = old_div((F - C*v - K*u), m) # Check for friction module, when velocity is reversed if velCheck: if v0*v < 0.0: break uc, vc, ac = runge_kutta(u0, v0, a0, dt, substeps, F, K, C, m, velCheck) self.assertTrue(u==uc) self.assertTrue(v==vc) self.assertTrue(a==ac) def testEulerAngles(self): from proteus.mprans.BodyDynamics import getEulerAngles coords = np.array([ [1.,0.,0.], [0.,1.,0.], [0.,0.,1.] ]) anglex = radians(5.0) angley = radians(10.) anglez = radians(15.) # rotation around x-axis rotx = np.array([ [ 1.0, 0.0, 0.0 ], [ 0.0, cos(anglex), sin(anglex) ], [ 0.0, -sin(anglex), cos(anglex) ] ]) # rotation around y-axis roty = np.array([ [ cos(angley), 0.0, -sin(angley) ], [ 0.0, 1.0, 0.0 ], [ sin(angley), 0.0, cos(angley) ] ]) # rotation around z-axis rotz = np.array([ [ cos(anglez), sin(anglez), 0.0 ], [ -sin(anglez), cos(anglez), 0.0 ], [ 0.0, 0.0, 1.0 ] ]) # total 3D rotation rot3D = np.dot(np.dot(rotx,roty),rotz) coordinates = np.dot( rot3D, coords) ax = atan2(coordinates[1,2], coordinates[2,2]) ay = asin(-coordinates[0,2]) az = atan2(coordinates[0,1], coordinates[0,0]) angles = [ax, ay, az] rotation = getEulerAngles(coordinates) self.assertTrue(angles==rotation) class TestRigidBody(unittest.TestCase): def testCalculateInit(self): from proteus import Domain from proteus.mprans import SpatialTools as st from proteus.mprans import BodyDynamics as bd domain = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) rot = np.array([ [1.,0.,0.], [0.,1.,0.], [0.,0.,1.] ]) dim=(0.3, 0.385) caisson = st.Rectangle(domain, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.RigidBody(shape=caisson) st.assembleDomain(domain) c2d = caisson2D nd = 2 angle = bd.getEulerAngles(rot) c2d.calculate_init() npt.assert_equal(c2d.position, pos) npt.assert_equal(c2d.last_position, pos) npt.assert_equal(c2d.rotation, rot) npt.assert_equal(c2d.last_rotation, rot) npt.assert_equal(c2d.rotation_euler, angle) npt.assert_equal(c2d.last_rotation_euler, angle) def testStoreLastValues(self): from proteus import Domain from proteus.mprans import SpatialTools as st from proteus.mprans import BodyDynamics as bd domain = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) rot = np.array([ [1.,0.,0.], [0.,1.,0.], [0.,0.,1.] ]) dim=(0.3, 0.385) caisson = st.Rectangle(domain, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.RigidBody(shape=caisson) st.assembleDomain(domain) c2d = caisson2D nd = 2 anglez = radians(5.0) rotz = np.array([ [ cos(anglez), sin(anglez), 0.0 ], [ -sin(anglez), cos(anglez), 0.0 ], [ 0.0, 0.0, 1.0 ] ]) c2d.calculate_init() # Imposing values on rigid body's parameters c2d.position = np.array([2.0, 3.0, 0.0]) c2d.velocity = np.array([0.5, -0.3, 0.0]) c2d.acceleration = np.array([0.1, 0.2, 0.0]) c2d.rotation = rotz c2d.rotation_euler = bd.getEulerAngles(rotz) c2d.ang_disp = np.array([0.0, 0.0, 0.001]) c2d.ang_vel = np.array([0.0, 0.0, -0.003]) c2d.ang_acc = np.array([0.0, 0.0, 0.005]) c2d.F = np.array([100.0, -300.0, 0.0]) c2d.M = np.array([0.0, 0.0, 50.0]) c2d.pivot = c2d.barycenter c2d.ux = 0.5 c2d.uy = 0.05 c2d.uz = 0.0 c2d._store_last_values() npt.assert_equal(c2d.position, c2d.last_position) npt.assert_equal(c2d.velocity, c2d.last_velocity) npt.assert_equal(c2d.acceleration, c2d.last_acceleration) npt.assert_equal(c2d.rotation, c2d.last_rotation) npt.assert_equal(c2d.rotation_euler, c2d.last_rotation_euler) npt.assert_equal(c2d.ang_disp, c2d.last_ang_disp) npt.assert_equal(c2d.ang_vel, c2d.last_ang_vel) npt.assert_equal(c2d.ang_acc, c2d.last_ang_acc) npt.assert_equal(c2d.F, c2d.last_F) npt.assert_equal(c2d.M, c2d.last_M) npt.assert_equal(c2d.pivot, c2d.last_pivot) npt.assert_equal(c2d.ux, c2d.last_ux) npt.assert_equal(c2d.uy, c2d.last_uy) npt.assert_equal(c2d.uz, c2d.last_uz) def testGetInertia(self): from proteus import Domain from proteus import SpatialTools as st from proteus.mprans import SpatialTools as mst from proteus.mprans import BodyDynamics as bd # 2d case domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) dim = (0.3, 0.385) caisson = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.RigidBody(shape=caisson) mst.assembleDomain(domain2D) c2d = caisson2D c2d.nd = 2 Ix = (old_div((dim[0]**2),12.)) Iy = (old_div((dim[1]**2),12.)) It = Ix + Iy mass = 50.0 I1 = It*mass c2d.mass = mass c2d.It = It I2 = c2d.getInertia() npt.assert_equal(I1, I2) # 3d case pos, dim, caisson = [], [], [] domain3D = Domain.PiecewiseLinearComplexDomain() pos = np.array([0.0, 0.0, 0.0]) dim = (0.3, 0.385, 0.4) angle = radians(10.) Ix = (old_div((dim[0]**2),12.)) Iy = (old_div((dim[1]**2),12.)) Iz = (old_div((dim[2]**2),12.)) It = np.array([ [Iz + Iy, 0.0, 0.0], [0.0, Ix + Iz, 0.0], [0.0, 0.0, Ix + Iy] ]) mass = 50.0 # rotational axis and versors ax, ay, az = axis = np.array([1., 1., 1.]) mod = np.sqrt((ax**2)+(ay**2)+(az**2)) axis_ver = (old_div(axis,mod)) # shape caisson = mst.Cuboid(domain=domain3D, dim=dim, coords=[pos[0], pos[1], pos[2]]) caisson.rotate(rot=angle, axis=axis) coords_system = caisson.coords_system caisson3D = bd.RigidBody(shape=caisson) mst.assembleDomain(domain3D) # rotational operator for inertia calculation on an arbitrary axis rotx, roty, rotz = np.dot(axis_ver, np.linalg.inv(coords_system)) rot = np.array([ [(rotx**2), rotx*roty, rotx*rotz], [roty*rotx, (roty**2), roty*rotz], [rotz*rotx, rotz*roty, (rotz**2)] ]) #inertia = np.einsum('ij,ij->', mass*It, rot) inertia = np.sum(mass*It*rot) # testing from BodyDynamics c3d = caisson3D c3d.nd = 3 c3d.mass = mass c3d.It = It c3d.coords_system = coords_system I = c3d.getInertia(vec=axis) npt.assert_equal(I, inertia) def testGetAcceleration(self): from proteus import Domain from proteus.mprans import SpatialTools as st from proteus.mprans import BodyDynamics as bd domain = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) rot = np.array([ [1.,0.,0.], [0.,1.,0.], [0.,0.,1.] ]) dim=(0.3, 0.385) caisson = st.Rectangle(domain, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.RigidBody(shape=caisson) st.assembleDomain(domain) c2d = caisson2D F = np.array([100.0, -200.0, 10.0]) mass = 150.0 acceleration = old_div(F,mass) c2d.F = F c2d.mass = mass c2d.acceleration = c2d.getAcceleration() npt.assert_equal(c2d.acceleration, acceleration) def testGetAngularAcceleration(self): from proteus import Domain from proteus.mprans import SpatialTools as st from proteus.mprans import BodyDynamics as bd domain = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) rot = np.array([ [1.,0.,0.], [0.,1.,0.], [0.,0.,1.] ]) dim=(0.3, 0.385) caisson = st.Rectangle(domain, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.RigidBody(shape=caisson) st.assembleDomain(domain) c2d = caisson2D F = np.array([100.0, -200.0, 10.0]) mass = 150.0 acceleration = old_div(F,mass) c2d.F = F c2d.mass = mass c2d.acceleration = c2d.getAcceleration() npt.assert_equal(c2d.acceleration, acceleration) def testGetDisplacement(self): from proteus import Domain from proteus import SpatialTools as st from proteus.mprans import SpatialTools as mst from proteus.mprans import BodyDynamics as bd # parameters domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) dim = (0.3, 0.385) caisson = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.RigidBody(shape=caisson) mst.assembleDomain(domain2D) c2d = caisson2D c2d.nd = 2 Ix = (old_div((dim[0]**2),12.)) Iy = (old_div((dim[1]**2),12.)) It = Ix + Iy mass = 50.0 c2d.mass, c2d.It = mass, It Kx, Ky, Kz = K = [200000., 250000., 0.0] Cx, Cy, Cz = C = [2000., 4000., 0.0] c2d.Kx, c2d.Ky, c2d.Kz, c2d.Cx, c2d.Cy, c2d.Cz = Kx, Ky, Kz, Cx, Cy, Cz init_barycenter, last_position, last_velocity = pos, pos*2.0, np.array([0.05, 0.07, 0.0]) c2d.init_barycenter, c2d.last_position, c2d.last_velocity = init_barycenter, last_position, last_velocity Fx, Fy, Fz = F = np.array([200., 300., 0.0]) dt, substeps = 0.001, 50 dt_sub = c2d.dt_sub = float(old_div(dt,substeps)) c2d.F, c2d.substeps, c2d.dt, c2d.acceleration = F, substeps, dt, c2d.getAcceleration() # runge-kutta calculation c2d.scheme = 'Runge_Kutta' u0 = ux0, uy0, uz0 = last_position - init_barycenter v0 = vx0, vy0, vz0 = last_velocity a0 = ax0, ay0, az0 = old_div((F - C*v0 - K*u0), mass) for ii in range(substeps): ux, vx, ax = bd.runge_kutta(ux0, vx0, ax0, dt_sub, substeps, Fx, Kx, Cx, mass, False) uy, vy, ay = bd.runge_kutta(uy0, vy0, ay0, dt_sub, substeps, Fy, Ky, Cy, mass, False) uz, vz, az = bd.runge_kutta(uz0, vz0, az0, dt_sub, substeps, Fz, Kz, Cz, mass, False) h = hx, hy, hz = [ux-ux0, uy-uy0, uz-uz0] c2d.h = c2d.getDisplacement(dt) npt.assert_equal(c2d.h, h) def testStep(self): from proteus import Domain from proteus import SpatialTools as st from proteus.mprans import SpatialTools as mst from proteus.mprans import BodyDynamics as bd # parameters domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) dim = (0.3, 0.385) caisson = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.RigidBody(shape=caisson) mst.assembleDomain(domain2D) c2d = caisson2D nd = c2d.nd = 2 Ix = (old_div((dim[0]**2),12.)) Iy = (old_div((dim[1]**2),12.)) It = Ix + Iy mass = 50.0 I = mass*It c2d.mass, c2d.It = mass, It init_barycenter, last_position, last_velocity, last_rotation, last_ang_vel = pos, pos*2.0, np.array([0.05, 0.07, 0.0]), np.array([0.0, 0.0, 0.0001]), np.array([0., 0., 0.0000002]) c2d.init_barycenter, c2d.last_position, c2d.last_velocity, c2d.last_rotation, c2d.last_ang_vel = init_barycenter, last_position, last_velocity, last_rotation, last_ang_vel F = Fx, Fy, Fz = np.array([200., 300., 0.0]) M = Mx, My, Mz = np.array([0., 0., 50.0]) dt, substeps = 0.001, 20 dt_sub = c2d.dt_sub = float(old_div(dt,substeps)) c2d.F, c2d.substeps, c2d.dt, c2d.acceleration = F, substeps, dt, c2d.getAcceleration() c2d.InputMotion = False c2d.scheme = 'Forward_Euler' h, tra_velocity = bd.forward_euler(last_position, last_velocity, old_div(F,mass), dt) rot, rot_velocity = bd.forward_euler(last_rotation, last_ang_vel, old_div(M,I), dt) if rot[2] < 0.0: rot[2]=-rot[2] # 2d calculation caisson.translate(h[:nd]), caisson.rotate(rot[2]) posTra1, rot1 = caisson.barycenter, caisson.coords_system # 2d from bodydynamics caisson.translate(-h[:nd]), caisson.rotate(-rot[2]) c2d.step(dt) posTra2, rot2 = c2d.position, c2d.rotation[:nd,:nd] npt.assert_allclose(posTra1, posTra2, atol=1e-10) npt.assert_allclose(rot1, rot2, atol=1e-10) # def testSetRecordValues(self): # from proteus import Domain # from proteus import SpatialTools as st # from proteus.mprans import SpatialTools as mst # from proteus.mprans import BodyDynamics as bd # filename='test', all_values=True class CaissonBody(unittest.TestCase): def testGetInertia(self): from proteus import Domain from proteus import SpatialTools as st from proteus.mprans import SpatialTools as mst from proteus.mprans import BodyDynamics as bd # parameters domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) dim = (0.3, 0.385) dt, substeps = 0.001, 20 caisson = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.CaissonBody(shape=caisson, substeps=substeps) mst.assembleDomain(domain2D) c2d = caisson2D c2d.nd = 2 mass = c2d.mass = 50.0 pivot = np.array([(caisson.vertices[0][0]+caisson.vertices[1][0])*0.5, caisson.vertices[0][1], 0.0]) d = dx, dy, dz = pivot - caisson.barycenter # inertia transformation with different pivot Ix = (old_div((dim[0]**2),12.)) + dy**2 Iy = (old_div((dim[1]**2),12.)) + dx**2 It = Ix + Iy I = It*mass I1 = c2d.getInertia(vec=(0.,0.,1.), pivot=pivot) npt.assert_equal(I, I1) def testFrictionModule(self): from proteus import Domain from proteus import SpatialTools as st from proteus.mprans import SpatialTools as mst from proteus.mprans import BodyDynamics as bd ######################### # 1st case # ######################### # When sliding is true and caisson already experiences plastic displacements # parameters domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) dim = (0.3, 0.385) dt, substeps = 0.001, 20 caisson = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.CaissonBody(shape=caisson, substeps=substeps) mst.assembleDomain(domain2D) c2d = caisson2D c2d.nd = 2 dt_sub = c2d.dt_sub = float(old_div(dt,substeps)) Ix = (old_div((dim[0]**2),12.)) Iy = (old_div((dim[1]**2),12.)) It = Ix + Iy mass = 50.0 c2d.mass, c2d.It = mass, It K = Kx, Ky, Kz = [200000., 250000., 0.0] C = Cx, Cy, Cz = [2000., 4000., 0.0] c2d.Kx, c2d.Ky, c2d.Kz, c2d.Cx, c2d.Cy, c2d.Cz = Kx, Ky, Kz, Cx, Cy, Cz c2d.substeps, c2d.dt, c2d.acceleration = substeps, dt, c2d.getAcceleration() m_static, m_dynamic = 0.6, 0.4 c2d.setFriction(friction=True, m_static=m_static, m_dynamic=m_dynamic, tolerance=0.000001, grainSize=0.02) # sliding == True. dynamic sign and dynamic friction F = Fx, Fy, Fz = np.array([200., -300., 0.0]) disp = np.array([0.001, 0.001, 0.0]) init_barycenter, last_position, last_velocity = pos, pos+disp, np.array([0.05, 0.07, 0.0]) c2d.last_uxEl = pos[0]+disp[0]-init_barycenter[0] c2d.F, c2d.init_barycenter, c2d.last_position, c2d.last_velocity = F, init_barycenter, last_position, last_velocity eps = 10.**-30 sign_static, sign_dynamic = old_div(Fx,abs(Fx+eps)), old_div(last_velocity[0],abs(last_velocity[0]+eps)) c2d.sliding, sign, m = True, sign_dynamic, m_dynamic # vertical calculation and frictional force uy0, vy0 = (last_position[1] - init_barycenter[1]), last_velocity[1] ay0 = old_div((Fy - Cy*vy0 - Ky*uy0), mass) uy, vy, ay = bd.runge_kutta(uy0, vy0, ay0, dt_sub, substeps, Fy, Ky, Cy, mass, False) Rx = -Kx*(last_position[0]-init_barycenter[0]) Ry = -Ky*uy Ftan = -sign*abs(Ry)*m if Ftan == 0.0: Ftan = -sign*abs(Fy)*m # runge-kutta calculation c2d.scheme = 'Runge_Kutta' ux0, uz0 = last_position[0] - init_barycenter[0], last_position[2] - init_barycenter[2] vx0, vz0 = last_velocity[0], last_velocity[2] Fh = Fx+Ftan Kx, Cx = 0.0, 0.0 ax0, az0 = old_div((Fh - Cx*vx0 - Kx*ux0), mass) , old_div((Fz - Cz*vz0 - Kz*uz0), mass) ux, vx, ax = bd.runge_kutta(ux0, vx0, ax0, dt_sub, substeps, Fh, Kx, Cx, mass, True) uz, vz, az = bd.runge_kutta(uz0, vz0, az0, dt_sub, substeps, Fz, Kz, Cz, mass, False) # bodydynamics calculation c2d.friction_module(dt) # tests npt.assert_equal(c2d.ux, ux) EL1, PL1 = 0.0, 1.0 # elastic and plastic motion parameters npt.assert_equal(c2d.EL, EL1) npt.assert_equal(c2d.PL, PL1) ######################### # 2nd case # ######################### # When sliding is false but the caisson starts to experience sliding motion # parameters domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) dim = (0.3, 0.385) dt, substeps = 0.001, 20 caisson = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.CaissonBody(shape=caisson, substeps=substeps) mst.assembleDomain(domain2D) c2d = caisson2D c2d.nd = 2 dt_sub = c2d.dt_sub = float(old_div(dt,substeps)) Ix = (old_div((dim[0]**2),12.)) Iy = (old_div((dim[1]**2),12.)) It = Ix + Iy mass = 50.0 c2d.mass, c2d.It = mass, It K = Kx, Ky, Kz = [200000., 250000., 0.0] C = Cx, Cy, Cz = [2000., 4000., 0.0] c2d.Kx, c2d.Ky, c2d.Kz, c2d.Cx, c2d.Cy, c2d.Cz = Kx, Ky, Kz, Cx, Cy, Cz c2d.substeps, c2d.dt, c2d.acceleration = substeps, dt, c2d.getAcceleration() m_static, m_dynamic = 0.6, 0.4 c2d.setFriction(friction=True, m_static=m_static, m_dynamic=m_dynamic, tolerance=0.000001, grainSize=0.02) # sliding == False. static sign and static friction F = Fx, Fy, Fz = np.array([200., -300., 0.0]) disp = np.array([0.001, 0.001, 0.0]) init_barycenter, last_position, last_velocity = pos, pos+disp, np.array([0.05, 0.07, 0.0]) c2d.last_uxEl = pos[0]+disp[0]-init_barycenter[0] c2d.F, c2d.init_barycenter, c2d.last_position, c2d.last_velocity = F, init_barycenter, last_position, last_velocity eps = 10.**-30 sign_static, sign_dynamic = old_div(Fx,abs(Fx+eps)), old_div(last_velocity[0],abs(last_velocity[0]+eps)) c2d.sliding, sign, m = False, sign_static, m_static # vertical calculation and frictional force uy0, vy0 = (last_position[1] - init_barycenter[1]), last_velocity[1] ay0 = old_div((Fy - Cy*vy0 - Ky*uy0), mass) uy, vy, ay = bd.runge_kutta(uy0, vy0, ay0, dt_sub, substeps, Fy, Ky, Cy, mass, False) Rx = -Kx*(last_position[0]-init_barycenter[0]) Ry = -Ky*uy Ftan = -sign*abs(Ry)*m if Ftan == 0.0: Ftan = -sign*abs(Fy)*m # runge-kutta calculation c2d.scheme = 'Runge_Kutta' ux0, uz0 = last_position[0] - init_barycenter[0], last_position[2] - init_barycenter[2] vx0, vz0 = last_velocity[0], last_velocity[2] Fh = Fx+Ftan Kx, Cx = 0.0, 0.0 ax0, az0 = old_div((Fh - Cx*vx0 - Kx*ux0), mass) , old_div((Fz - Cz*vz0 - Kz*uz0), mass) ux, vx, ax = bd.runge_kutta(ux0, vx0, ax0, dt_sub, substeps, Fh, Kx, Cx, mass, True) uz, vz, az = bd.runge_kutta(uz0, vz0, az0, dt_sub, substeps, Fz, Kz, Cz, mass, False) # bodydynamics calculation c2d.friction_module(dt) # tests npt.assert_equal(c2d.ux, ux) EL1, PL1 = 0.0, 1.0 # elastic and plastic motion parameters npt.assert_equal(c2d.EL, EL1) npt.assert_equal(c2d.PL, PL1) ######################### # 3rd case # ######################### # When caisson experiences vibration motion # parameters domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) dim = (0.3, 0.385) dt, substeps = 0.001, 20 caisson = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.CaissonBody(shape=caisson, substeps=substeps) mst.assembleDomain(domain2D) c2d = caisson2D c2d.nd = 2 dt_sub = c2d.dt_sub = float(old_div(dt,substeps)) Ix = (old_div((dim[0]**2),12.)) Iy = (old_div((dim[1]**2),12.)) It = Ix + Iy mass = 50.0 c2d.mass, c2d.It = mass, It K = Kx, Ky, Kz = [200000., 250000., 0.0] C = Cx, Cy, Cz = [2000., 4000., 0.0] c2d.Kx, c2d.Ky, c2d.Kz, c2d.Cx, c2d.Cy, c2d.Cz = Kx, Ky, Kz, Cx, Cy, Cz c2d.substeps, c2d.dt, c2d.acceleration = substeps, dt, c2d.getAcceleration() m_static, m_dynamic = 0.6, 0.4 c2d.setFriction(friction=True, m_static=m_static, m_dynamic=m_dynamic, tolerance=0.000001, grainSize=0.02) # sliding == False. static sign and static friction. Kx and Cx different from 0! F = Fx, Fy, Fz = np.array([200., -300., 0.0]) disp = np.array([0.00001, 0.00001, 0.0]) init_barycenter, last_position, last_velocity = pos, pos+disp, np.array([0.05, 0.07, 0.0]) c2d.last_uxEl = pos[0]+disp[0]-init_barycenter[0] c2d.F, c2d.init_barycenter, c2d.last_position, c2d.last_velocity = F, init_barycenter, last_position, last_velocity eps = 10.**-30 sign_static, sign_dynamic = old_div(Fx,abs(Fx+eps)), old_div(last_velocity[0],abs(last_velocity[0]+eps)) c2d.sliding, sign, m = False, sign_static, m_static # vertical calculation and frictional force uy0, vy0 = (last_position[1] - init_barycenter[1]), last_velocity[1] ay0 = old_div((Fy - Cy*vy0 - Ky*uy0), mass) uy, vy, ay = bd.runge_kutta(uy0, vy0, ay0, dt_sub, substeps, Fy, Ky, Cy, mass, False) Rx = -Kx*(last_position[0]-init_barycenter[0]) Ry = -Ky*uy Ftan = -sign*abs(Ry)*m if Ftan == 0.0: Ftan = -sign*abs(Fy)*m # runge-kutta calculation c2d.scheme = 'Runge_Kutta' ux0, uz0 = last_position[0] - init_barycenter[0], last_position[2] - init_barycenter[2] vx0, vz0 = last_velocity[0], last_velocity[2] Fh = Fx ax0, az0 = old_div((Fh - Cx*vx0 - Kx*ux0), mass) , old_div((Fz - Cz*vz0 - Kz*uz0), mass) ux, vx, ax = bd.runge_kutta(ux0, vx0, ax0, dt_sub, substeps, Fh, Kx, Cx, mass, True) uz, vz, az = bd.runge_kutta(uz0, vz0, az0, dt_sub, substeps, Fz, Kz, Cz, mass, False) # bodydynamics calculation c2d.friction_module(dt) # tests npt.assert_equal(c2d.ux, ux) EL1, PL1 = 1.0, 0.0 # elastic and plastic motion parameters npt.assert_equal(c2d.EL, EL1) npt.assert_equal(c2d.PL, PL1) def testOverturningModule(self): from proteus import Domain from proteus import SpatialTools as st from proteus.mprans import SpatialTools as mst from proteus.mprans import BodyDynamics as bd # parameters domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([1.0, 1.0, 0.0]) dim = (0.3, 0.385) dt, substeps = 0.001, 20 caisson = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) caisson2D = bd.CaissonBody(shape=caisson, substeps=substeps) mst.assembleDomain(domain2D) c2d = caisson2D c2d.nd = 2 dt_sub = c2d.dt_sub = float(old_div(dt,substeps)) Krot = 200000. Crot = 2000. c2d.Krot, c2d.Crot = Krot, Crot c2d.substeps, c2d.dt, c2d.ang_acc = substeps, dt, c2d.getAngularAcceleration() c2d.setFriction(friction=True, m_static=0.0, m_dynamic=0.0, tolerance=0.000001, grainSize=0.02) rotation, last_rotation = c2d.Shape.coords_system, c2d.Shape.coords_system ang_vel, last_ang_vel = np.array([0., 0., 0.]), np.array([0., 0., 0.]) F = Fx, Fy, Fz = np.array([200., -300., 0.0]) M = np.array([0., 0., 10.0]) init_barycenter, last_position = pos, pos c2d.F, c2d.M, c2d.init_barycenter, c2d.last_position = F, M, init_barycenter, last_position eps = 10.**-30 mass = c2d.mass = 50.0 # moment and inertia transformations pivot = c2d.pivot_friction = np.array([(caisson.vertices[0][0]+caisson.vertices[1][0])*0.5, caisson.vertices[0][1], 0.0]) barycenter = caisson.barycenter distance = dx, dy, dz = pivot - barycenter Mpivot = np.array([0., 0., dx*Fy-dy*Fx]) # Moment calculated in pivot Mp = M - Mpivot # Moment transformation through the new pivot Ix = (old_div((dim[0]**2),12.)) + dy**2 Iy = (old_div((dim[1]**2),12.)) + dx**2 It = Ix + Iy I = It*mass c2d.springs = True # runge-kutta calculation c2d.scheme = 'Runge_Kutta' rz0, vrz0 = atan2(last_rotation[0,1], last_rotation[0,0]), last_ang_vel[2] arz0 = old_div((Mp[2] - Crot*vrz0 - Krot*rz0), I) rz, vrz, arz = bd.runge_kutta(rz0, vrz0, arz0, dt_sub, substeps, Mp[2], Krot, Crot, I, False) # calculation with bodydynamics mopdule c2d.cV_init = c2d.cV = c2d.cV_last = caisson.vertices c2d.inertia = c2d.getInertia(pivot=pivot) c2d.overturning_module(dt) # test ang_disp = rz - rz0 npt.assert_equal(c2d.ang_disp[2], ang_disp) npt.assert_equal(c2d.ang_vel[2], vrz) npt.assert_equal(c2d.ang_acc[2], arz) class Paddle(unittest.TestCase): def testCalculate_init(self): from proteus import Domain from proteus.mprans import SpatialTools as mst from proteus.mprans.BodyDynamics import PaddleBody domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([2.0, 0.1 , 0.0]) dim = (0.3, 1.) paddle = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) PB=PaddleBody(paddle,substeps=20) PB.calculate_init() npt.assert_equal(PB.position,[pos[0],0.,0.]) npt.assert_equal(PB.last_position,[pos[0],0.,0.]) npt.assert_equal(PB.rotation,np.eye(3)) npt.assert_equal(PB.last_rotation,np.eye(3)) from proteus.mprans.BodyDynamics import getEulerAngles npt.assert_equal(PB.rotation_euler,getEulerAngles(PB.rotation)) npt.assert_equal(PB.last_rotation_euler,getEulerAngles(PB.last_rotation)) npt.assert_equal(PB.cV_init,np.array([(1.85,-0.4), (2.15,-0.4), (2.15,0.6), (1.85,0.6)])) npt.assert_equal(PB.cV,np.array([(1.85,-0.4), (2.15,-0.4), (2.15,0.6), (1.85,0.6)])) npt.assert_equal(PB.cV_last,np.array([(1.85,-0.4), (2.15,-0.4), (2.15,0.6), (1.85,0.6)])) def testPaddleMotion(self): from proteus import Domain from proteus.mprans import SpatialTools as mst from proteus.mprans.BodyDynamics import PaddleBody domain2D = Domain.PlanarStraightLineGraphDomain() pos = np.array([2.0, 0.1 , 0.0]) dim = (0.3, 1.) paddle = mst.Rectangle(domain=domain2D, dim=dim, coords=[pos[0], pos[1]]) PB=PaddleBody(paddle,substeps=20) PB.calculate_init() At = [1.,0.,0.] Ar = [0.1,0.,0.] Tt = Tr = [0.5,0.,0.] rampS = 0.1 rampE = 0.1 Tend = 2. PB.inputMotion(InputMotion=True, pivot=None, At=At, Tt=Tt, Ar=Ar, Tr=Tr, rampStart=rampS, rampEnd =rampE, Tend = Tend) # tersting initial ramp times= [0.04, 0.95 ,1.93] for tt in times: ramp = min(1.,tt/rampS,(Tend-tt)/rampE) getVars = PB.imposeSinusoidalMotion(tt=tt) disp = ramp*np.array(At)*np.sin(2*np.pi/Tt[0]*tt) rot = ramp*np.array(Ar)*np.sin(2*np.pi/Tt[0]*tt) disp = disp - (PB.last_position - PB.init_barycenter) npt.assert_equal(disp,getVars[0]) npt.assert_equal(rot,getVars[1]) if __name__ == '__main__': unittest.main(verbosity=2)
erdc/proteus
proteus/tests/test_bodydynamics.py
Python
mit
32,368
#! /usr/bin/env/python 3.1 # # Script that runs each bat file in each CWE directory. # The bat files contain instructions for compiling the test cases # in that directory. # # This script must be run in a visual studio command prompt. # import sys # add parent directory to search path so we can use py_common sys.path.append("..") import py_common def run_example_tool(bat_file): """ This method is called from the run_analysis method. It is called for each matching file. Files are matched against the glob expression specified in main. When this method is called, the script will have changed to the directory where the batch file exists. """ # In order to run a source code analysis tool, build appropriate command # line(s) as shown in the commented out example below """ build_name = "toolname.c_and_cpp." + py_common.get_timestamp() + "." + bat_file[:-4] command1 = "mytool --build " + build_name + " --option1 --option2 " + bat_file py_common.print_with_timestamp("Running " + command1) py_common.run_commands([command1]) command2 = "mytool --analyze " + build_name + " --output " + build_name + ".xml" py_common.print_with_timestamp("Running " + command2) py_common.run_commands([command2]) """ # The code below will just run the batch file to compile the test cases without using a tool # Remove or comment out this code when modifying this file to use an analysis tool command = bat_file py_common.print_with_timestamp("Running " + command) py_common.run_commands([command]) if __name__ == '__main__': # Analyze the test cases py_common.run_analysis("testcases", "CWE.*\.bat", run_example_tool)
JianpingZeng/xcc
xcc/test/juliet/run_analysis_example_tool.py
Python
bsd-3-clause
1,704
from befh.market_data import L2Depth, Trade from befh.exchanges.gateway import ExchangeGateway from befh.instrument import Instrument from befh.ws_api_socket import WebSocketApiClient from befh.util import Logger import time import threading import json from functools import partial from datetime import datetime class ExchGwBitfinexWs(WebSocketApiClient): """ Exchange gateway BTCC RESTfulApi """ def __init__(self): """ Constructor """ WebSocketApiClient.__init__(self, 'ExchGwBitfinex') @classmethod def get_link(cls): return 'wss://api2.bitfinex.com:3000/ws' @classmethod def get_order_book_subscription_string(cls, instmt): return json.dumps({"event":"subscribe", "channel": "book", "pair": instmt.get_instmt_code(), "freq": "F0"}) @classmethod def get_trades_subscription_string(cls, instmt): return json.dumps({"event":"subscribe", "channel": "trades", "pair": instmt.get_instmt_code()}) @classmethod def parse_l2_depth(cls, instmt, raw): """ Parse raw data to L2 depth :param instmt: Instrument :param raw: Raw data in JSON """ # No order book mapping from config. Need to decode here. l2_depth = instmt.get_l2_depth() l2_depth.date_time = datetime.utcnow().strftime("%Y%m%d %H:%M:%S.%f") if isinstance(raw[0], list): # Start subscription for i in range(0, 25): bid = raw[i] ask = raw[25+i] l2_depth.bids[i] = L2Depth.Depth(price=bid[0], count=bid[1], volume=bid[2]) l2_depth.asks[i] = L2Depth.Depth(price=ask[0], count=ask[1], volume=-ask[2]) else: price = raw[1] count = raw[2] volume = raw[3] found = False if count == 0: # Deletion if volume > 0: for i in range(0, len(l2_depth.bids)): if price == l2_depth.bids[i].price: found = True del l2_depth.bids[i] break else: for i in range(0, len(l2_depth.asks)): if price == l2_depth.asks[i].price: found = True del l2_depth.asks[i] break if not found: depth_text = "" for i in range(0, l2_depth.depth): if i < len(l2_depth.bids): depth_text += "%.4f,%d,%.4f" % \ (l2_depth.bids[i].volume, \ l2_depth.bids[i].count, \ l2_depth.bids[i].price) else: depth_text += " " depth_text += "<--->" if i < len(l2_depth.asks): depth_text += "%.4f,%d,%.4f" % \ (l2_depth.asks[i].volume, \ l2_depth.asks[i].count, \ l2_depth.asks[i].price) else: depth_text += " " depth_text += "\n" Logger.info(cls.__name__, "Cannot find the deletion of the message: %s\nDepth:\n%s\n" % \ (raw, depth_text)) else: # Insertion/Update if volume > 0: # Update for i in range(0, len(l2_depth.bids)): if price == l2_depth.bids[i].price: l2_depth.bids[i].count = count l2_depth.bids[i].volume = volume found = True break if not found: # Insertion l2_depth.bids.append(L2Depth.Depth(price=price, count=count, volume=volume)) l2_depth.sort_bids() if len(l2_depth.bids) > l2_depth.depth * 2: del l2_depth.bids[l2_depth.depth:] else: for i in range(0, len(l2_depth.asks)): # Update if price == l2_depth.asks[i].price: l2_depth.asks[i].count = count l2_depth.asks[i].volume = -volume found = True break if not found: # Insertion l2_depth.asks.append(L2Depth.Depth(price=price, count=count, volume=-volume)) l2_depth.sort_asks() if len(l2_depth.asks) > l2_depth.depth * 2: del l2_depth.asks[l2_depth.depth:] return l2_depth @classmethod def parse_trade(cls, instmt, raw): """ :param instmt: Instrument :param raw: Raw data in JSON :return: """ trade = Trade() trade_id = raw[0] timestamp = raw[1] trade_price = raw[2] trade_volume = raw[3] trade.date_time = datetime.utcfromtimestamp(timestamp).strftime("%Y%m%d %H:%M:%S.%f") trade.trade_side = Trade.Side.BUY if trade_volume > 0 else Trade.Side.SELL trade.trade_volume = abs(trade_volume) trade.trade_id = str(trade_id) trade.trade_price = trade_price return trade class ExchGwBitfinex(ExchangeGateway): """ Exchange gateway BTCC """ def __init__(self, db_clients): """ Constructor :param db_client: Database client """ ExchangeGateway.__init__(self, ExchGwBitfinexWs(), db_clients) @classmethod def get_exchange_name(cls): """ Get exchange name :return: Exchange name string """ return 'Bitfinex' def on_open_handler(self, instmt, ws): """ Socket on open handler :param instmt: Instrument :param ws: Web socket """ Logger.info(self.__class__.__name__, "Instrument %s is subscribed in channel %s" % \ (instmt.get_instmt_code(), instmt.get_exchange_name())) if not instmt.get_subscribed(): ws.send(self.api_socket.get_order_book_subscription_string(instmt)) ws.send(self.api_socket.get_trades_subscription_string(instmt)) instmt.set_subscribed(True) def on_close_handler(self, instmt, ws): """ Socket on close handler :param instmt: Instrument :param ws: Web socket """ Logger.info(self.__class__.__name__, "Instrument %s is unsubscribed in channel %s" % \ (instmt.get_instmt_code(), instmt.get_exchange_name())) instmt.set_subscribed(False) def on_message_handler(self, instmt, message): """ Incoming message handler :param instmt: Instrument :param message: Message """ if isinstance(message, dict): keys = message.keys() if 'event' in keys and message['event'] == 'info' and 'version' in keys: Logger.info(self.__class__.__name__, "Bitfinex version: %s" % message['version']) elif 'event' in keys and message['event'] == 'subscribed': if instmt.get_instmt_code() == message['pair']: if message['channel'] == 'book': instmt.set_order_book_channel_id(message['chanId']) elif message['channel'] == 'trades': instmt.set_trades_channel_id(message['chanId']) else: raise Exception("Unknown channel %s : <%s>" % (message['channel'], message)) Logger.info(self.__class__.__name__, 'Subscription: %s, pair: %s, channel Id: %s' % \ (message['channel'], instmt.get_instmt_code(), message['chanId'])) elif isinstance(message, list): if message[0] == instmt.get_order_book_channel_id(): if isinstance(message[1], list): self.api_socket.parse_l2_depth(instmt, message[1]) elif len(message) != 2: instmt.set_prev_l2_depth(instmt.get_l2_depth().copy()) self.api_socket.parse_l2_depth(instmt, message) else: return if instmt.get_l2_depth().is_diff(instmt.get_prev_l2_depth()): instmt.incr_order_book_id() self.insert_order_book(instmt) elif message[0] == instmt.get_trades_channel_id(): # No recovery trade # if isinstance(message[1], list): # raw_trades = message[1] # raw_trades.sort(key=lambda x:x[0]) # for raw in raw_trades: # trade = self.api_socket.parse_trade(instmt, raw) # try: # if int(trade.trade_id) > int(instmt.get_exch_trade_id()): # instmt.incr_trade_id() # instmt.set_exch_trade_id(trade.trade_id) # self.insert_trade(instmt, trade) # except Exception as e: # Logger.info('test', "trade.trade_id(%s):%s" % (type(trade.trade_id), trade.trade_id)) # Logger.info('test', "instmt.get_exch_trade_id()(%s):%s" % (type(instmt.get_exch_trade_id()), instmt.get_exch_trade_id())) # raise e if message[1] == 'tu': trade = self.api_socket.parse_trade(instmt, message[3:]) if int(trade.trade_id) > int(instmt.get_exch_trade_id()): instmt.incr_trade_id() instmt.set_exch_trade_id(trade.trade_id) self.insert_trade(instmt, trade) def start(self, instmt): """ Start the exchange gateway :param instmt: Instrument :return List of threads """ instmt.set_l2_depth(L2Depth(25)) instmt.set_prev_l2_depth(L2Depth(25)) instmt.set_instmt_snapshot_table_name(self.get_instmt_snapshot_table_name(instmt.get_exchange_name(), instmt.get_instmt_name())) self.init_instmt_snapshot_table(instmt) return [self.api_socket.connect(self.api_socket.get_link(), on_message_handler=partial(self.on_message_handler, instmt), on_open_handler=partial(self.on_open_handler, instmt), on_close_handler=partial(self.on_close_handler, instmt))]
Aurora-Team/BitcoinExchangeFH
befh/exchanges/bitfinex.py
Python
apache-2.0
11,420
# -*- coding: utf-8 -*- from vilya.libs.store import mc class MLockMeta(type): def __getattr__(cls, name): return MLock(name) class MLock(object): __metaclass__ = MLockMeta def __init__(self, mc_prefix): self.mc_prefix = mc_prefix def __call__(self, **kw): parts = [self.mc_prefix] for pair in sorted(kw.items()): parts += list(pair) mc_key = ':'.join(map(str, parts)) return MLockContext(mc_key) class MLockContext(object): def __init__(self, mc_key, value=1, expire=30): self.mc_key = mc_key self.value = value self.expire = expire def __str__(self): return ('<MLockContext(mc_key=%s, value=%s, expire=%s)>' % (self.mc_key, self.get_value(), self.expire)) __repr__ = __str__ def acquire(self): if not mc.add(self.mc_key, self.value, self.expire): raise MLockExclusiveError def release(self): mc.delete(self.mc_key) def get_value(self): return mc.get(self.mc_key) def __enter__(self): try: self.acquire() except MLockExclusiveError as e: return e def __exit__(self, type_, value, traceback): if traceback is None: self.release() class MLockExclusiveError(Exception): pass
douban/code
vilya/libs/mlock.py
Python
bsd-3-clause
1,347
# 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. """ VMware vCloud driver. """ import copy import sys import re import base64 import os from libcloud.utils.py3 import httplib from libcloud.utils.py3 import urlencode from libcloud.utils.py3 import urlparse from libcloud.utils.py3 import b from libcloud.utils.py3 import next urlparse = urlparse.urlparse import time try: from lxml import etree as ET except ImportError: from xml.etree import ElementTree as ET from xml.parsers.expat import ExpatError from libcloud.common.base import XmlResponse, ConnectionUserAndKey from libcloud.common.types import InvalidCredsError, LibcloudError from libcloud.compute.providers import Provider from libcloud.compute.types import NodeState from libcloud.compute.base import Node, NodeDriver, NodeLocation from libcloud.compute.base import NodeSize, NodeImage """ From vcloud api "The VirtualQuantity element defines the number of MB of memory. This should be either 512 or a multiple of 1024 (1 GB)." """ VIRTUAL_MEMORY_VALS = [512] + [1024 * i for i in range(1, 9)] # Default timeout (in seconds) for long running tasks DEFAULT_TASK_COMPLETION_TIMEOUT = 600 DEFAULT_API_VERSION = '0.8' """ Valid vCloud API v1.5 input values. """ VIRTUAL_CPU_VALS_1_5 = [i for i in range(1, 9)] FENCE_MODE_VALS_1_5 = ['bridged', 'isolated', 'natRouted'] IP_MODE_VALS_1_5 = ['POOL', 'DHCP', 'MANUAL', 'NONE'] def fixxpath(root, xpath): """ElementTree wants namespaces in its xpaths, so here we add them.""" namespace, root_tag = root.tag[1:].split("}", 1) fixed_xpath = "/".join(["{%s}%s" % (namespace, e) for e in xpath.split("/")]) return fixed_xpath def get_url_path(url): return urlparse(url.strip()).path class Vdc(object): """ Virtual datacenter (vDC) representation """ def __init__(self, id, name, driver, allocation_model=None, cpu=None, memory=None, storage=None): self.id = id self.name = name self.driver = driver self.allocation_model = allocation_model self.cpu = cpu self.memory = memory self.storage = storage def __repr__(self): return ('<Vdc: id=%s, name=%s, driver=%s ...>' % (self.id, self.name, self.driver.name)) class Capacity(object): """ Represents CPU, Memory or Storage capacity of vDC. """ def __init__(self, limit, used, units): self.limit = limit self.used = used self.units = units def __repr__(self): return ('<Capacity: limit=%s, used=%s, units=%s>' % (self.limit, self.used, self.units)) class ControlAccess(object): """ Represents control access settings of a node """ class AccessLevel(object): READ_ONLY = 'ReadOnly' CHANGE = 'Change' FULL_CONTROL = 'FullControl' def __init__(self, node, everyone_access_level, subjects=None): self.node = node self.everyone_access_level = everyone_access_level if not subjects: subjects = [] self.subjects = subjects def __repr__(self): return ('<ControlAccess: node=%s, everyone_access_level=%s, ' 'subjects=%s>' % (self.node, self.everyone_access_level, self.subjects)) class Subject(object): """ User or group subject """ def __init__(self, type, name, access_level, id=None): self.type = type self.name = name self.access_level = access_level self.id = id def __repr__(self): return ('<Subject: type=%s, name=%s, access_level=%s>' % (self.type, self.name, self.access_level)) class InstantiateVAppXML(object): def __init__(self, name, template, net_href, cpus, memory, password=None, row=None, group=None): self.name = name self.template = template self.net_href = net_href self.cpus = cpus self.memory = memory self.password = password self.row = row self.group = group self._build_xmltree() def tostring(self): return ET.tostring(self.root) def _build_xmltree(self): self.root = self._make_instantiation_root() self._add_vapp_template(self.root) instantiation_params = ET.SubElement(self.root, "InstantiationParams") # product and virtual hardware self._make_product_section(instantiation_params) self._make_virtual_hardware(instantiation_params) network_config_section = ET.SubElement(instantiation_params, "NetworkConfigSection") network_config = ET.SubElement(network_config_section, "NetworkConfig") self._add_network_association(network_config) def _make_instantiation_root(self): return ET.Element( "InstantiateVAppTemplateParams", {'name': self.name, 'xml:lang': 'en', 'xmlns': "http://www.vmware.com/vcloud/v0.8", 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance"} ) def _add_vapp_template(self, parent): return ET.SubElement( parent, "VAppTemplate", {'href': self.template} ) def _make_product_section(self, parent): prod_section = ET.SubElement( parent, "ProductSection", {'xmlns:q1': "http://www.vmware.com/vcloud/v0.8", 'xmlns:ovf': "http://schemas.dmtf.org/ovf/envelope/1"} ) if self.password: self._add_property(prod_section, 'password', self.password) if self.row: self._add_property(prod_section, 'row', self.row) if self.group: self._add_property(prod_section, 'group', self.group) return prod_section def _add_property(self, parent, ovfkey, ovfvalue): return ET.SubElement( parent, "Property", {'xmlns': 'http://schemas.dmtf.org/ovf/envelope/1', 'ovf:key': ovfkey, 'ovf:value': ovfvalue} ) def _make_virtual_hardware(self, parent): vh = ET.SubElement( parent, "VirtualHardwareSection", {'xmlns:q1': "http://www.vmware.com/vcloud/v0.8"} ) self._add_cpu(vh) self._add_memory(vh) return vh def _add_cpu(self, parent): cpu_item = ET.SubElement( parent, "Item", {'xmlns': "http://schemas.dmtf.org/ovf/envelope/1"} ) self._add_instance_id(cpu_item, '1') self._add_resource_type(cpu_item, '3') self._add_virtual_quantity(cpu_item, self.cpus) return cpu_item def _add_memory(self, parent): mem_item = ET.SubElement( parent, 'Item', {'xmlns': "http://schemas.dmtf.org/ovf/envelope/1"} ) self._add_instance_id(mem_item, '2') self._add_resource_type(mem_item, '4') self._add_virtual_quantity(mem_item, self.memory) return mem_item def _add_instance_id(self, parent, id): elm = ET.SubElement( parent, 'InstanceID', {'xmlns': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/' 'CIM_ResourceAllocationSettingData'} ) elm.text = id return elm def _add_resource_type(self, parent, type): elm = ET.SubElement( parent, 'ResourceType', {'xmlns': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/' 'CIM_ResourceAllocationSettingData'} ) elm.text = type return elm def _add_virtual_quantity(self, parent, amount): elm = ET.SubElement( parent, 'VirtualQuantity', {'xmlns': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/' 'CIM_ResourceAllocationSettingData'} ) elm.text = amount return elm def _add_network_association(self, parent): return ET.SubElement( parent, 'NetworkAssociation', {'href': self.net_href} ) class VCloudResponse(XmlResponse): def success(self): return self.status in (httplib.OK, httplib.CREATED, httplib.NO_CONTENT, httplib.ACCEPTED) class VCloudConnection(ConnectionUserAndKey): """ Connection class for the vCloud driver """ responseCls = VCloudResponse token = None host = None def request(self, *args, **kwargs): self._get_auth_token() return super(VCloudConnection, self).request(*args, **kwargs) def check_org(self): # the only way to get our org is by logging in. self._get_auth_token() def _get_auth_headers(self): """Some providers need different headers than others""" return { 'Authorization': "Basic %s" % base64.b64encode( b('%s:%s' % (self.user_id, self.key))).decode('utf-8'), 'Content-Length': '0', 'Accept': 'application/*+xml' } def _get_auth_token(self): if not self.token: self.connection.request(method='POST', url='/api/v0.8/login', headers=self._get_auth_headers()) resp = self.connection.getresponse() headers = dict(resp.getheaders()) body = ET.XML(resp.read()) try: self.token = headers['set-cookie'] except KeyError: raise InvalidCredsError() self.driver.org = get_url_path( body.find(fixxpath(body, 'Org')).get('href') ) def add_default_headers(self, headers): headers['Cookie'] = self.token headers['Accept'] = 'application/*+xml' return headers class VCloudNodeDriver(NodeDriver): """ vCloud node driver """ type = Provider.VCLOUD name = 'vCloud' website = 'http://www.vmware.com/products/vcloud/' connectionCls = VCloudConnection org = None _vdcs = None NODE_STATE_MAP = {'0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING} features = {'create_node': ['password']} def __new__(cls, key, secret=None, secure=True, host=None, port=None, api_version=DEFAULT_API_VERSION, **kwargs): if cls is VCloudNodeDriver: if api_version == '0.8': cls = VCloudNodeDriver elif api_version == '1.5': cls = VCloud_1_5_NodeDriver elif api_version == '5.1': cls = VCloud_5_1_NodeDriver elif api_version == '5.5': cls = VCloud_5_5_NodeDriver else: raise NotImplementedError( "No VCloudNodeDriver found for API version %s" % (api_version)) return super(VCloudNodeDriver, cls).__new__(cls) @property def vdcs(self): """ vCloud virtual data centers (vDCs). :return: list of vDC objects :rtype: ``list`` of :class:`Vdc` """ if not self._vdcs: self.connection.check_org() # make sure the org is set. res = self.connection.request(self.org) self._vdcs = [ self._to_vdc( self.connection.request(get_url_path(i.get('href'))).object ) for i in res.object.findall(fixxpath(res.object, "Link")) if i.get('type') == 'application/vnd.vmware.vcloud.vdc+xml' ] return self._vdcs def _to_vdc(self, vdc_elm): return Vdc(vdc_elm.get('href'), vdc_elm.get('name'), self) def _get_vdc(self, vdc_name): vdc = None if not vdc_name: # Return the first organisation VDC found vdc = self.vdcs[0] else: for v in self.vdcs: if v.name == vdc_name: vdc = v if vdc is None: raise ValueError('%s virtual data centre could not be found', vdc_name) return vdc @property def networks(self): networks = [] for vdc in self.vdcs: res = self.connection.request(get_url_path(vdc.id)).object networks.extend( [network for network in res.findall( fixxpath(res, 'AvailableNetworks/Network') )] ) return networks def _to_image(self, image): image = NodeImage(id=image.get('href'), name=image.get('name'), driver=self.connection.driver) return image def _to_node(self, elm): state = self.NODE_STATE_MAP[elm.get('status')] name = elm.get('name') public_ips = [] private_ips = [] # Following code to find private IPs works for Terremark connections = elm.findall('%s/%s' % ( '{http://schemas.dmtf.org/ovf/envelope/1}NetworkConnectionSection', fixxpath(elm, 'NetworkConnection')) ) if not connections: connections = elm.findall( fixxpath( elm, 'Children/Vm/NetworkConnectionSection/NetworkConnection')) for connection in connections: ips = [ip.text for ip in connection.findall(fixxpath(elm, "IpAddress"))] if connection.get('Network') == 'Internal': private_ips.extend(ips) else: public_ips.extend(ips) node = Node(id=elm.get('href'), name=name, state=state, public_ips=public_ips, private_ips=private_ips, driver=self.connection.driver) return node def _get_catalog_hrefs(self): res = self.connection.request(self.org) catalogs = [ i.get('href') for i in res.object.findall(fixxpath(res.object, "Link")) if i.get('type') == 'application/vnd.vmware.vcloud.catalog+xml' ] return catalogs def _wait_for_task_completion(self, task_href, timeout=DEFAULT_TASK_COMPLETION_TIMEOUT): start_time = time.time() res = self.connection.request(get_url_path(task_href)) status = res.object.get('status') while status != 'success': if status == 'error': # Get error reason from the response body error_elem = res.object.find(fixxpath(res.object, 'Error')) error_msg = "Unknown error" if error_elem is not None: error_msg = error_elem.get('message') raise Exception("Error status returned by task %s.: %s" % (task_href, error_msg)) if status == 'canceled': raise Exception("Canceled status returned by task %s." % task_href) if (time.time() - start_time >= timeout): raise Exception("Timeout (%s sec) while waiting for task %s." % (timeout, task_href)) time.sleep(5) res = self.connection.request(get_url_path(task_href)) status = res.object.get('status') def destroy_node(self, node): node_path = get_url_path(node.id) # blindly poweroff node, it will throw an exception if already off try: res = self.connection.request('%s/power/action/poweroff' % node_path, method='POST') self._wait_for_task_completion(res.object.get('href')) except Exception: pass try: res = self.connection.request('%s/action/undeploy' % node_path, method='POST') self._wait_for_task_completion(res.object.get('href')) except ExpatError: # The undeploy response is malformed XML atm. # We can remove this whent he providers fix the problem. pass except Exception: # Some vendors don't implement undeploy at all yet, # so catch this and move on. pass res = self.connection.request(node_path, method='DELETE') return res.status == httplib.ACCEPTED def reboot_node(self, node): res = self.connection.request('%s/power/action/reset' % get_url_path(node.id), method='POST') return res.status in [httplib.ACCEPTED, httplib.NO_CONTENT] def list_nodes(self): return self.ex_list_nodes() def ex_list_nodes(self, vdcs=None): """ List all nodes across all vDCs. Using 'vdcs' you can specify which vDCs should be queried. :param vdcs: None, vDC or a list of vDCs to query. If None all vDCs will be queried. :type vdcs: :class:`Vdc` :rtype: ``list`` of :class:`Node` """ if not vdcs: vdcs = self.vdcs if not isinstance(vdcs, (list, tuple)): vdcs = [vdcs] nodes = [] for vdc in vdcs: res = self.connection.request(get_url_path(vdc.id)) elms = res.object.findall(fixxpath( res.object, "ResourceEntities/ResourceEntity") ) vapps = [ (i.get('name'), i.get('href')) for i in elms if i.get('type') == 'application/vnd.vmware.vcloud.vApp+xml' and i.get('name') ] for vapp_name, vapp_href in vapps: try: res = self.connection.request( get_url_path(vapp_href), headers={'Content-Type': 'application/vnd.vmware.vcloud.vApp+xml'} ) nodes.append(self._to_node(res.object)) except Exception: # The vApp was probably removed since the previous vDC # query, ignore e = sys.exc_info()[1] if not (e.args[0].tag.endswith('Error') and e.args[0].get('minorErrorCode') == 'ACCESS_TO_RESOURCE_IS_FORBIDDEN'): raise return nodes def _to_size(self, ram): ns = NodeSize( id=None, name="%s Ram" % ram, ram=ram, disk=None, bandwidth=None, price=None, driver=self.connection.driver ) return ns def list_sizes(self, location=None): sizes = [self._to_size(i) for i in VIRTUAL_MEMORY_VALS] return sizes def _get_catalogitems_hrefs(self, catalog): """Given a catalog href returns contained catalog item hrefs""" res = self.connection.request( get_url_path(catalog), headers={ 'Content-Type': 'application/vnd.vmware.vcloud.catalog+xml' } ).object cat_items = res.findall(fixxpath(res, "CatalogItems/CatalogItem")) cat_item_hrefs = [i.get('href') for i in cat_items if i.get('type') == 'application/vnd.vmware.vcloud.catalogItem+xml'] return cat_item_hrefs def _get_catalogitem(self, catalog_item): """Given a catalog item href returns elementree""" res = self.connection.request( get_url_path(catalog_item), headers={ 'Content-Type': 'application/vnd.vmware.vcloud.catalogItem+xml' } ).object return res def list_images(self, location=None): images = [] for vdc in self.vdcs: res = self.connection.request(get_url_path(vdc.id)).object res_ents = res.findall(fixxpath( res, "ResourceEntities/ResourceEntity") ) images += [ self._to_image(i) for i in res_ents if i.get('type') == 'application/vnd.vmware.vcloud.vAppTemplate+xml' ] for catalog in self._get_catalog_hrefs(): for cat_item in self._get_catalogitems_hrefs(catalog): res = self._get_catalogitem(cat_item) res_ents = res.findall(fixxpath(res, 'Entity')) images += [ self._to_image(i) for i in res_ents if i.get('type') == 'application/vnd.vmware.vcloud.vAppTemplate+xml' ] def idfun(image): return image.id return self._uniquer(images, idfun) def _uniquer(self, seq, idfun=None): if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result def create_node(self, **kwargs): """ Creates and returns node. :keyword ex_network: link to a "Network" e.g., ``https://services.vcloudexpress...`` :type ex_network: ``str`` :keyword ex_vdc: Name of organisation's virtual data center where vApp VMs will be deployed. :type ex_vdc: ``str`` :keyword ex_cpus: number of virtual cpus (limit depends on provider) :type ex_cpus: ``int`` :type ex_row: ``str`` :type ex_group: ``str`` """ name = kwargs['name'] image = kwargs['image'] size = kwargs['size'] # Some providers don't require a network link try: network = kwargs.get('ex_network', self.networks[0].get('href')) except IndexError: network = '' password = None auth = self._get_and_check_auth(kwargs.get('auth')) password = auth.password instantiate_xml = InstantiateVAppXML( name=name, template=image.id, net_href=network, cpus=str(kwargs.get('ex_cpus', 1)), memory=str(size.ram), password=password, row=kwargs.get('ex_row', None), group=kwargs.get('ex_group', None) ) vdc = self._get_vdc(kwargs.get('ex_vdc', None)) # Instantiate VM and get identifier. content_type = \ 'application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml' res = self.connection.request( '%s/action/instantiateVAppTemplate' % get_url_path(vdc.id), data=instantiate_xml.tostring(), method='POST', headers={'Content-Type': content_type} ) vapp_path = get_url_path(res.object.get('href')) # Deploy the VM from the identifier. res = self.connection.request('%s/action/deploy' % vapp_path, method='POST') self._wait_for_task_completion(res.object.get('href')) # Power on the VM. res = self.connection.request('%s/power/action/powerOn' % vapp_path, method='POST') res = self.connection.request(vapp_path) node = self._to_node(res.object) if getattr(auth, "generated", False): node.extra['password'] = auth.password return node class HostingComConnection(VCloudConnection): """ vCloud connection subclass for Hosting.com """ host = "vcloud.safesecureweb.com" def _get_auth_headers(self): """hosting.com doesn't follow the standard vCloud authentication API""" return { 'Authentication': base64.b64encode(b('%s:%s' % (self.user_id, self.key))), 'Content-Length': '0' } class HostingComDriver(VCloudNodeDriver): """ vCloud node driver for Hosting.com """ connectionCls = HostingComConnection class TerremarkConnection(VCloudConnection): """ vCloud connection subclass for Terremark """ host = "services.vcloudexpress.terremark.com" class TerremarkDriver(VCloudNodeDriver): """ vCloud node driver for Terremark """ connectionCls = TerremarkConnection def list_locations(self): return [NodeLocation(0, "Terremark Texas", 'US', self)] class VCloud_1_5_Connection(VCloudConnection): def _get_auth_headers(self): """Compatibility for using v1.5 API under vCloud Director 5.1""" return { 'Authorization': "Basic %s" % base64.b64encode( b('%s:%s' % (self.user_id, self.key))).decode('utf-8'), 'Content-Length': '0', 'Accept': 'application/*+xml;version=1.5' } def _get_auth_token(self): if not self.token: # Log In self.connection.request(method='POST', url='/api/sessions', headers=self._get_auth_headers()) resp = self.connection.getresponse() headers = dict(resp.getheaders()) # Set authorization token try: self.token = headers['x-vcloud-authorization'] except KeyError: raise InvalidCredsError() # Get the URL of the Organization body = ET.XML(resp.read()) self.org_name = body.get('org') org_list_url = get_url_path( next((link for link in body.findall(fixxpath(body, 'Link')) if link.get('type') == 'application/vnd.vmware.vcloud.orgList+xml')).get('href') ) if self.proxy_url is not None: self.connection.set_http_proxy(self.proxy_url) self.connection.request(method='GET', url=org_list_url, headers=self.add_default_headers({})) body = ET.XML(self.connection.getresponse().read()) self.driver.org = get_url_path( next((org for org in body.findall(fixxpath(body, 'Org')) if org.get('name') == self.org_name)).get('href') ) def add_default_headers(self, headers): headers['Accept'] = 'application/*+xml;version=1.5' headers['x-vcloud-authorization'] = self.token return headers class VCloud_5_5_Connection(VCloud_1_5_Connection): def add_default_headers(self, headers): headers['Accept'] = 'application/*+xml;version=5.5' headers['x-vcloud-authorization'] = self.token return headers class Instantiate_1_5_VAppXML(object): def __init__(self, name, template, network, vm_network=None, vm_fence=None): self.name = name self.template = template self.network = network self.vm_network = vm_network self.vm_fence = vm_fence self._build_xmltree() def tostring(self): return ET.tostring(self.root) def _build_xmltree(self): self.root = self._make_instantiation_root() if self.network is not None: instantionation_params = ET.SubElement(self.root, 'InstantiationParams') network_config_section = ET.SubElement(instantionation_params, 'NetworkConfigSection') ET.SubElement( network_config_section, 'Info', {'xmlns': 'http://schemas.dmtf.org/ovf/envelope/1'} ) network_config = ET.SubElement(network_config_section, 'NetworkConfig') self._add_network_association(network_config) self._add_vapp_template(self.root) def _make_instantiation_root(self): return ET.Element( 'InstantiateVAppTemplateParams', {'name': self.name, 'deploy': 'false', 'powerOn': 'false', 'xml:lang': 'en', 'xmlns': 'http://www.vmware.com/vcloud/v1.5', 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance'} ) def _add_vapp_template(self, parent): return ET.SubElement( parent, 'Source', {'href': self.template} ) def _add_network_association(self, parent): if self.vm_network is None: # Don't set a custom vApp VM network name parent.set('networkName', self.network.get('name')) else: # Set a custom vApp VM network name parent.set('networkName', self.vm_network) configuration = ET.SubElement(parent, 'Configuration') ET.SubElement(configuration, 'ParentNetwork', {'href': self.network.get('href')}) if self.vm_fence is None: fencemode = self.network.find(fixxpath(self.network, 'Configuration/FenceMode')).text else: fencemode = self.vm_fence ET.SubElement(configuration, 'FenceMode').text = fencemode class VCloud_1_5_NodeDriver(VCloudNodeDriver): connectionCls = VCloud_1_5_Connection # Based on # http://pubs.vmware.com/vcloud-api-1-5/api_prog/ # GUID-843BE3AD-5EF6-4442-B864-BCAE44A51867.html NODE_STATE_MAP = {'-1': NodeState.UNKNOWN, '0': NodeState.PENDING, '1': NodeState.PENDING, '2': NodeState.PENDING, '3': NodeState.PENDING, '4': NodeState.RUNNING, '5': NodeState.RUNNING, '6': NodeState.UNKNOWN, '7': NodeState.UNKNOWN, '8': NodeState.STOPPED, '9': NodeState.UNKNOWN, '10': NodeState.UNKNOWN} def list_locations(self): return [NodeLocation(id=self.connection.host, name=self.connection.host, country="N/A", driver=self)] def ex_find_node(self, node_name, vdcs=None): """ Searches for node across specified vDCs. This is more effective than querying all nodes to get a single instance. :param node_name: The name of the node to search for :type node_name: ``str`` :param vdcs: None, vDC or a list of vDCs to search in. If None all vDCs will be searched. :type vdcs: :class:`Vdc` :return: node instance or None if not found :rtype: :class:`Node` or ``None`` """ if not vdcs: vdcs = self.vdcs if not getattr(vdcs, '__iter__', False): vdcs = [vdcs] for vdc in vdcs: res = self.connection.request(get_url_path(vdc.id)) xpath = fixxpath(res.object, "ResourceEntities/ResourceEntity") entity_elems = res.object.findall(xpath) for entity_elem in entity_elems: if entity_elem.get('type') == \ 'application/vnd.vmware.vcloud.vApp+xml' and \ entity_elem.get('name') == node_name: path = get_url_path(entity_elem.get('href')) headers = {'Content-Type': 'application/vnd.vmware.vcloud.vApp+xml'} res = self.connection.request(path, headers=headers) return self._to_node(res.object) return None def destroy_node(self, node): try: self.ex_undeploy_node(node) except Exception: # Some vendors don't implement undeploy at all yet, # so catch this and move on. pass res = self.connection.request(get_url_path(node.id), method='DELETE') return res.status == httplib.ACCEPTED def reboot_node(self, node): res = self.connection.request('%s/power/action/reset' % get_url_path(node.id), method='POST') if res.status in [httplib.ACCEPTED, httplib.NO_CONTENT]: self._wait_for_task_completion(res.object.get('href')) return True else: return False def ex_deploy_node(self, node): """ Deploys existing node. Equal to vApp "start" operation. :param node: The node to be deployed :type node: :class:`Node` :rtype: :class:`Node` """ data = {'powerOn': 'true', 'xmlns': 'http://www.vmware.com/vcloud/v1.5'} deploy_xml = ET.Element('DeployVAppParams', data) path = get_url_path(node.id) headers = { 'Content-Type': 'application/vnd.vmware.vcloud.deployVAppParams+xml' } res = self.connection.request('%s/action/deploy' % path, data=ET.tostring(deploy_xml), method='POST', headers=headers) self._wait_for_task_completion(res.object.get('href')) res = self.connection.request(get_url_path(node.id)) return self._to_node(res.object) def ex_undeploy_node(self, node): """ Undeploys existing node. Equal to vApp "stop" operation. :param node: The node to be deployed :type node: :class:`Node` :rtype: :class:`Node` """ data = {'xmlns': 'http://www.vmware.com/vcloud/v1.5'} undeploy_xml = ET.Element('UndeployVAppParams', data) undeploy_power_action_xml = ET.SubElement(undeploy_xml, 'UndeployPowerAction') undeploy_power_action_xml.text = 'shutdown' headers = { 'Content-Type': 'application/vnd.vmware.vcloud.undeployVAppParams+xml' } try: res = self.connection.request( '%s/action/undeploy' % get_url_path(node.id), data=ET.tostring(undeploy_xml), method='POST', headers=headers) self._wait_for_task_completion(res.object.get('href')) except Exception: undeploy_power_action_xml.text = 'powerOff' res = self.connection.request( '%s/action/undeploy' % get_url_path(node.id), data=ET.tostring(undeploy_xml), method='POST', headers=headers) self._wait_for_task_completion(res.object.get('href')) res = self.connection.request(get_url_path(node.id)) return self._to_node(res.object) def ex_power_off_node(self, node): """ Powers on all VMs under specified node. VMs need to be This operation is allowed only when the vApp/VM is powered on. :param node: The node to be powered off :type node: :class:`Node` :rtype: :class:`Node` """ return self._perform_power_operation(node, 'powerOff') def ex_power_on_node(self, node): """ Powers on all VMs under specified node. This operation is allowed only when the vApp/VM is powered off or suspended. :param node: The node to be powered on :type node: :class:`Node` :rtype: :class:`Node` """ return self._perform_power_operation(node, 'powerOn') def ex_shutdown_node(self, node): """ Shutdowns all VMs under specified node. This operation is allowed only when the vApp/VM is powered on. :param node: The node to be shut down :type node: :class:`Node` :rtype: :class:`Node` """ return self._perform_power_operation(node, 'shutdown') def ex_suspend_node(self, node): """ Suspends all VMs under specified node. This operation is allowed only when the vApp/VM is powered on. :param node: The node to be suspended :type node: :class:`Node` :rtype: :class:`Node` """ return self._perform_power_operation(node, 'suspend') def _perform_power_operation(self, node, operation): res = self.connection.request( '%s/power/action/%s' % (get_url_path(node.id), operation), method='POST') self._wait_for_task_completion(res.object.get('href')) res = self.connection.request(get_url_path(node.id)) return self._to_node(res.object) def ex_get_control_access(self, node): """ Returns the control access settings for specified node. :param node: node to get the control access for :type node: :class:`Node` :rtype: :class:`ControlAccess` """ res = self.connection.request( '%s/controlAccess' % get_url_path(node.id)) everyone_access_level = None is_shared_elem = res.object.find( fixxpath(res.object, "IsSharedToEveryone")) if is_shared_elem is not None and is_shared_elem.text == 'true': everyone_access_level = res.object.find( fixxpath(res.object, "EveryoneAccessLevel")).text # Parse all subjects subjects = [] xpath = fixxpath(res.object, "AccessSettings/AccessSetting") for elem in res.object.findall(xpath): access_level = elem.find(fixxpath(res.object, "AccessLevel")).text subject_elem = elem.find(fixxpath(res.object, "Subject")) if subject_elem.get('type') == \ 'application/vnd.vmware.admin.group+xml': subj_type = 'group' else: subj_type = 'user' path = get_url_path(subject_elem.get('href')) res = self.connection.request(path) name = res.object.get('name') subject = Subject(type=subj_type, name=name, access_level=access_level, id=subject_elem.get('href')) subjects.append(subject) return ControlAccess(node, everyone_access_level, subjects) def ex_set_control_access(self, node, control_access): """ Sets control access for the specified node. :param node: node :type node: :class:`Node` :param control_access: control access settings :type control_access: :class:`ControlAccess` :rtype: ``None`` """ xml = ET.Element('ControlAccessParams', {'xmlns': 'http://www.vmware.com/vcloud/v1.5'}) shared_to_everyone = ET.SubElement(xml, 'IsSharedToEveryone') if control_access.everyone_access_level: shared_to_everyone.text = 'true' everyone_access_level = ET.SubElement(xml, 'EveryoneAccessLevel') everyone_access_level.text = control_access.everyone_access_level else: shared_to_everyone.text = 'false' # Set subjects if control_access.subjects: access_settings_elem = ET.SubElement(xml, 'AccessSettings') for subject in control_access.subjects: setting = ET.SubElement(access_settings_elem, 'AccessSetting') if subject.id: href = subject.id else: res = self.ex_query(type=subject.type, filter='name==' + subject.name) if not res: raise LibcloudError('Specified subject "%s %s" not found ' % (subject.type, subject.name)) href = res[0]['href'] ET.SubElement(setting, 'Subject', {'href': href}) ET.SubElement(setting, 'AccessLevel').text = subject.access_level headers = { 'Content-Type': 'application/vnd.vmware.vcloud.controlAccess+xml' } self.connection.request( '%s/action/controlAccess' % get_url_path(node.id), data=ET.tostring(xml), headers=headers, method='POST') def ex_get_metadata(self, node): """ :param node: node :type node: :class:`Node` :return: dictionary mapping metadata keys to metadata values :rtype: dictionary mapping ``str`` to ``str`` """ res = self.connection.request('%s/metadata' % (get_url_path(node.id))) xpath = fixxpath(res.object, 'MetadataEntry') metadata_entries = res.object.findall(xpath) res_dict = {} for entry in metadata_entries: key = entry.findtext(fixxpath(res.object, 'Key')) value = entry.findtext(fixxpath(res.object, 'Value')) res_dict[key] = value return res_dict def ex_set_metadata_entry(self, node, key, value): """ :param node: node :type node: :class:`Node` :param key: metadata key to be set :type key: ``str`` :param value: metadata value to be set :type value: ``str`` :rtype: ``None`` """ metadata_elem = ET.Element( 'Metadata', {'xmlns': "http://www.vmware.com/vcloud/v1.5", 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance"} ) entry = ET.SubElement(metadata_elem, 'MetadataEntry') key_elem = ET.SubElement(entry, 'Key') key_elem.text = key value_elem = ET.SubElement(entry, 'Value') value_elem.text = value # send it back to the server res = self.connection.request( '%s/metadata' % get_url_path(node.id), data=ET.tostring(metadata_elem), headers={ 'Content-Type': 'application/vnd.vmware.vcloud.metadata+xml' }, method='POST') self._wait_for_task_completion(res.object.get('href')) def ex_query(self, type, filter=None, page=1, page_size=100, sort_asc=None, sort_desc=None): """ Queries vCloud for specified type. See http://www.vmware.com/pdf/vcd_15_api_guide.pdf for details. Each element of the returned list is a dictionary with all attributes from the record. :param type: type to query (r.g. user, group, vApp etc.) :type type: ``str`` :param filter: filter expression (see documentation for syntax) :type filter: ``str`` :param page: page number :type page: ``int`` :param page_size: page size :type page_size: ``int`` :param sort_asc: sort in ascending order by specified field :type sort_asc: ``str`` :param sort_desc: sort in descending order by specified field :type sort_desc: ``str`` :rtype: ``list`` of dict """ # This is a workaround for filter parameter encoding # the urllib encodes (name==Developers%20Only) into # %28name%3D%3DDevelopers%20Only%29) which is not accepted by vCloud params = { 'type': type, 'pageSize': page_size, 'page': page, } if sort_asc: params['sortAsc'] = sort_asc if sort_desc: params['sortDesc'] = sort_desc url = '/api/query?' + urlencode(params) if filter: if not filter.startswith('('): filter = '(' + filter + ')' url += '&filter=' + filter.replace(' ', '+') results = [] res = self.connection.request(url) for elem in res.object: if not elem.tag.endswith('Link'): result = elem.attrib result['type'] = elem.tag.split('}')[1] results.append(result) return results def create_node(self, **kwargs): """ Creates and returns node. If the source image is: - vApp template - a new vApp is instantiated from template - existing vApp - a new vApp is cloned from the source vApp. Can not clone more vApps is parallel otherwise resource busy error is raised. @inherits: :class:`NodeDriver.create_node` :keyword image: OS Image to boot on node. (required). Can be a NodeImage or existing Node that will be cloned. :type image: :class:`NodeImage` or :class:`Node` :keyword ex_network: Organisation's network name for attaching vApp VMs to. :type ex_network: ``str`` :keyword ex_vdc: Name of organisation's virtual data center where vApp VMs will be deployed. :type ex_vdc: ``str`` :keyword ex_vm_names: list of names to be used as a VM and computer name. The name must be max. 15 characters long and follow the host name requirements. :type ex_vm_names: ``list`` of ``str`` :keyword ex_vm_cpu: number of virtual CPUs/cores to allocate for each vApp VM. :type ex_vm_cpu: ``int`` :keyword ex_vm_memory: amount of memory in MB to allocate for each vApp VM. :type ex_vm_memory: ``int`` :keyword ex_vm_script: full path to file containing guest customisation script for each vApp VM. Useful for creating users & pushing out public SSH keys etc. :type ex_vm_script: ``str`` :keyword ex_vm_network: Override default vApp VM network name. Useful for when you've imported an OVF originating from outside of the vCloud. :type ex_vm_network: ``str`` :keyword ex_vm_fence: Fence mode for connecting the vApp VM network (ex_vm_network) to the parent organisation network (ex_network). :type ex_vm_fence: ``str`` :keyword ex_vm_ipmode: IP address allocation mode for all vApp VM network connections. :type ex_vm_ipmode: ``str`` :keyword ex_deploy: set to False if the node shouldn't be deployed (started) after creation :type ex_deploy: ``bool`` :keyword ex_clone_timeout: timeout in seconds for clone/instantiate VM operation. Cloning might be a time consuming operation especially when linked clones are disabled or VMs are created on different datastores. Overrides the default task completion value. :type ex_clone_timeout: ``int`` """ name = kwargs['name'] image = kwargs['image'] ex_vm_names = kwargs.get('ex_vm_names') ex_vm_cpu = kwargs.get('ex_vm_cpu') ex_vm_memory = kwargs.get('ex_vm_memory') ex_vm_script = kwargs.get('ex_vm_script') ex_vm_fence = kwargs.get('ex_vm_fence', None) ex_network = kwargs.get('ex_network', None) ex_vm_network = kwargs.get('ex_vm_network', None) ex_vm_ipmode = kwargs.get('ex_vm_ipmode', None) ex_deploy = kwargs.get('ex_deploy', True) ex_vdc = kwargs.get('ex_vdc', None) ex_clone_timeout = kwargs.get('ex_clone_timeout', DEFAULT_TASK_COMPLETION_TIMEOUT) self._validate_vm_names(ex_vm_names) self._validate_vm_cpu(ex_vm_cpu) self._validate_vm_memory(ex_vm_memory) self._validate_vm_fence(ex_vm_fence) self._validate_vm_ipmode(ex_vm_ipmode) ex_vm_script = self._validate_vm_script(ex_vm_script) # Some providers don't require a network link if ex_network: network_href = self._get_network_href(ex_network) network_elem = self.connection.request( get_url_path(network_href)).object else: network_elem = None vdc = self._get_vdc(ex_vdc) if self._is_node(image): vapp_name, vapp_href = self._clone_node(name, image, vdc, ex_clone_timeout) else: vapp_name, vapp_href = self._instantiate_node(name, image, network_elem, vdc, ex_vm_network, ex_vm_fence, ex_clone_timeout) self._change_vm_names(vapp_href, ex_vm_names) self._change_vm_cpu(vapp_href, ex_vm_cpu) self._change_vm_memory(vapp_href, ex_vm_memory) self._change_vm_script(vapp_href, ex_vm_script) self._change_vm_ipmode(vapp_href, ex_vm_ipmode) # Power on the VM. if ex_deploy: # Retry 3 times: when instantiating large number of VMs at the same # time some may fail on resource allocation retry = 3 while True: try: res = self.connection.request( '%s/power/action/powerOn' % get_url_path(vapp_href), method='POST') self._wait_for_task_completion(res.object.get('href')) break except Exception: if retry <= 0: raise retry -= 1 time.sleep(10) res = self.connection.request(get_url_path(vapp_href)) node = self._to_node(res.object) return node def _instantiate_node(self, name, image, network_elem, vdc, vm_network, vm_fence, instantiate_timeout): instantiate_xml = Instantiate_1_5_VAppXML( name=name, template=image.id, network=network_elem, vm_network=vm_network, vm_fence=vm_fence ) # Instantiate VM and get identifier. headers = { 'Content-Type': 'application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml' } res = self.connection.request( '%s/action/instantiateVAppTemplate' % get_url_path(vdc.id), data=instantiate_xml.tostring(), method='POST', headers=headers ) vapp_name = res.object.get('name') vapp_href = res.object.get('href') task_href = res.object.find(fixxpath(res.object, "Tasks/Task")).get( 'href') self._wait_for_task_completion(task_href, instantiate_timeout) return vapp_name, vapp_href def _clone_node(self, name, sourceNode, vdc, clone_timeout): clone_xml = ET.Element( "CloneVAppParams", {'name': name, 'deploy': 'false', 'powerOn': 'false', 'xmlns': "http://www.vmware.com/vcloud/v1.5", 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance"} ) ET.SubElement(clone_xml, 'Description').text = 'Clone of ' + sourceNode.name ET.SubElement(clone_xml, 'Source', {'href': sourceNode.id}) headers = { 'Content-Type': 'application/vnd.vmware.vcloud.cloneVAppParams+xml' } res = self.connection.request( '%s/action/cloneVApp' % get_url_path(vdc.id), data=ET.tostring(clone_xml), method='POST', headers=headers ) vapp_name = res.object.get('name') vapp_href = res.object.get('href') task_href = res.object.find( fixxpath(res.object, "Tasks/Task")).get('href') self._wait_for_task_completion(task_href, clone_timeout) res = self.connection.request(get_url_path(vapp_href)) vms = res.object.findall(fixxpath(res.object, "Children/Vm")) # Fix the networking for VMs for i, vm in enumerate(vms): # Remove network network_xml = ET.Element("NetworkConnectionSection", { 'ovf:required': 'false', 'xmlns': "http://www.vmware.com/vcloud/v1.5", 'xmlns:ovf': 'http://schemas.dmtf.org/ovf/envelope/1'}) ET.SubElement(network_xml, "ovf:Info").text = \ 'Specifies the available VM network connections' headers = { 'Content-Type': 'application/vnd.vmware.vcloud.networkConnectionSection+xml' } res = self.connection.request( '%s/networkConnectionSection' % get_url_path(vm.get('href')), data=ET.tostring(network_xml), method='PUT', headers=headers ) self._wait_for_task_completion(res.object.get('href')) # Re-add network network_xml = vm.find(fixxpath(vm, 'NetworkConnectionSection')) network_conn_xml = network_xml.find( fixxpath(network_xml, 'NetworkConnection')) network_conn_xml.set('needsCustomization', 'true') network_conn_xml.remove( network_conn_xml.find(fixxpath(network_xml, 'IpAddress'))) network_conn_xml.remove( network_conn_xml.find(fixxpath(network_xml, 'MACAddress'))) headers = { 'Content-Type': 'application/vnd.vmware.vcloud.networkConnectionSection+xml' } res = self.connection.request( '%s/networkConnectionSection' % get_url_path(vm.get('href')), data=ET.tostring(network_xml), method='PUT', headers=headers ) self._wait_for_task_completion(res.object.get('href')) return vapp_name, vapp_href def ex_set_vm_cpu(self, vapp_or_vm_id, vm_cpu): """ Sets the number of virtual CPUs for the specified VM or VMs under the vApp. If the vapp_or_vm_id param represents a link to an vApp all VMs that are attached to this vApp will be modified. Please ensure that hot-adding a virtual CPU is enabled for the powered on virtual machines. Otherwise use this method on undeployed vApp. :keyword vapp_or_vm_id: vApp or VM ID that will be modified. If a vApp ID is used here all attached VMs will be modified :type vapp_or_vm_id: ``str`` :keyword vm_cpu: number of virtual CPUs/cores to allocate for specified VMs :type vm_cpu: ``int`` :rtype: ``None`` """ self._validate_vm_cpu(vm_cpu) self._change_vm_cpu(vapp_or_vm_id, vm_cpu) def ex_set_vm_memory(self, vapp_or_vm_id, vm_memory): """ Sets the virtual memory in MB to allocate for the specified VM or VMs under the vApp. If the vapp_or_vm_id param represents a link to an vApp all VMs that are attached to this vApp will be modified. Please ensure that hot-change of virtual memory is enabled for the powered on virtual machines. Otherwise use this method on undeployed vApp. :keyword vapp_or_vm_id: vApp or VM ID that will be modified. If a vApp ID is used here all attached VMs will be modified :type vapp_or_vm_id: ``str`` :keyword vm_memory: virtual memory in MB to allocate for the specified VM or VMs :type vm_memory: ``int`` :rtype: ``None`` """ self._validate_vm_memory(vm_memory) self._change_vm_memory(vapp_or_vm_id, vm_memory) def ex_add_vm_disk(self, vapp_or_vm_id, vm_disk_size): """ Adds a virtual disk to the specified VM or VMs under the vApp. If the vapp_or_vm_id param represents a link to an vApp all VMs that are attached to this vApp will be modified. :keyword vapp_or_vm_id: vApp or VM ID that will be modified. If a vApp ID is used here all attached VMs will be modified :type vapp_or_vm_id: ``str`` :keyword vm_disk_size: the disk capacity in GB that will be added to the specified VM or VMs :type vm_disk_size: ``int`` :rtype: ``None`` """ self._validate_vm_disk_size(vm_disk_size) self._add_vm_disk(vapp_or_vm_id, vm_disk_size) @staticmethod def _validate_vm_names(names): if names is None: return hname_re = re.compile( '^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9]*)[\-])*([A-Za-z]|[A-Za-z][A-Za-z0-9]*[A-Za-z0-9])$') # NOQA for name in names: if len(name) > 15: raise ValueError( 'The VM name "' + name + '" is too long for the computer ' 'name (max 15 chars allowed).') if not hname_re.match(name): raise ValueError('The VM name "' + name + '" can not be ' 'used. "' + name + '" is not a valid ' 'computer name for the VM.') @staticmethod def _validate_vm_memory(vm_memory): if vm_memory is None: return elif vm_memory not in VIRTUAL_MEMORY_VALS: raise ValueError( '%s is not a valid vApp VM memory value' % vm_memory) @staticmethod def _validate_vm_cpu(vm_cpu): if vm_cpu is None: return elif vm_cpu not in VIRTUAL_CPU_VALS_1_5: raise ValueError('%s is not a valid vApp VM CPU value' % vm_cpu) @staticmethod def _validate_vm_disk_size(vm_disk): if vm_disk is None: return elif int(vm_disk) < 0: raise ValueError('%s is not a valid vApp VM disk space value', vm_disk) @staticmethod def _validate_vm_script(vm_script): if vm_script is None: return # Try to locate the script file if not os.path.isabs(vm_script): vm_script = os.path.expanduser(vm_script) vm_script = os.path.abspath(vm_script) if not os.path.isfile(vm_script): raise LibcloudError( "%s the VM script file does not exist" % vm_script) try: open(vm_script).read() except: raise return vm_script @staticmethod def _validate_vm_fence(vm_fence): if vm_fence is None: return elif vm_fence not in FENCE_MODE_VALS_1_5: raise ValueError('%s is not a valid fencing mode value' % vm_fence) @staticmethod def _validate_vm_ipmode(vm_ipmode): if vm_ipmode is None: return elif vm_ipmode == 'MANUAL': raise NotImplementedError( 'MANUAL IP mode: The interface for supplying ' 'IPAddress does not exist yet') elif vm_ipmode not in IP_MODE_VALS_1_5: raise ValueError( '%s is not a valid IP address allocation mode value' % vm_ipmode) def _change_vm_names(self, vapp_or_vm_id, vm_names): if vm_names is None: return vms = self._get_vm_elements(vapp_or_vm_id) for i, vm in enumerate(vms): if len(vm_names) <= i: return # Get GuestCustomizationSection res = self.connection.request( '%s/guestCustomizationSection' % get_url_path(vm.get('href'))) # Update GuestCustomizationSection res.object.find( fixxpath(res.object, 'ComputerName')).text = vm_names[i] # Remove AdminPassword from customization section admin_pass = res.object.find(fixxpath(res.object, 'AdminPassword')) if admin_pass is not None: res.object.remove(admin_pass) headers = { 'Content-Type': 'application/vnd.vmware.vcloud.guestCustomizationSection+xml' } res = self.connection.request( '%s/guestCustomizationSection' % get_url_path(vm.get('href')), data=ET.tostring(res.object), method='PUT', headers=headers ) self._wait_for_task_completion(res.object.get('href')) # Update Vm name req_xml = ET.Element("Vm", { 'name': vm_names[i], 'xmlns': "http://www.vmware.com/vcloud/v1.5"}) res = self.connection.request( get_url_path(vm.get('href')), data=ET.tostring(req_xml), method='PUT', headers={ 'Content-Type': 'application/vnd.vmware.vcloud.vm+xml'} ) self._wait_for_task_completion(res.object.get('href')) def _change_vm_cpu(self, vapp_or_vm_id, vm_cpu): if vm_cpu is None: return vms = self._get_vm_elements(vapp_or_vm_id) for vm in vms: # Get virtualHardwareSection/cpu section res = self.connection.request( '%s/virtualHardwareSection/cpu' % get_url_path(vm.get('href'))) # Update VirtualQuantity field xpath = ('{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/' 'CIM_ResourceAllocationSettingData}VirtualQuantity') res.object.find(xpath).text = str(vm_cpu) headers = { 'Content-Type': 'application/vnd.vmware.vcloud.rasdItem+xml' } res = self.connection.request( '%s/virtualHardwareSection/cpu' % get_url_path(vm.get('href')), data=ET.tostring(res.object), method='PUT', headers=headers ) self._wait_for_task_completion(res.object.get('href')) def _change_vm_memory(self, vapp_or_vm_id, vm_memory): if vm_memory is None: return vms = self._get_vm_elements(vapp_or_vm_id) for vm in vms: # Get virtualHardwareSection/memory section res = self.connection.request( '%s/virtualHardwareSection/memory' % get_url_path(vm.get('href'))) # Update VirtualQuantity field xpath = ('{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/' 'CIM_ResourceAllocationSettingData}VirtualQuantity') res.object.find(xpath).text = str(vm_memory) headers = { 'Content-Type': 'application/vnd.vmware.vcloud.rasdItem+xml' } res = self.connection.request( '%s/virtualHardwareSection/memory' % get_url_path( vm.get('href')), data=ET.tostring(res.object), method='PUT', headers=headers ) self._wait_for_task_completion(res.object.get('href')) def _add_vm_disk(self, vapp_or_vm_id, vm_disk): if vm_disk is None: return rasd_ns = ('{http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/' 'CIM_ResourceAllocationSettingData}') vms = self._get_vm_elements(vapp_or_vm_id) for vm in vms: # Get virtualHardwareSection/disks section res = self.connection.request( '%s/virtualHardwareSection/disks' % get_url_path(vm.get('href'))) existing_ids = [] new_disk = None for item in res.object.findall(fixxpath(res.object, 'Item')): # Clean Items from unnecessary stuff for elem in item: if elem.tag == '%sInstanceID' % rasd_ns: existing_ids.append(int(elem.text)) if elem.tag in ['%sAddressOnParent' % rasd_ns, '%sParent' % rasd_ns]: item.remove(elem) if item.find('%sHostResource' % rasd_ns) is not None: new_disk = item new_disk = copy.deepcopy(new_disk) disk_id = max(existing_ids) + 1 new_disk.find('%sInstanceID' % rasd_ns).text = str(disk_id) new_disk.find('%sElementName' % rasd_ns).text = 'Hard Disk ' + str(disk_id) new_disk.find('%sHostResource' % rasd_ns).set( fixxpath(new_disk, 'capacity'), str(int(vm_disk) * 1024)) res.object.append(new_disk) headers = { 'Content-Type': 'application/vnd.vmware.vcloud.rasditemslist+xml' } res = self.connection.request( '%s/virtualHardwareSection/disks' % get_url_path( vm.get('href')), data=ET.tostring(res.object), method='PUT', headers=headers ) self._wait_for_task_completion(res.object.get('href')) def _change_vm_script(self, vapp_or_vm_id, vm_script): if vm_script is None: return vms = self._get_vm_elements(vapp_or_vm_id) try: script = open(vm_script).read() except: return # ElementTree escapes script characters automatically. Escape # requirements: # http://www.vmware.com/support/vcd/doc/rest-api-doc-1.5-html/types/ # GuestCustomizationSectionType.html for vm in vms: # Get GuestCustomizationSection res = self.connection.request( '%s/guestCustomizationSection' % get_url_path(vm.get('href'))) # Attempt to update any existing CustomizationScript element try: res.object.find( fixxpath(res.object, 'CustomizationScript')).text = script except: # CustomizationScript section does not exist, insert it just # before ComputerName for i, e in enumerate(res.object): if e.tag == \ '{http://www.vmware.com/vcloud/v1.5}ComputerName': break e = ET.Element( '{http://www.vmware.com/vcloud/v1.5}CustomizationScript') e.text = script res.object.insert(i, e) # Remove AdminPassword from customization section due to an API # quirk admin_pass = res.object.find(fixxpath(res.object, 'AdminPassword')) if admin_pass is not None: res.object.remove(admin_pass) # Update VM's GuestCustomizationSection headers = { 'Content-Type': 'application/vnd.vmware.vcloud.guestCustomizationSection+xml' } res = self.connection.request( '%s/guestCustomizationSection' % get_url_path(vm.get('href')), data=ET.tostring(res.object), method='PUT', headers=headers ) self._wait_for_task_completion(res.object.get('href')) def _change_vm_ipmode(self, vapp_or_vm_id, vm_ipmode): if vm_ipmode is None: return vms = self._get_vm_elements(vapp_or_vm_id) for vm in vms: res = self.connection.request( '%s/networkConnectionSection' % get_url_path(vm.get('href'))) net_conns = res.object.findall( fixxpath(res.object, 'NetworkConnection')) for c in net_conns: c.find(fixxpath(c, 'IpAddressAllocationMode')).text = vm_ipmode headers = { 'Content-Type': 'application/vnd.vmware.vcloud.networkConnectionSection+xml' } res = self.connection.request( '%s/networkConnectionSection' % get_url_path(vm.get('href')), data=ET.tostring(res.object), method='PUT', headers=headers ) self._wait_for_task_completion(res.object.get('href')) def _get_network_href(self, network_name): network_href = None # Find the organisation's network href res = self.connection.request(self.org) links = res.object.findall(fixxpath(res.object, 'Link')) for l in links: if l.attrib['type'] == \ 'application/vnd.vmware.vcloud.orgNetwork+xml' \ and l.attrib['name'] == network_name: network_href = l.attrib['href'] if network_href is None: raise ValueError( '%s is not a valid organisation network name' % network_name) else: return network_href def _get_vm_elements(self, vapp_or_vm_id): res = self.connection.request(get_url_path(vapp_or_vm_id)) if res.object.tag.endswith('VApp'): vms = res.object.findall(fixxpath(res.object, 'Children/Vm')) elif res.object.tag.endswith('Vm'): vms = [res.object] else: raise ValueError( 'Specified ID value is not a valid VApp or Vm identifier.') return vms def _is_node(self, node_or_image): return isinstance(node_or_image, Node) def _to_node(self, node_elm): # Parse snapshots and VMs as extra if node_elm.find(fixxpath(node_elm, "SnapshotSection")) is None: snapshots = None else: snapshots = [] for snapshot_elem in node_elm.findall( fixxpath(node_elm, 'SnapshotSection/Snapshot')): snapshots.append({ "created": snapshot_elem.get("created"), "poweredOn": snapshot_elem.get("poweredOn"), "size": snapshot_elem.get("size"), }) vms = [] for vm_elem in node_elm.findall(fixxpath(node_elm, 'Children/Vm')): public_ips = [] private_ips = [] xpath = fixxpath(vm_elem, 'NetworkConnectionSection/NetworkConnection') for connection in vm_elem.findall(xpath): ip = connection.find(fixxpath(connection, "IpAddress")) if ip is not None: private_ips.append(ip.text) external_ip = connection.find( fixxpath(connection, "ExternalIpAddress")) if external_ip is not None: public_ips.append(external_ip.text) elif ip is not None: public_ips.append(ip.text) xpath = ('{http://schemas.dmtf.org/ovf/envelope/1}' 'OperatingSystemSection') os_type_elem = vm_elem.find(xpath) if os_type_elem is not None: os_type = os_type_elem.get( '{http://www.vmware.com/schema/ovf}osType') else: os_type = None vm = { 'id': vm_elem.get('href'), 'name': vm_elem.get('name'), 'state': self.NODE_STATE_MAP[vm_elem.get('status')], 'public_ips': public_ips, 'private_ips': private_ips, 'os_type': os_type } vms.append(vm) # Take the node IP addresses from all VMs public_ips = [] private_ips = [] for vm in vms: public_ips.extend(vm['public_ips']) private_ips.extend(vm['private_ips']) # Find vDC vdc_id = next(link.get('href') for link in node_elm.findall(fixxpath(node_elm, 'Link')) if link.get('type') == 'application/vnd.vmware.vcloud.vdc+xml') vdc = next(vdc for vdc in self.vdcs if vdc.id == vdc_id) extra = {'vdc': vdc.name, 'vms': vms} if snapshots is not None: extra['snapshots'] = snapshots node = Node(id=node_elm.get('href'), name=node_elm.get('name'), state=self.NODE_STATE_MAP[node_elm.get('status')], public_ips=public_ips, private_ips=private_ips, driver=self.connection.driver, extra=extra) return node def _to_vdc(self, vdc_elm): def get_capacity_values(capacity_elm): if capacity_elm is None: return None limit = int(capacity_elm.findtext(fixxpath(capacity_elm, 'Limit'))) used = int(capacity_elm.findtext(fixxpath(capacity_elm, 'Used'))) units = capacity_elm.findtext(fixxpath(capacity_elm, 'Units')) return Capacity(limit, used, units) cpu = get_capacity_values( vdc_elm.find(fixxpath(vdc_elm, 'ComputeCapacity/Cpu'))) memory = get_capacity_values( vdc_elm.find(fixxpath(vdc_elm, 'ComputeCapacity/Memory'))) storage = get_capacity_values( vdc_elm.find(fixxpath(vdc_elm, 'StorageCapacity'))) return Vdc(id=vdc_elm.get('href'), name=vdc_elm.get('name'), driver=self, allocation_model=vdc_elm.findtext( fixxpath(vdc_elm, 'AllocationModel')), cpu=cpu, memory=memory, storage=storage) class VCloud_5_1_NodeDriver(VCloud_1_5_NodeDriver): @staticmethod def _validate_vm_memory(vm_memory): if vm_memory is None: return None elif (vm_memory % 4) != 0: # The vcd 5.1 virtual machine memory size must be a multiple of 4 # MB raise ValueError( '%s is not a valid vApp VM memory value' % (vm_memory)) class VCloud_5_5_NodeDriver(VCloud_5_1_NodeDriver): '''Use 5.5 Connection class to explicitly set 5.5 for the version in Accept headers ''' connectionCls = VCloud_5_5_Connection def ex_create_snapshot(self, node): """ Creates new snapshot of a virtual machine or of all the virtual machines in a vApp. Prior to creation of the new snapshots, any existing user created snapshots associated with the virtual machines are removed. :param node: node :type node: :class:`Node` :rtype: :class:`Node` """ snapshot_xml = ET.Element( "CreateSnapshotParams", {'memory': 'true', 'name': 'name', 'quiesce': 'true', 'xmlns': "http://www.vmware.com/vcloud/v1.5", 'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance"} ) ET.SubElement(snapshot_xml, 'Description').text = 'Description' content_type = 'application/vnd.vmware.vcloud.createSnapshotParams+xml' headers = { 'Content-Type': content_type } return self._perform_snapshot_operation(node, "createSnapshot", snapshot_xml, headers) def ex_remove_snapshots(self, node): """ Removes all user created snapshots for a vApp or virtual machine. :param node: node :type node: :class:`Node` :rtype: :class:`Node` """ return self._perform_snapshot_operation(node, "removeAllSnapshots", None, None) def ex_revert_to_snapshot(self, node): """ Reverts a vApp or virtual machine to the current snapshot, if any. :param node: node :type node: :class:`Node` :rtype: :class:`Node` """ return self._perform_snapshot_operation(node, "revertToCurrentSnapshot", None, None) def _perform_snapshot_operation(self, node, operation, xml_data, headers): res = self.connection.request( '%s/action/%s' % (get_url_path(node.id), operation), data=ET.tostring(xml_data) if xml_data else None, method='POST', headers=headers) self._wait_for_task_completion(res.object.get('href')) res = self.connection.request(get_url_path(node.id)) return self._to_node(res.object) def ex_acquire_mks_ticket(self, vapp_or_vm_id, vm_num=0): """ Retrieve a mks ticket that you can use to gain access to the console of a running VM. If successful, returns a dict with the following keys: - host: host (or proxy) through which the console connection is made - vmx: a reference to the VMX file of the VM for which this ticket was issued - ticket: screen ticket to use to authenticate the client - port: host port to be used for console access :param vapp_or_vm_id: vApp or VM ID you want to connect to. :type vapp_or_vm_id: ``str`` :param vm_num: If a vApp ID is provided, vm_num is position in the vApp VM list of the VM you want to get a screen ticket. Default is 0. :type vm_num: ``int`` :rtype: ``dict`` """ vm = self._get_vm_elements(vapp_or_vm_id)[vm_num] try: res = self.connection.request('%s/screen/action/acquireMksTicket' % (get_url_path(vm.get('href'))), method='POST') output = { "host": res.object.find(fixxpath(res.object, 'Host')).text, "vmx": res.object.find(fixxpath(res.object, 'Vmx')).text, "ticket": res.object.find(fixxpath(res.object, 'Ticket')).text, "port": res.object.find(fixxpath(res.object, 'Port')).text, } return output except: return None
niteoweb/libcloud
libcloud/compute/drivers/vcloud.py
Python
apache-2.0
80,770
#pylint: disable=W0703,R0904,W0105 ''' Copyright 2014 eBay Software Foundation 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. ''' """ Thread to perform service deletes """ from agent.lib.agent_thread.agent_thread import AgentThread from pylons import config from agent.lib.errors import Errors, AgentException from agent.lib.utils import xstr import traceback import logging LOG = logging.getLogger(__name__) class AgentThreadCancel(AgentThread): """ Cancel distribution """ def __init__(self, threadMgr, uuid): """ Constructor """ AgentThread.__init__(self, threadMgr, cat = [uuid], name = 'cancel_agentthread') self.__uuid = uuid def doRun(self): """ Main body of the thread """ try: appGlobal = config['pylons.app_globals'] thread = appGlobal.threadMgr.getThreadByUuid(self.__uuid) # Check if indeed trying to stop only distribution client threads if thread is None: self._updateStatus(httpStatus = 500, error = Errors.AGENT_THREAD_NOT_CANCELABLE, errorMsg = 'Non-existing thread %s cannot be canceled' % self.__uuid) return if not (issubclass(thread.__class__, AgentThread)): self._updateStatus(httpStatus = 500, error = Errors.AGENT_THREAD_NOT_CANCELABLE, errorMsg = 'thread of type %s cannot be canceled' % xstr(thread.__class__)) return self._updateStatus(progress = 50) #Ignore if thread is not alive if (thread.isAlive()): thread.stop() self._updateStatus(progress = 100) except AgentException as exc: msg = 'Could not cancel distribution thread with uuid %s %s' % (self.__uuid, exc.getMsg) self._updateStatus(httpStatus = 500, error = exc.getCode(), errorMsg = msg) except Exception as exc: code = Errors.UNKNOWN_ERROR msg = 'Could not cancel distribution thread with uuid ' + \ self.__uuid + '(#' + str(code) + '). ' + traceback.format_exc(5) self._updateStatus(httpStatus = 500, error = code, errorMsg = msg)
eBay/cronus-agent
agent/agent/lib/agent_thread/cancel_agentthread.py
Python
apache-2.0
2,779
from scipy.stats import entropy as kl_div import bet.postProcess.compareP as compP from helpers import * """ The ``helpers.py`` file contains functions that define sample sets of an arbitrary dimension with probabilities uniformly distributed in a hypercube of sidelength ``delta``. The hypercube can be in three locations: - corner at [0, 0, ..., 0] in ``unit_bottom_set`` - centered at [0.5, 0.5, ... 0.5] in ``unit_center_set`` - corner in [1, 1, ..., 1] in `` unit_top_set`` and the number of samples will determine the fidelity of the approximation since we are using voronoi-cell approximations. """ num_left_samples = 50 num_right_samples = 50 delta = 0.5 # width of measure's support per dimension dim = 2 # define two sets that will be compared L = unit_center_set(dim, num_left_samples, delta) R = unit_center_set(dim, num_right_samples, delta) # choose a reference sigma-algebra to compare both solutions # against (using nearest-neighbor query). num_comparison_samples = 2000 # the compP.compare method instantiates the compP.comparison class. mm = compP.compare(L, R, num_comparison_samples) # initialize metric # Use existing common library functions # Use a function of your own! def inftynorm(x, y): """ Infinity norm between two vectors. """ return np.max(np.abs(x - y)) mm.set_left(unit_center_set(2, 1000, delta / 2)) mm.set_right(unit_center_set(2, 1000, delta)) print([mm.value(kl_div), mm.value(inftynorm), mm.value('tv'), mm.value('totvar'), mm.value('mink', w=0.5, p=1), mm.value('norm'), mm.value('sqhell'), mm.value('hell'), mm.value('hellinger')])
smattis/BET-1
examples/compare/comparison.py
Python
gpl-3.0
1,659
import os from collections import defaultdict import dill import numpy as np import pySDC.helpers.plot_helper as plt_helper from pySDC.helpers.stats_helper import filter_stats, sort_stats from pySDC.implementations.collocation_classes.gauss_lobatto import CollGaussLobatto from pySDC.implementations.controller_classes.controller_nonMPI import controller_nonMPI from pySDC.implementations.problem_classes.FermiPastaUlamTsingou import fermi_pasta_ulam_tsingou from pySDC.implementations.sweeper_classes.verlet import verlet from pySDC.implementations.transfer_classes.TransferParticles_NoCoarse import particles_to_particles from pySDC.projects.Hamiltonian.hamiltonian_and_energy_output import hamiltonian_and_energy_output def setup_fput(): """ Helper routine for setting up everything for the Fermi-Pasta-Ulam-Tsingou problem Returns: description (dict): description of the controller controller_params (dict): controller parameters """ # initialize level parameters level_params = dict() level_params['restol'] = 1E-12 level_params['dt'] = 2.0 # initialize sweeper parameters sweeper_params = dict() sweeper_params['collocation_class'] = CollGaussLobatto sweeper_params['num_nodes'] = [5, 3] sweeper_params['initial_guess'] = 'zero' # initialize problem parameters for the Penning trap problem_params = dict() problem_params['npart'] = 2048 problem_params['alpha'] = 0.25 problem_params['k'] = 1.0 problem_params['energy_modes'] = [[1, 2, 3, 4]] # initialize step parameters step_params = dict() step_params['maxiter'] = 50 # initialize controller parameters controller_params = dict() controller_params['hook_class'] = hamiltonian_and_energy_output controller_params['logger_level'] = 30 # Fill description dictionary for easy hierarchy creation description = dict() description['problem_class'] = fermi_pasta_ulam_tsingou description['problem_params'] = problem_params description['sweeper_class'] = verlet description['sweeper_params'] = sweeper_params description['level_params'] = level_params description['step_params'] = step_params description['space_transfer_class'] = particles_to_particles return description, controller_params def run_simulation(): """ Routine to run the simulation of a second order problem """ description, controller_params = setup_fput() # set time parameters t0 = 0.0 # set this to 10000 to reproduce the picture in # http://www.scholarpedia.org/article/Fermi-Pasta-Ulam_nonlinear_lattice_oscillations Tend = 1000.0 num_procs = 1 f = open('fput_out.txt', 'w') out = 'Running fput problem with %s processors...' % num_procs f.write(out + '\n') print(out) # instantiate the controller controller = controller_nonMPI(num_procs=num_procs, controller_params=controller_params, description=description) # get initial values on finest level P = controller.MS[0].levels[0].prob uinit = P.u_exact(t=t0) # call main function to get things done... uend, stats = controller.run(u0=uinit, t0=t0, Tend=Tend) # filter statistics by type (number of iterations) filtered_stats = filter_stats(stats, type='niter') # convert filtered statistics to list of iterations count, sorted by process iter_counts = sort_stats(filtered_stats, sortby='time') # compute and print statistics # for item in iter_counts: # out = 'Number of iterations for time %4.2f: %2i' % item # f.write(out + '\n') # print(out) niters = np.array([item[1] for item in iter_counts]) out = ' Mean number of iterations: %4.2f' % np.mean(niters) f.write(out + '\n') print(out) out = ' Range of values for number of iterations: %2i ' % np.ptp(niters) f.write(out + '\n') print(out) out = ' Position of max/min number of iterations: %2i -- %2i' % \ (int(np.argmax(niters)), int(np.argmin(niters))) f.write(out + '\n') print(out) out = ' Std and var for number of iterations: %4.2f -- %4.2f' % (float(np.std(niters)), float(np.var(niters))) f.write(out + '\n') print(out) # get runtime timing_run = sort_stats(filter_stats(stats, type='timing_run'), sortby='time')[0][1] out = '... took %6.4f seconds to run this.' % timing_run f.write(out + '\n') print(out) f.close() # assert np.mean(niters) <= 3.46, 'Mean number of iterations is too high, got %s' % np.mean(niters) fname = 'data/fput.dat' f = open(fname, 'wb') dill.dump(stats, f) f.close() assert os.path.isfile(fname), 'Run for %s did not create stats file' def show_results(cwd=''): """ Helper function to plot the error of the Hamiltonian Args: cwd (str): current working directory """ # read in the dill data f = open(cwd + 'data/fput.dat', 'rb') stats = dill.load(f) f.close() plt_helper.mpl.style.use('classic') plt_helper.setup_mpl() # HAMILTONIAN PLOTTING # # extract error in hamiltonian and prepare for plotting extract_stats = filter_stats(stats, type='err_hamiltonian') result = defaultdict(list) for k, v in extract_stats.items(): result[k.iter].append((k.time, v)) for k, _ in result.items(): result[k] = sorted(result[k], key=lambda x: x[0]) plt_helper.newfig(textwidth=238.96, scale=0.89) # Rearrange data for easy plotting err_ham = 1 for k, v in result.items(): time = [item[0] for item in v] ham = [item[1] for item in v] err_ham = ham[-1] plt_helper.plt.semilogy(time, ham, '-', lw=1, label='Iter ' + str(k)) print(err_ham) # assert err_ham < 6E-10, 'Error in the Hamiltonian is too large, got %s' % err_ham plt_helper.plt.xlabel('Time') plt_helper.plt.ylabel('Error in Hamiltonian') plt_helper.plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) fname = 'data/fput_hamiltonian' plt_helper.savefig(fname) assert os.path.isfile(fname + '.pdf'), 'ERROR: plotting did not create PDF file' # assert os.path.isfile(fname + '.pgf'), 'ERROR: plotting did not create PGF file' assert os.path.isfile(fname + '.png'), 'ERROR: plotting did not create PNG file' # ENERGY PLOTTING # # extract error in hamiltonian and prepare for plotting extract_stats = filter_stats(stats, type='energy_step') result = sort_stats(extract_stats, sortby='time') plt_helper.newfig(textwidth=238.96, scale=0.89) # Rearrange data for easy plotting for mode in result[0][1].keys(): time = [item[0] for item in result] energy = [item[1][mode] for item in result] plt_helper.plt.plot(time, energy, label=str(mode) + 'th mode') plt_helper.plt.xlabel('Time') plt_helper.plt.ylabel('Energy') plt_helper.plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) fname = 'data/fput_energy' plt_helper.savefig(fname) assert os.path.isfile(fname + '.pdf'), 'ERROR: plotting did not create PDF file' # assert os.path.isfile(fname + '.pgf'), 'ERROR: plotting did not create PGF file' assert os.path.isfile(fname + '.png'), 'ERROR: plotting did not create PNG file' # POSITION PLOTTING # # extract positions and prepare for plotting extract_stats = filter_stats(stats, type='position') result = sort_stats(extract_stats, sortby='time') plt_helper.newfig(textwidth=238.96, scale=0.89) # Rearrange data for easy plotting nparts = len(result[0][1]) nsteps = len(result) pos = np.zeros((nparts, nsteps)) time = np.zeros(nsteps) for idx, item in enumerate(result): time[idx] = item[0] for n in range(nparts): pos[n, idx] = item[1][n] for n in range(min(nparts, 16)): plt_helper.plt.plot(time, pos[n, :]) fname = 'data/fput_positions' plt_helper.savefig(fname) assert os.path.isfile(fname + '.pdf'), 'ERROR: plotting did not create PDF file' # assert os.path.isfile(fname + '.pgf'), 'ERROR: plotting did not create PGF file' assert os.path.isfile(fname + '.png'), 'ERROR: plotting did not create PNG file' def main(): run_simulation() show_results() if __name__ == "__main__": main()
Parallel-in-Time/pySDC
pySDC/projects/Hamiltonian/fput.py
Python
bsd-2-clause
8,363
from __future__ import absolute_import, division, unicode_literals import string import gettext _ = gettext.gettext EOF = None E = { "null-character": _("Null character in input stream, replaced with U+FFFD."), "invalid-codepoint": _("Invalid codepoint in stream."), "incorrectly-placed-solidus": _("Solidus (/) incorrectly placed in tag."), "incorrect-cr-newline-entity": _("Incorrect CR newline entity, replaced with LF."), "illegal-windows-1252-entity": _("Entity used with illegal number (windows-1252 reference)."), "cant-convert-numeric-entity": _("Numeric entity couldn't be converted to character " "(codepoint U+%(charAsInt)08x)."), "illegal-codepoint-for-numeric-entity": _("Numeric entity represents an illegal codepoint: " "U+%(charAsInt)08x."), "numeric-entity-without-semicolon": _("Numeric entity didn't end with ';'."), "expected-numeric-entity-but-got-eof": _("Numeric entity expected. Got end of file instead."), "expected-numeric-entity": _("Numeric entity expected but none found."), "named-entity-without-semicolon": _("Named entity didn't end with ';'."), "expected-named-entity": _("Named entity expected. Got none."), "attributes-in-end-tag": _("End tag contains unexpected attributes."), 'self-closing-flag-on-end-tag': _("End tag contains unexpected self-closing flag."), "expected-tag-name-but-got-right-bracket": _("Expected tag name. Got '>' instead."), "expected-tag-name-but-got-question-mark": _("Expected tag name. Got '?' instead. (HTML doesn't " "support processing instructions.)"), "expected-tag-name": _("Expected tag name. Got something else instead"), "expected-closing-tag-but-got-right-bracket": _("Expected closing tag. Got '>' instead. Ignoring '</>'."), "expected-closing-tag-but-got-eof": _("Expected closing tag. Unexpected end of file."), "expected-closing-tag-but-got-char": _("Expected closing tag. Unexpected character '%(data)s' found."), "eof-in-tag-name": _("Unexpected end of file in the tag name."), "expected-attribute-name-but-got-eof": _("Unexpected end of file. Expected attribute name instead."), "eof-in-attribute-name": _("Unexpected end of file in attribute name."), "invalid-character-in-attribute-name": _("Invalid character in attribute name"), "duplicate-attribute": _("Dropped duplicate attribute on tag."), "expected-end-of-tag-name-but-got-eof": _("Unexpected end of file. Expected = or end of tag."), "expected-attribute-value-but-got-eof": _("Unexpected end of file. Expected attribute value."), "expected-attribute-value-but-got-right-bracket": _("Expected attribute value. Got '>' instead."), 'equals-in-unquoted-attribute-value': _("Unexpected = in unquoted attribute"), 'unexpected-character-in-unquoted-attribute-value': _("Unexpected character in unquoted attribute"), "invalid-character-after-attribute-name": _("Unexpected character after attribute name."), "unexpected-character-after-attribute-value": _("Unexpected character after attribute value."), "eof-in-attribute-value-double-quote": _("Unexpected end of file in attribute value (\")."), "eof-in-attribute-value-single-quote": _("Unexpected end of file in attribute value (')."), "eof-in-attribute-value-no-quotes": _("Unexpected end of file in attribute value."), "unexpected-EOF-after-solidus-in-tag": _("Unexpected end of file in tag. Expected >"), "unexpected-character-after-solidus-in-tag": _("Unexpected character after / in tag. Expected >"), "expected-dashes-or-doctype": _("Expected '--' or 'DOCTYPE'. Not found."), "unexpected-bang-after-double-dash-in-comment": _("Unexpected ! after -- in comment"), "unexpected-space-after-double-dash-in-comment": _("Unexpected space after -- in comment"), "incorrect-comment": _("Incorrect comment."), "eof-in-comment": _("Unexpected end of file in comment."), "eof-in-comment-end-dash": _("Unexpected end of file in comment (-)"), "unexpected-dash-after-double-dash-in-comment": _("Unexpected '-' after '--' found in comment."), "eof-in-comment-double-dash": _("Unexpected end of file in comment (--)."), "eof-in-comment-end-space-state": _("Unexpected end of file in comment."), "eof-in-comment-end-bang-state": _("Unexpected end of file in comment."), "unexpected-char-in-comment": _("Unexpected character in comment found."), "need-space-after-doctype": _("No space after literal string 'DOCTYPE'."), "expected-doctype-name-but-got-right-bracket": _("Unexpected > character. Expected DOCTYPE name."), "expected-doctype-name-but-got-eof": _("Unexpected end of file. Expected DOCTYPE name."), "eof-in-doctype-name": _("Unexpected end of file in DOCTYPE name."), "eof-in-doctype": _("Unexpected end of file in DOCTYPE."), "expected-space-or-right-bracket-in-doctype": _("Expected space or '>'. Got '%(data)s'"), "unexpected-end-of-doctype": _("Unexpected end of DOCTYPE."), "unexpected-char-in-doctype": _("Unexpected character in DOCTYPE."), "eof-in-innerhtml": _("XXX innerHTML EOF"), "unexpected-doctype": _("Unexpected DOCTYPE. Ignored."), "non-html-root": _("html needs to be the first start tag."), "expected-doctype-but-got-eof": _("Unexpected End of file. Expected DOCTYPE."), "unknown-doctype": _("Erroneous DOCTYPE."), "expected-doctype-but-got-chars": _("Unexpected non-space characters. Expected DOCTYPE."), "expected-doctype-but-got-start-tag": _("Unexpected start tag (%(name)s). Expected DOCTYPE."), "expected-doctype-but-got-end-tag": _("Unexpected end tag (%(name)s). Expected DOCTYPE."), "end-tag-after-implied-root": _("Unexpected end tag (%(name)s) after the (implied) root element."), "expected-named-closing-tag-but-got-eof": _("Unexpected end of file. Expected end tag (%(name)s)."), "two-heads-are-not-better-than-one": _("Unexpected start tag head in existing head. Ignored."), "unexpected-end-tag": _("Unexpected end tag (%(name)s). Ignored."), "unexpected-start-tag-out-of-my-head": _("Unexpected start tag (%(name)s) that can be in head. Moved."), "unexpected-start-tag": _("Unexpected start tag (%(name)s)."), "missing-end-tag": _("Missing end tag (%(name)s)."), "missing-end-tags": _("Missing end tags (%(name)s)."), "unexpected-start-tag-implies-end-tag": _("Unexpected start tag (%(startName)s) " "implies end tag (%(endName)s)."), "unexpected-start-tag-treated-as": _("Unexpected start tag (%(originalName)s). Treated as %(newName)s."), "deprecated-tag": _("Unexpected start tag %(name)s. Don't use it!"), "unexpected-start-tag-ignored": _("Unexpected start tag %(name)s. Ignored."), "expected-one-end-tag-but-got-another": _("Unexpected end tag (%(gotName)s). " "Missing end tag (%(expectedName)s)."), "end-tag-too-early": _("End tag (%(name)s) seen too early. Expected other end tag."), "end-tag-too-early-named": _("Unexpected end tag (%(gotName)s). Expected end tag (%(expectedName)s)."), "end-tag-too-early-ignored": _("End tag (%(name)s) seen too early. Ignored."), "adoption-agency-1.1": _("End tag (%(name)s) violates step 1, " "paragraph 1 of the adoption agency algorithm."), "adoption-agency-1.2": _("End tag (%(name)s) violates step 1, " "paragraph 2 of the adoption agency algorithm."), "adoption-agency-1.3": _("End tag (%(name)s) violates step 1, " "paragraph 3 of the adoption agency algorithm."), "adoption-agency-4.4": _("End tag (%(name)s) violates step 4, " "paragraph 4 of the adoption agency algorithm."), "unexpected-end-tag-treated-as": _("Unexpected end tag (%(originalName)s). Treated as %(newName)s."), "no-end-tag": _("This element (%(name)s) has no end tag."), "unexpected-implied-end-tag-in-table": _("Unexpected implied end tag (%(name)s) in the table phase."), "unexpected-implied-end-tag-in-table-body": _("Unexpected implied end tag (%(name)s) in the table body phase."), "unexpected-char-implies-table-voodoo": _("Unexpected non-space characters in " "table context caused voodoo mode."), "unexpected-hidden-input-in-table": _("Unexpected input with type hidden in table context."), "unexpected-form-in-table": _("Unexpected form in table context."), "unexpected-start-tag-implies-table-voodoo": _("Unexpected start tag (%(name)s) in " "table context caused voodoo mode."), "unexpected-end-tag-implies-table-voodoo": _("Unexpected end tag (%(name)s) in " "table context caused voodoo mode."), "unexpected-cell-in-table-body": _("Unexpected table cell start tag (%(name)s) " "in the table body phase."), "unexpected-cell-end-tag": _("Got table cell end tag (%(name)s) " "while required end tags are missing."), "unexpected-end-tag-in-table-body": _("Unexpected end tag (%(name)s) in the table body phase. Ignored."), "unexpected-implied-end-tag-in-table-row": _("Unexpected implied end tag (%(name)s) in the table row phase."), "unexpected-end-tag-in-table-row": _("Unexpected end tag (%(name)s) in the table row phase. Ignored."), "unexpected-select-in-select": _("Unexpected select start tag in the select phase " "treated as select end tag."), "unexpected-input-in-select": _("Unexpected input start tag in the select phase."), "unexpected-start-tag-in-select": _("Unexpected start tag token (%(name)s in the select phase. " "Ignored."), "unexpected-end-tag-in-select": _("Unexpected end tag (%(name)s) in the select phase. Ignored."), "unexpected-table-element-start-tag-in-select-in-table": _("Unexpected table element start tag (%(name)s) in the select in table phase."), "unexpected-table-element-end-tag-in-select-in-table": _("Unexpected table element end tag (%(name)s) in the select in table phase."), "unexpected-char-after-body": _("Unexpected non-space characters in the after body phase."), "unexpected-start-tag-after-body": _("Unexpected start tag token (%(name)s)" " in the after body phase."), "unexpected-end-tag-after-body": _("Unexpected end tag token (%(name)s)" " in the after body phase."), "unexpected-char-in-frameset": _("Unexpected characters in the frameset phase. Characters ignored."), "unexpected-start-tag-in-frameset": _("Unexpected start tag token (%(name)s)" " in the frameset phase. Ignored."), "unexpected-frameset-in-frameset-innerhtml": _("Unexpected end tag token (frameset) " "in the frameset phase (innerHTML)."), "unexpected-end-tag-in-frameset": _("Unexpected end tag token (%(name)s)" " in the frameset phase. Ignored."), "unexpected-char-after-frameset": _("Unexpected non-space characters in the " "after frameset phase. Ignored."), "unexpected-start-tag-after-frameset": _("Unexpected start tag (%(name)s)" " in the after frameset phase. Ignored."), "unexpected-end-tag-after-frameset": _("Unexpected end tag (%(name)s)" " in the after frameset phase. Ignored."), "unexpected-end-tag-after-body-innerhtml": _("Unexpected end tag after body(innerHtml)"), "expected-eof-but-got-char": _("Unexpected non-space characters. Expected end of file."), "expected-eof-but-got-start-tag": _("Unexpected start tag (%(name)s)" ". Expected end of file."), "expected-eof-but-got-end-tag": _("Unexpected end tag (%(name)s)" ". Expected end of file."), "eof-in-table": _("Unexpected end of file. Expected table content."), "eof-in-select": _("Unexpected end of file. Expected select content."), "eof-in-frameset": _("Unexpected end of file. Expected frameset content."), "eof-in-script-in-script": _("Unexpected end of file. Expected script content."), "eof-in-foreign-lands": _("Unexpected end of file. Expected foreign content"), "non-void-element-with-trailing-solidus": _("Trailing solidus not allowed on element %(name)s"), "unexpected-html-element-in-foreign-content": _("Element %(name)s not allowed in a non-html context"), "unexpected-end-tag-before-html": _("Unexpected end tag (%(name)s) before html."), "XXX-undefined-error": _("Undefined error (this sucks and should be fixed)"), } namespaces = { "html": "http://www.w3.org/1999/xhtml", "mathml": "http://www.w3.org/1998/Math/MathML", "svg": "http://www.w3.org/2000/svg", "xlink": "http://www.w3.org/1999/xlink", "xml": "http://www.w3.org/XML/1998/namespace", "xmlns": "http://www.w3.org/2000/xmlns/" } scopingElements = frozenset(( (namespaces["html"], "applet"), (namespaces["html"], "caption"), (namespaces["html"], "html"), (namespaces["html"], "marquee"), (namespaces["html"], "object"), (namespaces["html"], "table"), (namespaces["html"], "td"), (namespaces["html"], "th"), (namespaces["mathml"], "mi"), (namespaces["mathml"], "mo"), (namespaces["mathml"], "mn"), (namespaces["mathml"], "ms"), (namespaces["mathml"], "mtext"), (namespaces["mathml"], "annotation-xml"), (namespaces["svg"], "foreignObject"), (namespaces["svg"], "desc"), (namespaces["svg"], "title"), )) formattingElements = frozenset(( (namespaces["html"], "a"), (namespaces["html"], "b"), (namespaces["html"], "big"), (namespaces["html"], "code"), (namespaces["html"], "em"), (namespaces["html"], "font"), (namespaces["html"], "i"), (namespaces["html"], "nobr"), (namespaces["html"], "s"), (namespaces["html"], "small"), (namespaces["html"], "strike"), (namespaces["html"], "strong"), (namespaces["html"], "tt"), (namespaces["html"], "u") )) specialElements = frozenset(( (namespaces["html"], "address"), (namespaces["html"], "applet"), (namespaces["html"], "area"), (namespaces["html"], "article"), (namespaces["html"], "aside"), (namespaces["html"], "base"), (namespaces["html"], "basefont"), (namespaces["html"], "bgsound"), (namespaces["html"], "blockquote"), (namespaces["html"], "body"), (namespaces["html"], "br"), (namespaces["html"], "button"), (namespaces["html"], "caption"), (namespaces["html"], "center"), (namespaces["html"], "col"), (namespaces["html"], "colgroup"), (namespaces["html"], "command"), (namespaces["html"], "dd"), (namespaces["html"], "details"), (namespaces["html"], "dir"), (namespaces["html"], "div"), (namespaces["html"], "dl"), (namespaces["html"], "dt"), (namespaces["html"], "embed"), (namespaces["html"], "fieldset"), (namespaces["html"], "figure"), (namespaces["html"], "footer"), (namespaces["html"], "form"), (namespaces["html"], "frame"), (namespaces["html"], "frameset"), (namespaces["html"], "h1"), (namespaces["html"], "h2"), (namespaces["html"], "h3"), (namespaces["html"], "h4"), (namespaces["html"], "h5"), (namespaces["html"], "h6"), (namespaces["html"], "head"), (namespaces["html"], "header"), (namespaces["html"], "hr"), (namespaces["html"], "html"), (namespaces["html"], "iframe"), # Note that image is commented out in the spec as "this isn't an # element that can end up on the stack, so it doesn't matter," (namespaces["html"], "image"), (namespaces["html"], "img"), (namespaces["html"], "input"), (namespaces["html"], "isindex"), (namespaces["html"], "li"), (namespaces["html"], "link"), (namespaces["html"], "listing"), (namespaces["html"], "marquee"), (namespaces["html"], "menu"), (namespaces["html"], "meta"), (namespaces["html"], "nav"), (namespaces["html"], "noembed"), (namespaces["html"], "noframes"), (namespaces["html"], "noscript"), (namespaces["html"], "object"), (namespaces["html"], "ol"), (namespaces["html"], "p"), (namespaces["html"], "param"), (namespaces["html"], "plaintext"), (namespaces["html"], "pre"), (namespaces["html"], "script"), (namespaces["html"], "section"), (namespaces["html"], "select"), (namespaces["html"], "style"), (namespaces["html"], "table"), (namespaces["html"], "tbody"), (namespaces["html"], "td"), (namespaces["html"], "textarea"), (namespaces["html"], "tfoot"), (namespaces["html"], "th"), (namespaces["html"], "thead"), (namespaces["html"], "title"), (namespaces["html"], "tr"), (namespaces["html"], "ul"), (namespaces["html"], "wbr"), (namespaces["html"], "xmp"), (namespaces["svg"], "foreignObject") )) htmlIntegrationPointElements = frozenset(( (namespaces["mathml"], "annotaion-xml"), (namespaces["svg"], "foreignObject"), (namespaces["svg"], "desc"), (namespaces["svg"], "title") )) mathmlTextIntegrationPointElements = frozenset(( (namespaces["mathml"], "mi"), (namespaces["mathml"], "mo"), (namespaces["mathml"], "mn"), (namespaces["mathml"], "ms"), (namespaces["mathml"], "mtext") )) adjustForeignAttributes = { "xlink:actuate": ("xlink", "actuate", namespaces["xlink"]), "xlink:arcrole": ("xlink", "arcrole", namespaces["xlink"]), "xlink:href": ("xlink", "href", namespaces["xlink"]), "xlink:role": ("xlink", "role", namespaces["xlink"]), "xlink:show": ("xlink", "show", namespaces["xlink"]), "xlink:title": ("xlink", "title", namespaces["xlink"]), "xlink:type": ("xlink", "type", namespaces["xlink"]), "xml:base": ("xml", "base", namespaces["xml"]), "xml:lang": ("xml", "lang", namespaces["xml"]), "xml:space": ("xml", "space", namespaces["xml"]), "xmlns": (None, "xmlns", namespaces["xmlns"]), "xmlns:xlink": ("xmlns", "xlink", namespaces["xmlns"]) } unadjustForeignAttributes = dict([((ns, local), qname) for qname, (prefix, local, ns) in adjustForeignAttributes.items()]) spaceCharacters = frozenset(( "\t", "\n", "\u000C", " ", "\r" )) tableInsertModeElements = frozenset(( "table", "tbody", "tfoot", "thead", "tr" )) asciiLowercase = frozenset(string.ascii_lowercase) asciiUppercase = frozenset(string.ascii_uppercase) asciiLetters = frozenset(string.ascii_letters) digits = frozenset(string.digits) hexDigits = frozenset(string.hexdigits) asciiUpper2Lower = dict([(ord(c), ord(c.lower())) for c in string.ascii_uppercase]) # Heading elements need to be ordered headingElements = ( "h1", "h2", "h3", "h4", "h5", "h6" ) voidElements = frozenset(( "base", "command", "event-source", "link", "meta", "hr", "br", "img", "embed", "param", "area", "col", "input", "source", "track" )) cdataElements = frozenset(('title', 'textarea')) rcdataElements = frozenset(( 'style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'noscript' )) booleanAttributes = { "": frozenset(("irrelevant",)), "style": frozenset(("scoped",)), "img": frozenset(("ismap",)), "audio": frozenset(("autoplay", "controls")), "video": frozenset(("autoplay", "controls")), "script": frozenset(("defer", "async")), "details": frozenset(("open",)), "datagrid": frozenset(("multiple", "disabled")), "command": frozenset(("hidden", "disabled", "checked", "default")), "hr": frozenset(("noshade")), "menu": frozenset(("autosubmit",)), "fieldset": frozenset(("disabled", "readonly")), "option": frozenset(("disabled", "readonly", "selected")), "optgroup": frozenset(("disabled", "readonly")), "button": frozenset(("disabled", "autofocus")), "input": frozenset(("disabled", "readonly", "required", "autofocus", "checked", "ismap")), "select": frozenset(("disabled", "readonly", "autofocus", "multiple")), "output": frozenset(("disabled", "readonly")), } # entitiesWindows1252 has to be _ordered_ and needs to have an index. It # therefore can't be a frozenset. entitiesWindows1252 = ( 8364, # 0x80 0x20AC EURO SIGN 65533, # 0x81 UNDEFINED 8218, # 0x82 0x201A SINGLE LOW-9 QUOTATION MARK 402, # 0x83 0x0192 LATIN SMALL LETTER F WITH HOOK 8222, # 0x84 0x201E DOUBLE LOW-9 QUOTATION MARK 8230, # 0x85 0x2026 HORIZONTAL ELLIPSIS 8224, # 0x86 0x2020 DAGGER 8225, # 0x87 0x2021 DOUBLE DAGGER 710, # 0x88 0x02C6 MODIFIER LETTER CIRCUMFLEX ACCENT 8240, # 0x89 0x2030 PER MILLE SIGN 352, # 0x8A 0x0160 LATIN CAPITAL LETTER S WITH CARON 8249, # 0x8B 0x2039 SINGLE LEFT-POINTING ANGLE QUOTATION MARK 338, # 0x8C 0x0152 LATIN CAPITAL LIGATURE OE 65533, # 0x8D UNDEFINED 381, # 0x8E 0x017D LATIN CAPITAL LETTER Z WITH CARON 65533, # 0x8F UNDEFINED 65533, # 0x90 UNDEFINED 8216, # 0x91 0x2018 LEFT SINGLE QUOTATION MARK 8217, # 0x92 0x2019 RIGHT SINGLE QUOTATION MARK 8220, # 0x93 0x201C LEFT DOUBLE QUOTATION MARK 8221, # 0x94 0x201D RIGHT DOUBLE QUOTATION MARK 8226, # 0x95 0x2022 BULLET 8211, # 0x96 0x2013 EN DASH 8212, # 0x97 0x2014 EM DASH 732, # 0x98 0x02DC SMALL TILDE 8482, # 0x99 0x2122 TRADE MARK SIGN 353, # 0x9A 0x0161 LATIN SMALL LETTER S WITH CARON 8250, # 0x9B 0x203A SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 339, # 0x9C 0x0153 LATIN SMALL LIGATURE OE 65533, # 0x9D UNDEFINED 382, # 0x9E 0x017E LATIN SMALL LETTER Z WITH CARON 376 # 0x9F 0x0178 LATIN CAPITAL LETTER Y WITH DIAERESIS ) xmlEntities = frozenset(('lt;', 'gt;', 'amp;', 'apos;', 'quot;')) entities = { "AElig": "\xc6", "AElig;": "\xc6", "AMP": "&", "AMP;": "&", "Aacute": "\xc1", "Aacute;": "\xc1", "Abreve;": "\u0102", "Acirc": "\xc2", "Acirc;": "\xc2", "Acy;": "\u0410", "Afr;": "\U0001d504", "Agrave": "\xc0", "Agrave;": "\xc0", "Alpha;": "\u0391", "Amacr;": "\u0100", "And;": "\u2a53", "Aogon;": "\u0104", "Aopf;": "\U0001d538", "ApplyFunction;": "\u2061", "Aring": "\xc5", "Aring;": "\xc5", "Ascr;": "\U0001d49c", "Assign;": "\u2254", "Atilde": "\xc3", "Atilde;": "\xc3", "Auml": "\xc4", "Auml;": "\xc4", "Backslash;": "\u2216", "Barv;": "\u2ae7", "Barwed;": "\u2306", "Bcy;": "\u0411", "Because;": "\u2235", "Bernoullis;": "\u212c", "Beta;": "\u0392", "Bfr;": "\U0001d505", "Bopf;": "\U0001d539", "Breve;": "\u02d8", "Bscr;": "\u212c", "Bumpeq;": "\u224e", "CHcy;": "\u0427", "COPY": "\xa9", "COPY;": "\xa9", "Cacute;": "\u0106", "Cap;": "\u22d2", "CapitalDifferentialD;": "\u2145", "Cayleys;": "\u212d", "Ccaron;": "\u010c", "Ccedil": "\xc7", "Ccedil;": "\xc7", "Ccirc;": "\u0108", "Cconint;": "\u2230", "Cdot;": "\u010a", "Cedilla;": "\xb8", "CenterDot;": "\xb7", "Cfr;": "\u212d", "Chi;": "\u03a7", "CircleDot;": "\u2299", "CircleMinus;": "\u2296", "CirclePlus;": "\u2295", "CircleTimes;": "\u2297", "ClockwiseContourIntegral;": "\u2232", "CloseCurlyDoubleQuote;": "\u201d", "CloseCurlyQuote;": "\u2019", "Colon;": "\u2237", "Colone;": "\u2a74", "Congruent;": "\u2261", "Conint;": "\u222f", "ContourIntegral;": "\u222e", "Copf;": "\u2102", "Coproduct;": "\u2210", "CounterClockwiseContourIntegral;": "\u2233", "Cross;": "\u2a2f", "Cscr;": "\U0001d49e", "Cup;": "\u22d3", "CupCap;": "\u224d", "DD;": "\u2145", "DDotrahd;": "\u2911", "DJcy;": "\u0402", "DScy;": "\u0405", "DZcy;": "\u040f", "Dagger;": "\u2021", "Darr;": "\u21a1", "Dashv;": "\u2ae4", "Dcaron;": "\u010e", "Dcy;": "\u0414", "Del;": "\u2207", "Delta;": "\u0394", "Dfr;": "\U0001d507", "DiacriticalAcute;": "\xb4", "DiacriticalDot;": "\u02d9", "DiacriticalDoubleAcute;": "\u02dd", "DiacriticalGrave;": "`", "DiacriticalTilde;": "\u02dc", "Diamond;": "\u22c4", "DifferentialD;": "\u2146", "Dopf;": "\U0001d53b", "Dot;": "\xa8", "DotDot;": "\u20dc", "DotEqual;": "\u2250", "DoubleContourIntegral;": "\u222f", "DoubleDot;": "\xa8", "DoubleDownArrow;": "\u21d3", "DoubleLeftArrow;": "\u21d0", "DoubleLeftRightArrow;": "\u21d4", "DoubleLeftTee;": "\u2ae4", "DoubleLongLeftArrow;": "\u27f8", "DoubleLongLeftRightArrow;": "\u27fa", "DoubleLongRightArrow;": "\u27f9", "DoubleRightArrow;": "\u21d2", "DoubleRightTee;": "\u22a8", "DoubleUpArrow;": "\u21d1", "DoubleUpDownArrow;": "\u21d5", "DoubleVerticalBar;": "\u2225", "DownArrow;": "\u2193", "DownArrowBar;": "\u2913", "DownArrowUpArrow;": "\u21f5", "DownBreve;": "\u0311", "DownLeftRightVector;": "\u2950", "DownLeftTeeVector;": "\u295e", "DownLeftVector;": "\u21bd", "DownLeftVectorBar;": "\u2956", "DownRightTeeVector;": "\u295f", "DownRightVector;": "\u21c1", "DownRightVectorBar;": "\u2957", "DownTee;": "\u22a4", "DownTeeArrow;": "\u21a7", "Downarrow;": "\u21d3", "Dscr;": "\U0001d49f", "Dstrok;": "\u0110", "ENG;": "\u014a", "ETH": "\xd0", "ETH;": "\xd0", "Eacute": "\xc9", "Eacute;": "\xc9", "Ecaron;": "\u011a", "Ecirc": "\xca", "Ecirc;": "\xca", "Ecy;": "\u042d", "Edot;": "\u0116", "Efr;": "\U0001d508", "Egrave": "\xc8", "Egrave;": "\xc8", "Element;": "\u2208", "Emacr;": "\u0112", "EmptySmallSquare;": "\u25fb", "EmptyVerySmallSquare;": "\u25ab", "Eogon;": "\u0118", "Eopf;": "\U0001d53c", "Epsilon;": "\u0395", "Equal;": "\u2a75", "EqualTilde;": "\u2242", "Equilibrium;": "\u21cc", "Escr;": "\u2130", "Esim;": "\u2a73", "Eta;": "\u0397", "Euml": "\xcb", "Euml;": "\xcb", "Exists;": "\u2203", "ExponentialE;": "\u2147", "Fcy;": "\u0424", "Ffr;": "\U0001d509", "FilledSmallSquare;": "\u25fc", "FilledVerySmallSquare;": "\u25aa", "Fopf;": "\U0001d53d", "ForAll;": "\u2200", "Fouriertrf;": "\u2131", "Fscr;": "\u2131", "GJcy;": "\u0403", "GT": ">", "GT;": ">", "Gamma;": "\u0393", "Gammad;": "\u03dc", "Gbreve;": "\u011e", "Gcedil;": "\u0122", "Gcirc;": "\u011c", "Gcy;": "\u0413", "Gdot;": "\u0120", "Gfr;": "\U0001d50a", "Gg;": "\u22d9", "Gopf;": "\U0001d53e", "GreaterEqual;": "\u2265", "GreaterEqualLess;": "\u22db", "GreaterFullEqual;": "\u2267", "GreaterGreater;": "\u2aa2", "GreaterLess;": "\u2277", "GreaterSlantEqual;": "\u2a7e", "GreaterTilde;": "\u2273", "Gscr;": "\U0001d4a2", "Gt;": "\u226b", "HARDcy;": "\u042a", "Hacek;": "\u02c7", "Hat;": "^", "Hcirc;": "\u0124", "Hfr;": "\u210c", "HilbertSpace;": "\u210b", "Hopf;": "\u210d", "HorizontalLine;": "\u2500", "Hscr;": "\u210b", "Hstrok;": "\u0126", "HumpDownHump;": "\u224e", "HumpEqual;": "\u224f", "IEcy;": "\u0415", "IJlig;": "\u0132", "IOcy;": "\u0401", "Iacute": "\xcd", "Iacute;": "\xcd", "Icirc": "\xce", "Icirc;": "\xce", "Icy;": "\u0418", "Idot;": "\u0130", "Ifr;": "\u2111", "Igrave": "\xcc", "Igrave;": "\xcc", "Im;": "\u2111", "Imacr;": "\u012a", "ImaginaryI;": "\u2148", "Implies;": "\u21d2", "Int;": "\u222c", "Integral;": "\u222b", "Intersection;": "\u22c2", "InvisibleComma;": "\u2063", "InvisibleTimes;": "\u2062", "Iogon;": "\u012e", "Iopf;": "\U0001d540", "Iota;": "\u0399", "Iscr;": "\u2110", "Itilde;": "\u0128", "Iukcy;": "\u0406", "Iuml": "\xcf", "Iuml;": "\xcf", "Jcirc;": "\u0134", "Jcy;": "\u0419", "Jfr;": "\U0001d50d", "Jopf;": "\U0001d541", "Jscr;": "\U0001d4a5", "Jsercy;": "\u0408", "Jukcy;": "\u0404", "KHcy;": "\u0425", "KJcy;": "\u040c", "Kappa;": "\u039a", "Kcedil;": "\u0136", "Kcy;": "\u041a", "Kfr;": "\U0001d50e", "Kopf;": "\U0001d542", "Kscr;": "\U0001d4a6", "LJcy;": "\u0409", "LT": "<", "LT;": "<", "Lacute;": "\u0139", "Lambda;": "\u039b", "Lang;": "\u27ea", "Laplacetrf;": "\u2112", "Larr;": "\u219e", "Lcaron;": "\u013d", "Lcedil;": "\u013b", "Lcy;": "\u041b", "LeftAngleBracket;": "\u27e8", "LeftArrow;": "\u2190", "LeftArrowBar;": "\u21e4", "LeftArrowRightArrow;": "\u21c6", "LeftCeiling;": "\u2308", "LeftDoubleBracket;": "\u27e6", "LeftDownTeeVector;": "\u2961", "LeftDownVector;": "\u21c3", "LeftDownVectorBar;": "\u2959", "LeftFloor;": "\u230a", "LeftRightArrow;": "\u2194", "LeftRightVector;": "\u294e", "LeftTee;": "\u22a3", "LeftTeeArrow;": "\u21a4", "LeftTeeVector;": "\u295a", "LeftTriangle;": "\u22b2", "LeftTriangleBar;": "\u29cf", "LeftTriangleEqual;": "\u22b4", "LeftUpDownVector;": "\u2951", "LeftUpTeeVector;": "\u2960", "LeftUpVector;": "\u21bf", "LeftUpVectorBar;": "\u2958", "LeftVector;": "\u21bc", "LeftVectorBar;": "\u2952", "Leftarrow;": "\u21d0", "Leftrightarrow;": "\u21d4", "LessEqualGreater;": "\u22da", "LessFullEqual;": "\u2266", "LessGreater;": "\u2276", "LessLess;": "\u2aa1", "LessSlantEqual;": "\u2a7d", "LessTilde;": "\u2272", "Lfr;": "\U0001d50f", "Ll;": "\u22d8", "Lleftarrow;": "\u21da", "Lmidot;": "\u013f", "LongLeftArrow;": "\u27f5", "LongLeftRightArrow;": "\u27f7", "LongRightArrow;": "\u27f6", "Longleftarrow;": "\u27f8", "Longleftrightarrow;": "\u27fa", "Longrightarrow;": "\u27f9", "Lopf;": "\U0001d543", "LowerLeftArrow;": "\u2199", "LowerRightArrow;": "\u2198", "Lscr;": "\u2112", "Lsh;": "\u21b0", "Lstrok;": "\u0141", "Lt;": "\u226a", "Map;": "\u2905", "Mcy;": "\u041c", "MediumSpace;": "\u205f", "Mellintrf;": "\u2133", "Mfr;": "\U0001d510", "MinusPlus;": "\u2213", "Mopf;": "\U0001d544", "Mscr;": "\u2133", "Mu;": "\u039c", "NJcy;": "\u040a", "Nacute;": "\u0143", "Ncaron;": "\u0147", "Ncedil;": "\u0145", "Ncy;": "\u041d", "NegativeMediumSpace;": "\u200b", "NegativeThickSpace;": "\u200b", "NegativeThinSpace;": "\u200b", "NegativeVeryThinSpace;": "\u200b", "NestedGreaterGreater;": "\u226b", "NestedLessLess;": "\u226a", "NewLine;": "\n", "Nfr;": "\U0001d511", "NoBreak;": "\u2060", "NonBreakingSpace;": "\xa0", "Nopf;": "\u2115", "Not;": "\u2aec", "NotCongruent;": "\u2262", "NotCupCap;": "\u226d", "NotDoubleVerticalBar;": "\u2226", "NotElement;": "\u2209", "NotEqual;": "\u2260", "NotEqualTilde;": "\u2242\u0338", "NotExists;": "\u2204", "NotGreater;": "\u226f", "NotGreaterEqual;": "\u2271", "NotGreaterFullEqual;": "\u2267\u0338", "NotGreaterGreater;": "\u226b\u0338", "NotGreaterLess;": "\u2279", "NotGreaterSlantEqual;": "\u2a7e\u0338", "NotGreaterTilde;": "\u2275", "NotHumpDownHump;": "\u224e\u0338", "NotHumpEqual;": "\u224f\u0338", "NotLeftTriangle;": "\u22ea", "NotLeftTriangleBar;": "\u29cf\u0338", "NotLeftTriangleEqual;": "\u22ec", "NotLess;": "\u226e", "NotLessEqual;": "\u2270", "NotLessGreater;": "\u2278", "NotLessLess;": "\u226a\u0338", "NotLessSlantEqual;": "\u2a7d\u0338", "NotLessTilde;": "\u2274", "NotNestedGreaterGreater;": "\u2aa2\u0338", "NotNestedLessLess;": "\u2aa1\u0338", "NotPrecedes;": "\u2280", "NotPrecedesEqual;": "\u2aaf\u0338", "NotPrecedesSlantEqual;": "\u22e0", "NotReverseElement;": "\u220c", "NotRightTriangle;": "\u22eb", "NotRightTriangleBar;": "\u29d0\u0338", "NotRightTriangleEqual;": "\u22ed", "NotSquareSubset;": "\u228f\u0338", "NotSquareSubsetEqual;": "\u22e2", "NotSquareSuperset;": "\u2290\u0338", "NotSquareSupersetEqual;": "\u22e3", "NotSubset;": "\u2282\u20d2", "NotSubsetEqual;": "\u2288", "NotSucceeds;": "\u2281", "NotSucceedsEqual;": "\u2ab0\u0338", "NotSucceedsSlantEqual;": "\u22e1", "NotSucceedsTilde;": "\u227f\u0338", "NotSuperset;": "\u2283\u20d2", "NotSupersetEqual;": "\u2289", "NotTilde;": "\u2241", "NotTildeEqual;": "\u2244", "NotTildeFullEqual;": "\u2247", "NotTildeTilde;": "\u2249", "NotVerticalBar;": "\u2224", "Nscr;": "\U0001d4a9", "Ntilde": "\xd1", "Ntilde;": "\xd1", "Nu;": "\u039d", "OElig;": "\u0152", "Oacute": "\xd3", "Oacute;": "\xd3", "Ocirc": "\xd4", "Ocirc;": "\xd4", "Ocy;": "\u041e", "Odblac;": "\u0150", "Ofr;": "\U0001d512", "Ograve": "\xd2", "Ograve;": "\xd2", "Omacr;": "\u014c", "Omega;": "\u03a9", "Omicron;": "\u039f", "Oopf;": "\U0001d546", "OpenCurlyDoubleQuote;": "\u201c", "OpenCurlyQuote;": "\u2018", "Or;": "\u2a54", "Oscr;": "\U0001d4aa", "Oslash": "\xd8", "Oslash;": "\xd8", "Otilde": "\xd5", "Otilde;": "\xd5", "Otimes;": "\u2a37", "Ouml": "\xd6", "Ouml;": "\xd6", "OverBar;": "\u203e", "OverBrace;": "\u23de", "OverBracket;": "\u23b4", "OverParenthesis;": "\u23dc", "PartialD;": "\u2202", "Pcy;": "\u041f", "Pfr;": "\U0001d513", "Phi;": "\u03a6", "Pi;": "\u03a0", "PlusMinus;": "\xb1", "Poincareplane;": "\u210c", "Popf;": "\u2119", "Pr;": "\u2abb", "Precedes;": "\u227a", "PrecedesEqual;": "\u2aaf", "PrecedesSlantEqual;": "\u227c", "PrecedesTilde;": "\u227e", "Prime;": "\u2033", "Product;": "\u220f", "Proportion;": "\u2237", "Proportional;": "\u221d", "Pscr;": "\U0001d4ab", "Psi;": "\u03a8", "QUOT": "\"", "QUOT;": "\"", "Qfr;": "\U0001d514", "Qopf;": "\u211a", "Qscr;": "\U0001d4ac", "RBarr;": "\u2910", "REG": "\xae", "REG;": "\xae", "Racute;": "\u0154", "Rang;": "\u27eb", "Rarr;": "\u21a0", "Rarrtl;": "\u2916", "Rcaron;": "\u0158", "Rcedil;": "\u0156", "Rcy;": "\u0420", "Re;": "\u211c", "ReverseElement;": "\u220b", "ReverseEquilibrium;": "\u21cb", "ReverseUpEquilibrium;": "\u296f", "Rfr;": "\u211c", "Rho;": "\u03a1", "RightAngleBracket;": "\u27e9", "RightArrow;": "\u2192", "RightArrowBar;": "\u21e5", "RightArrowLeftArrow;": "\u21c4", "RightCeiling;": "\u2309", "RightDoubleBracket;": "\u27e7", "RightDownTeeVector;": "\u295d", "RightDownVector;": "\u21c2", "RightDownVectorBar;": "\u2955", "RightFloor;": "\u230b", "RightTee;": "\u22a2", "RightTeeArrow;": "\u21a6", "RightTeeVector;": "\u295b", "RightTriangle;": "\u22b3", "RightTriangleBar;": "\u29d0", "RightTriangleEqual;": "\u22b5", "RightUpDownVector;": "\u294f", "RightUpTeeVector;": "\u295c", "RightUpVector;": "\u21be", "RightUpVectorBar;": "\u2954", "RightVector;": "\u21c0", "RightVectorBar;": "\u2953", "Rightarrow;": "\u21d2", "Ropf;": "\u211d", "RoundImplies;": "\u2970", "Rrightarrow;": "\u21db", "Rscr;": "\u211b", "Rsh;": "\u21b1", "RuleDelayed;": "\u29f4", "SHCHcy;": "\u0429", "SHcy;": "\u0428", "SOFTcy;": "\u042c", "Sacute;": "\u015a", "Sc;": "\u2abc", "Scaron;": "\u0160", "Scedil;": "\u015e", "Scirc;": "\u015c", "Scy;": "\u0421", "Sfr;": "\U0001d516", "ShortDownArrow;": "\u2193", "ShortLeftArrow;": "\u2190", "ShortRightArrow;": "\u2192", "ShortUpArrow;": "\u2191", "Sigma;": "\u03a3", "SmallCircle;": "\u2218", "Sopf;": "\U0001d54a", "Sqrt;": "\u221a", "Square;": "\u25a1", "SquareIntersection;": "\u2293", "SquareSubset;": "\u228f", "SquareSubsetEqual;": "\u2291", "SquareSuperset;": "\u2290", "SquareSupersetEqual;": "\u2292", "SquareUnion;": "\u2294", "Sscr;": "\U0001d4ae", "Star;": "\u22c6", "Sub;": "\u22d0", "Subset;": "\u22d0", "SubsetEqual;": "\u2286", "Succeeds;": "\u227b", "SucceedsEqual;": "\u2ab0", "SucceedsSlantEqual;": "\u227d", "SucceedsTilde;": "\u227f", "SuchThat;": "\u220b", "Sum;": "\u2211", "Sup;": "\u22d1", "Superset;": "\u2283", "SupersetEqual;": "\u2287", "Supset;": "\u22d1", "THORN": "\xde", "THORN;": "\xde", "TRADE;": "\u2122", "TSHcy;": "\u040b", "TScy;": "\u0426", "Tab;": "\t", "Tau;": "\u03a4", "Tcaron;": "\u0164", "Tcedil;": "\u0162", "Tcy;": "\u0422", "Tfr;": "\U0001d517", "Therefore;": "\u2234", "Theta;": "\u0398", "ThickSpace;": "\u205f\u200a", "ThinSpace;": "\u2009", "Tilde;": "\u223c", "TildeEqual;": "\u2243", "TildeFullEqual;": "\u2245", "TildeTilde;": "\u2248", "Topf;": "\U0001d54b", "TripleDot;": "\u20db", "Tscr;": "\U0001d4af", "Tstrok;": "\u0166", "Uacute": "\xda", "Uacute;": "\xda", "Uarr;": "\u219f", "Uarrocir;": "\u2949", "Ubrcy;": "\u040e", "Ubreve;": "\u016c", "Ucirc": "\xdb", "Ucirc;": "\xdb", "Ucy;": "\u0423", "Udblac;": "\u0170", "Ufr;": "\U0001d518", "Ugrave": "\xd9", "Ugrave;": "\xd9", "Umacr;": "\u016a", "UnderBar;": "_", "UnderBrace;": "\u23df", "UnderBracket;": "\u23b5", "UnderParenthesis;": "\u23dd", "Union;": "\u22c3", "UnionPlus;": "\u228e", "Uogon;": "\u0172", "Uopf;": "\U0001d54c", "UpArrow;": "\u2191", "UpArrowBar;": "\u2912", "UpArrowDownArrow;": "\u21c5", "UpDownArrow;": "\u2195", "UpEquilibrium;": "\u296e", "UpTee;": "\u22a5", "UpTeeArrow;": "\u21a5", "Uparrow;": "\u21d1", "Updownarrow;": "\u21d5", "UpperLeftArrow;": "\u2196", "UpperRightArrow;": "\u2197", "Upsi;": "\u03d2", "Upsilon;": "\u03a5", "Uring;": "\u016e", "Uscr;": "\U0001d4b0", "Utilde;": "\u0168", "Uuml": "\xdc", "Uuml;": "\xdc", "VDash;": "\u22ab", "Vbar;": "\u2aeb", "Vcy;": "\u0412", "Vdash;": "\u22a9", "Vdashl;": "\u2ae6", "Vee;": "\u22c1", "Verbar;": "\u2016", "Vert;": "\u2016", "VerticalBar;": "\u2223", "VerticalLine;": "|", "VerticalSeparator;": "\u2758", "VerticalTilde;": "\u2240", "VeryThinSpace;": "\u200a", "Vfr;": "\U0001d519", "Vopf;": "\U0001d54d", "Vscr;": "\U0001d4b1", "Vvdash;": "\u22aa", "Wcirc;": "\u0174", "Wedge;": "\u22c0", "Wfr;": "\U0001d51a", "Wopf;": "\U0001d54e", "Wscr;": "\U0001d4b2", "Xfr;": "\U0001d51b", "Xi;": "\u039e", "Xopf;": "\U0001d54f", "Xscr;": "\U0001d4b3", "YAcy;": "\u042f", "YIcy;": "\u0407", "YUcy;": "\u042e", "Yacute": "\xdd", "Yacute;": "\xdd", "Ycirc;": "\u0176", "Ycy;": "\u042b", "Yfr;": "\U0001d51c", "Yopf;": "\U0001d550", "Yscr;": "\U0001d4b4", "Yuml;": "\u0178", "ZHcy;": "\u0416", "Zacute;": "\u0179", "Zcaron;": "\u017d", "Zcy;": "\u0417", "Zdot;": "\u017b", "ZeroWidthSpace;": "\u200b", "Zeta;": "\u0396", "Zfr;": "\u2128", "Zopf;": "\u2124", "Zscr;": "\U0001d4b5", "aacute": "\xe1", "aacute;": "\xe1", "abreve;": "\u0103", "ac;": "\u223e", "acE;": "\u223e\u0333", "acd;": "\u223f", "acirc": "\xe2", "acirc;": "\xe2", "acute": "\xb4", "acute;": "\xb4", "acy;": "\u0430", "aelig": "\xe6", "aelig;": "\xe6", "af;": "\u2061", "afr;": "\U0001d51e", "agrave": "\xe0", "agrave;": "\xe0", "alefsym;": "\u2135", "aleph;": "\u2135", "alpha;": "\u03b1", "amacr;": "\u0101", "amalg;": "\u2a3f", "amp": "&", "amp;": "&", "and;": "\u2227", "andand;": "\u2a55", "andd;": "\u2a5c", "andslope;": "\u2a58", "andv;": "\u2a5a", "ang;": "\u2220", "ange;": "\u29a4", "angle;": "\u2220", "angmsd;": "\u2221", "angmsdaa;": "\u29a8", "angmsdab;": "\u29a9", "angmsdac;": "\u29aa", "angmsdad;": "\u29ab", "angmsdae;": "\u29ac", "angmsdaf;": "\u29ad", "angmsdag;": "\u29ae", "angmsdah;": "\u29af", "angrt;": "\u221f", "angrtvb;": "\u22be", "angrtvbd;": "\u299d", "angsph;": "\u2222", "angst;": "\xc5", "angzarr;": "\u237c", "aogon;": "\u0105", "aopf;": "\U0001d552", "ap;": "\u2248", "apE;": "\u2a70", "apacir;": "\u2a6f", "ape;": "\u224a", "apid;": "\u224b", "apos;": "'", "approx;": "\u2248", "approxeq;": "\u224a", "aring": "\xe5", "aring;": "\xe5", "ascr;": "\U0001d4b6", "ast;": "*", "asymp;": "\u2248", "asympeq;": "\u224d", "atilde": "\xe3", "atilde;": "\xe3", "auml": "\xe4", "auml;": "\xe4", "awconint;": "\u2233", "awint;": "\u2a11", "bNot;": "\u2aed", "backcong;": "\u224c", "backepsilon;": "\u03f6", "backprime;": "\u2035", "backsim;": "\u223d", "backsimeq;": "\u22cd", "barvee;": "\u22bd", "barwed;": "\u2305", "barwedge;": "\u2305", "bbrk;": "\u23b5", "bbrktbrk;": "\u23b6", "bcong;": "\u224c", "bcy;": "\u0431", "bdquo;": "\u201e", "becaus;": "\u2235", "because;": "\u2235", "bemptyv;": "\u29b0", "bepsi;": "\u03f6", "bernou;": "\u212c", "beta;": "\u03b2", "beth;": "\u2136", "between;": "\u226c", "bfr;": "\U0001d51f", "bigcap;": "\u22c2", "bigcirc;": "\u25ef", "bigcup;": "\u22c3", "bigodot;": "\u2a00", "bigoplus;": "\u2a01", "bigotimes;": "\u2a02", "bigsqcup;": "\u2a06", "bigstar;": "\u2605", "bigtriangledown;": "\u25bd", "bigtriangleup;": "\u25b3", "biguplus;": "\u2a04", "bigvee;": "\u22c1", "bigwedge;": "\u22c0", "bkarow;": "\u290d", "blacklozenge;": "\u29eb", "blacksquare;": "\u25aa", "blacktriangle;": "\u25b4", "blacktriangledown;": "\u25be", "blacktriangleleft;": "\u25c2", "blacktriangleright;": "\u25b8", "blank;": "\u2423", "blk12;": "\u2592", "blk14;": "\u2591", "blk34;": "\u2593", "block;": "\u2588", "bne;": "=\u20e5", "bnequiv;": "\u2261\u20e5", "bnot;": "\u2310", "bopf;": "\U0001d553", "bot;": "\u22a5", "bottom;": "\u22a5", "bowtie;": "\u22c8", "boxDL;": "\u2557", "boxDR;": "\u2554", "boxDl;": "\u2556", "boxDr;": "\u2553", "boxH;": "\u2550", "boxHD;": "\u2566", "boxHU;": "\u2569", "boxHd;": "\u2564", "boxHu;": "\u2567", "boxUL;": "\u255d", "boxUR;": "\u255a", "boxUl;": "\u255c", "boxUr;": "\u2559", "boxV;": "\u2551", "boxVH;": "\u256c", "boxVL;": "\u2563", "boxVR;": "\u2560", "boxVh;": "\u256b", "boxVl;": "\u2562", "boxVr;": "\u255f", "boxbox;": "\u29c9", "boxdL;": "\u2555", "boxdR;": "\u2552", "boxdl;": "\u2510", "boxdr;": "\u250c", "boxh;": "\u2500", "boxhD;": "\u2565", "boxhU;": "\u2568", "boxhd;": "\u252c", "boxhu;": "\u2534", "boxminus;": "\u229f", "boxplus;": "\u229e", "boxtimes;": "\u22a0", "boxuL;": "\u255b", "boxuR;": "\u2558", "boxul;": "\u2518", "boxur;": "\u2514", "boxv;": "\u2502", "boxvH;": "\u256a", "boxvL;": "\u2561", "boxvR;": "\u255e", "boxvh;": "\u253c", "boxvl;": "\u2524", "boxvr;": "\u251c", "bprime;": "\u2035", "breve;": "\u02d8", "brvbar": "\xa6", "brvbar;": "\xa6", "bscr;": "\U0001d4b7", "bsemi;": "\u204f", "bsim;": "\u223d", "bsime;": "\u22cd", "bsol;": "\\", "bsolb;": "\u29c5", "bsolhsub;": "\u27c8", "bull;": "\u2022", "bullet;": "\u2022", "bump;": "\u224e", "bumpE;": "\u2aae", "bumpe;": "\u224f", "bumpeq;": "\u224f", "cacute;": "\u0107", "cap;": "\u2229", "capand;": "\u2a44", "capbrcup;": "\u2a49", "capcap;": "\u2a4b", "capcup;": "\u2a47", "capdot;": "\u2a40", "caps;": "\u2229\ufe00", "caret;": "\u2041", "caron;": "\u02c7", "ccaps;": "\u2a4d", "ccaron;": "\u010d", "ccedil": "\xe7", "ccedil;": "\xe7", "ccirc;": "\u0109", "ccups;": "\u2a4c", "ccupssm;": "\u2a50", "cdot;": "\u010b", "cedil": "\xb8", "cedil;": "\xb8", "cemptyv;": "\u29b2", "cent": "\xa2", "cent;": "\xa2", "centerdot;": "\xb7", "cfr;": "\U0001d520", "chcy;": "\u0447", "check;": "\u2713", "checkmark;": "\u2713", "chi;": "\u03c7", "cir;": "\u25cb", "cirE;": "\u29c3", "circ;": "\u02c6", "circeq;": "\u2257", "circlearrowleft;": "\u21ba", "circlearrowright;": "\u21bb", "circledR;": "\xae", "circledS;": "\u24c8", "circledast;": "\u229b", "circledcirc;": "\u229a", "circleddash;": "\u229d", "cire;": "\u2257", "cirfnint;": "\u2a10", "cirmid;": "\u2aef", "cirscir;": "\u29c2", "clubs;": "\u2663", "clubsuit;": "\u2663", "colon;": ":", "colone;": "\u2254", "coloneq;": "\u2254", "comma;": ",", "commat;": "@", "comp;": "\u2201", "compfn;": "\u2218", "complement;": "\u2201", "complexes;": "\u2102", "cong;": "\u2245", "congdot;": "\u2a6d", "conint;": "\u222e", "copf;": "\U0001d554", "coprod;": "\u2210", "copy": "\xa9", "copy;": "\xa9", "copysr;": "\u2117", "crarr;": "\u21b5", "cross;": "\u2717", "cscr;": "\U0001d4b8", "csub;": "\u2acf", "csube;": "\u2ad1", "csup;": "\u2ad0", "csupe;": "\u2ad2", "ctdot;": "\u22ef", "cudarrl;": "\u2938", "cudarrr;": "\u2935", "cuepr;": "\u22de", "cuesc;": "\u22df", "cularr;": "\u21b6", "cularrp;": "\u293d", "cup;": "\u222a", "cupbrcap;": "\u2a48", "cupcap;": "\u2a46", "cupcup;": "\u2a4a", "cupdot;": "\u228d", "cupor;": "\u2a45", "cups;": "\u222a\ufe00", "curarr;": "\u21b7", "curarrm;": "\u293c", "curlyeqprec;": "\u22de", "curlyeqsucc;": "\u22df", "curlyvee;": "\u22ce", "curlywedge;": "\u22cf", "curren": "\xa4", "curren;": "\xa4", "curvearrowleft;": "\u21b6", "curvearrowright;": "\u21b7", "cuvee;": "\u22ce", "cuwed;": "\u22cf", "cwconint;": "\u2232", "cwint;": "\u2231", "cylcty;": "\u232d", "dArr;": "\u21d3", "dHar;": "\u2965", "dagger;": "\u2020", "daleth;": "\u2138", "darr;": "\u2193", "dash;": "\u2010", "dashv;": "\u22a3", "dbkarow;": "\u290f", "dblac;": "\u02dd", "dcaron;": "\u010f", "dcy;": "\u0434", "dd;": "\u2146", "ddagger;": "\u2021", "ddarr;": "\u21ca", "ddotseq;": "\u2a77", "deg": "\xb0", "deg;": "\xb0", "delta;": "\u03b4", "demptyv;": "\u29b1", "dfisht;": "\u297f", "dfr;": "\U0001d521", "dharl;": "\u21c3", "dharr;": "\u21c2", "diam;": "\u22c4", "diamond;": "\u22c4", "diamondsuit;": "\u2666", "diams;": "\u2666", "die;": "\xa8", "digamma;": "\u03dd", "disin;": "\u22f2", "div;": "\xf7", "divide": "\xf7", "divide;": "\xf7", "divideontimes;": "\u22c7", "divonx;": "\u22c7", "djcy;": "\u0452", "dlcorn;": "\u231e", "dlcrop;": "\u230d", "dollar;": "$", "dopf;": "\U0001d555", "dot;": "\u02d9", "doteq;": "\u2250", "doteqdot;": "\u2251", "dotminus;": "\u2238", "dotplus;": "\u2214", "dotsquare;": "\u22a1", "doublebarwedge;": "\u2306", "downarrow;": "\u2193", "downdownarrows;": "\u21ca", "downharpoonleft;": "\u21c3", "downharpoonright;": "\u21c2", "drbkarow;": "\u2910", "drcorn;": "\u231f", "drcrop;": "\u230c", "dscr;": "\U0001d4b9", "dscy;": "\u0455", "dsol;": "\u29f6", "dstrok;": "\u0111", "dtdot;": "\u22f1", "dtri;": "\u25bf", "dtrif;": "\u25be", "duarr;": "\u21f5", "duhar;": "\u296f", "dwangle;": "\u29a6", "dzcy;": "\u045f", "dzigrarr;": "\u27ff", "eDDot;": "\u2a77", "eDot;": "\u2251", "eacute": "\xe9", "eacute;": "\xe9", "easter;": "\u2a6e", "ecaron;": "\u011b", "ecir;": "\u2256", "ecirc": "\xea", "ecirc;": "\xea", "ecolon;": "\u2255", "ecy;": "\u044d", "edot;": "\u0117", "ee;": "\u2147", "efDot;": "\u2252", "efr;": "\U0001d522", "eg;": "\u2a9a", "egrave": "\xe8", "egrave;": "\xe8", "egs;": "\u2a96", "egsdot;": "\u2a98", "el;": "\u2a99", "elinters;": "\u23e7", "ell;": "\u2113", "els;": "\u2a95", "elsdot;": "\u2a97", "emacr;": "\u0113", "empty;": "\u2205", "emptyset;": "\u2205", "emptyv;": "\u2205", "emsp13;": "\u2004", "emsp14;": "\u2005", "emsp;": "\u2003", "eng;": "\u014b", "ensp;": "\u2002", "eogon;": "\u0119", "eopf;": "\U0001d556", "epar;": "\u22d5", "eparsl;": "\u29e3", "eplus;": "\u2a71", "epsi;": "\u03b5", "epsilon;": "\u03b5", "epsiv;": "\u03f5", "eqcirc;": "\u2256", "eqcolon;": "\u2255", "eqsim;": "\u2242", "eqslantgtr;": "\u2a96", "eqslantless;": "\u2a95", "equals;": "=", "equest;": "\u225f", "equiv;": "\u2261", "equivDD;": "\u2a78", "eqvparsl;": "\u29e5", "erDot;": "\u2253", "erarr;": "\u2971", "escr;": "\u212f", "esdot;": "\u2250", "esim;": "\u2242", "eta;": "\u03b7", "eth": "\xf0", "eth;": "\xf0", "euml": "\xeb", "euml;": "\xeb", "euro;": "\u20ac", "excl;": "!", "exist;": "\u2203", "expectation;": "\u2130", "exponentiale;": "\u2147", "fallingdotseq;": "\u2252", "fcy;": "\u0444", "female;": "\u2640", "ffilig;": "\ufb03", "fflig;": "\ufb00", "ffllig;": "\ufb04", "ffr;": "\U0001d523", "filig;": "\ufb01", "fjlig;": "fj", "flat;": "\u266d", "fllig;": "\ufb02", "fltns;": "\u25b1", "fnof;": "\u0192", "fopf;": "\U0001d557", "forall;": "\u2200", "fork;": "\u22d4", "forkv;": "\u2ad9", "fpartint;": "\u2a0d", "frac12": "\xbd", "frac12;": "\xbd", "frac13;": "\u2153", "frac14": "\xbc", "frac14;": "\xbc", "frac15;": "\u2155", "frac16;": "\u2159", "frac18;": "\u215b", "frac23;": "\u2154", "frac25;": "\u2156", "frac34": "\xbe", "frac34;": "\xbe", "frac35;": "\u2157", "frac38;": "\u215c", "frac45;": "\u2158", "frac56;": "\u215a", "frac58;": "\u215d", "frac78;": "\u215e", "frasl;": "\u2044", "frown;": "\u2322", "fscr;": "\U0001d4bb", "gE;": "\u2267", "gEl;": "\u2a8c", "gacute;": "\u01f5", "gamma;": "\u03b3", "gammad;": "\u03dd", "gap;": "\u2a86", "gbreve;": "\u011f", "gcirc;": "\u011d", "gcy;": "\u0433", "gdot;": "\u0121", "ge;": "\u2265", "gel;": "\u22db", "geq;": "\u2265", "geqq;": "\u2267", "geqslant;": "\u2a7e", "ges;": "\u2a7e", "gescc;": "\u2aa9", "gesdot;": "\u2a80", "gesdoto;": "\u2a82", "gesdotol;": "\u2a84", "gesl;": "\u22db\ufe00", "gesles;": "\u2a94", "gfr;": "\U0001d524", "gg;": "\u226b", "ggg;": "\u22d9", "gimel;": "\u2137", "gjcy;": "\u0453", "gl;": "\u2277", "glE;": "\u2a92", "gla;": "\u2aa5", "glj;": "\u2aa4", "gnE;": "\u2269", "gnap;": "\u2a8a", "gnapprox;": "\u2a8a", "gne;": "\u2a88", "gneq;": "\u2a88", "gneqq;": "\u2269", "gnsim;": "\u22e7", "gopf;": "\U0001d558", "grave;": "`", "gscr;": "\u210a", "gsim;": "\u2273", "gsime;": "\u2a8e", "gsiml;": "\u2a90", "gt": ">", "gt;": ">", "gtcc;": "\u2aa7", "gtcir;": "\u2a7a", "gtdot;": "\u22d7", "gtlPar;": "\u2995", "gtquest;": "\u2a7c", "gtrapprox;": "\u2a86", "gtrarr;": "\u2978", "gtrdot;": "\u22d7", "gtreqless;": "\u22db", "gtreqqless;": "\u2a8c", "gtrless;": "\u2277", "gtrsim;": "\u2273", "gvertneqq;": "\u2269\ufe00", "gvnE;": "\u2269\ufe00", "hArr;": "\u21d4", "hairsp;": "\u200a", "half;": "\xbd", "hamilt;": "\u210b", "hardcy;": "\u044a", "harr;": "\u2194", "harrcir;": "\u2948", "harrw;": "\u21ad", "hbar;": "\u210f", "hcirc;": "\u0125", "hearts;": "\u2665", "heartsuit;": "\u2665", "hellip;": "\u2026", "hercon;": "\u22b9", "hfr;": "\U0001d525", "hksearow;": "\u2925", "hkswarow;": "\u2926", "hoarr;": "\u21ff", "homtht;": "\u223b", "hookleftarrow;": "\u21a9", "hookrightarrow;": "\u21aa", "hopf;": "\U0001d559", "horbar;": "\u2015", "hscr;": "\U0001d4bd", "hslash;": "\u210f", "hstrok;": "\u0127", "hybull;": "\u2043", "hyphen;": "\u2010", "iacute": "\xed", "iacute;": "\xed", "ic;": "\u2063", "icirc": "\xee", "icirc;": "\xee", "icy;": "\u0438", "iecy;": "\u0435", "iexcl": "\xa1", "iexcl;": "\xa1", "iff;": "\u21d4", "ifr;": "\U0001d526", "igrave": "\xec", "igrave;": "\xec", "ii;": "\u2148", "iiiint;": "\u2a0c", "iiint;": "\u222d", "iinfin;": "\u29dc", "iiota;": "\u2129", "ijlig;": "\u0133", "imacr;": "\u012b", "image;": "\u2111", "imagline;": "\u2110", "imagpart;": "\u2111", "imath;": "\u0131", "imof;": "\u22b7", "imped;": "\u01b5", "in;": "\u2208", "incare;": "\u2105", "infin;": "\u221e", "infintie;": "\u29dd", "inodot;": "\u0131", "int;": "\u222b", "intcal;": "\u22ba", "integers;": "\u2124", "intercal;": "\u22ba", "intlarhk;": "\u2a17", "intprod;": "\u2a3c", "iocy;": "\u0451", "iogon;": "\u012f", "iopf;": "\U0001d55a", "iota;": "\u03b9", "iprod;": "\u2a3c", "iquest": "\xbf", "iquest;": "\xbf", "iscr;": "\U0001d4be", "isin;": "\u2208", "isinE;": "\u22f9", "isindot;": "\u22f5", "isins;": "\u22f4", "isinsv;": "\u22f3", "isinv;": "\u2208", "it;": "\u2062", "itilde;": "\u0129", "iukcy;": "\u0456", "iuml": "\xef", "iuml;": "\xef", "jcirc;": "\u0135", "jcy;": "\u0439", "jfr;": "\U0001d527", "jmath;": "\u0237", "jopf;": "\U0001d55b", "jscr;": "\U0001d4bf", "jsercy;": "\u0458", "jukcy;": "\u0454", "kappa;": "\u03ba", "kappav;": "\u03f0", "kcedil;": "\u0137", "kcy;": "\u043a", "kfr;": "\U0001d528", "kgreen;": "\u0138", "khcy;": "\u0445", "kjcy;": "\u045c", "kopf;": "\U0001d55c", "kscr;": "\U0001d4c0", "lAarr;": "\u21da", "lArr;": "\u21d0", "lAtail;": "\u291b", "lBarr;": "\u290e", "lE;": "\u2266", "lEg;": "\u2a8b", "lHar;": "\u2962", "lacute;": "\u013a", "laemptyv;": "\u29b4", "lagran;": "\u2112", "lambda;": "\u03bb", "lang;": "\u27e8", "langd;": "\u2991", "langle;": "\u27e8", "lap;": "\u2a85", "laquo": "\xab", "laquo;": "\xab", "larr;": "\u2190", "larrb;": "\u21e4", "larrbfs;": "\u291f", "larrfs;": "\u291d", "larrhk;": "\u21a9", "larrlp;": "\u21ab", "larrpl;": "\u2939", "larrsim;": "\u2973", "larrtl;": "\u21a2", "lat;": "\u2aab", "latail;": "\u2919", "late;": "\u2aad", "lates;": "\u2aad\ufe00", "lbarr;": "\u290c", "lbbrk;": "\u2772", "lbrace;": "{", "lbrack;": "[", "lbrke;": "\u298b", "lbrksld;": "\u298f", "lbrkslu;": "\u298d", "lcaron;": "\u013e", "lcedil;": "\u013c", "lceil;": "\u2308", "lcub;": "{", "lcy;": "\u043b", "ldca;": "\u2936", "ldquo;": "\u201c", "ldquor;": "\u201e", "ldrdhar;": "\u2967", "ldrushar;": "\u294b", "ldsh;": "\u21b2", "le;": "\u2264", "leftarrow;": "\u2190", "leftarrowtail;": "\u21a2", "leftharpoondown;": "\u21bd", "leftharpoonup;": "\u21bc", "leftleftarrows;": "\u21c7", "leftrightarrow;": "\u2194", "leftrightarrows;": "\u21c6", "leftrightharpoons;": "\u21cb", "leftrightsquigarrow;": "\u21ad", "leftthreetimes;": "\u22cb", "leg;": "\u22da", "leq;": "\u2264", "leqq;": "\u2266", "leqslant;": "\u2a7d", "les;": "\u2a7d", "lescc;": "\u2aa8", "lesdot;": "\u2a7f", "lesdoto;": "\u2a81", "lesdotor;": "\u2a83", "lesg;": "\u22da\ufe00", "lesges;": "\u2a93", "lessapprox;": "\u2a85", "lessdot;": "\u22d6", "lesseqgtr;": "\u22da", "lesseqqgtr;": "\u2a8b", "lessgtr;": "\u2276", "lesssim;": "\u2272", "lfisht;": "\u297c", "lfloor;": "\u230a", "lfr;": "\U0001d529", "lg;": "\u2276", "lgE;": "\u2a91", "lhard;": "\u21bd", "lharu;": "\u21bc", "lharul;": "\u296a", "lhblk;": "\u2584", "ljcy;": "\u0459", "ll;": "\u226a", "llarr;": "\u21c7", "llcorner;": "\u231e", "llhard;": "\u296b", "lltri;": "\u25fa", "lmidot;": "\u0140", "lmoust;": "\u23b0", "lmoustache;": "\u23b0", "lnE;": "\u2268", "lnap;": "\u2a89", "lnapprox;": "\u2a89", "lne;": "\u2a87", "lneq;": "\u2a87", "lneqq;": "\u2268", "lnsim;": "\u22e6", "loang;": "\u27ec", "loarr;": "\u21fd", "lobrk;": "\u27e6", "longleftarrow;": "\u27f5", "longleftrightarrow;": "\u27f7", "longmapsto;": "\u27fc", "longrightarrow;": "\u27f6", "looparrowleft;": "\u21ab", "looparrowright;": "\u21ac", "lopar;": "\u2985", "lopf;": "\U0001d55d", "loplus;": "\u2a2d", "lotimes;": "\u2a34", "lowast;": "\u2217", "lowbar;": "_", "loz;": "\u25ca", "lozenge;": "\u25ca", "lozf;": "\u29eb", "lpar;": "(", "lparlt;": "\u2993", "lrarr;": "\u21c6", "lrcorner;": "\u231f", "lrhar;": "\u21cb", "lrhard;": "\u296d", "lrm;": "\u200e", "lrtri;": "\u22bf", "lsaquo;": "\u2039", "lscr;": "\U0001d4c1", "lsh;": "\u21b0", "lsim;": "\u2272", "lsime;": "\u2a8d", "lsimg;": "\u2a8f", "lsqb;": "[", "lsquo;": "\u2018", "lsquor;": "\u201a", "lstrok;": "\u0142", "lt": "<", "lt;": "<", "ltcc;": "\u2aa6", "ltcir;": "\u2a79", "ltdot;": "\u22d6", "lthree;": "\u22cb", "ltimes;": "\u22c9", "ltlarr;": "\u2976", "ltquest;": "\u2a7b", "ltrPar;": "\u2996", "ltri;": "\u25c3", "ltrie;": "\u22b4", "ltrif;": "\u25c2", "lurdshar;": "\u294a", "luruhar;": "\u2966", "lvertneqq;": "\u2268\ufe00", "lvnE;": "\u2268\ufe00", "mDDot;": "\u223a", "macr": "\xaf", "macr;": "\xaf", "male;": "\u2642", "malt;": "\u2720", "maltese;": "\u2720", "map;": "\u21a6", "mapsto;": "\u21a6", "mapstodown;": "\u21a7", "mapstoleft;": "\u21a4", "mapstoup;": "\u21a5", "marker;": "\u25ae", "mcomma;": "\u2a29", "mcy;": "\u043c", "mdash;": "\u2014", "measuredangle;": "\u2221", "mfr;": "\U0001d52a", "mho;": "\u2127", "micro": "\xb5", "micro;": "\xb5", "mid;": "\u2223", "midast;": "*", "midcir;": "\u2af0", "middot": "\xb7", "middot;": "\xb7", "minus;": "\u2212", "minusb;": "\u229f", "minusd;": "\u2238", "minusdu;": "\u2a2a", "mlcp;": "\u2adb", "mldr;": "\u2026", "mnplus;": "\u2213", "models;": "\u22a7", "mopf;": "\U0001d55e", "mp;": "\u2213", "mscr;": "\U0001d4c2", "mstpos;": "\u223e", "mu;": "\u03bc", "multimap;": "\u22b8", "mumap;": "\u22b8", "nGg;": "\u22d9\u0338", "nGt;": "\u226b\u20d2", "nGtv;": "\u226b\u0338", "nLeftarrow;": "\u21cd", "nLeftrightarrow;": "\u21ce", "nLl;": "\u22d8\u0338", "nLt;": "\u226a\u20d2", "nLtv;": "\u226a\u0338", "nRightarrow;": "\u21cf", "nVDash;": "\u22af", "nVdash;": "\u22ae", "nabla;": "\u2207", "nacute;": "\u0144", "nang;": "\u2220\u20d2", "nap;": "\u2249", "napE;": "\u2a70\u0338", "napid;": "\u224b\u0338", "napos;": "\u0149", "napprox;": "\u2249", "natur;": "\u266e", "natural;": "\u266e", "naturals;": "\u2115", "nbsp": "\xa0", "nbsp;": "\xa0", "nbump;": "\u224e\u0338", "nbumpe;": "\u224f\u0338", "ncap;": "\u2a43", "ncaron;": "\u0148", "ncedil;": "\u0146", "ncong;": "\u2247", "ncongdot;": "\u2a6d\u0338", "ncup;": "\u2a42", "ncy;": "\u043d", "ndash;": "\u2013", "ne;": "\u2260", "neArr;": "\u21d7", "nearhk;": "\u2924", "nearr;": "\u2197", "nearrow;": "\u2197", "nedot;": "\u2250\u0338", "nequiv;": "\u2262", "nesear;": "\u2928", "nesim;": "\u2242\u0338", "nexist;": "\u2204", "nexists;": "\u2204", "nfr;": "\U0001d52b", "ngE;": "\u2267\u0338", "nge;": "\u2271", "ngeq;": "\u2271", "ngeqq;": "\u2267\u0338", "ngeqslant;": "\u2a7e\u0338", "nges;": "\u2a7e\u0338", "ngsim;": "\u2275", "ngt;": "\u226f", "ngtr;": "\u226f", "nhArr;": "\u21ce", "nharr;": "\u21ae", "nhpar;": "\u2af2", "ni;": "\u220b", "nis;": "\u22fc", "nisd;": "\u22fa", "niv;": "\u220b", "njcy;": "\u045a", "nlArr;": "\u21cd", "nlE;": "\u2266\u0338", "nlarr;": "\u219a", "nldr;": "\u2025", "nle;": "\u2270", "nleftarrow;": "\u219a", "nleftrightarrow;": "\u21ae", "nleq;": "\u2270", "nleqq;": "\u2266\u0338", "nleqslant;": "\u2a7d\u0338", "nles;": "\u2a7d\u0338", "nless;": "\u226e", "nlsim;": "\u2274", "nlt;": "\u226e", "nltri;": "\u22ea", "nltrie;": "\u22ec", "nmid;": "\u2224", "nopf;": "\U0001d55f", "not": "\xac", "not;": "\xac", "notin;": "\u2209", "notinE;": "\u22f9\u0338", "notindot;": "\u22f5\u0338", "notinva;": "\u2209", "notinvb;": "\u22f7", "notinvc;": "\u22f6", "notni;": "\u220c", "notniva;": "\u220c", "notnivb;": "\u22fe", "notnivc;": "\u22fd", "npar;": "\u2226", "nparallel;": "\u2226", "nparsl;": "\u2afd\u20e5", "npart;": "\u2202\u0338", "npolint;": "\u2a14", "npr;": "\u2280", "nprcue;": "\u22e0", "npre;": "\u2aaf\u0338", "nprec;": "\u2280", "npreceq;": "\u2aaf\u0338", "nrArr;": "\u21cf", "nrarr;": "\u219b", "nrarrc;": "\u2933\u0338", "nrarrw;": "\u219d\u0338", "nrightarrow;": "\u219b", "nrtri;": "\u22eb", "nrtrie;": "\u22ed", "nsc;": "\u2281", "nsccue;": "\u22e1", "nsce;": "\u2ab0\u0338", "nscr;": "\U0001d4c3", "nshortmid;": "\u2224", "nshortparallel;": "\u2226", "nsim;": "\u2241", "nsime;": "\u2244", "nsimeq;": "\u2244", "nsmid;": "\u2224", "nspar;": "\u2226", "nsqsube;": "\u22e2", "nsqsupe;": "\u22e3", "nsub;": "\u2284", "nsubE;": "\u2ac5\u0338", "nsube;": "\u2288", "nsubset;": "\u2282\u20d2", "nsubseteq;": "\u2288", "nsubseteqq;": "\u2ac5\u0338", "nsucc;": "\u2281", "nsucceq;": "\u2ab0\u0338", "nsup;": "\u2285", "nsupE;": "\u2ac6\u0338", "nsupe;": "\u2289", "nsupset;": "\u2283\u20d2", "nsupseteq;": "\u2289", "nsupseteqq;": "\u2ac6\u0338", "ntgl;": "\u2279", "ntilde": "\xf1", "ntilde;": "\xf1", "ntlg;": "\u2278", "ntriangleleft;": "\u22ea", "ntrianglelefteq;": "\u22ec", "ntriangleright;": "\u22eb", "ntrianglerighteq;": "\u22ed", "nu;": "\u03bd", "num;": "#", "numero;": "\u2116", "numsp;": "\u2007", "nvDash;": "\u22ad", "nvHarr;": "\u2904", "nvap;": "\u224d\u20d2", "nvdash;": "\u22ac", "nvge;": "\u2265\u20d2", "nvgt;": ">\u20d2", "nvinfin;": "\u29de", "nvlArr;": "\u2902", "nvle;": "\u2264\u20d2", "nvlt;": "<\u20d2", "nvltrie;": "\u22b4\u20d2", "nvrArr;": "\u2903", "nvrtrie;": "\u22b5\u20d2", "nvsim;": "\u223c\u20d2", "nwArr;": "\u21d6", "nwarhk;": "\u2923", "nwarr;": "\u2196", "nwarrow;": "\u2196", "nwnear;": "\u2927", "oS;": "\u24c8", "oacute": "\xf3", "oacute;": "\xf3", "oast;": "\u229b", "ocir;": "\u229a", "ocirc": "\xf4", "ocirc;": "\xf4", "ocy;": "\u043e", "odash;": "\u229d", "odblac;": "\u0151", "odiv;": "\u2a38", "odot;": "\u2299", "odsold;": "\u29bc", "oelig;": "\u0153", "ofcir;": "\u29bf", "ofr;": "\U0001d52c", "ogon;": "\u02db", "ograve": "\xf2", "ograve;": "\xf2", "ogt;": "\u29c1", "ohbar;": "\u29b5", "ohm;": "\u03a9", "oint;": "\u222e", "olarr;": "\u21ba", "olcir;": "\u29be", "olcross;": "\u29bb", "oline;": "\u203e", "olt;": "\u29c0", "omacr;": "\u014d", "omega;": "\u03c9", "omicron;": "\u03bf", "omid;": "\u29b6", "ominus;": "\u2296", "oopf;": "\U0001d560", "opar;": "\u29b7", "operp;": "\u29b9", "oplus;": "\u2295", "or;": "\u2228", "orarr;": "\u21bb", "ord;": "\u2a5d", "order;": "\u2134", "orderof;": "\u2134", "ordf": "\xaa", "ordf;": "\xaa", "ordm": "\xba", "ordm;": "\xba", "origof;": "\u22b6", "oror;": "\u2a56", "orslope;": "\u2a57", "orv;": "\u2a5b", "oscr;": "\u2134", "oslash": "\xf8", "oslash;": "\xf8", "osol;": "\u2298", "otilde": "\xf5", "otilde;": "\xf5", "otimes;": "\u2297", "otimesas;": "\u2a36", "ouml": "\xf6", "ouml;": "\xf6", "ovbar;": "\u233d", "par;": "\u2225", "para": "\xb6", "para;": "\xb6", "parallel;": "\u2225", "parsim;": "\u2af3", "parsl;": "\u2afd", "part;": "\u2202", "pcy;": "\u043f", "percnt;": "%", "period;": ".", "permil;": "\u2030", "perp;": "\u22a5", "pertenk;": "\u2031", "pfr;": "\U0001d52d", "phi;": "\u03c6", "phiv;": "\u03d5", "phmmat;": "\u2133", "phone;": "\u260e", "pi;": "\u03c0", "pitchfork;": "\u22d4", "piv;": "\u03d6", "planck;": "\u210f", "planckh;": "\u210e", "plankv;": "\u210f", "plus;": "+", "plusacir;": "\u2a23", "plusb;": "\u229e", "pluscir;": "\u2a22", "plusdo;": "\u2214", "plusdu;": "\u2a25", "pluse;": "\u2a72", "plusmn": "\xb1", "plusmn;": "\xb1", "plussim;": "\u2a26", "plustwo;": "\u2a27", "pm;": "\xb1", "pointint;": "\u2a15", "popf;": "\U0001d561", "pound": "\xa3", "pound;": "\xa3", "pr;": "\u227a", "prE;": "\u2ab3", "prap;": "\u2ab7", "prcue;": "\u227c", "pre;": "\u2aaf", "prec;": "\u227a", "precapprox;": "\u2ab7", "preccurlyeq;": "\u227c", "preceq;": "\u2aaf", "precnapprox;": "\u2ab9", "precneqq;": "\u2ab5", "precnsim;": "\u22e8", "precsim;": "\u227e", "prime;": "\u2032", "primes;": "\u2119", "prnE;": "\u2ab5", "prnap;": "\u2ab9", "prnsim;": "\u22e8", "prod;": "\u220f", "profalar;": "\u232e", "profline;": "\u2312", "profsurf;": "\u2313", "prop;": "\u221d", "propto;": "\u221d", "prsim;": "\u227e", "prurel;": "\u22b0", "pscr;": "\U0001d4c5", "psi;": "\u03c8", "puncsp;": "\u2008", "qfr;": "\U0001d52e", "qint;": "\u2a0c", "qopf;": "\U0001d562", "qprime;": "\u2057", "qscr;": "\U0001d4c6", "quaternions;": "\u210d", "quatint;": "\u2a16", "quest;": "?", "questeq;": "\u225f", "quot": "\"", "quot;": "\"", "rAarr;": "\u21db", "rArr;": "\u21d2", "rAtail;": "\u291c", "rBarr;": "\u290f", "rHar;": "\u2964", "race;": "\u223d\u0331", "racute;": "\u0155", "radic;": "\u221a", "raemptyv;": "\u29b3", "rang;": "\u27e9", "rangd;": "\u2992", "range;": "\u29a5", "rangle;": "\u27e9", "raquo": "\xbb", "raquo;": "\xbb", "rarr;": "\u2192", "rarrap;": "\u2975", "rarrb;": "\u21e5", "rarrbfs;": "\u2920", "rarrc;": "\u2933", "rarrfs;": "\u291e", "rarrhk;": "\u21aa", "rarrlp;": "\u21ac", "rarrpl;": "\u2945", "rarrsim;": "\u2974", "rarrtl;": "\u21a3", "rarrw;": "\u219d", "ratail;": "\u291a", "ratio;": "\u2236", "rationals;": "\u211a", "rbarr;": "\u290d", "rbbrk;": "\u2773", "rbrace;": "}", "rbrack;": "]", "rbrke;": "\u298c", "rbrksld;": "\u298e", "rbrkslu;": "\u2990", "rcaron;": "\u0159", "rcedil;": "\u0157", "rceil;": "\u2309", "rcub;": "}", "rcy;": "\u0440", "rdca;": "\u2937", "rdldhar;": "\u2969", "rdquo;": "\u201d", "rdquor;": "\u201d", "rdsh;": "\u21b3", "real;": "\u211c", "realine;": "\u211b", "realpart;": "\u211c", "reals;": "\u211d", "rect;": "\u25ad", "reg": "\xae", "reg;": "\xae", "rfisht;": "\u297d", "rfloor;": "\u230b", "rfr;": "\U0001d52f", "rhard;": "\u21c1", "rharu;": "\u21c0", "rharul;": "\u296c", "rho;": "\u03c1", "rhov;": "\u03f1", "rightarrow;": "\u2192", "rightarrowtail;": "\u21a3", "rightharpoondown;": "\u21c1", "rightharpoonup;": "\u21c0", "rightleftarrows;": "\u21c4", "rightleftharpoons;": "\u21cc", "rightrightarrows;": "\u21c9", "rightsquigarrow;": "\u219d", "rightthreetimes;": "\u22cc", "ring;": "\u02da", "risingdotseq;": "\u2253", "rlarr;": "\u21c4", "rlhar;": "\u21cc", "rlm;": "\u200f", "rmoust;": "\u23b1", "rmoustache;": "\u23b1", "rnmid;": "\u2aee", "roang;": "\u27ed", "roarr;": "\u21fe", "robrk;": "\u27e7", "ropar;": "\u2986", "ropf;": "\U0001d563", "roplus;": "\u2a2e", "rotimes;": "\u2a35", "rpar;": ")", "rpargt;": "\u2994", "rppolint;": "\u2a12", "rrarr;": "\u21c9", "rsaquo;": "\u203a", "rscr;": "\U0001d4c7", "rsh;": "\u21b1", "rsqb;": "]", "rsquo;": "\u2019", "rsquor;": "\u2019", "rthree;": "\u22cc", "rtimes;": "\u22ca", "rtri;": "\u25b9", "rtrie;": "\u22b5", "rtrif;": "\u25b8", "rtriltri;": "\u29ce", "ruluhar;": "\u2968", "rx;": "\u211e", "sacute;": "\u015b", "sbquo;": "\u201a", "sc;": "\u227b", "scE;": "\u2ab4", "scap;": "\u2ab8", "scaron;": "\u0161", "sccue;": "\u227d", "sce;": "\u2ab0", "scedil;": "\u015f", "scirc;": "\u015d", "scnE;": "\u2ab6", "scnap;": "\u2aba", "scnsim;": "\u22e9", "scpolint;": "\u2a13", "scsim;": "\u227f", "scy;": "\u0441", "sdot;": "\u22c5", "sdotb;": "\u22a1", "sdote;": "\u2a66", "seArr;": "\u21d8", "searhk;": "\u2925", "searr;": "\u2198", "searrow;": "\u2198", "sect": "\xa7", "sect;": "\xa7", "semi;": ";", "seswar;": "\u2929", "setminus;": "\u2216", "setmn;": "\u2216", "sext;": "\u2736", "sfr;": "\U0001d530", "sfrown;": "\u2322", "sharp;": "\u266f", "shchcy;": "\u0449", "shcy;": "\u0448", "shortmid;": "\u2223", "shortparallel;": "\u2225", "shy": "\xad", "shy;": "\xad", "sigma;": "\u03c3", "sigmaf;": "\u03c2", "sigmav;": "\u03c2", "sim;": "\u223c", "simdot;": "\u2a6a", "sime;": "\u2243", "simeq;": "\u2243", "simg;": "\u2a9e", "simgE;": "\u2aa0", "siml;": "\u2a9d", "simlE;": "\u2a9f", "simne;": "\u2246", "simplus;": "\u2a24", "simrarr;": "\u2972", "slarr;": "\u2190", "smallsetminus;": "\u2216", "smashp;": "\u2a33", "smeparsl;": "\u29e4", "smid;": "\u2223", "smile;": "\u2323", "smt;": "\u2aaa", "smte;": "\u2aac", "smtes;": "\u2aac\ufe00", "softcy;": "\u044c", "sol;": "/", "solb;": "\u29c4", "solbar;": "\u233f", "sopf;": "\U0001d564", "spades;": "\u2660", "spadesuit;": "\u2660", "spar;": "\u2225", "sqcap;": "\u2293", "sqcaps;": "\u2293\ufe00", "sqcup;": "\u2294", "sqcups;": "\u2294\ufe00", "sqsub;": "\u228f", "sqsube;": "\u2291", "sqsubset;": "\u228f", "sqsubseteq;": "\u2291", "sqsup;": "\u2290", "sqsupe;": "\u2292", "sqsupset;": "\u2290", "sqsupseteq;": "\u2292", "squ;": "\u25a1", "square;": "\u25a1", "squarf;": "\u25aa", "squf;": "\u25aa", "srarr;": "\u2192", "sscr;": "\U0001d4c8", "ssetmn;": "\u2216", "ssmile;": "\u2323", "sstarf;": "\u22c6", "star;": "\u2606", "starf;": "\u2605", "straightepsilon;": "\u03f5", "straightphi;": "\u03d5", "strns;": "\xaf", "sub;": "\u2282", "subE;": "\u2ac5", "subdot;": "\u2abd", "sube;": "\u2286", "subedot;": "\u2ac3", "submult;": "\u2ac1", "subnE;": "\u2acb", "subne;": "\u228a", "subplus;": "\u2abf", "subrarr;": "\u2979", "subset;": "\u2282", "subseteq;": "\u2286", "subseteqq;": "\u2ac5", "subsetneq;": "\u228a", "subsetneqq;": "\u2acb", "subsim;": "\u2ac7", "subsub;": "\u2ad5", "subsup;": "\u2ad3", "succ;": "\u227b", "succapprox;": "\u2ab8", "succcurlyeq;": "\u227d", "succeq;": "\u2ab0", "succnapprox;": "\u2aba", "succneqq;": "\u2ab6", "succnsim;": "\u22e9", "succsim;": "\u227f", "sum;": "\u2211", "sung;": "\u266a", "sup1": "\xb9", "sup1;": "\xb9", "sup2": "\xb2", "sup2;": "\xb2", "sup3": "\xb3", "sup3;": "\xb3", "sup;": "\u2283", "supE;": "\u2ac6", "supdot;": "\u2abe", "supdsub;": "\u2ad8", "supe;": "\u2287", "supedot;": "\u2ac4", "suphsol;": "\u27c9", "suphsub;": "\u2ad7", "suplarr;": "\u297b", "supmult;": "\u2ac2", "supnE;": "\u2acc", "supne;": "\u228b", "supplus;": "\u2ac0", "supset;": "\u2283", "supseteq;": "\u2287", "supseteqq;": "\u2ac6", "supsetneq;": "\u228b", "supsetneqq;": "\u2acc", "supsim;": "\u2ac8", "supsub;": "\u2ad4", "supsup;": "\u2ad6", "swArr;": "\u21d9", "swarhk;": "\u2926", "swarr;": "\u2199", "swarrow;": "\u2199", "swnwar;": "\u292a", "szlig": "\xdf", "szlig;": "\xdf", "target;": "\u2316", "tau;": "\u03c4", "tbrk;": "\u23b4", "tcaron;": "\u0165", "tcedil;": "\u0163", "tcy;": "\u0442", "tdot;": "\u20db", "telrec;": "\u2315", "tfr;": "\U0001d531", "there4;": "\u2234", "therefore;": "\u2234", "theta;": "\u03b8", "thetasym;": "\u03d1", "thetav;": "\u03d1", "thickapprox;": "\u2248", "thicksim;": "\u223c", "thinsp;": "\u2009", "thkap;": "\u2248", "thksim;": "\u223c", "thorn": "\xfe", "thorn;": "\xfe", "tilde;": "\u02dc", "times": "\xd7", "times;": "\xd7", "timesb;": "\u22a0", "timesbar;": "\u2a31", "timesd;": "\u2a30", "tint;": "\u222d", "toea;": "\u2928", "top;": "\u22a4", "topbot;": "\u2336", "topcir;": "\u2af1", "topf;": "\U0001d565", "topfork;": "\u2ada", "tosa;": "\u2929", "tprime;": "\u2034", "trade;": "\u2122", "triangle;": "\u25b5", "triangledown;": "\u25bf", "triangleleft;": "\u25c3", "trianglelefteq;": "\u22b4", "triangleq;": "\u225c", "triangleright;": "\u25b9", "trianglerighteq;": "\u22b5", "tridot;": "\u25ec", "trie;": "\u225c", "triminus;": "\u2a3a", "triplus;": "\u2a39", "trisb;": "\u29cd", "tritime;": "\u2a3b", "trpezium;": "\u23e2", "tscr;": "\U0001d4c9", "tscy;": "\u0446", "tshcy;": "\u045b", "tstrok;": "\u0167", "twixt;": "\u226c", "twoheadleftarrow;": "\u219e", "twoheadrightarrow;": "\u21a0", "uArr;": "\u21d1", "uHar;": "\u2963", "uacute": "\xfa", "uacute;": "\xfa", "uarr;": "\u2191", "ubrcy;": "\u045e", "ubreve;": "\u016d", "ucirc": "\xfb", "ucirc;": "\xfb", "ucy;": "\u0443", "udarr;": "\u21c5", "udblac;": "\u0171", "udhar;": "\u296e", "ufisht;": "\u297e", "ufr;": "\U0001d532", "ugrave": "\xf9", "ugrave;": "\xf9", "uharl;": "\u21bf", "uharr;": "\u21be", "uhblk;": "\u2580", "ulcorn;": "\u231c", "ulcorner;": "\u231c", "ulcrop;": "\u230f", "ultri;": "\u25f8", "umacr;": "\u016b", "uml": "\xa8", "uml;": "\xa8", "uogon;": "\u0173", "uopf;": "\U0001d566", "uparrow;": "\u2191", "updownarrow;": "\u2195", "upharpoonleft;": "\u21bf", "upharpoonright;": "\u21be", "uplus;": "\u228e", "upsi;": "\u03c5", "upsih;": "\u03d2", "upsilon;": "\u03c5", "upuparrows;": "\u21c8", "urcorn;": "\u231d", "urcorner;": "\u231d", "urcrop;": "\u230e", "uring;": "\u016f", "urtri;": "\u25f9", "uscr;": "\U0001d4ca", "utdot;": "\u22f0", "utilde;": "\u0169", "utri;": "\u25b5", "utrif;": "\u25b4", "uuarr;": "\u21c8", "uuml": "\xfc", "uuml;": "\xfc", "uwangle;": "\u29a7", "vArr;": "\u21d5", "vBar;": "\u2ae8", "vBarv;": "\u2ae9", "vDash;": "\u22a8", "vangrt;": "\u299c", "varepsilon;": "\u03f5", "varkappa;": "\u03f0", "varnothing;": "\u2205", "varphi;": "\u03d5", "varpi;": "\u03d6", "varpropto;": "\u221d", "varr;": "\u2195", "varrho;": "\u03f1", "varsigma;": "\u03c2", "varsubsetneq;": "\u228a\ufe00", "varsubsetneqq;": "\u2acb\ufe00", "varsupsetneq;": "\u228b\ufe00", "varsupsetneqq;": "\u2acc\ufe00", "vartheta;": "\u03d1", "vartriangleleft;": "\u22b2", "vartriangleright;": "\u22b3", "vcy;": "\u0432", "vdash;": "\u22a2", "vee;": "\u2228", "veebar;": "\u22bb", "veeeq;": "\u225a", "vellip;": "\u22ee", "verbar;": "|", "vert;": "|", "vfr;": "\U0001d533", "vltri;": "\u22b2", "vnsub;": "\u2282\u20d2", "vnsup;": "\u2283\u20d2", "vopf;": "\U0001d567", "vprop;": "\u221d", "vrtri;": "\u22b3", "vscr;": "\U0001d4cb", "vsubnE;": "\u2acb\ufe00", "vsubne;": "\u228a\ufe00", "vsupnE;": "\u2acc\ufe00", "vsupne;": "\u228b\ufe00", "vzigzag;": "\u299a", "wcirc;": "\u0175", "wedbar;": "\u2a5f", "wedge;": "\u2227", "wedgeq;": "\u2259", "weierp;": "\u2118", "wfr;": "\U0001d534", "wopf;": "\U0001d568", "wp;": "\u2118", "wr;": "\u2240", "wreath;": "\u2240", "wscr;": "\U0001d4cc", "xcap;": "\u22c2", "xcirc;": "\u25ef", "xcup;": "\u22c3", "xdtri;": "\u25bd", "xfr;": "\U0001d535", "xhArr;": "\u27fa", "xharr;": "\u27f7", "xi;": "\u03be", "xlArr;": "\u27f8", "xlarr;": "\u27f5", "xmap;": "\u27fc", "xnis;": "\u22fb", "xodot;": "\u2a00", "xopf;": "\U0001d569", "xoplus;": "\u2a01", "xotime;": "\u2a02", "xrArr;": "\u27f9", "xrarr;": "\u27f6", "xscr;": "\U0001d4cd", "xsqcup;": "\u2a06", "xuplus;": "\u2a04", "xutri;": "\u25b3", "xvee;": "\u22c1", "xwedge;": "\u22c0", "yacute": "\xfd", "yacute;": "\xfd", "yacy;": "\u044f", "ycirc;": "\u0177", "ycy;": "\u044b", "yen": "\xa5", "yen;": "\xa5", "yfr;": "\U0001d536", "yicy;": "\u0457", "yopf;": "\U0001d56a", "yscr;": "\U0001d4ce", "yucy;": "\u044e", "yuml": "\xff", "yuml;": "\xff", "zacute;": "\u017a", "zcaron;": "\u017e", "zcy;": "\u0437", "zdot;": "\u017c", "zeetrf;": "\u2128", "zeta;": "\u03b6", "zfr;": "\U0001d537", "zhcy;": "\u0436", "zigrarr;": "\u21dd", "zopf;": "\U0001d56b", "zscr;": "\U0001d4cf", "zwj;": "\u200d", "zwnj;": "\u200c", } replacementCharacters = { 0x0: "\uFFFD", 0x0d: "\u000D", 0x80: "\u20AC", 0x81: "\u0081", 0x81: "\u0081", 0x82: "\u201A", 0x83: "\u0192", 0x84: "\u201E", 0x85: "\u2026", 0x86: "\u2020", 0x87: "\u2021", 0x88: "\u02C6", 0x89: "\u2030", 0x8A: "\u0160", 0x8B: "\u2039", 0x8C: "\u0152", 0x8D: "\u008D", 0x8E: "\u017D", 0x8F: "\u008F", 0x90: "\u0090", 0x91: "\u2018", 0x92: "\u2019", 0x93: "\u201C", 0x94: "\u201D", 0x95: "\u2022", 0x96: "\u2013", 0x97: "\u2014", 0x98: "\u02DC", 0x99: "\u2122", 0x9A: "\u0161", 0x9B: "\u203A", 0x9C: "\u0153", 0x9D: "\u009D", 0x9E: "\u017E", 0x9F: "\u0178", } encodings = { '437': 'cp437', '850': 'cp850', '852': 'cp852', '855': 'cp855', '857': 'cp857', '860': 'cp860', '861': 'cp861', '862': 'cp862', '863': 'cp863', '865': 'cp865', '866': 'cp866', '869': 'cp869', 'ansix341968': 'ascii', 'ansix341986': 'ascii', 'arabic': 'iso8859-6', 'ascii': 'ascii', 'asmo708': 'iso8859-6', 'big5': 'big5', 'big5hkscs': 'big5hkscs', 'chinese': 'gbk', 'cp037': 'cp037', 'cp1026': 'cp1026', 'cp154': 'ptcp154', 'cp367': 'ascii', 'cp424': 'cp424', 'cp437': 'cp437', 'cp500': 'cp500', 'cp775': 'cp775', 'cp819': 'windows-1252', 'cp850': 'cp850', 'cp852': 'cp852', 'cp855': 'cp855', 'cp857': 'cp857', 'cp860': 'cp860', 'cp861': 'cp861', 'cp862': 'cp862', 'cp863': 'cp863', 'cp864': 'cp864', 'cp865': 'cp865', 'cp866': 'cp866', 'cp869': 'cp869', 'cp936': 'gbk', 'cpgr': 'cp869', 'cpis': 'cp861', 'csascii': 'ascii', 'csbig5': 'big5', 'cseuckr': 'cp949', 'cseucpkdfmtjapanese': 'euc_jp', 'csgb2312': 'gbk', 'cshproman8': 'hp-roman8', 'csibm037': 'cp037', 'csibm1026': 'cp1026', 'csibm424': 'cp424', 'csibm500': 'cp500', 'csibm855': 'cp855', 'csibm857': 'cp857', 'csibm860': 'cp860', 'csibm861': 'cp861', 'csibm863': 'cp863', 'csibm864': 'cp864', 'csibm865': 'cp865', 'csibm866': 'cp866', 'csibm869': 'cp869', 'csiso2022jp': 'iso2022_jp', 'csiso2022jp2': 'iso2022_jp_2', 'csiso2022kr': 'iso2022_kr', 'csiso58gb231280': 'gbk', 'csisolatin1': 'windows-1252', 'csisolatin2': 'iso8859-2', 'csisolatin3': 'iso8859-3', 'csisolatin4': 'iso8859-4', 'csisolatin5': 'windows-1254', 'csisolatin6': 'iso8859-10', 'csisolatinarabic': 'iso8859-6', 'csisolatincyrillic': 'iso8859-5', 'csisolatingreek': 'iso8859-7', 'csisolatinhebrew': 'iso8859-8', 'cskoi8r': 'koi8-r', 'csksc56011987': 'cp949', 'cspc775baltic': 'cp775', 'cspc850multilingual': 'cp850', 'cspc862latinhebrew': 'cp862', 'cspc8codepage437': 'cp437', 'cspcp852': 'cp852', 'csptcp154': 'ptcp154', 'csshiftjis': 'shift_jis', 'csunicode11utf7': 'utf-7', 'cyrillic': 'iso8859-5', 'cyrillicasian': 'ptcp154', 'ebcdiccpbe': 'cp500', 'ebcdiccpca': 'cp037', 'ebcdiccpch': 'cp500', 'ebcdiccphe': 'cp424', 'ebcdiccpnl': 'cp037', 'ebcdiccpus': 'cp037', 'ebcdiccpwt': 'cp037', 'ecma114': 'iso8859-6', 'ecma118': 'iso8859-7', 'elot928': 'iso8859-7', 'eucjp': 'euc_jp', 'euckr': 'cp949', 'extendedunixcodepackedformatforjapanese': 'euc_jp', 'gb18030': 'gb18030', 'gb2312': 'gbk', 'gb231280': 'gbk', 'gbk': 'gbk', 'greek': 'iso8859-7', 'greek8': 'iso8859-7', 'hebrew': 'iso8859-8', 'hproman8': 'hp-roman8', 'hzgb2312': 'hz', 'ibm037': 'cp037', 'ibm1026': 'cp1026', 'ibm367': 'ascii', 'ibm424': 'cp424', 'ibm437': 'cp437', 'ibm500': 'cp500', 'ibm775': 'cp775', 'ibm819': 'windows-1252', 'ibm850': 'cp850', 'ibm852': 'cp852', 'ibm855': 'cp855', 'ibm857': 'cp857', 'ibm860': 'cp860', 'ibm861': 'cp861', 'ibm862': 'cp862', 'ibm863': 'cp863', 'ibm864': 'cp864', 'ibm865': 'cp865', 'ibm866': 'cp866', 'ibm869': 'cp869', 'iso2022jp': 'iso2022_jp', 'iso2022jp2': 'iso2022_jp_2', 'iso2022kr': 'iso2022_kr', 'iso646irv1991': 'ascii', 'iso646us': 'ascii', 'iso88591': 'windows-1252', 'iso885910': 'iso8859-10', 'iso8859101992': 'iso8859-10', 'iso885911987': 'windows-1252', 'iso885913': 'iso8859-13', 'iso885914': 'iso8859-14', 'iso8859141998': 'iso8859-14', 'iso885915': 'iso8859-15', 'iso885916': 'iso8859-16', 'iso8859162001': 'iso8859-16', 'iso88592': 'iso8859-2', 'iso885921987': 'iso8859-2', 'iso88593': 'iso8859-3', 'iso885931988': 'iso8859-3', 'iso88594': 'iso8859-4', 'iso885941988': 'iso8859-4', 'iso88595': 'iso8859-5', 'iso885951988': 'iso8859-5', 'iso88596': 'iso8859-6', 'iso885961987': 'iso8859-6', 'iso88597': 'iso8859-7', 'iso885971987': 'iso8859-7', 'iso88598': 'iso8859-8', 'iso885981988': 'iso8859-8', 'iso88599': 'windows-1254', 'iso885991989': 'windows-1254', 'isoceltic': 'iso8859-14', 'isoir100': 'windows-1252', 'isoir101': 'iso8859-2', 'isoir109': 'iso8859-3', 'isoir110': 'iso8859-4', 'isoir126': 'iso8859-7', 'isoir127': 'iso8859-6', 'isoir138': 'iso8859-8', 'isoir144': 'iso8859-5', 'isoir148': 'windows-1254', 'isoir149': 'cp949', 'isoir157': 'iso8859-10', 'isoir199': 'iso8859-14', 'isoir226': 'iso8859-16', 'isoir58': 'gbk', 'isoir6': 'ascii', 'koi8r': 'koi8-r', 'koi8u': 'koi8-u', 'korean': 'cp949', 'ksc5601': 'cp949', 'ksc56011987': 'cp949', 'ksc56011989': 'cp949', 'l1': 'windows-1252', 'l10': 'iso8859-16', 'l2': 'iso8859-2', 'l3': 'iso8859-3', 'l4': 'iso8859-4', 'l5': 'windows-1254', 'l6': 'iso8859-10', 'l8': 'iso8859-14', 'latin1': 'windows-1252', 'latin10': 'iso8859-16', 'latin2': 'iso8859-2', 'latin3': 'iso8859-3', 'latin4': 'iso8859-4', 'latin5': 'windows-1254', 'latin6': 'iso8859-10', 'latin8': 'iso8859-14', 'latin9': 'iso8859-15', 'ms936': 'gbk', 'mskanji': 'shift_jis', 'pt154': 'ptcp154', 'ptcp154': 'ptcp154', 'r8': 'hp-roman8', 'roman8': 'hp-roman8', 'shiftjis': 'shift_jis', 'tis620': 'cp874', 'unicode11utf7': 'utf-7', 'us': 'ascii', 'usascii': 'ascii', 'utf16': 'utf-16', 'utf16be': 'utf-16-be', 'utf16le': 'utf-16-le', 'utf8': 'utf-8', 'windows1250': 'cp1250', 'windows1251': 'cp1251', 'windows1252': 'cp1252', 'windows1253': 'cp1253', 'windows1254': 'cp1254', 'windows1255': 'cp1255', 'windows1256': 'cp1256', 'windows1257': 'cp1257', 'windows1258': 'cp1258', 'windows936': 'gbk', 'x-x-big5': 'big5'} tokenTypes = { "Doctype": 0, "Characters": 1, "SpaceCharacters": 2, "StartTag": 3, "EndTag": 4, "EmptyTag": 5, "Comment": 6, "ParseError": 7 } tagTokenTypes = frozenset((tokenTypes["StartTag"], tokenTypes["EndTag"], tokenTypes["EmptyTag"])) prefixes = dict([(v, k) for k, v in namespaces.items()]) prefixes["http://www.w3.org/1998/Math/MathML"] = "math" class DataLossWarning(UserWarning): pass class ReparseException(Exception): pass
cortext/crawtextV2
~/venvs/crawler/lib/python2.7/site-packages/pip/_vendor/html5lib/constants.py
Python
mit
87,346
from pyccel.stdlib.internal.blas import dgemv from numpy import zeros n = 4 m = 5 a = zeros((n,m), 'double') x = zeros(m, 'double') y = zeros(n, 'double') # ... a[0,0] = 1.0 a[1,0] = 6.0 a[2,0] = 11.0 a[3,0] = 16.0 a[0,1] = 2.0 a[1,1] = 7.0 a[2,1] = 12.0 a[3,1] = 17.0 a[0,2] = 3.0 a[1,2] = 8.0 a[2,2] = 13.0 a[3,2] = 18.0 a[0,3] = 4.0 a[1,3] = 9.0 a[2,3] = 14.0 a[3,3] = 19.0 a[0,4] = 5.0 a[1,4] = 10.0 a[2,4] = 15.0 a[3,4] = 20.0 # ... # ... x[0] = 2.0 x[1] = 3.0 x[2] = 4.0 x[3] = 5.0 x[4] = 6.0 # ... alpha = 2.0 beta = 0.0 incx = 1 incy = 1 dgemv('N', n, m, alpha, a, n, x, incx, beta, y, incy)
ratnania/pyccel
tests/internal/scripts/blas/ex2.py
Python
mit
611
from flask import Blueprint, render_template, request from bson import json_util from app import mongo mod_main = Blueprint('main', __name__) @mod_main.route('/', methods=['GET','POST']) def index(): ''' Renders the App index page. :return: ''' db = mongo.db.arkep if request.method == 'GET': return render_template('index.html') elif request.method == 'POST': data = request.form.to_dict() db.insert(data) return json_util.dumbs(data) else: return 'Bad request' @mod_main.route('/<string:id>', methods=['GET']) def get_doc(id): #Return a mongo document with the specified id. #return MongoDb Cursor db = mongo.db.arkep if request.method == 'GET': doc = db.find({"_id":Object (id)}) return "You requested a document with ID" + id else: return 'Bad request'
lorinamorina/techstitution-
app/mod_main/views.py
Python
cc0-1.0
859
#! /usr/bin/python3 #-*- coding: UTF-8 -*- import re import unidecode from goose3 import Goose GRAB_FIRST_TWO_SENTENCES_RE = '[.!?][\s]{1,2}(?=[A-Z])' REMOVE_SPECIAL_CHARACTERS_RE = '[^A-Za-z0-9]+' REMOVE_SPECIAL_CHARACTERS_KEEP_DASHES_RE = '[^A-Za-z0-9-]+' CLOSE_PAREN = ")" COLON = "&#58" COMMA = "," DASH = "-" EMPTY = "" MARKDOWN_SUFFIX = ".md" OPEN_PAREN = "(" PERIOD = "." QUOTE = "\"" UNDERSCORE = "_" SPACE = " " def get_excerpt_from_page(url): """ Rudimentary excerpt creator.""" try: regex_object = re.compile(GRAB_FIRST_TWO_SENTENCES_RE) all_text_on_page = Goose().extract(url=url).cleaned_text if url != EMPTY else EMPTY sentences = regex_object.split(all_text_on_page, re.UNICODE) except: return EMPTY if len(sentences) == 0 or _is_common_bad_excerpt(sentences[0]): return EMPTY if len(sentences) == 1: return _cleanup_excerpt(sentences[0] + PERIOD.replace(COLON, EMPTY)) else: return _cleanup_excerpt((sentences[0] + PERIOD + SPACE + sentences[1] + PERIOD).replace(COLON, EMPTY)) def _cleanup_excerpt(str): return " ".join(str.split()).replace(COLON, EMPTY).replace(":", "") def _is_common_bad_excerpt(sentence): common_bad_excerpts = [ "JavaScript isn't enabled in your browser", "Get YouTube without the ads", ] for excerpt in common_bad_excerpts: if excerpt in sentence: return True return False def title_to_file_path(title, resource_type): resources_folder_path = "../../collections/_" resources_folder_path = resources_folder_path + resource_type + "/" if title == EMPTY or title == UNDERSCORE: return EMPTY return "{}{}{}".format( resources_folder_path, _camel_case_to_dashed(_remove_extraneous_symbols(title.replace("58", ""))), MARKDOWN_SUFFIX) def author_to_file_path(valid_author_slug): """ Replaces extraneous symbols and cleans up accents and umlauts in author names. """ if valid_author_slug == EMPTY or valid_author_slug == UNDERSCORE: return EMPTY return "{}{}{}".format( "../../collections/_authors/", valid_author_slug, MARKDOWN_SUFFIX) def get_valid_author_slug(author): return _remove_extraneous_symbols_keep_dashes(unidecode.unidecode( re.sub(UNDERSCORE, DASH, re.sub(SPACE, DASH, author.strip().lower())))) def _camel_case_to_dashed(title): return re.sub('([a-z0-9])([A-Z])', r'\1-\2', re.sub('(.)([A-Z][a-z]+)',r'\1-\2', title)).lower() def _remove_extraneous_symbols(str): return _remove_extraneous_symbols_with_regex( str, REMOVE_SPECIAL_CHARACTERS_RE) def _remove_extraneous_symbols_keep_dashes(str): return _remove_extraneous_symbols_with_regex( str, REMOVE_SPECIAL_CHARACTERS_KEEP_DASHES_RE) def _remove_extraneous_symbols_with_regex(str, regex): str = _replace_apostrophe_char_with_char(['s', 'S', 't', 'T'], str) return re.sub( '-+', '-', re.sub(regex, EMPTY, str)) def _replace_apostrophe_char_with_char(chars, str): for char in chars: str = re.sub(r"(\w+)'{}".format(char), r'\1{}'.format(char.lower()), str) return str
gabridome/gabridome.github.io
scripts/spreadsheet_to_resource_mds/util.py
Python
apache-2.0
3,226
# -*- coding: utf-8 -*- #/############################################################################# # # Tech-Receptives Solutions Pvt. Ltd. # Copyright (C) 2004-TODAY Tech-Receptives(<http://www.techreceptives.com>) # Special Credit and Thanks to Thymbra Latinoamericana S.A. # # 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 osv import osv from osv import fields class OeMedicalPathologyCategory(osv.Model): _name = 'oemedical.pathology.category' _columns = { 'childs': fields.one2many('oemedical.pathology.category', 'parent_id', string='Children Category', ), 'name': fields.char(size=256, string='Category Name', required=True), 'parent_id': fields.many2one('oemedical.pathology.category', string='Parent Category', select=True), } _constraints = [ (osv.Model._check_recursion, 'Error ! You cannot create recursive \n' 'Category.', ['parent_id']) ] OeMedicalPathologyCategory() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
jmesteve/medical
openerp/oemedical/oemedical/oemedical_pathology_category/oemedical_pathology_category.py
Python
agpl-3.0
1,851
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'ansiapp.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )
muranga/laughing-octo-nemesis
src/ansiapp/urls.py
Python
unlicense
298
from django.db import models class Dummy(models.Model): parent = models.ForeignKey('self', null=True, blank=True) country = models.ForeignKey('cities_light.country') region = models.ForeignKey('cities_light.region') def __unicode__(self): return u'%s %s' % (self.country, self.region)
spookylukey/django-autocomplete-light
test_project/dependant_autocomplete/models.py
Python
mit
311
import piface.pfio as piface piface.init() piface.digital_write(1, 0)
SeanDS/slow-cooker
test.py
Python
gpl-2.0
72
from imports import QVBoxLayout, QPlainTextEdit, QDialog, QHBoxLayout, QLineEdit, QLabel, QPushButton class NotesDialog(QDialog): def __init__(self): super().__init__() layout = QVBoxLayout() self.notepad = QPlainTextEdit() layout.addWidget(self.notepad) self.setLayout(layout) def accept(self): self.hide() def reject(self): self.hide() def getText(self): return self.notepad.toPlainText() def setText(self, text): self.notepad.setPlainText(text) class CoderDialog(QDialog): def __init__(self, coderName, parent=None): super().__init__(parent=parent) self.setWindowTitle('Edit default coder name') self._coderName = coderName layout = QVBoxLayout() self.setLayout(layout) inputLayout = QHBoxLayout() layout.addLayout(inputLayout) self.coderNameLineEdit = QLineEdit(self._coderName) inputLayout.addWidget(QLabel('Default coder:')) inputLayout.addWidget(self.coderNameLineEdit) buttonLayout = QHBoxLayout() layout.addLayout(buttonLayout) okButton = QPushButton('Ok') buttonLayout.addWidget(okButton) okButton.clicked.connect(self.accept) cancelButton = QPushButton('Cancel') buttonLayout.addWidget(cancelButton) cancelButton.clicked.connect(self.reject) def accept(self): self._coderName = self.coderNameLineEdit.text() super().accept() @property def coderName(self): return self._coderName
PhonologicalCorpusTools/SLP-Annotator
slpa/gui/notes.py
Python
gpl-3.0
1,584
""" Patterns for legalizing the `base` instruction set. The base Cretonne instruction set is 'fat', and many instructions don't have legal representations in a given target ISA. This module defines legalization patterns that describe how base instructions can be transformed to other base instructions that are legal. """ from __future__ import absolute_import from .immediates import intcc, imm64, ieee32, ieee64 from . import instructions as insts from . import types from .instructions import iadd, iadd_cout, iadd_cin, iadd_carry, iadd_imm from .instructions import isub, isub_bin, isub_bout, isub_borrow, irsub_imm from .instructions import imul, imul_imm from .instructions import sdiv, sdiv_imm, udiv, udiv_imm from .instructions import srem, srem_imm, urem, urem_imm from .instructions import band, bor, bxor, isplit, iconcat from .instructions import bnot, band_not, bor_not, bxor_not from .instructions import band_imm, bor_imm, bxor_imm from .instructions import icmp, icmp_imm, ifcmp, ifcmp_imm from .instructions import iconst, bint, select from .instructions import ishl, ishl_imm, sshr, sshr_imm, ushr, ushr_imm from .instructions import rotl, rotl_imm, rotr, rotr_imm from .instructions import f32const, f64const from cdsl.ast import Var from cdsl.xform import Rtl, XFormGroup narrow = XFormGroup('narrow', """ Legalize instructions by narrowing. The transformations in the 'narrow' group work by expressing instructions in terms of smaller types. Operations on vector types are expressed in terms of vector types with fewer lanes, and integer operations are expressed in terms of smaller integer types. """) widen = XFormGroup('widen', """ Legalize instructions by widening. The transformations in the 'widen' group work by expressing instructions in terms of larger types. """) expand = XFormGroup('expand', """ Legalize instructions by expansion. Rewrite instructions in terms of other instructions, generally operating on the same types as the original instructions. """) expand_flags = XFormGroup('expand_flags', """ Instruction expansions for architectures with flags. Expand some instructions using CPU flags, then fall back to the normal expansions. Not all architectures support CPU flags, so these patterns are kept separate. """, chain=expand) # Custom expansions for memory objects. expand.custom_legalize(insts.global_addr, 'expand_global_addr') expand.custom_legalize(insts.heap_addr, 'expand_heap_addr') # Custom expansions that need to change the CFG. # TODO: Add sufficient XForm syntax that we don't need to hand-code these. expand.custom_legalize(insts.trapz, 'expand_cond_trap') expand.custom_legalize(insts.trapnz, 'expand_cond_trap') expand.custom_legalize(insts.br_table, 'expand_br_table') expand.custom_legalize(insts.select, 'expand_select') # Custom expansions for floating point constants. # These expansions require bit-casting or creating constant pool entries. expand.custom_legalize(insts.f32const, 'expand_fconst') expand.custom_legalize(insts.f64const, 'expand_fconst') x = Var('x') y = Var('y') a = Var('a') a1 = Var('a1') a2 = Var('a2') b = Var('b') b1 = Var('b1') b2 = Var('b2') b_in = Var('b_in') b_int = Var('b_int') c = Var('c') c1 = Var('c1') c2 = Var('c2') c_in = Var('c_in') c_int = Var('c_int') xl = Var('xl') xh = Var('xh') yl = Var('yl') yh = Var('yh') al = Var('al') ah = Var('ah') cc = Var('cc') narrow.legalize( a << iadd(x, y), Rtl( (xl, xh) << isplit(x), (yl, yh) << isplit(y), (al, c) << iadd_cout(xl, yl), ah << iadd_cin(xh, yh, c), a << iconcat(al, ah) )) narrow.legalize( a << isub(x, y), Rtl( (xl, xh) << isplit(x), (yl, yh) << isplit(y), (al, b) << isub_bout(xl, yl), ah << isub_bin(xh, yh, b), a << iconcat(al, ah) )) for bitop in [band, bor, bxor]: narrow.legalize( a << bitop(x, y), Rtl( (xl, xh) << isplit(x), (yl, yh) << isplit(y), al << bitop(xl, yl), ah << bitop(xh, yh), a << iconcat(al, ah) )) narrow.legalize( a << select(c, x, y), Rtl( (xl, xh) << isplit(x), (yl, yh) << isplit(y), al << select(c, xl, yl), ah << select(c, xh, yh), a << iconcat(al, ah) )) # Expand integer operations with carry for RISC architectures that don't have # the flags. expand.legalize( (a, c) << iadd_cout(x, y), Rtl( a << iadd(x, y), c << icmp(intcc.ult, a, x) )) expand.legalize( (a, b) << isub_bout(x, y), Rtl( a << isub(x, y), b << icmp(intcc.ugt, a, x) )) expand.legalize( a << iadd_cin(x, y, c), Rtl( a1 << iadd(x, y), c_int << bint(c), a << iadd(a1, c_int) )) expand.legalize( a << isub_bin(x, y, b), Rtl( a1 << isub(x, y), b_int << bint(b), a << isub(a1, b_int) )) expand.legalize( (a, c) << iadd_carry(x, y, c_in), Rtl( (a1, c1) << iadd_cout(x, y), c_int << bint(c_in), (a, c2) << iadd_cout(a1, c_int), c << bor(c1, c2) )) expand.legalize( (a, b) << isub_borrow(x, y, b_in), Rtl( (a1, b1) << isub_bout(x, y), b_int << bint(b_in), (a, b2) << isub_bout(a1, b_int), b << bor(b1, b2) )) # Expansions for immediate operands that are out of range. for inst_imm, inst in [ (iadd_imm, iadd), (imul_imm, imul), (sdiv_imm, sdiv), (udiv_imm, udiv), (srem_imm, srem), (urem_imm, urem), (band_imm, band), (bor_imm, bor), (bxor_imm, bor), (ifcmp_imm, ifcmp)]: expand.legalize( a << inst_imm(x, y), Rtl( a1 << iconst(y), a << inst(x, a1) )) expand.legalize( a << irsub_imm(y, x), Rtl( a1 << iconst(x), a << isub(a1, y) )) # Rotates and shifts. for inst_imm, inst in [ (rotl_imm, rotl), (rotr_imm, rotr), (ishl_imm, ishl), (sshr_imm, sshr), (ushr_imm, ushr)]: expand.legalize( a << inst_imm(x, y), Rtl( a1 << iconst.i32(y), a << inst(x, a1) )) expand.legalize( a << icmp_imm(cc, x, y), Rtl( a1 << iconst(y), a << icmp(cc, x, a1) )) # Expansions for *_not variants of bitwise ops. for inst_not, inst in [ (band_not, band), (bor_not, bor), (bxor_not, bxor)]: expand.legalize( a << inst_not(x, y), Rtl( a1 << bnot(y), a << inst(x, a1) )) # Floating-point sign manipulations. for ty, minus_zero in [ (types.f32, f32const(ieee32.bits(0x80000000))), (types.f64, f64const(ieee64.bits(0x8000000000000000)))]: expand.legalize( a << insts.fabs.bind(ty)(x), Rtl( b << minus_zero, a << band_not(x, b), )) expand.legalize( a << insts.fneg.bind(ty)(x), Rtl( b << minus_zero, a << bxor(x, b), )) expand.legalize( a << insts.fcopysign.bind(ty)(x, y), Rtl( b << minus_zero, a1 << band_not(x, b), a2 << band(y, b), a << bor(a1, a2) )) # Expansions using CPU flags. expand_flags.custom_legalize(insts.stack_check, 'expand_stack_check') expand_flags.legalize( insts.trapnz(x, c), Rtl( a << insts.ifcmp_imm(x, imm64(0)), insts.trapif(intcc.ne, a, c) )) expand_flags.legalize( insts.trapz(x, c), Rtl( a << insts.ifcmp_imm(x, imm64(0)), insts.trapif(intcc.eq, a, c) ))
sunfishcode/cretonne
lib/cretonne/meta/base/legalize.py
Python
apache-2.0
8,302
from __future__ import print_function, absolute_import, division import math from numpy import * class Point2D: def __init__(self, node_list): if(len(node_list) != 1): raise Exception("wrong number of nodes! should be 1!!") self.nodes = node_list for node in self.nodes: if(node.Id < 0): raise Exception("node with Id lesser than 0 found") # def Nodes(self): # return self.nodes def __getitem__(self, key): return self.nodes[key] def GetNumberOfNodes(self): return 1 def ShapeFunctions(self, order=1): '''this function provides the shape function values, derivatives and integration_weight''' '''at the location of the gauss points. Order of integration is controlled''' '''by the optional parameter "order".''' '''N[gauss][i] contains the shape function of node i computed at the position of "gauss" ''' '''derivatives[gauss][i,k] contains the derivative of node i, component k at the position of gauss ''' '''weights[gauss] includes the integration weights, including the det of the jacobian, to be used ''' '''at the gauss point''' derivatives = [] weights = [] Ncontainer = [] Ncontainer.append(array([1.0])) #does not make sense weights = [1.0] derivatives = [] #does not make sense return [Ncontainer, derivatives, weights]
RiccardoRossi/pyKratos
pyKratos/point2d.py
Python
bsd-2-clause
1,473
#!/usr/bin/env python """ Author : Jaganadh Gopinadhan <jaganadhg@gmail.com> Copywright (C) : Jaganadh Gopinadhan 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 sys,os import re from nltk.corpus import wordnet class SentiWordNet(object): """ Interface to SentiWordNet """ def __init__(self,swn_file): """ """ self.swn_file = swn_file self.pos_synset = self.__parse_swn_file() def __parse_swn_file(self): """ Parse the SentiWordNet file and populate the POS and SynsetID hash """ pos_synset_hash = {} swn_data = open(self.swn_file,'r').readlines() head_less_swn_data = filter((lambda line: not re.search(r"^\s*#",\ line)), swn_data) for data in head_less_swn_data: fields = data.strip().split("\t") try: pos,syn_set_id,pos_score,neg_score,syn_set_score,\ gloss = fields except: print("Found data without all details") pass if pos and syn_set_score: pos_synset_hash[(pos,int(syn_set_id))] = (float(pos_score),\ float(neg_score)) return pos_synset_hash def get_score(self,word,pos=None): """ Get score for a given word/word pos combination """ senti_scores = [] synsets = wordnet.synsets(word,pos) for synset in synsets: if (synset.pos(), synset.offset()) in self.pos_synset: pos_val, neg_val = self.pos_synset[(synset.pos(), synset.offset())] senti_scores.append({"pos":pos_val,"neg":neg_val,\ "obj": 1.0 - (pos_val - neg_val),'synset':synset}) return senti_scores
gsi-upm/senpy-plugins-community
sentiment-basic/sentiwn.py
Python
apache-2.0
2,250
from abc import ABCMeta, abstractmethod class NotificationSource(): """ Abstract class for all notification sources. """ __metaclass__ = ABCMeta @abstractmethod def poll(self): """ Used to get a set of changes between data retrieved in this call and the last. """ raise NotImplementedError('No concrete implementation!') @abstractmethod def name(self): """ Returns a unique name for the source type. """ raise NotImplementedError('No concrete implementation!')
DanNixon/Sakuya
pc_client/sakuyaclient/NotificationSource.py
Python
apache-2.0
562
import numpy as np from PyQt5.QtGui import QPainterPath, QPen from PyQt5.QtWidgets import QGraphicsPathItem from urh import settings from urh.cythonext import path_creator from urh.ui.painting.GridScene import GridScene from urh.ui.painting.SceneManager import SceneManager class FFTSceneManager(SceneManager): def __init__(self, parent, graphic_view=None): self.peak = [] super().__init__(parent) self.scene = GridScene(parent=graphic_view) self.scene.setBackgroundBrush(settings.BGCOLOR) self.peak_item = self.scene.addPath(QPainterPath(), QPen(settings.PEAK_COLOR, 0)) # type: QGraphicsPathItem def show_scene_section(self, x1: float, x2: float, subpath_ranges=None, colors=None): start = int(x1) if x1 > 0 else 0 end = int(x2) if x2 < self.num_samples else self.num_samples paths = path_creator.create_path(np.log10(self.plot_data), start, end) self.set_path(paths, colors=None) try: if len(self.peak) > 0: peak_path = path_creator.create_path(np.log10(self.peak), start, end)[0] self.peak_item.setPath(peak_path) except RuntimeWarning: pass def init_scene(self, draw_grid=True): self.scene.draw_grid = draw_grid self.peak = self.plot_data if len(self.peak) < self.num_samples else np.maximum(self.peak, self.plot_data) self.scene.setSceneRect(0, -5, self.num_samples, 10) def clear_path(self): for item in self.scene.items(): if isinstance(item, QGraphicsPathItem) and item != self.peak_item: self.scene.removeItem(item) item.setParentItem(None) del item def clear_peak(self): self.peak = [] if self.peak_item: self.peak_item.setPath(QPainterPath()) def eliminate(self): super().eliminate() self.peak = None self.peak_item = None
jopohl/urh
src/urh/ui/painting/FFTSceneManager.py
Python
gpl-3.0
1,960
# -*- coding: utf-8 -*- # Copyright 2016 Daniel Campos - Avanzosc S.L. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import preventive_operation from . import preventive_master from . import preventive_machine_operation from . import mrp_repair from . import machinery
odoomrp/odoomrp-wip
machine_manager_preventive/models/__init__.py
Python
agpl-3.0
295
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.nix_vector_routing', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class] module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## 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') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::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']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper [class] module.add_class('Ipv4NixVectorHelper', parent=root_module['ns3::Ipv4RoutingHelper']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration] module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration] module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketPriorityTag [class] module.add_class('SocketPriorityTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## 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']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## 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']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## net-device.h (module 'network'): ns3::NetDeviceQueue [class] module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface [class] module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object']) ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## net-device.h (module 'network'): ns3::QueueItem [class] module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) ## net-device.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration] module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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']) ## bridge-channel.h (module 'bridge'): ns3::BridgeChannel [class] module.add_class('BridgeChannel', import_from_module='ns.bridge', parent=root_module['ns3::Channel']) ## bridge-net-device.h (module 'bridge'): ns3::BridgeNetDevice [class] module.add_class('BridgeNetDevice', import_from_module='ns.bridge', parent=root_module['ns3::NetDevice']) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting [class] module.add_class('Ipv4ListRouting', import_from_module='ns.internet', parent=root_module['ns3::Ipv4RoutingProtocol']) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorRouting [class] module.add_class('Ipv4NixVectorRouting', parent=root_module['ns3::Ipv4RoutingProtocol']) module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >', u'ns3::NixMap_t') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >*', u'ns3::NixMap_t*') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >&', u'ns3::NixMap_t&') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >', u'ns3::Ipv4RouteMap_t') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >*', u'ns3::Ipv4RouteMap_t*') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >&', u'ns3::Ipv4RouteMap_t&') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&') def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_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_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Ipv4NixVectorHelper_methods(root_module, root_module['ns3::Ipv4NixVectorHelper']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__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__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_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_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue']) register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3BridgeChannel_methods(root_module, root_module['ns3::BridgeChannel']) register_Ns3BridgeNetDevice_methods(root_module, root_module['ns3::BridgeNetDevice']) register_Ns3Ipv4ListRouting_methods(root_module, root_module['ns3::Ipv4ListRouting']) register_Ns3Ipv4NixVectorRouting_methods(root_module, root_module['ns3::Ipv4NixVectorRouting']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_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'): uint8_t ns3::InetSocketAddress::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_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_Ns3Ipv4RoutingHelper_methods(root_module, cls): ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper() [constructor] cls.add_constructor([]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper(ns3::Ipv4RoutingHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingHelper const &', 'arg0')]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper * ns3::Ipv4RoutingHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::Ipv4RoutingHelper *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4RoutingHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAllAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAllEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintNeighborCacheEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintNeighborCacheEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintRoutingTableAllAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintRoutingTableAllEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintRoutingTableAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## ipv4-routing-helper.h (module 'internet'): static void ns3::Ipv4RoutingHelper::PrintRoutingTableEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('PrintRoutingTableEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], deprecated=True, is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_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 & value) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 21 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'delay')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')], deprecated=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function] cls.add_method('GetSize', 'std::size_t', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function] cls.add_method('SetSize', 'ns3::TypeId', [param('std::size_t', 'size')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable] cls.add_instance_attribute('callback', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Ipv4NixVectorHelper_methods(root_module, cls): ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper::Ipv4NixVectorHelper() [constructor] cls.add_constructor([]) ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper::Ipv4NixVectorHelper(ns3::Ipv4NixVectorHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4NixVectorHelper const &', 'arg0')]) ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper * ns3::Ipv4NixVectorHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::Ipv4NixVectorHelper *', [], is_const=True, is_virtual=True) ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4NixVectorHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): bool ns3::Object::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [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_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__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__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_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'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function] cls.add_method('GetPeerName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function] cls.add_method('IpTos2Priority', 'uint8_t', [param('uint8_t', 'ipTos')], is_static=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address,std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function] cls.add_method('Ipv6LeaveGroup', 'void', [], is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, 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::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [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_Ns3SocketPriorityTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketPriorityTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [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_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_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_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_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [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_Ns3Ipv4MulticastRoute_methods(root_module, cls): ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function] cls.add_method('GetOutputTtlMap', 'std::map< unsigned int, unsigned int >', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'src')]) return def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void,ns3::Ptr<ns3::Ipv4Route>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_pure_virtual=True, is_virtual=True) return def register_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_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_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_Ns3NetDeviceQueue_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function] cls.add_method('IsStopped', 'bool', [], is_const=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetWakeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function] cls.add_method('Wake', 'void', [], is_virtual=True) return def register_Ns3NetDeviceQueueInterface_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::CreateTxQueues() [member function] cls.add_method('CreateTxQueues', 'void', []) ## net-device.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function] cls.add_method('GetNTxQueues', 'uint8_t', [], is_const=True) ## net-device.h (module 'network'): ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function] cls.add_method('GetSelectQueueCallback', 'ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(uint8_t i) const [member function] cls.add_method('GetTxQueue', 'ns3::Ptr< ns3::NetDeviceQueue >', [param('uint8_t', 'i')], is_const=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetSelectQueueCallback', 'void', [param('ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function] cls.add_method('SetTxQueuesN', 'void', [param('uint8_t', 'numTxQueues')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): ns3::Time ns3::Node::GetLocalTime() const [member function] cls.add_method('GetLocalTime', 'ns3::Time', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_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_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'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) ## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function] cls.add_method('ToString', 'std::string', [], is_const=True) return def register_Ns3QueueItem_methods(root_module, cls): cls.add_output_stream_operator() ## net-device.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')]) ## net-device.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## net-device.h (module 'network'): uint32_t ns3::QueueItem::GetPacketSize() const [member function] cls.add_method('GetPacketSize', 'uint32_t', [], is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function] cls.add_method('GetUint8Value', 'bool', [param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')], is_const=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_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_Ns3BridgeChannel_methods(root_module, cls): ## bridge-channel.h (module 'bridge'): static ns3::TypeId ns3::BridgeChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bridge-channel.h (module 'bridge'): ns3::BridgeChannel::BridgeChannel() [constructor] cls.add_constructor([]) ## bridge-channel.h (module 'bridge'): void ns3::BridgeChannel::AddChannel(ns3::Ptr<ns3::Channel> bridgedChannel) [member function] cls.add_method('AddChannel', 'void', [param('ns3::Ptr< ns3::Channel >', 'bridgedChannel')]) ## bridge-channel.h (module 'bridge'): uint32_t ns3::BridgeChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## bridge-channel.h (module 'bridge'): ns3::Ptr<ns3::NetDevice> ns3::BridgeChannel::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) return def register_Ns3BridgeNetDevice_methods(root_module, cls): ## bridge-net-device.h (module 'bridge'): ns3::BridgeNetDevice::BridgeNetDevice() [constructor] cls.add_constructor([]) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::AddBridgePort(ns3::Ptr<ns3::NetDevice> bridgePort) [member function] cls.add_method('AddBridgePort', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'bridgePort')]) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::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) ## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::NetDevice> ns3::BridgeNetDevice::GetBridgePort(uint32_t n) const [member function] cls.add_method('GetBridgePort', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'n')], is_const=True) ## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::Channel> ns3::BridgeNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): uint32_t ns3::BridgeNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): uint16_t ns3::BridgeNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): uint32_t ns3::BridgeNetDevice::GetNBridgePorts() const [member function] cls.add_method('GetNBridgePorts', 'uint32_t', [], is_const=True) ## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::Node> ns3::BridgeNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): static ns3::TypeId ns3::BridgeNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::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) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::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) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::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) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::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) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::ForwardBroadcast(ns3::Ptr<ns3::NetDevice> incomingPort, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address src, ns3::Mac48Address dst) [member function] cls.add_method('ForwardBroadcast', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'incomingPort'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'src'), param('ns3::Mac48Address', 'dst')], visibility='protected') ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::ForwardUnicast(ns3::Ptr<ns3::NetDevice> incomingPort, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address src, ns3::Mac48Address dst) [member function] cls.add_method('ForwardUnicast', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'incomingPort'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'src'), param('ns3::Mac48Address', 'dst')], visibility='protected') ## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::NetDevice> ns3::BridgeNetDevice::GetLearnedState(ns3::Mac48Address source) [member function] cls.add_method('GetLearnedState', 'ns3::Ptr< ns3::NetDevice >', [param('ns3::Mac48Address', 'source')], visibility='protected') ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::Learn(ns3::Mac48Address source, ns3::Ptr<ns3::NetDevice> port) [member function] cls.add_method('Learn', 'void', [param('ns3::Mac48Address', 'source'), param('ns3::Ptr< ns3::NetDevice >', 'port')], visibility='protected') ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::ReceiveFromDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Address const & source, ns3::Address const & destination, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('ReceiveFromDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'destination'), param('ns3::NetDevice::PacketType', 'packetType')], visibility='protected') return def register_Ns3Ipv4ListRouting_methods(root_module, cls): ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting(ns3::Ipv4ListRouting const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4ListRouting const &', 'arg0')]) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting() [constructor] cls.add_constructor([]) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::AddRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol, int16_t priority) [member function] cls.add_method('AddRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol'), param('int16_t', 'priority')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): uint32_t ns3::Ipv4ListRouting::GetNRoutingProtocols() const [member function] cls.add_method('GetNRoutingProtocols', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4ListRouting::GetRoutingProtocol(uint32_t index, int16_t & priority) const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('uint32_t', 'index'), param('int16_t &', 'priority', direction=2)], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): static ns3::TypeId ns3::Ipv4ListRouting::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): bool ns3::Ipv4ListRouting::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void,ns3::Ptr<ns3::Ipv4Route>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4ListRouting::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv4NixVectorRouting_methods(root_module, cls): ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorRouting::Ipv4NixVectorRouting(ns3::Ipv4NixVectorRouting const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4NixVectorRouting const &', 'arg0')]) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorRouting::Ipv4NixVectorRouting() [constructor] cls.add_constructor([]) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::FlushGlobalNixRoutingCache() const [member function] cls.add_method('FlushGlobalNixRoutingCache', 'void', [], is_const=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): static ns3::TypeId ns3::Ipv4NixVectorRouting::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True, visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): bool ns3::Ipv4NixVectorRouting::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void,ns3::Ptr<ns3::Ipv4Route>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4NixVectorRouting::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], visibility='private', is_virtual=True) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def 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()
shravya-ks/ECN-ns3
src/nix-vector-routing/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
390,572
import csv import os from django.core.management.base import NoArgsCommand from django.contrib.gis.geos import Point from ... import models class Command(NoArgsCommand): def handle_noargs(self, *args, **kwargs): with open(os.environ['DATA_FILE']) as f: reader = csv.reader(f) legend = reader.next() for row_values in reader: row = dict(zip(legend, row_values)) month, day, year = row['Orig Date'].split('/') models.Hospital.objects.get_or_create( file_nbr=row['File Nbr'], license_number=row['LIC#'], name=row['Name'], address=row['Selected Address'], city=row['City'], state=row['St'], zipcode=int(row['Zip']), coordinates=Point(float(row['Lng']), float(row['Lat'])), county=row['County'], phone=row['Phone'], status=row['Status'], original_date='%s-%s-%s' % (year, month, day) )
texastribune/tt_hospitals
tt_hospitals/management/commands/tt_hospitals_import.py
Python
apache-2.0
1,137
from macropy.core.macros import * from macropy.core.quotes import macros, ast, u from ast import * def classes_transform(node, gen_sym): @Walker def transform(tree, **k2): if isinstance(tree, ClassDef): self_name = gen_sym() attr_name = gen_sym() value_name = gen_sym() newfunc = FunctionDef(name='__setattr__', args=arguments(args=[Name(id=self_name, ctx=Param()), Name(id=attr_name, ctx=Param()), Name(id=value_name, ctx=Param())], vararg=None, kwarg=None, defaults=[]), decorator_list=[], body=[Assign([Subscript(value=Attribute(value=Name(id=self_name, ctx=Load()), attr='__dict__', ctx=Load()), slice=Index(Name(id=attr_name, ctx=Load())), ctx=Store())], Call(func=Attribute(value=Name(id='JeevesLib', ctx=Load()), attr='jassign', ctx=Load()), args=[Call(func=Attribute(value=Attribute(value=Name(id=self_name), attr='__dict__', ctx=Load()), attr='get', ctx=Load()), args=[Name(id=attr_name), Call(func=Attribute(value=Name(id='JeevesLib', ctx=Load()), attr='Unassigned', ctx=Load()), args=[BinOp(left=Str(s="attribute '%s'"), op=Mod(), right=Name(id=attr_name))], keywords=[], starargs=None, kwargs=None)], keywords=[], starargs=None, kwargs=None), Name(id=value_name)], keywords=[], starargs=None, kwargs=None))]) return copy_location(ClassDef(name=tree.name, bases=tree.bases, body=([newfunc] + tree.body), decorator_list=tree.decorator_list), tree) return transform.recurse(node)
jeanqasaur/jeeves
sourcetrans/classes.py
Python
mit
1,471
from collections import namedtuple import pytest from dockci.models.auth import OAuthToken from dockci.models.project import Project class TestRepoFs(object): """ Test utilization of the ``Project.repo_fs`` field """ @pytest.mark.parametrize( 'repo,github_repo_id,gitlab_repo_id,exp_display,exp_command', [ ( 'http://example.com/should/be/replaced.git', None, 'sprucedev/DockCI', 'http://oauth2:****@localhost:8000/sprucedev/DockCI.git', 'http://oauth2:authkey@localhost:8000/sprucedev/DockCI.git', ), ( 'http://example.com/should/be/replaced.git', 'sprucedev/DockCI', None, 'https://oauth2:****@github.com/sprucedev/DockCI.git', 'https://oauth2:authkey@github.com/sprucedev/DockCI.git', ), ( 'http://example.com/should/clone/this.git', None, None, 'http://example.com/should/clone/this.git', 'http://example.com/should/clone/this.git', ), ] ) def test_fs_outputs(self, mocker, repo, github_repo_id, gitlab_repo_id, exp_display, exp_command, ): """ Ensure that github, gitlab, manual project types are represented correctly with ``display_repo`` and ``command_repo`` """ mocker.patch( 'dockci.models.project.CONFIG', namedtuple('Config', ['gitlab_base_url'])( 'http://localhost:8000' ), ) project = Project( repo=repo, github_repo_id=github_repo_id, gitlab_repo_id=gitlab_repo_id, ) service = None if github_repo_id is not None: service = 'github' elif gitlab_repo_id is not None: service = 'gitlab' if service is not None: project.external_auth_token = OAuthToken( key='authkey', secret='authsecret', service=service, ) assert project.display_repo == exp_display assert project.command_repo == exp_command
sprucedev/DockCI
tests/models/test_project_model.py
Python
isc
2,383