repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
turbokongen/home-assistant
homeassistant/components/vacuum/__init__.py
16
11808
"""Support for vacuum cleaner robots (botvacs).""" from datetime import timedelta from functools import partial import logging import voluptuous as vol from homeassistant.const import ( # noqa: F401 # STATE_PAUSED/IDLE are API ATTR_BATTERY_LEVEL, ATTR_COMMAND, SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_IDLE, STATE_ON, STATE_PAUSED, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import ( # noqa: F401 PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, make_entity_service_schema, ) from homeassistant.helpers.entity import Entity, ToggleEntity from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.icon import icon_for_battery_level from homeassistant.loader import bind_hass # mypy: allow-untyped-defs, no-check-untyped-defs _LOGGER = logging.getLogger(__name__) DOMAIN = "vacuum" SCAN_INTERVAL = timedelta(seconds=20) ATTR_BATTERY_ICON = "battery_icon" ATTR_CLEANED_AREA = "cleaned_area" ATTR_FAN_SPEED = "fan_speed" ATTR_FAN_SPEED_LIST = "fan_speed_list" ATTR_PARAMS = "params" ATTR_STATUS = "status" SERVICE_CLEAN_SPOT = "clean_spot" SERVICE_LOCATE = "locate" SERVICE_RETURN_TO_BASE = "return_to_base" SERVICE_SEND_COMMAND = "send_command" SERVICE_SET_FAN_SPEED = "set_fan_speed" SERVICE_START_PAUSE = "start_pause" SERVICE_START = "start" SERVICE_PAUSE = "pause" SERVICE_STOP = "stop" STATE_CLEANING = "cleaning" STATE_DOCKED = "docked" STATE_RETURNING = "returning" STATE_ERROR = "error" STATES = [STATE_CLEANING, STATE_DOCKED, STATE_RETURNING, STATE_ERROR] DEFAULT_NAME = "Vacuum cleaner robot" SUPPORT_TURN_ON = 1 SUPPORT_TURN_OFF = 2 SUPPORT_PAUSE = 4 SUPPORT_STOP = 8 SUPPORT_RETURN_HOME = 16 SUPPORT_FAN_SPEED = 32 SUPPORT_BATTERY = 64 SUPPORT_STATUS = 128 SUPPORT_SEND_COMMAND = 256 SUPPORT_LOCATE = 512 SUPPORT_CLEAN_SPOT = 1024 SUPPORT_MAP = 2048 SUPPORT_STATE = 4096 SUPPORT_START = 8192 @bind_hass def is_on(hass, entity_id): """Return if the vacuum is on based on the statemachine.""" return hass.states.is_state(entity_id, STATE_ON) async def async_setup(hass, config): """Set up the vacuum component.""" component = hass.data[DOMAIN] = EntityComponent( _LOGGER, DOMAIN, hass, SCAN_INTERVAL ) await component.async_setup(config) component.async_register_entity_service(SERVICE_TURN_ON, {}, "async_turn_on") component.async_register_entity_service(SERVICE_TURN_OFF, {}, "async_turn_off") component.async_register_entity_service(SERVICE_TOGGLE, {}, "async_toggle") component.async_register_entity_service( SERVICE_START_PAUSE, {}, "async_start_pause" ) component.async_register_entity_service(SERVICE_START, {}, "async_start") component.async_register_entity_service(SERVICE_PAUSE, {}, "async_pause") component.async_register_entity_service( SERVICE_RETURN_TO_BASE, {}, "async_return_to_base" ) component.async_register_entity_service(SERVICE_CLEAN_SPOT, {}, "async_clean_spot") component.async_register_entity_service(SERVICE_LOCATE, {}, "async_locate") component.async_register_entity_service(SERVICE_STOP, {}, "async_stop") component.async_register_entity_service( SERVICE_SET_FAN_SPEED, {vol.Required(ATTR_FAN_SPEED): cv.string}, "async_set_fan_speed", ) component.async_register_entity_service( SERVICE_SEND_COMMAND, { vol.Required(ATTR_COMMAND): cv.string, vol.Optional(ATTR_PARAMS): vol.Any(dict, cv.ensure_list), }, "async_send_command", ) return True async def async_setup_entry(hass, entry): """Set up a config entry.""" return await hass.data[DOMAIN].async_setup_entry(entry) async def async_unload_entry(hass, entry): """Unload a config entry.""" return await hass.data[DOMAIN].async_unload_entry(entry) class _BaseVacuum(Entity): """Representation of a base vacuum. Contains common properties and functions for all vacuum devices. """ @property def supported_features(self): """Flag vacuum cleaner features that are supported.""" raise NotImplementedError() @property def battery_level(self): """Return the battery level of the vacuum cleaner.""" return None @property def battery_icon(self): """Return the battery icon for the vacuum cleaner.""" raise NotImplementedError() @property def fan_speed(self): """Return the fan speed of the vacuum cleaner.""" return None @property def fan_speed_list(self): """Get the list of available fan speed steps of the vacuum cleaner.""" raise NotImplementedError() @property def capability_attributes(self): """Return capability attributes.""" if self.supported_features & SUPPORT_FAN_SPEED: return {ATTR_FAN_SPEED_LIST: self.fan_speed_list} @property def state_attributes(self): """Return the state attributes of the vacuum cleaner.""" data = {} if self.supported_features & SUPPORT_BATTERY: data[ATTR_BATTERY_LEVEL] = self.battery_level data[ATTR_BATTERY_ICON] = self.battery_icon if self.supported_features & SUPPORT_FAN_SPEED: data[ATTR_FAN_SPEED] = self.fan_speed return data def stop(self, **kwargs): """Stop the vacuum cleaner.""" raise NotImplementedError() async def async_stop(self, **kwargs): """Stop the vacuum cleaner. This method must be run in the event loop. """ await self.hass.async_add_executor_job(partial(self.stop, **kwargs)) def return_to_base(self, **kwargs): """Set the vacuum cleaner to return to the dock.""" raise NotImplementedError() async def async_return_to_base(self, **kwargs): """Set the vacuum cleaner to return to the dock. This method must be run in the event loop. """ await self.hass.async_add_executor_job(partial(self.return_to_base, **kwargs)) def clean_spot(self, **kwargs): """Perform a spot clean-up.""" raise NotImplementedError() async def async_clean_spot(self, **kwargs): """Perform a spot clean-up. This method must be run in the event loop. """ await self.hass.async_add_executor_job(partial(self.clean_spot, **kwargs)) def locate(self, **kwargs): """Locate the vacuum cleaner.""" raise NotImplementedError() async def async_locate(self, **kwargs): """Locate the vacuum cleaner. This method must be run in the event loop. """ await self.hass.async_add_executor_job(partial(self.locate, **kwargs)) def set_fan_speed(self, fan_speed, **kwargs): """Set fan speed.""" raise NotImplementedError() async def async_set_fan_speed(self, fan_speed, **kwargs): """Set fan speed. This method must be run in the event loop. """ await self.hass.async_add_executor_job( partial(self.set_fan_speed, fan_speed, **kwargs) ) def send_command(self, command, params=None, **kwargs): """Send a command to a vacuum cleaner.""" raise NotImplementedError() async def async_send_command(self, command, params=None, **kwargs): """Send a command to a vacuum cleaner. This method must be run in the event loop. """ await self.hass.async_add_executor_job( partial(self.send_command, command, params=params, **kwargs) ) class VacuumEntity(_BaseVacuum, ToggleEntity): """Representation of a vacuum cleaner robot.""" @property def status(self): """Return the status of the vacuum cleaner.""" return None @property def battery_icon(self): """Return the battery icon for the vacuum cleaner.""" charging = False if self.status is not None: charging = "charg" in self.status.lower() return icon_for_battery_level( battery_level=self.battery_level, charging=charging ) @property def state_attributes(self): """Return the state attributes of the vacuum cleaner.""" data = super().state_attributes if self.supported_features & SUPPORT_STATUS: data[ATTR_STATUS] = self.status return data def turn_on(self, **kwargs): """Turn the vacuum on and start cleaning.""" raise NotImplementedError() async def async_turn_on(self, **kwargs): """Turn the vacuum on and start cleaning. This method must be run in the event loop. """ await self.hass.async_add_executor_job(partial(self.turn_on, **kwargs)) def turn_off(self, **kwargs): """Turn the vacuum off stopping the cleaning and returning home.""" raise NotImplementedError() async def async_turn_off(self, **kwargs): """Turn the vacuum off stopping the cleaning and returning home. This method must be run in the event loop. """ await self.hass.async_add_executor_job(partial(self.turn_off, **kwargs)) def start_pause(self, **kwargs): """Start, pause or resume the cleaning task.""" raise NotImplementedError() async def async_start_pause(self, **kwargs): """Start, pause or resume the cleaning task. This method must be run in the event loop. """ await self.hass.async_add_executor_job(partial(self.start_pause, **kwargs)) async def async_pause(self): """Not supported.""" async def async_start(self): """Not supported.""" class VacuumDevice(VacuumEntity): """Representation of a vacuum (for backwards compatibility).""" def __init_subclass__(cls, **kwargs): """Print deprecation warning.""" super().__init_subclass__(**kwargs) _LOGGER.warning( "VacuumDevice is deprecated, modify %s to extend VacuumEntity", cls.__name__ ) class StateVacuumEntity(_BaseVacuum): """Representation of a vacuum cleaner robot that supports states.""" @property def state(self): """Return the state of the vacuum cleaner.""" return None @property def battery_icon(self): """Return the battery icon for the vacuum cleaner.""" charging = bool(self.state == STATE_DOCKED) return icon_for_battery_level( battery_level=self.battery_level, charging=charging ) def start(self): """Start or resume the cleaning task.""" raise NotImplementedError() async def async_start(self): """Start or resume the cleaning task. This method must be run in the event loop. """ await self.hass.async_add_executor_job(self.start) def pause(self): """Pause the cleaning task.""" raise NotImplementedError() async def async_pause(self): """Pause the cleaning task. This method must be run in the event loop. """ await self.hass.async_add_executor_job(self.pause) async def async_turn_on(self, **kwargs): """Not supported.""" async def async_turn_off(self, **kwargs): """Not supported.""" async def async_toggle(self, **kwargs): """Not supported.""" class StateVacuumDevice(StateVacuumEntity): """Representation of a vacuum (for backwards compatibility).""" def __init_subclass__(cls, **kwargs): """Print deprecation warning.""" super().__init_subclass__(**kwargs) _LOGGER.warning( "StateVacuumDevice is deprecated, modify %s to extend StateVacuumEntity", cls.__name__, )
apache-2.0
srvg/ansible-modules-extras
network/f5/bigip_routedomain.py
32
16675
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2016 F5 Networks Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: bigip_routedomain short_description: Manage route domains on a BIG-IP description: - Manage route domains on a BIG-IP version_added: "2.2" options: bwc_policy: description: - The bandwidth controller for the route domain. connection_limit: description: - The maximum number of concurrent connections allowed for the route domain. Setting this to C(0) turns off connection limits. description: description: - Specifies descriptive text that identifies the route domain. flow_eviction_policy: description: - The eviction policy to use with this route domain. Apply an eviction policy to provide customized responses to flow overflows and slow flows on the route domain. id: description: - The unique identifying integer representing the route domain. required: true parent: description: Specifies the route domain the system searches when it cannot find a route in the configured domain. required: false routing_protocol: description: - Dynamic routing protocols for the system to use in the route domain. choices: - BFD - BGP - IS-IS - OSPFv2 - OSPFv3 - PIM - RIP - RIPng service_policy: description: - Service policy to associate with the route domain. state: description: - Whether the route domain should exist or not. required: false default: present choices: - present - absent strict: description: - Specifies whether the system enforces cross-routing restrictions or not. choices: - enabled - disabled vlans: description: - VLANs for the system to use in the route domain notes: - Requires the f5-sdk Python package on the host. This is as easy as pip install f5-sdk. extends_documentation_fragment: f5 requirements: - f5-sdk author: - Tim Rupp (@caphrim007) ''' EXAMPLES = ''' - name: Create a route domain bigip_routedomain: id: "1234" password: "secret" server: "lb.mydomain.com" state: "present" user: "admin" delegate_to: localhost - name: Set VLANs on the route domain bigip_routedomain: id: "1234" password: "secret" server: "lb.mydomain.com" state: "present" user: "admin" vlans: - net1 - foo delegate_to: localhost ''' RETURN = ''' id: description: The ID of the route domain that was changed returned: changed type: int sample: 2 description: description: The description of the route domain returned: changed type: string sample: "route domain foo" strict: description: The new strict isolation setting returned: changed type: string sample: "enabled" parent: description: The new parent route domain returned: changed type: int sample: 0 vlans: description: List of new VLANs the route domain is applied to returned: changed type: list sample: ['/Common/http-tunnel', '/Common/socks-tunnel'] routing_protocol: description: List of routing protocols applied to the route domain returned: changed type: list sample: ['bfd', 'bgp'] bwc_policy: description: The new bandwidth controller returned: changed type: string sample: /Common/foo connection_limit: description: The new connection limit for the route domain returned: changed type: integer sample: 100 flow_eviction_policy: description: The new eviction policy to use with this route domain returned: changed type: string sample: /Common/default-eviction-policy service_policy: description: The new service policy to use with this route domain returned: changed type: string sample: /Common-my-service-policy ''' try: from f5.bigip import ManagementRoot from icontrol.session import iControlUnexpectedHTTPError HAS_F5SDK = True except ImportError: HAS_F5SDK = False PROTOCOLS = [ 'BFD', 'BGP', 'IS-IS', 'OSPFv2', 'OSPFv3', 'PIM', 'RIP', 'RIPng' ] STRICTS = ['enabled', 'disabled'] class BigIpRouteDomain(object): def __init__(self, *args, **kwargs): if not HAS_F5SDK: raise F5ModuleError("The python f5-sdk module is required") # The params that change in the module self.cparams = dict() kwargs['name'] = str(kwargs['id']) # Stores the params that are sent to the module self.params = kwargs self.api = ManagementRoot(kwargs['server'], kwargs['user'], kwargs['password'], port=kwargs['server_port']) def absent(self): if not self.exists(): return False if self.params['check_mode']: return True rd = self.api.tm.net.route_domains.route_domain.load( name=self.params['name'] ) rd.delete() if self.exists(): raise F5ModuleError("Failed to delete the route domain") else: return True def present(self): if self.exists(): return self.update() else: if self.params['check_mode']: return True return self.create() def read(self): """Read information and transform it The values that are returned by BIG-IP in the f5-sdk can have encoding attached to them as well as be completely missing in some cases. Therefore, this method will transform the data from the BIG-IP into a format that is more easily consumable by the rest of the class and the parameters that are supported by the module. """ p = dict() r = self.api.tm.net.route_domains.route_domain.load( name=self.params['name'] ) p['id'] = int(r.id) p['name'] = str(r.name) if hasattr(r, 'connectionLimit'): p['connection_limit'] = int(r.connectionLimit) if hasattr(r, 'description'): p['description'] = str(r.description) if hasattr(r, 'strict'): p['strict'] = str(r.strict) if hasattr(r, 'parent'): p['parent'] = r.parent if hasattr(r, 'vlans'): p['vlans'] = list(set([str(x) for x in r.vlans])) if hasattr(r, 'routingProtocol'): p['routing_protocol'] = list(set([str(x) for x in r.routingProtocol])) if hasattr(r, 'flowEvictionPolicy'): p['flow_eviction_policy'] = str(r.flowEvictionPolicy) if hasattr(r, 'bwcPolicy'): p['bwc_policy'] = str(r.bwcPolicy) if hasattr(r, 'servicePolicy'): p['service_policy'] = str(r.servicePolicy) return p def domains(self): result = [] domains = self.api.tm.net.route_domains.get_collection() for domain in domains: # Just checking for the addition of the partition here for # different versions of BIG-IP if '/' + self.params['partition'] + '/' in domain.name: result.append(domain.name) else: full_name = '/%s/%s' % (self.params['partition'], domain.name) result.append(full_name) return result def create(self): params = dict() params['id'] = self.params['id'] params['name'] = self.params['name'] partition = self.params['partition'] description = self.params['description'] strict = self.params['strict'] parent = self.params['parent'] bwc_policy = self.params['bwc_policy'] vlans = self.params['vlans'] routing_protocol = self.params['routing_protocol'] connection_limit = self.params['connection_limit'] flow_eviction_policy = self.params['flow_eviction_policy'] service_policy = self.params['service_policy'] if description is not None: params['description'] = description if strict is not None: params['strict'] = strict if parent is not None: parent = '/%s/%s' % (partition, parent) if parent in self.domains(): params['parent'] = parent else: raise F5ModuleError( "The parent route domain was not found" ) if bwc_policy is not None: policy = '/%s/%s' % (partition, bwc_policy) params['bwcPolicy'] = policy if vlans is not None: params['vlans'] = [] for vlan in vlans: vname = '/%s/%s' % (partition, vlan) params['vlans'].append(vname) if routing_protocol is not None: params['routingProtocol'] = [] for protocol in routing_protocol: if protocol in PROTOCOLS: params['routingProtocol'].append(protocol) else: raise F5ModuleError( "routing_protocol must be one of: %s" % (PROTOCOLS) ) if connection_limit is not None: params['connectionLimit'] = connection_limit if flow_eviction_policy is not None: policy = '/%s/%s' % (partition, flow_eviction_policy) params['flowEvictionPolicy'] = policy if service_policy is not None: policy = '/%s/%s' % (partition, service_policy) params['servicePolicy'] = policy self.api.tm.net.route_domains.route_domain.create(**params) exists = self.api.tm.net.route_domains.route_domain.exists( name=self.params['name'] ) if exists: return True else: raise F5ModuleError( "An error occurred while creating the route domain" ) def update(self): changed = False params = dict() current = self.read() check_mode = self.params['check_mode'] partition = self.params['partition'] description = self.params['description'] strict = self.params['strict'] parent = self.params['parent'] bwc_policy = self.params['bwc_policy'] vlans = self.params['vlans'] routing_protocol = self.params['routing_protocol'] connection_limit = self.params['connection_limit'] flow_eviction_policy = self.params['flow_eviction_policy'] service_policy = self.params['service_policy'] if description is not None: if 'description' in current: if description != current['description']: params['description'] = description else: params['description'] = description if strict is not None: if strict != current['strict']: params['strict'] = strict if parent is not None: parent = '/%s/%s' % (partition, parent) if 'parent' in current: if parent != current['parent']: params['parent'] = parent else: params['parent'] = parent if bwc_policy is not None: policy = '/%s/%s' % (partition, bwc_policy) if 'bwc_policy' in current: if policy != current['bwc_policy']: params['bwcPolicy'] = policy else: params['bwcPolicy'] = policy if vlans is not None: tmp = set() for vlan in vlans: vname = '/%s/%s' % (partition, vlan) tmp.add(vname) tmp = list(tmp) if 'vlans' in current: if tmp != current['vlans']: params['vlans'] = tmp else: params['vlans'] = tmp if routing_protocol is not None: tmp = set() for protocol in routing_protocol: if protocol in PROTOCOLS: tmp.add(protocol) else: raise F5ModuleError( "routing_protocol must be one of: %s" % (PROTOCOLS) ) tmp = list(tmp) if 'routing_protocol' in current: if tmp != current['routing_protocol']: params['routingProtocol'] = tmp else: params['routingProtocol'] = tmp if connection_limit is not None: if connection_limit != current['connection_limit']: params['connectionLimit'] = connection_limit if flow_eviction_policy is not None: policy = '/%s/%s' % (partition, flow_eviction_policy) if 'flow_eviction_policy' in current: if policy != current['flow_eviction_policy']: params['flowEvictionPolicy'] = policy else: params['flowEvictionPolicy'] = policy if service_policy is not None: policy = '/%s/%s' % (partition, service_policy) if 'service_policy' in current: if policy != current['service_policy']: params['servicePolicy'] = policy else: params['servicePolicy'] = policy if params: changed = True self.cparams = camel_dict_to_snake_dict(params) if check_mode: return changed else: return changed try: rd = self.api.tm.net.route_domains.route_domain.load( name=self.params['name'] ) rd.update(**params) rd.refresh() except iControlUnexpectedHTTPError as e: raise F5ModuleError(e) return True def exists(self): return self.api.tm.net.route_domains.route_domain.exists( name=self.params['name'] ) def flush(self): result = dict() state = self.params['state'] if self.params['check_mode']: if value == current: changed = False else: changed = True else: if state == "present": changed = self.present() current = self.read() result.update(current) elif state == "absent": changed = self.absent() result.update(dict(changed=changed)) return result def main(): argument_spec = f5_argument_spec() meta_args = dict( id=dict(required=True, type='int'), description=dict(required=False, default=None), strict=dict(required=False, default=None, choices=STRICTS), parent=dict(required=False, type='int', default=None), vlans=dict(required=False, default=None, type='list'), routing_protocol=dict(required=False, default=None, type='list'), bwc_policy=dict(required=False, type='str', default=None), connection_limit=dict(required=False, type='int', default=None), flow_eviction_policy=dict(required=False, type='str', default=None), service_policy=dict(required=False, type='str', default=None) ) argument_spec.update(meta_args) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) try: obj = BigIpRouteDomain(check_mode=module.check_mode, **module.params) result = obj.flush() module.exit_json(**result) except F5ModuleError as e: module.fail_json(msg=str(e)) from ansible.module_utils.basic import * from ansible.module_utils.ec2 import camel_dict_to_snake_dict from ansible.module_utils.f5 import * if __name__ == '__main__': main()
gpl-3.0
robbiet480/home-assistant
tests/components/homekit_controller/specific_devices/test_ecobee_occupancy.py
7
1323
""" Regression tests for Ecobee occupancy. https://github.com/home-assistant/home-assistant/issues/31827 """ from tests.components.homekit_controller.common import ( Helper, setup_accessories_from_file, setup_test_accessories, ) async def test_ecobee_occupancy_setup(hass): """Test that an Ecbobee occupancy sensor be correctly setup in HA.""" accessories = await setup_accessories_from_file(hass, "ecobee_occupancy.json") config_entry, pairing = await setup_test_accessories(hass, accessories) entity_registry = await hass.helpers.entity_registry.async_get_registry() sensor = entity_registry.async_get("binary_sensor.master_fan") assert sensor.unique_id == "homekit-111111111111-56" sensor_helper = Helper( hass, "binary_sensor.master_fan", pairing, accessories[0], config_entry ) sensor_state = await sensor_helper.poll_and_get_state() assert sensor_state.attributes["friendly_name"] == "Master Fan" device_registry = await hass.helpers.device_registry.async_get_registry() device = device_registry.async_get(sensor.device_id) assert device.manufacturer == "ecobee Inc." assert device.name == "Master Fan" assert device.model == "ecobee Switch+" assert device.sw_version == "4.5.130201" assert device.via_device_id is None
apache-2.0
citrix-openstack-build/heat
heat/tests/test_vpc.py
5
28455
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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 testtools import skipIf from heat.common import exception from heat.common import template_format from heat.engine import parser from heat.engine import clients from heat.engine import resource from heat.engine import scheduler from heat.tests.common import HeatTestCase from heat.tests import fakes from heat.tests import utils try: from neutronclient.common.exceptions import NeutronClientException from neutronclient.v2_0 import client as neutronclient except ImportError: neutronclient = None class VPCTestBase(HeatTestCase): @skipIf(neutronclient is None, 'neutronclient unavaialble') def setUp(self): super(VPCTestBase, self).setUp() utils.setup_dummy_db() self.m.StubOutWithMock(neutronclient.Client, 'add_interface_router') self.m.StubOutWithMock(neutronclient.Client, 'add_gateway_router') self.m.StubOutWithMock(neutronclient.Client, 'create_network') self.m.StubOutWithMock(neutronclient.Client, 'create_port') self.m.StubOutWithMock(neutronclient.Client, 'create_router') self.m.StubOutWithMock(neutronclient.Client, 'create_subnet') self.m.StubOutWithMock(neutronclient.Client, 'delete_network') self.m.StubOutWithMock(neutronclient.Client, 'delete_port') self.m.StubOutWithMock(neutronclient.Client, 'delete_router') self.m.StubOutWithMock(neutronclient.Client, 'delete_subnet') self.m.StubOutWithMock(neutronclient.Client, 'list_networks') self.m.StubOutWithMock(neutronclient.Client, 'list_routers') self.m.StubOutWithMock(neutronclient.Client, 'remove_gateway_router') self.m.StubOutWithMock(neutronclient.Client, 'remove_interface_router') self.m.StubOutWithMock(neutronclient.Client, 'show_subnet') self.m.StubOutWithMock(neutronclient.Client, 'show_network') self.m.StubOutWithMock(neutronclient.Client, 'show_router') self.m.StubOutWithMock(neutronclient.Client, 'create_security_group') self.m.StubOutWithMock(neutronclient.Client, 'show_security_group') self.m.StubOutWithMock(neutronclient.Client, 'delete_security_group') self.m.StubOutWithMock( neutronclient.Client, 'create_security_group_rule') self.m.StubOutWithMock( neutronclient.Client, 'delete_security_group_rule') self.m.StubOutWithMock(clients.OpenStackClients, 'keystone') def create_stack(self, template): t = template_format.parse(template) stack = self.parse_stack(t) self.assertEqual(None, stack.create()) return stack def parse_stack(self, t): stack_name = 'test_stack' tmpl = parser.Template(t) stack = parser.Stack(utils.dummy_context(), stack_name, tmpl) stack.store() return stack def mock_keystone(self): clients.OpenStackClients.keystone().AndReturn( fakes.FakeKeystoneClient()) def mock_create_network(self): self.vpc_name = utils.PhysName('test_stack', 'the_vpc') neutronclient.Client.create_network( { 'network': {'name': self.vpc_name} }).AndReturn({'network': { 'status': 'BUILD', 'subnets': [], 'name': 'name', 'admin_state_up': True, 'shared': False, 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'id': 'aaaa' }}) neutronclient.Client.show_network( 'aaaa' ).AndReturn({"network": { "status": "BUILD", "subnets": [], "name": self.vpc_name, "admin_state_up": False, "shared": False, "tenant_id": "c1210485b2424d48804aad5d39c61b8f", "id": "aaaa" }}) neutronclient.Client.show_network( 'aaaa' ).MultipleTimes().AndReturn({"network": { "status": "ACTIVE", "subnets": [], "name": self.vpc_name, "admin_state_up": False, "shared": False, "tenant_id": "c1210485b2424d48804aad5d39c61b8f", "id": "aaaa" }}) neutronclient.Client.create_router( {'router': {'name': self.vpc_name}}).AndReturn({ 'router': { 'status': 'BUILD', 'name': self.vpc_name, 'admin_state_up': True, 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'id': 'bbbb' }}) neutronclient.Client.list_routers(name=self.vpc_name).AndReturn({ "routers": [{ "status": "BUILD", "external_gateway_info": None, "name": self.vpc_name, "admin_state_up": True, "tenant_id": "3e21026f2dc94372b105808c0e721661", "routes": [], "id": "bbbb" }] }) self.mock_router_for_vpc() def mock_create_subnet(self): self.subnet_name = utils.PhysName('test_stack', 'the_subnet') neutronclient.Client.create_subnet( {'subnet': { 'network_id': u'aaaa', 'cidr': u'10.0.0.0/24', 'ip_version': 4, 'name': self.subnet_name}}).AndReturn({ 'subnet': { 'status': 'ACTIVE', 'name': self.subnet_name, 'admin_state_up': True, 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'id': 'cccc'}}) self.mock_router_for_vpc() neutronclient.Client.add_interface_router( u'bbbb', {'subnet_id': 'cccc'}).AndReturn(None) def mock_show_subnet(self): neutronclient.Client.show_subnet('cccc').AndReturn({ 'subnet': { 'name': self.subnet_name, 'network_id': 'aaaa', 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'allocation_pools': [{'start': '10.0.0.2', 'end': '10.0.0.254'}], 'gateway_ip': '10.0.0.1', 'ip_version': 4, 'cidr': '10.0.0.0/24', 'id': 'cccc', 'enable_dhcp': False, }}) def mock_create_security_group(self): self.sg_name = utils.PhysName('test_stack', 'the_sg') neutronclient.Client.create_security_group({ 'security_group': { 'name': self.sg_name, 'description': 'SSH access' } }).AndReturn({ 'security_group': { 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'name': self.sg_name, 'description': 'SSH access', 'security_group_rules': [], 'id': 'eeee' } }) neutronclient.Client.create_security_group_rule({ 'security_group_rule': { 'direction': 'ingress', 'remote_group_id': None, 'remote_ip_prefix': '0.0.0.0/0', 'port_range_min': '22', 'ethertype': 'IPv4', 'port_range_max': '22', 'protocol': 'tcp', 'security_group_id': 'eeee' } }).AndReturn({ 'security_group_rule': { 'direction': 'ingress', 'remote_group_id': None, 'remote_ip_prefix': '0.0.0.0/0', 'port_range_min': '22', 'ethertype': 'IPv4', 'port_range_max': '22', 'protocol': 'tcp', 'security_group_id': 'eeee', 'id': 'bbbb' } }) def mock_show_security_group(self, group='eeee'): sg_name = utils.PhysName('test_stack', 'the_sg') if group == 'eeee': neutronclient.Client.show_security_group(group).AndReturn({ 'security_group': { 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'name': sg_name, 'description': '', 'security_group_rules': [{ 'direction': 'ingress', 'protocol': 'tcp', 'port_range_max': '22', 'id': 'bbbb', 'ethertype': 'IPv4', 'security_group_id': 'eeee', 'remote_group_id': None, 'remote_ip_prefix': '0.0.0.0/0', 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'port_range_min': '22' }], 'id': 'eeee'}}) elif group == 'INVALID-NO-REF': neutronclient.Client.show_security_group(group).AndRaise( NeutronClientException(status_code=404)) elif group == 'RaiseException': neutronclient.Client.show_security_group('eeee').AndRaise( NeutronClientException(status_code=403)) def mock_delete_security_group(self): self.mock_show_security_group() neutronclient.Client.delete_security_group_rule('bbbb').AndReturn(None) neutronclient.Client.delete_security_group('eeee').AndReturn(None) def mock_router_for_vpc(self): neutronclient.Client.list_routers(name=self.vpc_name).AndReturn({ "routers": [{ "status": "ACTIVE", "external_gateway_info": { "network_id": "zzzz", "enable_snat": True}, "name": self.vpc_name, "admin_state_up": True, "tenant_id": "3e21026f2dc94372b105808c0e721661", "routes": [], "id": "bbbb" }] }) def mock_delete_network(self): self.mock_router_for_vpc() neutronclient.Client.delete_router('bbbb').AndReturn(None) neutronclient.Client.delete_network('aaaa').AndReturn(None) def mock_delete_subnet(self): self.mock_router_for_vpc() neutronclient.Client.remove_interface_router( u'bbbb', {'subnet_id': 'cccc'}).AndReturn(None) neutronclient.Client.delete_subnet('cccc').AndReturn(None) def mock_create_route_table(self): self.rt_name = utils.PhysName('test_stack', 'the_route_table') neutronclient.Client.create_router({ 'router': {'name': self.rt_name}}).AndReturn({ 'router': { 'status': 'BUILD', 'name': self.rt_name, 'admin_state_up': True, 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'id': 'ffff' } }) neutronclient.Client.show_router('ffff').AndReturn({ 'router': { 'status': 'BUILD', 'name': self.rt_name, 'admin_state_up': True, 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'id': 'ffff' } }) neutronclient.Client.show_router('ffff').AndReturn({ 'router': { 'status': 'ACTIVE', 'name': self.rt_name, 'admin_state_up': True, 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'id': 'ffff' } }) self.mock_router_for_vpc() neutronclient.Client.add_gateway_router( 'ffff', {'network_id': 'zzzz'}).AndReturn(None) def mock_create_association(self): self.mock_show_subnet() self.mock_router_for_vpc() neutronclient.Client.remove_interface_router( 'bbbb', {'subnet_id': u'cccc'}).AndReturn(None) neutronclient.Client.add_interface_router( u'ffff', {'subnet_id': 'cccc'}).AndReturn(None) def mock_delete_association(self): self.mock_show_subnet() self.mock_router_for_vpc() neutronclient.Client.remove_interface_router( 'ffff', {'subnet_id': u'cccc'}).AndReturn(None) neutronclient.Client.add_interface_router( u'bbbb', {'subnet_id': 'cccc'}).AndReturn(None) def mock_delete_route_table(self): neutronclient.Client.delete_router('ffff').AndReturn(None) neutronclient.Client.remove_gateway_router('ffff').AndReturn(None) def assertResourceState(self, resource, ref_id): self.assertEqual(None, resource.validate()) self.assertEqual((resource.CREATE, resource.COMPLETE), resource.state) self.assertEqual(ref_id, resource.FnGetRefId()) def mock_rsrc_by_refid(self, sg): parser.Stack.resource_by_refid(sg).AndReturn(None) class VPCTest(VPCTestBase): test_template = ''' HeatTemplateFormatVersion: '2012-12-12' Resources: the_vpc: Type: AWS::EC2::VPC Properties: {CidrBlock: '10.0.0.0/16'} ''' def test_vpc(self): self.mock_keystone() self.mock_create_network() self.mock_delete_network() self.m.ReplayAll() stack = self.create_stack(self.test_template) vpc = stack['the_vpc'] self.assertResourceState(vpc, 'aaaa') self.assertRaises(resource.UpdateReplace, vpc.handle_update, {}, {}, {}) scheduler.TaskRunner(vpc.delete)() self.m.VerifyAll() class SubnetTest(VPCTestBase): test_template = ''' HeatTemplateFormatVersion: '2012-12-12' Resources: the_vpc: Type: AWS::EC2::VPC Properties: {CidrBlock: '10.0.0.0/16'} the_subnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/24 VpcId: {Ref: the_vpc} AvailabilityZone: moon ''' def test_subnet(self): self.mock_keystone() self.mock_create_network() self.mock_create_subnet() self.mock_delete_subnet() self.mock_delete_network() # mock delete subnet which is already deleted self.mock_router_for_vpc() neutronclient.Client.remove_interface_router( u'bbbb', {'subnet_id': 'cccc'}).AndRaise( NeutronClientException(status_code=404)) neutronclient.Client.delete_subnet('cccc').AndRaise( NeutronClientException(status_code=404)) self.m.ReplayAll() stack = self.create_stack(self.test_template) subnet = stack['the_subnet'] self.assertResourceState(subnet, 'cccc') self.assertRaises(resource.UpdateReplace, subnet.handle_update, {}, {}, {}) self.assertRaises( exception.InvalidTemplateAttribute, subnet.FnGetAtt, 'Foo') self.assertEqual('moon', subnet.FnGetAtt('AvailabilityZone')) scheduler.TaskRunner(subnet.delete)() subnet.state_set(subnet.CREATE, subnet.COMPLETE, 'to delete again') scheduler.TaskRunner(subnet.delete)() scheduler.TaskRunner(stack['the_vpc'].delete)() self.m.VerifyAll() class NetworkInterfaceTest(VPCTestBase): test_template = ''' HeatTemplateFormatVersion: '2012-12-12' Resources: the_sg: Type: AWS::EC2::SecurityGroup Properties: VpcId: {Ref: the_vpc} GroupDescription: SSH access SecurityGroupIngress: - IpProtocol: tcp FromPort: "22" ToPort: "22" CidrIp: 0.0.0.0/0 the_vpc: Type: AWS::EC2::VPC Properties: {CidrBlock: '10.0.0.0/16'} the_subnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/24 VpcId: {Ref: the_vpc} AvailabilityZone: moon the_nic: Type: AWS::EC2::NetworkInterface Properties: PrivateIpAddress: 10.0.0.100 SubnetId: {Ref: the_subnet} GroupSet: - Ref: the_sg ''' test_template_no_groupset = ''' HeatTemplateFormatVersion: '2012-12-12' Resources: the_vpc: Type: AWS::EC2::VPC Properties: {CidrBlock: '10.0.0.0/16'} the_subnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/24 VpcId: {Ref: the_vpc} AvailabilityZone: moon the_nic: Type: AWS::EC2::NetworkInterface Properties: PrivateIpAddress: 10.0.0.100 SubnetId: {Ref: the_subnet} ''' test_template_error = ''' HeatTemplateFormatVersion: '2012-12-12' Resources: the_sg: Type: AWS::EC2::SecurityGroup Properties: VpcId: {Ref: the_vpc} GroupDescription: SSH access SecurityGroupIngress: - IpProtocol: tcp FromPort: "22" ToPort: "22" CidrIp: 0.0.0.0/0 the_vpc: Type: AWS::EC2::VPC Properties: {CidrBlock: '10.0.0.0/16'} the_subnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/24 VpcId: {Ref: the_vpc} AvailabilityZone: moon the_nic: Type: AWS::EC2::NetworkInterface Properties: PrivateIpAddress: 10.0.0.100 SubnetId: {Ref: the_subnet} GroupSet: - Ref: INVALID-REF-IN-TEMPLATE ''' test_template_error_no_ref = ''' HeatTemplateFormatVersion: '2012-12-12' Resources: the_vpc: Type: AWS::EC2::VPC Properties: {CidrBlock: '10.0.0.0/16'} the_subnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/24 VpcId: {Ref: the_vpc} AvailabilityZone: moon the_nic: Type: AWS::EC2::NetworkInterface Properties: PrivateIpAddress: 10.0.0.100 SubnetId: {Ref: the_subnet} GroupSet: - INVALID-NO-REF ''' def mock_create_network_interface(self, security_groups=['eeee']): self.nic_name = utils.PhysName('test_stack', 'the_nic') port = {'network_id': 'aaaa', 'fixed_ips': [{ 'subnet_id': u'cccc', 'ip_address': u'10.0.0.100' }], 'name': self.nic_name, 'admin_state_up': True} if security_groups: port['security_groups'] = security_groups neutronclient.Client.create_port({'port': port}).AndReturn({ 'port': { 'admin_state_up': True, 'device_id': '', 'device_owner': '', 'fixed_ips': [ { 'ip_address': '10.0.0.100', 'subnet_id': 'cccc' } ], 'id': 'dddd', 'mac_address': 'fa:16:3e:25:32:5d', 'name': self.nic_name, 'network_id': 'aaaa', 'status': 'ACTIVE', 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f' } }) def mock_delete_network_interface(self): neutronclient.Client.delete_port('dddd').AndReturn(None) def test_network_interface(self): self.mock_keystone() self.mock_create_security_group() self.mock_create_network() self.mock_create_subnet() self.mock_show_subnet() self.mock_create_network_interface() self.mock_delete_network_interface() self.mock_delete_subnet() self.mock_delete_network() self.mock_delete_security_group() self.m.ReplayAll() stack = self.create_stack(self.test_template) try: self.assertEqual((stack.CREATE, stack.COMPLETE), stack.state) rsrc = stack['the_nic'] self.assertResourceState(rsrc, 'dddd') self.assertRaises(resource.UpdateReplace, rsrc.handle_update, {}, {}, {}) finally: scheduler.TaskRunner(stack.delete)() self.m.VerifyAll() def test_network_interface_existing_groupset(self): self.m.StubOutWithMock(parser.Stack, 'resource_by_refid') self.mock_rsrc_by_refid(sg='eeee') self.mock_keystone() self.mock_create_security_group() self.mock_create_network() self.mock_create_subnet() self.mock_show_subnet() self.mock_create_network_interface() self.mock_show_security_group() self.mock_delete_network_interface() self.mock_delete_subnet() self.mock_delete_network() self.mock_delete_security_group() self.m.ReplayAll() stack = self.create_stack(self.test_template) try: self.assertEqual((stack.CREATE, stack.COMPLETE), stack.state) rsrc = stack['the_nic'] self.assertResourceState(rsrc, 'dddd') self.assertRaises(resource.UpdateReplace, rsrc.handle_update, {}, {}, {}) finally: stack.delete() self.m.VerifyAll() def test_network_interface_no_groupset(self): self.mock_keystone() self.mock_create_network() self.mock_create_subnet() self.mock_show_subnet() self.mock_create_network_interface(security_groups=None) self.mock_delete_network_interface() self.mock_delete_subnet() self.mock_delete_network() self.m.ReplayAll() stack = self.create_stack(self.test_template_no_groupset) stack.delete() self.m.VerifyAll() def test_network_interface_exception(self): self.m.StubOutWithMock(parser.Stack, 'resource_by_refid') self.mock_rsrc_by_refid(sg='eeee') self.mock_keystone() self.mock_create_security_group() self.mock_create_network() self.mock_create_subnet() self.mock_show_subnet() self.mock_show_security_group(group='RaiseException') self.m.ReplayAll() try: stack = self.create_stack(self.test_template) rsrc = stack['the_nic'] self.assertEqual((rsrc.CREATE, rsrc.FAILED), rsrc.state) reason = rsrc.status_reason self.assertTrue(reason.startswith('NeutronClientException:')) finally: stack.delete() self.m.VerifyAll() def test_network_interface_error(self): real_exception = self.assertRaises( exception.InvalidTemplateReference, self.create_stack, self.test_template_error) expected_exception = exception.InvalidTemplateReference( resource='INVALID-REF-IN-TEMPLATE', key='the_nic.Properties.GroupSet[0]') self.assertEqual(str(expected_exception), str(real_exception)) def test_network_interface_error_no_ref(self): self.mock_keystone() self.mock_create_network() self.mock_create_subnet() self.mock_show_subnet() self.mock_show_security_group(group='INVALID-NO-REF') self.mock_delete_subnet() neutronclient.Client.delete_port(None).AndReturn(None) self.mock_delete_network() self.m.ReplayAll() stack = self.create_stack(self.test_template_error_no_ref) try: self.assertEqual((stack.CREATE, stack.FAILED), stack.state) rsrc = stack['the_nic'] self.assertEqual((rsrc.CREATE, rsrc.FAILED), rsrc.state) reason = rsrc.status_reason self.assertTrue(reason.startswith('InvalidTemplateAttribute:')) finally: scheduler.TaskRunner(stack.delete)() self.m.VerifyAll() class InternetGatewayTest(VPCTestBase): test_template = ''' HeatTemplateFormatVersion: '2012-12-12' Resources: the_gateway: Type: AWS::EC2::InternetGateway the_vpc: Type: AWS::EC2::VPC Properties: CidrBlock: '10.0.0.0/16' the_subnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/24 VpcId: {Ref: the_vpc} AvailabilityZone: moon the_attachment: Type: AWS::EC2::VPCGatewayAttachment Properties: VpcId: {Ref: the_vpc} InternetGatewayId: {Ref: the_gateway} the_route_table: Type: AWS::EC2::RouteTable Properties: VpcId: {Ref: the_vpc} the_association: Type: AWS::EC2::SubnetRouteTableAssocation Properties: RouteTableId: {Ref: the_route_table} SubnetId: {Ref: the_subnet} ''' def mock_create_internet_gateway(self): neutronclient.Client.list_networks( **{'router:external': True}).AndReturn({'networks': [{ 'status': 'ACTIVE', 'subnets': [], 'name': 'nova', 'router:external': True, 'tenant_id': 'c1210485b2424d48804aad5d39c61b8f', 'admin_state_up': True, 'shared': True, 'id': 'eeee' }]}) def mock_create_gateway_attachment(self): neutronclient.Client.add_gateway_router( 'ffff', {'network_id': 'eeee'}).AndReturn(None) def mock_delete_gateway_attachment(self): neutronclient.Client.remove_gateway_router('ffff').AndReturn(None) def test_internet_gateway(self): self.mock_keystone() self.mock_create_internet_gateway() self.mock_create_network() self.mock_create_subnet() self.mock_create_route_table() self.mock_create_association() self.mock_create_gateway_attachment() self.mock_delete_gateway_attachment() self.mock_delete_association() self.mock_delete_route_table() self.mock_delete_subnet() self.mock_delete_network() self.m.ReplayAll() stack = self.create_stack(self.test_template) gateway = stack['the_gateway'] self.assertResourceState(gateway, gateway.physical_resource_name()) self.assertRaises(resource.UpdateReplace, gateway.handle_update, {}, {}, {}) attachment = stack['the_attachment'] self.assertResourceState(attachment, 'the_attachment') self.assertRaises(resource.UpdateReplace, attachment.handle_update, {}, {}, {}) route_table = stack['the_route_table'] self.assertEqual([route_table], list(attachment._vpc_route_tables())) stack.delete() self.m.VerifyAll() class RouteTableTest(VPCTestBase): test_template = ''' HeatTemplateFormatVersion: '2012-12-12' Resources: the_vpc: Type: AWS::EC2::VPC Properties: CidrBlock: '10.0.0.0/16' the_subnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/24 VpcId: {Ref: the_vpc} AvailabilityZone: moon the_route_table: Type: AWS::EC2::RouteTable Properties: VpcId: {Ref: the_vpc} the_association: Type: AWS::EC2::SubnetRouteTableAssocation Properties: RouteTableId: {Ref: the_route_table} SubnetId: {Ref: the_subnet} ''' def test_route_table(self): self.mock_keystone() self.mock_create_network() self.mock_create_subnet() self.mock_create_route_table() self.mock_create_association() self.mock_delete_association() self.mock_delete_route_table() self.mock_delete_subnet() self.mock_delete_network() self.m.ReplayAll() stack = self.create_stack(self.test_template) route_table = stack['the_route_table'] self.assertResourceState(route_table, 'ffff') self.assertRaises( resource.UpdateReplace, route_table.handle_update, {}, {}, {}) association = stack['the_association'] self.assertResourceState(association, 'the_association') self.assertRaises( resource.UpdateReplace, association.handle_update, {}, {}, {}) scheduler.TaskRunner(association.delete)() scheduler.TaskRunner(route_table.delete)() stack.delete() self.m.VerifyAll()
apache-2.0
0Chencc/CTFCrackTools
Lib/Lib/xmllib.py
227
34865
"""A parser for XML, using the derived class as static DTD.""" # Author: Sjoerd Mullender. import re import string import warnings warnings.warn("The xmllib module is obsolete. Use xml.sax instead.", DeprecationWarning, 2) del warnings version = '0.3' class Error(RuntimeError): pass # Regular expressions used for parsing _S = '[ \t\r\n]+' # white space _opS = '[ \t\r\n]*' # optional white space _Name = '[a-zA-Z_:][-a-zA-Z0-9._:]*' # valid XML name _QStr = "(?:'[^']*'|\"[^\"]*\")" # quoted XML string illegal = re.compile('[^\t\r\n -\176\240-\377]') # illegal chars in content interesting = re.compile('[]&<]') amp = re.compile('&') ref = re.compile('&(' + _Name + '|#[0-9]+|#x[0-9a-fA-F]+)[^-a-zA-Z0-9._:]') entityref = re.compile('&(?P<name>' + _Name + ')[^-a-zA-Z0-9._:]') charref = re.compile('&#(?P<char>[0-9]+[^0-9]|x[0-9a-fA-F]+[^0-9a-fA-F])') space = re.compile(_S + '$') newline = re.compile('\n') attrfind = re.compile( _S + '(?P<name>' + _Name + ')' '(' + _opS + '=' + _opS + '(?P<value>'+_QStr+'|[-a-zA-Z0-9.:+*%?!\(\)_#=~]+))?') starttagopen = re.compile('<' + _Name) starttagend = re.compile(_opS + '(?P<slash>/?)>') starttagmatch = re.compile('<(?P<tagname>'+_Name+')' '(?P<attrs>(?:'+attrfind.pattern+')*)'+ starttagend.pattern) endtagopen = re.compile('</') endbracket = re.compile(_opS + '>') endbracketfind = re.compile('(?:[^>\'"]|'+_QStr+')*>') tagfind = re.compile(_Name) cdataopen = re.compile(r'<!\[CDATA\[') cdataclose = re.compile(r'\]\]>') # this matches one of the following: # SYSTEM SystemLiteral # PUBLIC PubidLiteral SystemLiteral _SystemLiteral = '(?P<%s>'+_QStr+')' _PublicLiteral = '(?P<%s>"[-\'\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*"|' \ "'[-\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*')" _ExternalId = '(?:SYSTEM|' \ 'PUBLIC'+_S+_PublicLiteral%'pubid'+ \ ')'+_S+_SystemLiteral%'syslit' doctype = re.compile('<!DOCTYPE'+_S+'(?P<name>'+_Name+')' '(?:'+_S+_ExternalId+')?'+_opS) xmldecl = re.compile('<\?xml'+_S+ 'version'+_opS+'='+_opS+'(?P<version>'+_QStr+')'+ '(?:'+_S+'encoding'+_opS+'='+_opS+ "(?P<encoding>'[A-Za-z][-A-Za-z0-9._]*'|" '"[A-Za-z][-A-Za-z0-9._]*"))?' '(?:'+_S+'standalone'+_opS+'='+_opS+ '(?P<standalone>\'(?:yes|no)\'|"(?:yes|no)"))?'+ _opS+'\?>') procopen = re.compile(r'<\?(?P<proc>' + _Name + ')' + _opS) procclose = re.compile(_opS + r'\?>') commentopen = re.compile('<!--') commentclose = re.compile('-->') doubledash = re.compile('--') attrtrans = string.maketrans(' \r\n\t', ' ') # definitions for XML namespaces _NCName = '[a-zA-Z_][-a-zA-Z0-9._]*' # XML Name, minus the ":" ncname = re.compile(_NCName + '$') qname = re.compile('(?:(?P<prefix>' + _NCName + '):)?' # optional prefix '(?P<local>' + _NCName + ')$') xmlns = re.compile('xmlns(?::(?P<ncname>'+_NCName+'))?$') # XML parser base class -- find tags and call handler functions. # Usage: p = XMLParser(); p.feed(data); ...; p.close(). # The dtd is defined by deriving a class which defines methods with # special names to handle tags: start_foo and end_foo to handle <foo> # and </foo>, respectively. The data between tags is passed to the # parser by calling self.handle_data() with some data as argument (the # data may be split up in arbitrary chunks). class XMLParser: attributes = {} # default, to be overridden elements = {} # default, to be overridden # parsing options, settable using keyword args in __init__ __accept_unquoted_attributes = 0 __accept_missing_endtag_name = 0 __map_case = 0 __accept_utf8 = 0 __translate_attribute_references = 1 # Interface -- initialize and reset this instance def __init__(self, **kw): self.__fixed = 0 if 'accept_unquoted_attributes' in kw: self.__accept_unquoted_attributes = kw['accept_unquoted_attributes'] if 'accept_missing_endtag_name' in kw: self.__accept_missing_endtag_name = kw['accept_missing_endtag_name'] if 'map_case' in kw: self.__map_case = kw['map_case'] if 'accept_utf8' in kw: self.__accept_utf8 = kw['accept_utf8'] if 'translate_attribute_references' in kw: self.__translate_attribute_references = kw['translate_attribute_references'] self.reset() def __fixelements(self): self.__fixed = 1 self.elements = {} self.__fixdict(self.__dict__) self.__fixclass(self.__class__) def __fixclass(self, kl): self.__fixdict(kl.__dict__) for k in kl.__bases__: self.__fixclass(k) def __fixdict(self, dict): for key in dict.keys(): if key[:6] == 'start_': tag = key[6:] start, end = self.elements.get(tag, (None, None)) if start is None: self.elements[tag] = getattr(self, key), end elif key[:4] == 'end_': tag = key[4:] start, end = self.elements.get(tag, (None, None)) if end is None: self.elements[tag] = start, getattr(self, key) # Interface -- reset this instance. Loses all unprocessed data def reset(self): self.rawdata = '' self.stack = [] self.nomoretags = 0 self.literal = 0 self.lineno = 1 self.__at_start = 1 self.__seen_doctype = None self.__seen_starttag = 0 self.__use_namespaces = 0 self.__namespaces = {'xml':None} # xml is implicitly declared # backward compatibility hack: if elements not overridden, # fill it in ourselves if self.elements is XMLParser.elements: self.__fixelements() # For derived classes only -- enter literal mode (CDATA) till EOF def setnomoretags(self): self.nomoretags = self.literal = 1 # For derived classes only -- enter literal mode (CDATA) def setliteral(self, *args): self.literal = 1 # Interface -- feed some data to the parser. Call this as # often as you want, with as little or as much text as you # want (may include '\n'). (This just saves the text, all the # processing is done by goahead().) def feed(self, data): self.rawdata = self.rawdata + data self.goahead(0) # Interface -- handle the remaining data def close(self): self.goahead(1) if self.__fixed: self.__fixed = 0 # remove self.elements so that we don't leak del self.elements # Interface -- translate references def translate_references(self, data, all = 1): if not self.__translate_attribute_references: return data i = 0 while 1: res = amp.search(data, i) if res is None: return data s = res.start(0) res = ref.match(data, s) if res is None: self.syntax_error("bogus `&'") i = s+1 continue i = res.end(0) str = res.group(1) rescan = 0 if str[0] == '#': if str[1] == 'x': str = chr(int(str[2:], 16)) else: str = chr(int(str[1:])) if data[i - 1] != ';': self.syntax_error("`;' missing after char reference") i = i-1 elif all: if str in self.entitydefs: str = self.entitydefs[str] rescan = 1 elif data[i - 1] != ';': self.syntax_error("bogus `&'") i = s + 1 # just past the & continue else: self.syntax_error("reference to unknown entity `&%s;'" % str) str = '&' + str + ';' elif data[i - 1] != ';': self.syntax_error("bogus `&'") i = s + 1 # just past the & continue # when we get here, str contains the translated text and i points # to the end of the string that is to be replaced data = data[:s] + str + data[i:] if rescan: i = s else: i = s + len(str) # Interface - return a dictionary of all namespaces currently valid def getnamespace(self): nsdict = {} for t, d, nst in self.stack: nsdict.update(d) return nsdict # Internal -- handle data as far as reasonable. May leave state # and data to be processed by a subsequent call. If 'end' is # true, force handling all data as if followed by EOF marker. def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: if i > 0: self.__at_start = 0 if self.nomoretags: data = rawdata[i:n] self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = n break res = interesting.search(rawdata, i) if res: j = res.start(0) else: j = n if i < j: data = rawdata[i:j] if self.__at_start and space.match(data) is None: self.syntax_error('illegal data at start of file') self.__at_start = 0 if not self.stack and space.match(data) is None: self.syntax_error('data not in content') if not self.__accept_utf8 and illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = j if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = i+1 continue k = self.parse_starttag(i) if k < 0: break self.__seen_starttag = 1 self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue if endtagopen.match(rawdata, i): k = self.parse_endtag(i) if k < 0: break self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue if commentopen.match(rawdata, i): if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = i+1 continue k = self.parse_comment(i) if k < 0: break self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue if cdataopen.match(rawdata, i): k = self.parse_cdata(i) if k < 0: break self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue res = xmldecl.match(rawdata, i) if res: if not self.__at_start: self.syntax_error("<?xml?> declaration not at start of document") version, encoding, standalone = res.group('version', 'encoding', 'standalone') if version[1:-1] != '1.0': raise Error('only XML version 1.0 supported') if encoding: encoding = encoding[1:-1] if standalone: standalone = standalone[1:-1] self.handle_xml(encoding, standalone) i = res.end(0) continue res = procopen.match(rawdata, i) if res: k = self.parse_proc(i) if k < 0: break self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue res = doctype.match(rawdata, i) if res: if self.literal: data = rawdata[i] self.handle_data(data) self.lineno = self.lineno + data.count('\n') i = i+1 continue if self.__seen_doctype: self.syntax_error('multiple DOCTYPE elements') if self.__seen_starttag: self.syntax_error('DOCTYPE not at beginning of document') k = self.parse_doctype(res) if k < 0: break self.__seen_doctype = res.group('name') if self.__map_case: self.__seen_doctype = self.__seen_doctype.lower() self.lineno = self.lineno + rawdata[i:k].count('\n') i = k continue elif rawdata[i] == '&': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue res = charref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in charref") i = i-1 if not self.stack: self.syntax_error('data not in content') self.handle_charref(res.group('char')[:-1]) self.lineno = self.lineno + res.group(0).count('\n') continue res = entityref.match(rawdata, i) if res is not None: i = res.end(0) if rawdata[i-1] != ';': self.syntax_error("`;' missing in entityref") i = i-1 name = res.group('name') if self.__map_case: name = name.lower() if name in self.entitydefs: self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:] n = len(rawdata) i = res.start(0) else: self.unknown_entityref(name) self.lineno = self.lineno + res.group(0).count('\n') continue elif rawdata[i] == ']': if self.literal: data = rawdata[i] self.handle_data(data) i = i+1 continue if n-i < 3: break if cdataclose.match(rawdata, i): self.syntax_error("bogus `]]>'") self.handle_data(rawdata[i]) i = i+1 continue else: raise Error('neither < nor & ??') # We get here only if incomplete matches but # nothing else break # end while if i > 0: self.__at_start = 0 if end and i < n: data = rawdata[i] self.syntax_error("bogus `%s'" % data) if not self.__accept_utf8 and illegal.search(data): self.syntax_error('illegal character in content') self.handle_data(data) self.lineno = self.lineno + data.count('\n') self.rawdata = rawdata[i+1:] return self.goahead(end) self.rawdata = rawdata[i:] if end: if not self.__seen_starttag: self.syntax_error('no elements in file') if self.stack: self.syntax_error('missing end tags') while self.stack: self.finish_endtag(self.stack[-1][0]) # Internal -- parse comment, return length or -1 if not terminated def parse_comment(self, i): rawdata = self.rawdata if rawdata[i:i+4] != '<!--': raise Error('unexpected call to handle_comment') res = commentclose.search(rawdata, i+4) if res is None: return -1 if doubledash.search(rawdata, i+4, res.start(0)): self.syntax_error("`--' inside comment") if rawdata[res.start(0)-1] == '-': self.syntax_error('comment cannot end in three dashes') if not self.__accept_utf8 and \ illegal.search(rawdata, i+4, res.start(0)): self.syntax_error('illegal character in comment') self.handle_comment(rawdata[i+4: res.start(0)]) return res.end(0) # Internal -- handle DOCTYPE tag, return length or -1 if not terminated def parse_doctype(self, res): rawdata = self.rawdata n = len(rawdata) name = res.group('name') if self.__map_case: name = name.lower() pubid, syslit = res.group('pubid', 'syslit') if pubid is not None: pubid = pubid[1:-1] # remove quotes pubid = ' '.join(pubid.split()) # normalize if syslit is not None: syslit = syslit[1:-1] # remove quotes j = k = res.end(0) if k >= n: return -1 if rawdata[k] == '[': level = 0 k = k+1 dq = sq = 0 while k < n: c = rawdata[k] if not sq and c == '"': dq = not dq elif not dq and c == "'": sq = not sq elif sq or dq: pass elif level <= 0 and c == ']': res = endbracket.match(rawdata, k+1) if res is None: return -1 self.handle_doctype(name, pubid, syslit, rawdata[j+1:k]) return res.end(0) elif c == '<': level = level + 1 elif c == '>': level = level - 1 if level < 0: self.syntax_error("bogus `>' in DOCTYPE") k = k+1 res = endbracketfind.match(rawdata, k) if res is None: return -1 if endbracket.match(rawdata, k) is None: self.syntax_error('garbage in DOCTYPE') self.handle_doctype(name, pubid, syslit, None) return res.end(0) # Internal -- handle CDATA tag, return length or -1 if not terminated def parse_cdata(self, i): rawdata = self.rawdata if rawdata[i:i+9] != '<![CDATA[': raise Error('unexpected call to parse_cdata') res = cdataclose.search(rawdata, i+9) if res is None: return -1 if not self.__accept_utf8 and \ illegal.search(rawdata, i+9, res.start(0)): self.syntax_error('illegal character in CDATA') if not self.stack: self.syntax_error('CDATA not in content') self.handle_cdata(rawdata[i+9:res.start(0)]) return res.end(0) __xml_namespace_attributes = {'ns':None, 'src':None, 'prefix':None} # Internal -- handle a processing instruction tag def parse_proc(self, i): rawdata = self.rawdata end = procclose.search(rawdata, i) if end is None: return -1 j = end.start(0) if not self.__accept_utf8 and illegal.search(rawdata, i+2, j): self.syntax_error('illegal character in processing instruction') res = tagfind.match(rawdata, i+2) if res is None: raise Error('unexpected call to parse_proc') k = res.end(0) name = res.group(0) if self.__map_case: name = name.lower() if name == 'xml:namespace': self.syntax_error('old-fashioned namespace declaration') self.__use_namespaces = -1 # namespace declaration # this must come after the <?xml?> declaration (if any) # and before the <!DOCTYPE> (if any). if self.__seen_doctype or self.__seen_starttag: self.syntax_error('xml:namespace declaration too late in document') attrdict, namespace, k = self.parse_attributes(name, k, j) if namespace: self.syntax_error('namespace declaration inside namespace declaration') for attrname in attrdict.keys(): if not attrname in self.__xml_namespace_attributes: self.syntax_error("unknown attribute `%s' in xml:namespace tag" % attrname) if not 'ns' in attrdict or not 'prefix' in attrdict: self.syntax_error('xml:namespace without required attributes') prefix = attrdict.get('prefix') if ncname.match(prefix) is None: self.syntax_error('xml:namespace illegal prefix value') return end.end(0) if prefix in self.__namespaces: self.syntax_error('xml:namespace prefix not unique') self.__namespaces[prefix] = attrdict['ns'] else: if name.lower() == 'xml': self.syntax_error('illegal processing instruction target name') self.handle_proc(name, rawdata[k:j]) return end.end(0) # Internal -- parse attributes between i and j def parse_attributes(self, tag, i, j): rawdata = self.rawdata attrdict = {} namespace = {} while i < j: res = attrfind.match(rawdata, i) if res is None: break attrname, attrvalue = res.group('name', 'value') if self.__map_case: attrname = attrname.lower() i = res.end(0) if attrvalue is None: self.syntax_error("no value specified for attribute `%s'" % attrname) attrvalue = attrname elif attrvalue[:1] == "'" == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] elif not self.__accept_unquoted_attributes: self.syntax_error("attribute `%s' value not quoted" % attrname) res = xmlns.match(attrname) if res is not None: # namespace declaration ncname = res.group('ncname') namespace[ncname or ''] = attrvalue or None if not self.__use_namespaces: self.__use_namespaces = len(self.stack)+1 continue if '<' in attrvalue: self.syntax_error("`<' illegal in attribute value") if attrname in attrdict: self.syntax_error("attribute `%s' specified twice" % attrname) attrvalue = attrvalue.translate(attrtrans) attrdict[attrname] = self.translate_references(attrvalue) return attrdict, namespace, i # Internal -- handle starttag, return length or -1 if not terminated def parse_starttag(self, i): rawdata = self.rawdata # i points to start of tag end = endbracketfind.match(rawdata, i+1) if end is None: return -1 tag = starttagmatch.match(rawdata, i) if tag is None or tag.end(0) != end.end(0): self.syntax_error('garbage in starttag') return end.end(0) nstag = tagname = tag.group('tagname') if self.__map_case: nstag = tagname = nstag.lower() if not self.__seen_starttag and self.__seen_doctype and \ tagname != self.__seen_doctype: self.syntax_error('starttag does not match DOCTYPE') if self.__seen_starttag and not self.stack: self.syntax_error('multiple elements on top level') k, j = tag.span('attrs') attrdict, nsdict, k = self.parse_attributes(tagname, k, j) self.stack.append((tagname, nsdict, nstag)) if self.__use_namespaces: res = qname.match(tagname) else: res = None if res is not None: prefix, nstag = res.group('prefix', 'local') if prefix is None: prefix = '' ns = None for t, d, nst in self.stack: if prefix in d: ns = d[prefix] if ns is None and prefix != '': ns = self.__namespaces.get(prefix) if ns is not None: nstag = ns + ' ' + nstag elif prefix != '': nstag = prefix + ':' + nstag # undo split self.stack[-1] = tagname, nsdict, nstag # translate namespace of attributes attrnamemap = {} # map from new name to old name (used for error reporting) for key in attrdict.keys(): attrnamemap[key] = key if self.__use_namespaces: nattrdict = {} for key, val in attrdict.items(): okey = key res = qname.match(key) if res is not None: aprefix, key = res.group('prefix', 'local') if self.__map_case: key = key.lower() if aprefix is not None: ans = None for t, d, nst in self.stack: if aprefix in d: ans = d[aprefix] if ans is None: ans = self.__namespaces.get(aprefix) if ans is not None: key = ans + ' ' + key else: key = aprefix + ':' + key nattrdict[key] = val attrnamemap[key] = okey attrdict = nattrdict attributes = self.attributes.get(nstag) if attributes is not None: for key in attrdict.keys(): if not key in attributes: self.syntax_error("unknown attribute `%s' in tag `%s'" % (attrnamemap[key], tagname)) for key, val in attributes.items(): if val is not None and not key in attrdict: attrdict[key] = val method = self.elements.get(nstag, (None, None))[0] self.finish_starttag(nstag, attrdict, method) if tag.group('slash') == '/': self.finish_endtag(tagname) return tag.end(0) # Internal -- parse endtag def parse_endtag(self, i): rawdata = self.rawdata end = endbracketfind.match(rawdata, i+1) if end is None: return -1 res = tagfind.match(rawdata, i+2) if res is None: if self.literal: self.handle_data(rawdata[i]) return i+1 if not self.__accept_missing_endtag_name: self.syntax_error('no name specified in end tag') tag = self.stack[-1][0] k = i+2 else: tag = res.group(0) if self.__map_case: tag = tag.lower() if self.literal: if not self.stack or tag != self.stack[-1][0]: self.handle_data(rawdata[i]) return i+1 k = res.end(0) if endbracket.match(rawdata, k) is None: self.syntax_error('garbage in end tag') self.finish_endtag(tag) return end.end(0) # Internal -- finish processing of start tag def finish_starttag(self, tagname, attrdict, method): if method is not None: self.handle_starttag(tagname, method, attrdict) else: self.unknown_starttag(tagname, attrdict) # Internal -- finish processing of end tag def finish_endtag(self, tag): self.literal = 0 if not tag: self.syntax_error('name-less end tag') found = len(self.stack) - 1 if found < 0: self.unknown_endtag(tag) return else: found = -1 for i in range(len(self.stack)): if tag == self.stack[i][0]: found = i if found == -1: self.syntax_error('unopened end tag') return while len(self.stack) > found: if found < len(self.stack) - 1: self.syntax_error('missing close tag for %s' % self.stack[-1][2]) nstag = self.stack[-1][2] method = self.elements.get(nstag, (None, None))[1] if method is not None: self.handle_endtag(nstag, method) else: self.unknown_endtag(nstag) if self.__use_namespaces == len(self.stack): self.__use_namespaces = 0 del self.stack[-1] # Overridable -- handle xml processing instruction def handle_xml(self, encoding, standalone): pass # Overridable -- handle DOCTYPE def handle_doctype(self, tag, pubid, syslit, data): pass # Overridable -- handle start tag def handle_starttag(self, tag, method, attrs): method(attrs) # Overridable -- handle end tag def handle_endtag(self, tag, method): method() # Example -- handle character reference, no need to override def handle_charref(self, name): try: if name[0] == 'x': n = int(name[1:], 16) else: n = int(name) except ValueError: self.unknown_charref(name) return if not 0 <= n <= 255: self.unknown_charref(name) return self.handle_data(chr(n)) # Definition of entities -- derived classes may override entitydefs = {'lt': '&#60;', # must use charref 'gt': '&#62;', 'amp': '&#38;', # must use charref 'quot': '&#34;', 'apos': '&#39;', } # Example -- handle data, should be overridden def handle_data(self, data): pass # Example -- handle cdata, could be overridden def handle_cdata(self, data): pass # Example -- handle comment, could be overridden def handle_comment(self, data): pass # Example -- handle processing instructions, could be overridden def handle_proc(self, name, data): pass # Example -- handle relatively harmless syntax errors, could be overridden def syntax_error(self, message): raise Error('Syntax error at line %d: %s' % (self.lineno, message)) # To be overridden -- handlers for unknown objects def unknown_starttag(self, tag, attrs): pass def unknown_endtag(self, tag): pass def unknown_charref(self, ref): pass def unknown_entityref(self, name): self.syntax_error("reference to unknown entity `&%s;'" % name) class TestXMLParser(XMLParser): def __init__(self, **kw): self.testdata = "" XMLParser.__init__(self, **kw) def handle_xml(self, encoding, standalone): self.flush() print 'xml: encoding =',encoding,'standalone =',standalone def handle_doctype(self, tag, pubid, syslit, data): self.flush() print 'DOCTYPE:',tag, repr(data) def handle_data(self, data): self.testdata = self.testdata + data if len(repr(self.testdata)) >= 70: self.flush() def flush(self): data = self.testdata if data: self.testdata = "" print 'data:', repr(data) def handle_cdata(self, data): self.flush() print 'cdata:', repr(data) def handle_proc(self, name, data): self.flush() print 'processing:',name,repr(data) def handle_comment(self, data): self.flush() r = repr(data) if len(r) > 68: r = r[:32] + '...' + r[-32:] print 'comment:', r def syntax_error(self, message): print 'error at line %d:' % self.lineno, message def unknown_starttag(self, tag, attrs): self.flush() if not attrs: print 'start tag: <' + tag + '>' else: print 'start tag: <' + tag, for name, value in attrs.items(): print name + '=' + '"' + value + '"', print '>' def unknown_endtag(self, tag): self.flush() print 'end tag: </' + tag + '>' def unknown_entityref(self, ref): self.flush() print '*** unknown entity ref: &' + ref + ';' def unknown_charref(self, ref): self.flush() print '*** unknown char ref: &#' + ref + ';' def close(self): XMLParser.close(self) self.flush() def test(args = None): import sys, getopt from time import time if not args: args = sys.argv[1:] opts, args = getopt.getopt(args, 'st') klass = TestXMLParser do_time = 0 for o, a in opts: if o == '-s': klass = XMLParser elif o == '-t': do_time = 1 if args: file = args[0] else: file = 'test.xml' if file == '-': f = sys.stdin else: try: f = open(file, 'r') except IOError, msg: print file, ":", msg sys.exit(1) data = f.read() if f is not sys.stdin: f.close() x = klass() t0 = time() try: if do_time: x.feed(data) x.close() else: for c in data: x.feed(c) x.close() except Error, msg: t1 = time() print msg if do_time: print 'total time: %g' % (t1-t0) sys.exit(1) t1 = time() if do_time: print 'total time: %g' % (t1-t0) if __name__ == '__main__': test()
gpl-3.0
datajoint/datajoint-python
tests/test_privileges.py
2
1416
from nose.tools import assert_true, raises import datajoint as dj from . import schema, CONN_INFO namespace = locals() class TestUnprivileged: @classmethod def setup_class(cls): """A connection with only SELECT privilege to djtest schemas""" cls.connection = dj.conn(host=CONN_INFO['host'], user='djview', password='djview', reset=True) @raises(dj.DataJointError) def test_fail_create_schema(self): """creating a schema with no CREATE privilege""" return dj.Schema('forbidden_schema', namespace, connection=self.connection) @raises(dj.DataJointError) def test_insert_failure(self): unprivileged = dj.Schema(schema.schema.database, namespace, connection=self.connection) unprivileged.spawn_missing_classes() assert_true(issubclass(Language, dj.Lookup) and len(Language()) == len(schema.Language()), 'failed to spawn missing classes') Language().insert1(('Socrates', 'Greek')) @raises(dj.DataJointError) def test_failure_to_create_table(self): unprivileged = dj.Schema(schema.schema.database, namespace, connection=self.connection) @unprivileged class Try(dj.Manual): definition = """ # should not matter really id : int --- value : float """ Try().insert1((1, 1.5))
lgpl-2.1
suhussai/youtube-dl
youtube_dl/extractor/wimp.py
65
1839
from __future__ import unicode_literals import re from .common import InfoExtractor from .youtube import YoutubeIE class WimpIE(InfoExtractor): _VALID_URL = r'http://(?:www\.)?wimp\.com/([^/]+)/' _TESTS = [{ 'url': 'http://www.wimp.com/maruexhausted/', 'md5': 'f1acced123ecb28d9bb79f2479f2b6a1', 'info_dict': { 'id': 'maruexhausted', 'ext': 'flv', 'title': 'Maru is exhausted.', 'description': 'md5:57e099e857c0a4ea312542b684a869b8', } }, { # youtube video 'url': 'http://www.wimp.com/clowncar/', 'info_dict': { 'id': 'cG4CEr2aiSg', 'ext': 'mp4', 'title': 'Basset hound clown car...incredible!', 'description': 'md5:8d228485e0719898c017203f900b3a35', 'uploader': 'Gretchen Hoey', 'uploader_id': 'gretchenandjeff1', 'upload_date': '20140303', }, 'add_ie': ['Youtube'], }] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group(1) webpage = self._download_webpage(url, video_id) video_url = self._search_regex( [r"[\"']file[\"']\s*[:,]\s*[\"'](.+?)[\"']", r"videoId\s*:\s*[\"']([^\"']+)[\"']"], webpage, 'video URL') if YoutubeIE.suitable(video_url): self.to_screen('Found YouTube video') return { '_type': 'url', 'url': video_url, 'ie_key': YoutubeIE.ie_key(), } return { 'id': video_id, 'url': video_url, 'title': self._og_search_title(webpage), 'thumbnail': self._og_search_thumbnail(webpage), 'description': self._og_search_description(webpage), }
unlicense
jordij/wagtail
wagtail/wagtailsearch/models.py
9
2902
from __future__ import unicode_literals import datetime from django.db import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailsearch.utils import normalise_query_string, MAX_QUERY_STRING_LENGTH @python_2_unicode_compatible class Query(models.Model): query_string = models.CharField(max_length=MAX_QUERY_STRING_LENGTH, unique=True) def save(self, *args, **kwargs): # Normalise query string self.query_string = normalise_query_string(self.query_string) super(Query, self).save(*args, **kwargs) def add_hit(self, date=None): if date is None: date = timezone.now().date() daily_hits, created = QueryDailyHits.objects.get_or_create(query=self, date=date) daily_hits.hits = models.F('hits') + 1 daily_hits.save() def __str__(self): return self.query_string @property def hits(self): hits = self.daily_hits.aggregate(models.Sum('hits'))['hits__sum'] return hits if hits else 0 @classmethod def garbage_collect(cls): """ Deletes all Query records that have no daily hits or editors picks """ cls.objects.filter(daily_hits__isnull=True, editors_picks__isnull=True).delete() @classmethod def get(cls, query_string): return cls.objects.get_or_create(query_string=normalise_query_string(query_string))[0] @classmethod def get_most_popular(cls, date_since=None): # TODO: Implement date_since return cls.objects.filter(daily_hits__isnull=False).annotate(_hits=models.Sum('daily_hits__hits')).distinct().order_by('-_hits') class QueryDailyHits(models.Model): query = models.ForeignKey(Query, db_index=True, related_name='daily_hits') date = models.DateField() hits = models.IntegerField(default=0) @classmethod def garbage_collect(cls): """ Deletes all QueryDailyHits records that are older than 7 days """ min_date = timezone.now().date() - datetime.timedelta(days=7) cls.objects.filter(date__lt=min_date).delete() class Meta: unique_together = ( ('query', 'date'), ) verbose_name = _('Query Daily Hits') class EditorsPick(models.Model): query = models.ForeignKey(Query, db_index=True, related_name='editors_picks') page = models.ForeignKey('wagtailcore.Page', verbose_name=_('Page')) sort_order = models.IntegerField(null=True, blank=True, editable=False) description = models.TextField(verbose_name=_('Description'), blank=True) def __repr__(self): return 'EditorsPick(query="' + self.query.query_string + '", page="' + self.page.title + '")' class Meta: ordering = ('sort_order', ) verbose_name = _("Editor's Pick")
bsd-3-clause
greenhost/viper
viper/provider/__init__.py
1
1457
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2013 Greenhost VOF # https://greenhost.nl -\- https://greenhost.io # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import os, sys, re import json import logging from viper import tools class ProviderSettings: def __init__(self): self.settings = {} def load(self, fn): logging.debug("Loading provider settings from '{0}'".format(fn)) with open(fn) as f: self.settings = json.loads( f.read() ) f.close() def get(self, name): return self.settings[name] if name in self.settings else None def get_provider_setting(name): """ Get a configuration value from the provider file for the given key """ provider = ProviderSettings() path = tools.get_viper_home() path = os.path.join(path, 'resources/provider.json') provider.load(path) return provider.get(name)
gpl-3.0
stethewwolf/Sapy
sapy_modules/gui/gtk/dialogs/__init__.py
1
1885
# Sapy # Copyright (C) 2018 stefano prina <stefano-prina@outlook.it> <stethewwolf@gmail.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/>. __all__ = [ 'Add_Mom_Dialog_View', 'Add_Lom_Dialog_View', 'Del_Mom_Dialog_View', 'Del_Lom_Dialog_View', 'Select_Lom_Dialog_View', 'Update_Mom_Dialog_View', 'Update_Lom_Dialog_View', 'Date_Picker', 'No_Item_Selected', 'Csv_Structure_Display_Message' ] # deprecated to keep older scripts who import this from breaking from sapy_modules.gui.gtk.dialogs.add_mom_dialog import Add_Mom_Dialog_View from sapy_modules.gui.gtk.dialogs.add_lom_dialog import Add_Lom_Dialog_View from sapy_modules.gui.gtk.dialogs.del_mom_dialog import Del_Mom_Dialog_View from sapy_modules.gui.gtk.dialogs.del_lom_dialog import Del_Lom_Dialog_View from sapy_modules.gui.gtk.dialogs.select_lom_dialog import Select_Lom_Dialog_View from sapy_modules.gui.gtk.dialogs.update_mom_dialog import Update_Mom_Dialog_View from sapy_modules.gui.gtk.dialogs.update_lom_dialog import Update_Lom_Dialog_View from sapy_modules.gui.gtk.dialogs.date_picker import Date_Picker from sapy_modules.gui.gtk.dialogs.no_item_selected import No_Item_Selected from sapy_modules.gui.gtk.dialogs.csv_structure_display_message import Csv_Structure_Display_Message
mit
dennybaa/st2contrib
packs/email/sensors/imap_sensor.py
2
3392
import eventlet import easyimap from flanker import mime from st2reactor.sensor.base import PollingSensor __all__ = [ 'IMAPSensor' ] eventlet.monkey_patch( os=True, select=True, socket=True, thread=True, time=True) class IMAPSensor(PollingSensor): def __init__(self, sensor_service, config=None, poll_interval=30): super(IMAPSensor, self).__init__(sensor_service=sensor_service, config=config, poll_interval=poll_interval) self._trigger = 'email.imap.message' self._logger = self._sensor_service.get_logger(__name__) self._mailboxes = {} def setup(self): self._logger.debug('[IMAPSensor]: entering setup') if 'imap_mailboxes' in self._config: self._parse_mailboxes(self._config['imap_mailboxes']) def poll(self): self._logger.debug('[IMAPSensor]: entering poll') for name, mailbox in self._mailboxes.items(): self._poll_for_unread_messages(name, mailbox) def cleanup(self): self._logger.debug('[IMAPSensor]: entering cleanup') for name, mailbox in self._mailboxes.items(): self._logger.debug('[IMAPSensor]: Disconnecting from {0}'.format(name)) mailbox.quit() def add_trigger(self, trigger): pass def update_trigger(self, trigger): pass def remove_trigger(self, trigger): pass def _parse_mailboxes(self, mailboxes): for mailbox, config in mailboxes.items(): server = config.get('server', 'localhost') port = config.get('port', 143) user = config.get('username', None) password = config.get('password', None) folder = config.get('mailbox', 'INBOX') ssl = config.get('ssl', False) if not user or not password: self._logger.debug("""[IMAPSensor]: Missing username/password for {0}""".format(mailbox)) elif not server: self._logger.debug("""[IMAPSensor]: Missing server for {0}""".format(mailbox)) else: connection = easyimap.connect(server, user, password, folder, ssl=ssl, port=port) self._mailboxes[mailbox] = connection def _poll_for_unread_messages(self, name, mailbox): self._logger.debug('[IMAPSensor]: polling mailbox {0}'.format(name)) for message in mailbox.unseen(): self._process_message(message.uid, mailbox) def _process_message(self, uid, mailbox): message = mailbox.mail(uid, include_raw=True) mime_msg = mime.from_string(message.raw) body = message.body sent_from = message.from_addr sent_to = message.to subject = message.title date = message.date message_id = message.message_id headers = mime_msg.headers.items() payload = { 'uid': uid, 'from': sent_from, 'to': sent_to, 'headers': headers, 'date': date, 'subject': subject, 'message_id': message_id, 'body': body, 'attachments': None } self._sensor_service.dispatch(trigger=self._trigger, payload=payload)
apache-2.0
AOSPU/external_chromium_org
tools/deep_memory_profiler/lib/dump.py
12
15534
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import copy import datetime import logging import os import re import time from lib.bucket import BUCKET_ID from lib.exceptions import EmptyDumpException, InvalidDumpException from lib.exceptions import ObsoleteDumpVersionException, ParsingException from lib.pageframe import PageFrame from lib.range_dict import ExclusiveRangeDict from lib.symbol import procfs LOGGER = logging.getLogger('dmprof') # Heap Profile Dump versions # DUMP_DEEP_[1-4] are obsolete. # DUMP_DEEP_2+ distinct mmap regions and malloc chunks. # DUMP_DEEP_3+ don't include allocation functions in their stack dumps. # DUMP_DEEP_4+ support comments with '#' and global stats "nonprofiled-*". # DUMP_DEEP_[1-2] should be processed by POLICY_DEEP_1. # DUMP_DEEP_[3-4] should be processed by POLICY_DEEP_2 or POLICY_DEEP_3. DUMP_DEEP_1 = 'DUMP_DEEP_1' DUMP_DEEP_2 = 'DUMP_DEEP_2' DUMP_DEEP_3 = 'DUMP_DEEP_3' DUMP_DEEP_4 = 'DUMP_DEEP_4' DUMP_DEEP_OBSOLETE = (DUMP_DEEP_1, DUMP_DEEP_2, DUMP_DEEP_3, DUMP_DEEP_4) # DUMP_DEEP_5 doesn't separate sections for malloc and mmap. # malloc and mmap are identified in bucket files. # DUMP_DEEP_5 should be processed by POLICY_DEEP_4. DUMP_DEEP_5 = 'DUMP_DEEP_5' # DUMP_DEEP_6 adds a mmap list to DUMP_DEEP_5. DUMP_DEEP_6 = 'DUMP_DEEP_6' class Dump(object): """Represents a heap profile dump.""" _PATH_PATTERN = re.compile(r'^(.*)\.([0-9]+)\.([0-9]+)\.heap$') _HOOK_PATTERN = re.compile( r'^ ([ \(])([a-f0-9]+)([ \)])-([ \(])([a-f0-9]+)([ \)])\s+' r'(hooked|unhooked)\s+(.+)$', re.IGNORECASE) _HOOKED_PATTERN = re.compile(r'(?P<TYPE>.+ )?(?P<COMMITTED>[0-9]+) / ' '(?P<RESERVED>[0-9]+) @ (?P<BUCKETID>[0-9]+)') _UNHOOKED_PATTERN = re.compile(r'(?P<TYPE>.+ )?(?P<COMMITTED>[0-9]+) / ' '(?P<RESERVED>[0-9]+)') _OLD_HOOKED_PATTERN = re.compile(r'(?P<TYPE>.+) @ (?P<BUCKETID>[0-9]+)') _OLD_UNHOOKED_PATTERN = re.compile(r'(?P<TYPE>.+) (?P<COMMITTED>[0-9]+)') _TIME_PATTERN_FORMAT = re.compile( r'^Time: ([0-9]+/[0-9]+/[0-9]+ [0-9]+:[0-9]+:[0-9]+)(\.[0-9]+)?') _TIME_PATTERN_SECONDS = re.compile(r'^Time: ([0-9]+)$') def __init__(self, path, modified_time): self._path = path matched = self._PATH_PATTERN.match(path) self._pid = int(matched.group(2)) self._count = int(matched.group(3)) self._time = modified_time self._map = {} self._procmaps = ExclusiveRangeDict(ProcMapsEntryAttribute) self._stacktrace_lines = [] self._global_stats = {} # used only in apply_policy self._run_id = '' self._pagesize = 4096 self._pageframe_length = 0 self._pageframe_encoding = '' self._has_pagecount = False self._version = '' self._lines = [] @property def path(self): return self._path @property def count(self): return self._count @property def time(self): return self._time @property def iter_map(self): for region in sorted(self._map.iteritems()): yield region[0], region[1] def iter_procmaps(self): for begin, end, attr in self._map.iter_range(): yield begin, end, attr @property def iter_stacktrace(self): for line in self._stacktrace_lines: yield line def global_stat(self, name): return self._global_stats[name] @property def run_id(self): return self._run_id @property def pagesize(self): return self._pagesize @property def pageframe_length(self): return self._pageframe_length @property def pageframe_encoding(self): return self._pageframe_encoding @property def has_pagecount(self): return self._has_pagecount @staticmethod def load(path, log_header='Loading a heap profile dump: '): """Loads a heap profile dump. Args: path: A file path string to load. log_header: A preceding string for log messages. Returns: A loaded Dump object. Raises: ParsingException for invalid heap profile dumps. """ dump = Dump(path, os.stat(path).st_mtime) with open(path, 'r') as f: dump.load_file(f, log_header) return dump def load_file(self, f, log_header): self._lines = [line for line in f if line and not line.startswith('#')] try: self._version, ln = self._parse_version() self._parse_meta_information() if self._version == DUMP_DEEP_6: self._parse_mmap_list() self._parse_global_stats() self._extract_stacktrace_lines(ln) except EmptyDumpException: LOGGER.info('%s%s ...ignored an empty dump.' % (log_header, self._path)) except ParsingException, e: LOGGER.error('%s%s ...error %s' % (log_header, self._path, e)) raise else: LOGGER.info('%s%s (version:%s)' % (log_header, self._path, self._version)) def _parse_version(self): """Parses a version string in self._lines. Returns: A pair of (a string representing a version of the stacktrace dump, and an integer indicating a line number next to the version string). Raises: ParsingException for invalid dump versions. """ version = '' # Skip until an identifiable line. headers = ('STACKTRACES:\n', 'MMAP_STACKTRACES:\n', 'heap profile: ') if not self._lines: raise EmptyDumpException('Empty heap dump file.') (ln, found) = skip_while( 0, len(self._lines), lambda n: not self._lines[n].startswith(headers)) if not found: raise InvalidDumpException('No version header.') # Identify a version. if self._lines[ln].startswith('heap profile: '): version = self._lines[ln][13:].strip() if version in (DUMP_DEEP_5, DUMP_DEEP_6): (ln, _) = skip_while( ln, len(self._lines), lambda n: self._lines[n] != 'STACKTRACES:\n') elif version in DUMP_DEEP_OBSOLETE: raise ObsoleteDumpVersionException(version) else: raise InvalidDumpException('Invalid version: %s' % version) elif self._lines[ln] == 'STACKTRACES:\n': raise ObsoleteDumpVersionException(DUMP_DEEP_1) elif self._lines[ln] == 'MMAP_STACKTRACES:\n': raise ObsoleteDumpVersionException(DUMP_DEEP_2) return (version, ln) def _parse_global_stats(self): """Parses lines in self._lines as global stats.""" (ln, _) = skip_while( 0, len(self._lines), lambda n: self._lines[n] != 'GLOBAL_STATS:\n') global_stat_names = [ 'total', 'absent', 'file-exec', 'file-nonexec', 'anonymous', 'stack', 'other', 'nonprofiled-absent', 'nonprofiled-anonymous', 'nonprofiled-file-exec', 'nonprofiled-file-nonexec', 'nonprofiled-stack', 'nonprofiled-other', 'profiled-mmap', 'profiled-malloc'] for prefix in global_stat_names: (ln, _) = skip_while( ln, len(self._lines), lambda n: self._lines[n].split()[0] != prefix) words = self._lines[ln].split() self._global_stats[prefix + '_virtual'] = int(words[-2]) self._global_stats[prefix + '_committed'] = int(words[-1]) def _parse_meta_information(self): """Parses lines in self._lines for meta information.""" (ln, found) = skip_while( 0, len(self._lines), lambda n: self._lines[n] != 'META:\n') if not found: return ln += 1 while True: if self._lines[ln].startswith('Time:'): matched_seconds = self._TIME_PATTERN_SECONDS.match(self._lines[ln]) matched_format = self._TIME_PATTERN_FORMAT.match(self._lines[ln]) if matched_format: self._time = time.mktime(datetime.datetime.strptime( matched_format.group(1), '%Y/%m/%d %H:%M:%S').timetuple()) if matched_format.group(2): self._time += float(matched_format.group(2)[1:]) / 1000.0 elif matched_seconds: self._time = float(matched_seconds.group(1)) elif self._lines[ln].startswith('Reason:'): pass # Nothing to do for 'Reason:' elif self._lines[ln].startswith('PageSize: '): self._pagesize = int(self._lines[ln][10:]) elif self._lines[ln].startswith('CommandLine:'): pass elif (self._lines[ln].startswith('PageFrame: ') or self._lines[ln].startswith('PFN: ')): if self._lines[ln].startswith('PageFrame: '): words = self._lines[ln][11:].split(',') else: words = self._lines[ln][5:].split(',') for word in words: if word == '24': self._pageframe_length = 24 elif word == 'Base64': self._pageframe_encoding = 'base64' elif word == 'PageCount': self._has_pagecount = True elif self._lines[ln].startswith('RunID: '): self._run_id = self._lines[ln][7:].strip() elif (self._lines[ln].startswith('MMAP_LIST:') or self._lines[ln].startswith('GLOBAL_STATS:')): # Skip until "MMAP_LIST:" or "GLOBAL_STATS" is found. break else: pass ln += 1 def _parse_mmap_list(self): """Parses lines in self._lines as a mmap list.""" (ln, found) = skip_while( 0, len(self._lines), lambda n: self._lines[n] != 'MMAP_LIST:\n') if not found: return {} ln += 1 self._map = {} current_vma = {} pageframe_list = [] while True: entry = procfs.ProcMaps.parse_line(self._lines[ln]) if entry: current_vma = {} for _, _, attr in self._procmaps.iter_range(entry.begin, entry.end): for key, value in entry.as_dict().iteritems(): attr[key] = value current_vma[key] = value ln += 1 continue if self._lines[ln].startswith(' PF: '): for pageframe in self._lines[ln][5:].split(): pageframe_list.append(PageFrame.parse(pageframe, self._pagesize)) ln += 1 continue matched = self._HOOK_PATTERN.match(self._lines[ln]) if not matched: break # 2: starting address # 5: end address # 7: hooked or unhooked # 8: additional information if matched.group(7) == 'hooked': submatched = self._HOOKED_PATTERN.match(matched.group(8)) if not submatched: submatched = self._OLD_HOOKED_PATTERN.match(matched.group(8)) elif matched.group(7) == 'unhooked': submatched = self._UNHOOKED_PATTERN.match(matched.group(8)) if not submatched: submatched = self._OLD_UNHOOKED_PATTERN.match(matched.group(8)) else: assert matched.group(7) in ['hooked', 'unhooked'] submatched_dict = submatched.groupdict() region_info = { 'vma': current_vma } if submatched_dict.get('TYPE'): region_info['type'] = submatched_dict['TYPE'].strip() if submatched_dict.get('COMMITTED'): region_info['committed'] = int(submatched_dict['COMMITTED']) if submatched_dict.get('RESERVED'): region_info['reserved'] = int(submatched_dict['RESERVED']) if submatched_dict.get('BUCKETID'): region_info['bucket_id'] = int(submatched_dict['BUCKETID']) if matched.group(1) == '(': start = current_vma['begin'] else: start = int(matched.group(2), 16) if matched.group(4) == '(': end = current_vma['end'] else: end = int(matched.group(5), 16) if pageframe_list and pageframe_list[0].start_truncated: pageframe_list[0].set_size( pageframe_list[0].size - start % self._pagesize) if pageframe_list and pageframe_list[-1].end_truncated: pageframe_list[-1].set_size( pageframe_list[-1].size - (self._pagesize - end % self._pagesize)) region_info['pageframe'] = pageframe_list pageframe_list = [] self._map[(start, end)] = (matched.group(7), region_info) ln += 1 def _extract_stacktrace_lines(self, line_number): """Extracts the position of stacktrace lines. Valid stacktrace lines are stored into self._stacktrace_lines. Args: line_number: A line number to start parsing in lines. Raises: ParsingException for invalid dump versions. """ if self._version in (DUMP_DEEP_5, DUMP_DEEP_6): (line_number, _) = skip_while( line_number, len(self._lines), lambda n: not self._lines[n].split()[0].isdigit()) stacktrace_start = line_number (line_number, _) = skip_while( line_number, len(self._lines), lambda n: self._check_stacktrace_line(self._lines[n])) self._stacktrace_lines = self._lines[stacktrace_start:line_number] elif self._version in DUMP_DEEP_OBSOLETE: raise ObsoleteDumpVersionException(self._version) else: raise InvalidDumpException('Invalid version: %s' % self._version) @staticmethod def _check_stacktrace_line(stacktrace_line): """Checks if a given stacktrace_line is valid as stacktrace. Args: stacktrace_line: A string to be checked. Returns: True if the given stacktrace_line is valid. """ words = stacktrace_line.split() if len(words) < BUCKET_ID + 1: return False if words[BUCKET_ID - 1] != '@': return False return True class DumpList(object): """Represents a sequence of heap profile dumps. Individual dumps are loaded into memory lazily as the sequence is accessed, either while being iterated through or randomly accessed. Loaded dumps are not cached, meaning a newly loaded Dump object is returned every time an element in the list is accessed. """ def __init__(self, dump_path_list): self._dump_path_list = dump_path_list @staticmethod def load(path_list): return DumpList(path_list) def __len__(self): return len(self._dump_path_list) def __iter__(self): for dump in self._dump_path_list: yield Dump.load(dump) def __getitem__(self, index): return Dump.load(self._dump_path_list[index]) class ProcMapsEntryAttribute(ExclusiveRangeDict.RangeAttribute): """Represents an entry of /proc/maps in range_dict.ExclusiveRangeDict.""" _DUMMY_ENTRY = procfs.ProcMapsEntry( 0, # begin 0, # end '-', # readable '-', # writable '-', # executable '-', # private 0, # offset '00', # major '00', # minor 0, # inode '' # name ) def __init__(self): super(ProcMapsEntryAttribute, self).__init__() self._entry = self._DUMMY_ENTRY.as_dict() def __str__(self): return str(self._entry) def __repr__(self): return 'ProcMapsEntryAttribute' + str(self._entry) def __getitem__(self, key): return self._entry[key] def __setitem__(self, key, value): if key not in self._entry: raise KeyError(key) self._entry[key] = value def copy(self): new_entry = ProcMapsEntryAttribute() for key, value in self._entry.iteritems(): new_entry[key] = copy.deepcopy(value) return new_entry def skip_while(index, max_index, skipping_condition): """Increments |index| until |skipping_condition|(|index|) is False. Returns: A pair of an integer indicating a line number after skipped, and a boolean value which is True if found a line which skipping_condition is False for. """ while skipping_condition(index): index += 1 if index >= max_index: return index, False return index, True
bsd-3-clause
iulian787/spack
var/spack/repos/builtin/packages/aocc/package.py
1
3072
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Aocc(Package): ''' The AOCC compiler system is a high performance, production quality code generation tool. The AOCC environment provides various options to developers when building and optimizing C, C++, and Fortran applications targeting 32-bit and 64-bit Linux platforms. The AOCC compiler system offers a high level of advanced optimizations, multi-threading and processor support that includes global optimization, vectorization, inter-procedural analyses, loop transformations, and code generation. AMD also provides highly optimized libraries, which extract the optimal performance from each x86 processor core when utilized. The AOCC Compiler Suite simplifies and accelerates development and tuning for x86 applications. Please install only if you agree to terms and conditions depicted under : http://developer.amd.com/wordpress/media/files/AOCC_EULA.pdf Example for installation: \'spack install aocc +license-agreed\' ''' family = 'compiler' homepage = "https://developer.amd.com/amd-aocc/" maintainers = ['amd-toolchain-support'] version(ver="2.3.0", sha256='9f8a1544a5268a7fb8cd21ac4bdb3f8d1571949d1de5ca48e2d3309928fc3d15', url='http://developer.amd.com/wordpress/media/files/aocc-compiler-2.3.0.tar') version(ver="2.2.0", sha256='500940ce36c19297dfba3aa56dcef33b6145867a1f34890945172ac2be83b286', url='http://developer.amd.com/wordpress/media/files/aocc-compiler-2.2.0.tar') # Licensing license_required = True license_comment = '#' license_files = ['AOCC_EULA.pdf'] license_url = 'http://developer.amd.com/wordpress/media/files/AOCC_EULA.pdf' install_example = "spack install aocc +license-agreed" depends_on('libxml2') depends_on('zlib') depends_on('ncurses') depends_on('libtool') depends_on('texinfo') variant('license-agreed', default=False, description='Agree to terms and conditions depicted under : {0}' .format(license_url)) @run_before('install') def abort_without_license_agreed(self): license_url = 'http://developer.amd.com/wordpress/media/files/AOCC_EULA.pdf' install_example = "spack install aocc +license-agreed" if not self.spec.variants['license-agreed'].value: raise InstallError("\n\n\nNOTE:\nUse +license-agreed " + "during installation " + "to accept terms and conditions " + "depicted under following link \n" + " {0}\n".format(license_url) + "Example: \'{0}\' \n".format(install_example)) def install(self, spec, prefix): print("Installing AOCC Compiler ... ") install_tree('.', prefix)
lgpl-2.1
mikedanese/test-infra
gubernator/regex.py
7
1750
#!/usr/bin/env python # Copyright 2016 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re # Match a specific word def wordRE(word): return re.compile(r'\b(%s)\b' % word, re.IGNORECASE) # Match lines with error messages # HACK: match ANSI colored lines by allowing preceding "m", # as in"\x1b[0;31mFAILED\x1b[0m" default_words = ["build timed out", "error", "fail", "failed", "fatal", "undefined"] error_re = re.compile( r'(?:\b|(?<=m))(%s)\b' % '|'.join(default_words), re.IGNORECASE) # Match the dictionary string in the given line def objref(line): return re.search(r'api\.ObjectReference(\{.*?&#34;\})', line) # Combine a list of words into one regex that match any of them def combine_wordsRE(words_list): return re.compile(r'\b(%s)\b' % '|'.join(words_list), re.IGNORECASE) # Match the file name of a log given a filepath to the log log_re = re.compile(r'[^/]+\.log$') # Match the container id given a line containing the pod name def containerID(line): return re.search(r'ContainerID:([0-9A-Fa-f]*)', line) def timestamp(line): return re.search(r'(\d\d-?\d\d[T\s]\d\d:\d\d:\d\d\.\d+)', line) def sub_timestamp(line): return re.sub(r'(-|T|\s)', "", timestamp(line).group(0))
apache-2.0
novaksam/python-jss
jss/contrib/requests/packages/chardet/langcyrillicmodel.py
2762
17725
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # KOI8-R language model # Character Mapping Table: KOI8R_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, # 80 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, # 90 223,224,225, 68,226,227,228,229,230,231,232,233,234,235,236,237, # a0 238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253, # b0 27, 3, 21, 28, 13, 2, 39, 19, 26, 4, 23, 11, 8, 12, 5, 1, # c0 15, 16, 9, 7, 6, 14, 24, 10, 17, 18, 20, 25, 30, 29, 22, 54, # d0 59, 37, 44, 58, 41, 48, 53, 46, 55, 42, 60, 36, 49, 38, 31, 34, # e0 35, 43, 45, 32, 40, 52, 56, 33, 61, 62, 51, 57, 47, 63, 50, 70, # f0 ) win1251_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, 223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238, 239,240,241,242,243,244,245,246, 68,247,248,249,250,251,252,253, 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16, ) latin5_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, 223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238, 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16, 239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255, ) macCyrillic_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, 223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238, 239,240,241,242,243,244,245,246,247,248,249,250,251,252, 68, 16, 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27,255, ) IBM855_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 191,192,193,194, 68,195,196,197,198,199,200,201,202,203,204,205, 206,207,208,209,210,211,212,213,214,215,216,217, 27, 59, 54, 70, 3, 37, 21, 44, 28, 58, 13, 41, 2, 48, 39, 53, 19, 46,218,219, 220,221,222,223,224, 26, 55, 4, 42,225,226,227,228, 23, 60,229, 230,231,232,233,234,235, 11, 36,236,237,238,239,240,241,242,243, 8, 49, 12, 38, 5, 31, 1, 34, 15,244,245,246,247, 35, 16,248, 43, 9, 45, 7, 32, 6, 40, 14, 52, 24, 56, 10, 33, 17, 61,249, 250, 18, 62, 20, 51, 25, 57, 30, 47, 29, 63, 22, 50,251,252,255, ) IBM866_CharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, 223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238, 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16, 239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255, ) # Model Table: # total sequences: 100% # first 512 sequences: 97.6601% # first 1024 sequences: 2.3389% # rest sequences: 0.1237% # negative sequences: 0.0009% RussianLangModel = ( 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3,3,1,3,3,3,2,3,2,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,2,2,2,2,0,0,2, 3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,2,3,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,2,2,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,2,3,3,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1, 0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1, 0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,2,2,2,3,1,3,3,1,3,3,3,3,2,2,3,0,2,2,2,3,3,2,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,3,3,3,2,2,3,2,3,3,3,2,1,2,2,0,1,2,2,2,2,2,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,3,0,2,2,3,3,2,1,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,1,2,3,2,2,3,2,3,3,3,3,2,2,3,0,3,2,2,3,1,1,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,2,3,3,3,3,2,2,2,0,3,3,3,2,2,2,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,2,3,2,2,0,1,3,2,1,2,2,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,1,1,3,0,1,1,1,1,2,1,1,0,2,2,2,1,2,0,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,2,2,2,2,1,3,2,3,2,3,2,1,2,2,0,1,1,2,1,2,1,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,3,3,3,2,2,2,2,0,2,2,2,2,3,1,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,2,3,2,2,3,3,3,3,3,3,3,3,3,1,3,2,0,0,3,3,3,3,2,3,3,3,3,2,3,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,3,2,2,3,3,0,2,1,0,3,2,3,2,3,0,0,1,2,0,0,1,0,1,2,1,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,3,0,2,3,3,3,3,2,3,3,3,3,1,2,2,0,0,2,3,2,2,2,3,2,3,2,2,3,0,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,0,2,3,2,3,0,1,2,3,3,2,0,2,3,0,0,2,3,2,2,0,1,3,1,3,2,2,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,3,0,2,3,3,3,3,3,3,3,3,2,1,3,2,0,0,2,2,3,3,3,2,3,3,0,2,2,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,2,3,3,2,2,2,3,3,0,0,1,1,1,1,1,2,0,0,1,1,1,1,0,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,2,3,3,3,3,3,3,3,0,3,2,3,3,2,3,2,0,2,1,0,1,1,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,3,2,2,2,2,3,1,3,2,3,1,1,2,1,0,2,2,2,2,1,3,1,0, 0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 2,2,3,3,3,3,3,1,2,2,1,3,1,0,3,0,0,3,0,0,0,1,1,0,1,2,1,0,0,0,0,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,2,1,1,3,3,3,2,2,1,2,2,3,1,1,2,0,0,2,2,1,3,0,0,2,1,1,2,1,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,3,3,3,1,2,2,2,1,2,1,3,3,1,1,2,1,2,1,2,2,0,2,0,0,1,1,0,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,3,2,1,3,2,2,3,2,0,3,2,0,3,0,1,0,1,1,0,0,1,1,1,1,0,1,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,3,3,3,2,2,2,3,3,1,2,1,2,1,0,1,0,1,1,0,1,0,0,2,1,1,1,0,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 3,1,1,2,1,2,3,3,2,2,1,2,2,3,0,2,1,0,0,2,2,3,2,1,2,2,2,2,2,3,1,0, 0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,1,1,0,1,1,2,2,1,1,3,0,0,1,3,1,1,1,0,0,0,1,0,1,1,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,3,3,3,2,0,0,0,2,1,0,1,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,0,1,0,0,2,3,2,2,2,1,2,2,2,1,2,1,0,0,1,1,1,0,2,0,1,1,1,0,0,1,1, 1,0,0,0,0,0,1,2,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,0,0,0,0,1,0,0,0,0,3,0,1,2,1,0,0,0,0,0,0,0,1,1,0,0,1,1, 1,0,1,0,1,2,0,0,1,1,2,1,0,1,1,1,1,0,1,1,1,1,0,1,0,0,1,0,0,1,1,0, 2,2,3,2,2,2,3,1,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,0,1,0,1,1,1,0,2,1, 1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,0,1,1,0, 3,3,3,2,2,2,2,3,2,2,1,1,2,2,2,2,1,1,3,1,2,1,2,0,0,1,1,0,1,0,2,1, 1,1,1,1,1,2,1,0,1,1,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,1,0, 2,0,0,1,0,3,2,2,2,2,1,2,1,2,1,2,0,0,0,2,1,2,2,1,1,2,2,0,1,1,0,2, 1,1,1,1,1,0,1,1,1,2,1,1,1,2,1,0,1,2,1,1,1,1,0,1,1,1,0,0,1,0,0,1, 1,3,2,2,2,1,1,1,2,3,0,0,0,0,2,0,2,2,1,0,0,0,0,0,0,1,0,0,0,0,1,1, 1,0,1,1,0,1,0,1,1,0,1,1,0,2,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0, 2,3,2,3,2,1,2,2,2,2,1,0,0,0,2,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,2,1, 1,1,2,1,0,2,0,0,1,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,0, 3,0,0,1,0,2,2,2,3,2,2,2,2,2,2,2,0,0,0,2,1,2,1,1,1,2,2,0,0,0,1,2, 1,1,1,1,1,0,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,1, 2,3,2,3,3,2,0,1,1,1,0,0,1,0,2,0,1,1,3,1,0,0,0,0,0,0,0,1,0,0,2,1, 1,1,1,1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0, 2,3,3,3,3,1,2,2,2,2,0,1,1,0,2,1,1,1,2,1,0,1,1,0,0,1,0,1,0,0,2,0, 0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,2,0,0,1,1,2,2,1,0,0,2,0,1,1,3,0,0,1,0,0,0,0,0,1,0,1,2,1, 1,1,2,0,1,1,1,0,1,0,1,1,0,1,0,1,1,1,1,0,1,0,0,0,0,0,0,1,0,1,1,0, 1,3,2,3,2,1,0,0,2,2,2,0,1,0,2,0,1,1,1,0,1,0,0,0,3,0,1,1,0,0,2,1, 1,1,1,0,1,1,0,0,0,0,1,1,0,1,0,0,2,1,1,0,1,0,0,0,1,0,1,0,0,1,1,0, 3,1,2,1,1,2,2,2,2,2,2,1,2,2,1,1,0,0,0,2,2,2,0,0,0,1,2,1,0,1,0,1, 2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,2,1,1,1,0,1,0,1,1,0,1,1,1,0,0,1, 3,0,0,0,0,2,0,1,1,1,1,1,1,1,0,1,0,0,0,1,1,1,0,1,0,1,1,0,0,1,0,1, 1,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,1, 1,3,3,2,2,0,0,0,2,2,0,0,0,1,2,0,1,1,2,0,0,0,0,0,0,0,0,1,0,0,2,1, 0,1,1,0,0,1,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0, 2,3,2,3,2,0,0,0,0,1,1,0,0,0,2,0,2,0,2,0,0,0,0,0,1,0,0,1,0,0,1,1, 1,1,2,0,1,2,1,0,1,1,2,1,1,1,1,1,2,1,1,0,1,0,0,1,1,1,1,1,0,1,1,0, 1,3,2,2,2,1,0,0,2,2,1,0,1,2,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1, 0,0,1,1,0,1,1,0,0,1,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,0,2,3,1,2,2,2,2,2,2,1,1,0,0,0,1,0,1,0,2,1,1,1,0,0,0,0,1, 1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0, 2,0,2,0,0,1,0,3,2,1,2,1,2,2,0,1,0,0,0,2,1,0,0,2,1,1,1,1,0,2,0,2, 2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,0,0,0,1,1,1,1,0,1,0,0,1, 1,2,2,2,2,1,0,0,1,0,0,0,0,0,2,0,1,1,1,1,0,0,0,0,1,0,1,2,0,0,2,0, 1,0,1,1,1,2,1,0,1,0,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0, 2,1,2,2,2,0,3,0,1,1,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 0,0,0,1,1,1,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0, 1,2,2,3,2,2,0,0,1,1,2,0,1,2,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1, 0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0, 2,2,1,1,2,1,2,2,2,2,2,1,2,2,0,1,0,0,0,1,2,2,2,1,2,1,1,1,1,1,2,1, 1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,0,1, 1,2,2,2,2,0,1,0,2,2,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0, 0,0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,2,0,0,0,2,2,2,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1, 0,1,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,2,0,0,0,0,1,0,0,1,1,2,0,0,0,0,1,0,1,0,0,1,0,0,2,0,0,0,1, 0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,1,1,2,0,2,1,1,1,1,0,2,2,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1, 0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 1,0,2,1,2,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0, 0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,0,0,2,0,1,2,1,0,1,1,1,0,1,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,1, 0,0,0,0,0,1,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1, 2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,1,1,0,1,0,1,0,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,1,0,1,1,0,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0, 0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, ) Koi8rModel = { 'charToOrderMap': KOI8R_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "KOI8-R" } Win1251CyrillicModel = { 'charToOrderMap': win1251_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "windows-1251" } Latin5CyrillicModel = { 'charToOrderMap': latin5_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "ISO-8859-5" } MacCyrillicModel = { 'charToOrderMap': macCyrillic_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "MacCyrillic" }; Ibm866Model = { 'charToOrderMap': IBM866_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "IBM866" } Ibm855Model = { 'charToOrderMap': IBM855_CharToOrderMap, 'precedenceMatrix': RussianLangModel, 'mTypicalPositiveRatio': 0.976601, 'keepEnglishLetter': False, 'charsetName': "IBM855" } # flake8: noqa
gpl-3.0
MattRijk/django-ecomsite
lib/python2.7/site-packages/django/contrib/sessions/backends/db.py
101
2929
import logging from django.contrib.sessions.backends.base import SessionBase, CreateError from django.core.exceptions import SuspiciousOperation from django.db import IntegrityError, transaction, router from django.utils import timezone from django.utils.encoding import force_text class SessionStore(SessionBase): """ Implements database session store. """ def __init__(self, session_key=None): super(SessionStore, self).__init__(session_key) def load(self): try: s = Session.objects.get( session_key=self.session_key, expire_date__gt=timezone.now() ) return self.decode(s.session_data) except (Session.DoesNotExist, SuspiciousOperation) as e: if isinstance(e, SuspiciousOperation): logger = logging.getLogger('django.security.%s' % e.__class__.__name__) logger.warning(force_text(e)) self.create() return {} def exists(self, session_key): return Session.objects.filter(session_key=session_key).exists() def create(self): while True: self._session_key = self._get_new_session_key() try: # Save immediately to ensure we have a unique entry in the # database. self.save(must_create=True) except CreateError: # Key wasn't unique. Try again. continue self.modified = True self._session_cache = {} return def save(self, must_create=False): """ Saves the current session data to the database. If 'must_create' is True, a database error will be raised if the saving operation doesn't create a *new* entry (as opposed to possibly updating an existing entry). """ obj = Session( session_key=self._get_or_create_session_key(), session_data=self.encode(self._get_session(no_load=must_create)), expire_date=self.get_expiry_date() ) using = router.db_for_write(Session, instance=obj) try: with transaction.atomic(using=using): obj.save(force_insert=must_create, using=using) except IntegrityError: if must_create: raise CreateError raise def delete(self, session_key=None): if session_key is None: if self.session_key is None: return session_key = self.session_key try: Session.objects.get(session_key=session_key).delete() except Session.DoesNotExist: pass @classmethod def clear_expired(cls): Session.objects.filter(expire_date__lt=timezone.now()).delete() # At bottom to avoid circular import from django.contrib.sessions.models import Session
cc0-1.0
thnee/ansible
test/units/modules/network/nxos/test_nxos_ospf.py
23
2029
# (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from units.compat.mock import patch from ansible.modules.network.nxos import nxos_ospf from .nxos_module import TestNxosModule, set_module_args class TestNxosOspfModule(TestNxosModule): module = nxos_ospf def setUp(self): super(TestNxosOspfModule, self).setUp() self.mock_load_config = patch('ansible.modules.network.nxos.nxos_ospf.load_config') self.load_config = self.mock_load_config.start() self.mock_get_config = patch('ansible.modules.network.nxos.nxos_ospf.get_config') self.get_config = self.mock_get_config.start() def tearDown(self): super(TestNxosOspfModule, self).tearDown() self.mock_load_config.stop() self.mock_get_config.stop() def load_fixtures(self, commands=None, device=''): self.load_config.return_value = None def test_nxos_ospf_present(self): set_module_args(dict(ospf=1, state='present')) result = self.execute_module(changed=True) self.assertEqual(result['commands'], ['router ospf 1']) def test_nxos_ospf_absent(self): set_module_args(dict(ospf=1, state='absent')) result = self.execute_module(changed=False) self.assertEqual(result['commands'], [])
gpl-3.0
aiguofer/bokeh
examples/app/gapminder/main.py
3
2668
# -*- coding: utf-8 -*- import pandas as pd from bokeh.core.properties import field from bokeh.io import curdoc from bokeh.layouts import layout from bokeh.models import ( ColumnDataSource, HoverTool, SingleIntervalTicker, Slider, Button, Label, CategoricalColorMapper, ) from bokeh.palettes import Spectral6 from bokeh.plotting import figure from data import process_data fertility_df, life_expectancy_df, population_df_size, regions_df, years, regions_list = process_data() sources = {} region_name = regions_df.Group region_name.name = 'region' for year in years: fertility = fertility_df[year] fertility.name = 'fertility' life = life_expectancy_df[year] life.name = 'life' population = population_df_size[year] population.name = 'population' df = pd.concat([fertility, life, population, region_name], axis=1) df = df.fillna('NaN') sources[year] = ColumnDataSource(df) source = sources[years[0]] plot = figure(x_range=(1, 9), y_range=(20, 100), title='Gapminder Data', plot_height=300) plot.xaxis.ticker = SingleIntervalTicker(interval=1) plot.xaxis.axis_label = "Children per woman (total fertility)" plot.yaxis.ticker = SingleIntervalTicker(interval=20) plot.yaxis.axis_label = "Life expectancy at birth (years)" label = Label(x=1.1, y=18, text=str(years[0]), text_font_size='70pt', text_color='#eeeeee') plot.add_layout(label) color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list) plot.circle( x='fertility', y='life', size='population', source=source, fill_color={'field': 'region', 'transform': color_mapper}, fill_alpha=0.8, line_color='#7c7e71', line_width=0.5, line_alpha=0.5, legend=field('region'), ) plot.add_tools(HoverTool(tooltips="@index", show_arrow=False, point_policy='follow_mouse')) def animate_update(): year = slider.value + 1 if year > years[-1]: year = years[0] slider.value = year def slider_update(attrname, old, new): year = slider.value label.text = str(year) source.data = sources[year].data slider = Slider(start=years[0], end=years[-1], value=years[0], step=1, title="Year") slider.on_change('value', slider_update) def animate(): if button.label == '► Play': button.label = '❚❚ Pause' curdoc().add_periodic_callback(animate_update, 200) else: button.label = '► Play' curdoc().remove_periodic_callback(animate_update) button = Button(label='► Play', width=60) button.on_click(animate) layout = layout([ [plot], [slider, button], ], sizing_mode='scale_width') curdoc().add_root(layout) curdoc().title = "Gapminder"
bsd-3-clause
tshrinivasan/open-tamil
examples/wordxsec.py
3
2497
#!/usr/bin/python # -*- coding: utf-8 -*- # (C) 2015 Muthiah Annamalai import copy, random import tamil from sys import version PYTHON3 = version > '3' # compute word intersection graph of the a wordlist # optimized for using the symmetry in computation but not space class WordXSec: @staticmethod def driver(wordlist): obj = WordXSec( wordlist ) obj.compute() obj.display() return obj def __init__(self,wordlist): self.wordlist = wordlist # adjacency list of intersection graph self.xsections = {} def compute( self ): # compute the intersection graph into @xsections dictionary wordlist = self.wordlist """ build a dictionary of words, and their intersections """ xsections = {} for i in range(len(wordlist)): word_i = wordlist[i] for j in range(len(wordlist)): word_j = wordlist[j] if i == j: # force self-intersection to be 0 if not xsections.get(word_i,None): xsections[word_i] = [''] else: xsections[word_i].extend(['']) continue # optimize for, i > j, info is calculated already if i > j: xsec_counts = xsections[word_j][i] else: xsec_counts = tamil.utf8.word_intersection( word_i, word_j ) if not xsections.get(word_i,None): xsections[word_i] = [xsec_counts] else: xsections[word_i].extend( [ xsec_counts ] ) self.xsections = xsections def display(self): # print adjacency list of intersection graph for k in self.wordlist: v = self.xsections[k] print( ",".join( ["%d"%len(vv) for vv in v] ) ) return if __name__ == "__main__": lang = ['EN','TA'][0] if lang == 'EN': wordlist = [u'food',u'water',u'shelter',u'clothing'] fill_letters = list(map(chr,[ord('a')+i for i in range(0,26)])) else: wordlist = [u'உப்பு', u'நாற்பண்',u'பராபரம்', u'கான்யாறு', u'ஆறு', u'சன்னியாசி', u'நெல்லி'] fill_letters = tamil.utf8.tamil_letters WordXSec.driver( wordlist )
mit
marckuz/django
django/contrib/gis/db/backends/spatialite/operations.py
257
11441
""" SQL functions reference lists: http://www.gaia-gis.it/spatialite-2.4.0/spatialite-sql-2.4.html http://www.gaia-gis.it/spatialite-3.0.0-BETA/spatialite-sql-3.0.0.html http://www.gaia-gis.it/gaia-sins/spatialite-sql-4.2.1.html """ import re import sys from django.contrib.gis.db.backends.base.operations import \ BaseSpatialOperations from django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter from django.contrib.gis.db.backends.utils import SpatialOperator from django.contrib.gis.db.models import aggregates from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Distance from django.core.exceptions import ImproperlyConfigured from django.db.backends.sqlite3.operations import DatabaseOperations from django.db.utils import DatabaseError from django.utils import six from django.utils.functional import cached_property class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations): name = 'spatialite' spatialite = True version_regex = re.compile(r'^(?P<major>\d)\.(?P<minor1>\d)\.(?P<minor2>\d+)') Adapter = SpatiaLiteAdapter Adaptor = Adapter # Backwards-compatibility alias. area = 'Area' centroid = 'Centroid' collect = 'Collect' contained = 'MbrWithin' difference = 'Difference' distance = 'Distance' envelope = 'Envelope' extent = 'Extent' intersection = 'Intersection' length = 'GLength' # OpenGis defines Length, but this conflicts with an SQLite reserved keyword num_geom = 'NumGeometries' num_points = 'NumPoints' point_on_surface = 'PointOnSurface' scale = 'ScaleCoords' svg = 'AsSVG' sym_difference = 'SymDifference' transform = 'Transform' translate = 'ShiftCoords' union = 'GUnion' # OpenGis defines Union, but this conflicts with an SQLite reserved keyword unionagg = 'GUnion' from_text = 'GeomFromText' from_wkb = 'GeomFromWKB' select = 'AsText(%s)' gis_operators = { 'equals': SpatialOperator(func='Equals'), 'disjoint': SpatialOperator(func='Disjoint'), 'touches': SpatialOperator(func='Touches'), 'crosses': SpatialOperator(func='Crosses'), 'within': SpatialOperator(func='Within'), 'overlaps': SpatialOperator(func='Overlaps'), 'contains': SpatialOperator(func='Contains'), 'intersects': SpatialOperator(func='Intersects'), 'relate': SpatialOperator(func='Relate'), # Returns true if B's bounding box completely contains A's bounding box. 'contained': SpatialOperator(func='MbrWithin'), # Returns true if A's bounding box completely contains B's bounding box. 'bbcontains': SpatialOperator(func='MbrContains'), # Returns true if A's bounding box overlaps B's bounding box. 'bboverlaps': SpatialOperator(func='MbrOverlaps'), # These are implemented here as synonyms for Equals 'same_as': SpatialOperator(func='Equals'), 'exact': SpatialOperator(func='Equals'), 'distance_gt': SpatialOperator(func='Distance', op='>'), 'distance_gte': SpatialOperator(func='Distance', op='>='), 'distance_lt': SpatialOperator(func='Distance', op='<'), 'distance_lte': SpatialOperator(func='Distance', op='<='), } @cached_property def function_names(self): return { 'Length': 'ST_Length', 'Reverse': 'ST_Reverse', 'Scale': 'ScaleCoords', 'Translate': 'ST_Translate' if self.spatial_version >= (3, 1, 0) else 'ShiftCoords', 'Union': 'ST_Union', } @cached_property def unsupported_functions(self): unsupported = {'BoundingCircle', 'ForceRHR', 'GeoHash', 'MemSize'} if self.spatial_version < (3, 1, 0): unsupported.add('SnapToGrid') if self.spatial_version < (4, 0, 0): unsupported.update({'Perimeter', 'Reverse'}) return unsupported @cached_property def spatial_version(self): """Determine the version of the SpatiaLite library.""" try: version = self.spatialite_version_tuple()[1:] except Exception as msg: new_msg = ( 'Cannot determine the SpatiaLite version for the "%s" ' 'database (error was "%s"). Was the SpatiaLite initialization ' 'SQL loaded on this database?') % (self.connection.settings_dict['NAME'], msg) six.reraise(ImproperlyConfigured, ImproperlyConfigured(new_msg), sys.exc_info()[2]) if version < (2, 4, 0): raise ImproperlyConfigured('GeoDjango only supports SpatiaLite versions ' '2.4.0 and above') return version @property def _version_greater_2_4_0_rc4(self): if self.spatial_version >= (2, 4, 1): return True else: # Spatialite 2.4.0-RC4 added AsGML and AsKML, however both # RC2 (shipped in popular Debian/Ubuntu packages) and RC4 # report version as '2.4.0', so we fall back to feature detection try: self._get_spatialite_func("AsGML(GeomFromText('POINT(1 1)'))") except DatabaseError: return False return True @cached_property def disallowed_aggregates(self): disallowed = (aggregates.Extent3D, aggregates.MakeLine) if self.spatial_version < (3, 0, 0): disallowed += (aggregates.Collect, aggregates.Extent) return disallowed @cached_property def gml(self): return 'AsGML' if self._version_greater_2_4_0_rc4 else None @cached_property def kml(self): return 'AsKML' if self._version_greater_2_4_0_rc4 else None @cached_property def geojson(self): return 'AsGeoJSON' if self.spatial_version >= (3, 0, 0) else None def convert_extent(self, box, srid): """ Convert the polygon data received from Spatialite to min/max values. """ if box is None: return None shell = Geometry(box, srid).shell xmin, ymin = shell[0][:2] xmax, ymax = shell[2][:2] return (xmin, ymin, xmax, ymax) def convert_geom(self, wkt, geo_field): """ Converts geometry WKT returned from a SpatiaLite aggregate. """ if wkt: return Geometry(wkt, geo_field.srid) else: return None def geo_db_type(self, f): """ Returns None because geometry columnas are added via the `AddGeometryColumn` stored procedure on SpatiaLite. """ return None def get_distance(self, f, value, lookup_type): """ Returns the distance parameters for the given geometry field, lookup value, and lookup type. SpatiaLite only supports regular cartesian-based queries (no spheroid/sphere calculations for point geometries like PostGIS). """ if not value: return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): raise ValueError('SpatiaLite does not support distance queries on ' 'geometry fields with a geodetic coordinate system. ' 'Distance objects; use a numeric value of your ' 'distance in degrees instead.') else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value return [dist_param] def get_geom_placeholder(self, f, value, compiler): """ Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the Transform() and GeomFromText() function call(s). """ def transform_value(value, srid): return not (value is None or value.srid == srid) if hasattr(value, 'as_sql'): if transform_value(value, f.srid): placeholder = '%s(%%s, %s)' % (self.transform, f.srid) else: placeholder = '%s' # No geometry value used for F expression, substitute in # the column name instead. sql, _ = compiler.compile(value) return placeholder % sql else: if transform_value(value, f.srid): # Adding Transform() to the SQL placeholder. return '%s(%s(%%s,%s), %s)' % (self.transform, self.from_text, value.srid, f.srid) else: return '%s(%%s,%s)' % (self.from_text, f.srid) def _get_spatialite_func(self, func): """ Helper routine for calling SpatiaLite functions and returning their result. Any error occurring in this method should be handled by the caller. """ cursor = self.connection._cursor() try: cursor.execute('SELECT %s' % func) row = cursor.fetchone() finally: cursor.close() return row[0] def geos_version(self): "Returns the version of GEOS used by SpatiaLite as a string." return self._get_spatialite_func('geos_version()') def proj4_version(self): "Returns the version of the PROJ.4 library used by SpatiaLite." return self._get_spatialite_func('proj4_version()') def spatialite_version(self): "Returns the SpatiaLite library version as a string." return self._get_spatialite_func('spatialite_version()') def spatialite_version_tuple(self): """ Returns the SpatiaLite version as a tuple (version string, major, minor, subminor). """ version = self.spatialite_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception('Could not parse SpatiaLite version string: %s' % version) return (version, major, minor1, minor2) def spatial_aggregate_name(self, agg_name): """ Returns the spatial aggregate SQL template and function for the given Aggregate instance. """ agg_name = 'unionagg' if agg_name.lower() == 'union' else agg_name.lower() return getattr(self, agg_name) # Routines for getting the OGC-compliant models. def geometry_columns(self): from django.contrib.gis.db.backends.spatialite.models import SpatialiteGeometryColumns return SpatialiteGeometryColumns def spatial_ref_sys(self): from django.contrib.gis.db.backends.spatialite.models import SpatialiteSpatialRefSys return SpatialiteSpatialRefSys def get_db_converters(self, expression): converters = super(SpatiaLiteOperations, self).get_db_converters(expression) if hasattr(expression.output_field, 'geom_type'): converters.append(self.convert_geometry) return converters def convert_geometry(self, value, expression, connection, context): if value: value = Geometry(value) if 'transformed_srid' in context: value.srid = context['transformed_srid'] return value
bsd-3-clause
bdelliott/wordgame
web/django/views/generic/dates.py
5
19345
import time import datetime from django.db import models from django.core.exceptions import ImproperlyConfigured from django.http import Http404 from django.views.generic.base import View from django.views.generic.detail import BaseDetailView, SingleObjectTemplateResponseMixin from django.views.generic.list import MultipleObjectMixin, MultipleObjectTemplateResponseMixin class YearMixin(object): year_format = '%Y' year = None def get_year_format(self): """ Get a year format string in strptime syntax to be used to parse the year from url variables. """ return self.year_format def get_year(self): "Return the year for which this view should display data" year = self.year if year is None: try: year = self.kwargs['year'] except KeyError: try: year = self.request.GET['year'] except KeyError: raise Http404("No year specified") return year class MonthMixin(object): month_format = '%b' month = None def get_month_format(self): """ Get a month format string in strptime syntax to be used to parse the month from url variables. """ return self.month_format def get_month(self): "Return the month for which this view should display data" month = self.month if month is None: try: month = self.kwargs['month'] except KeyError: try: month = self.request.GET['month'] except KeyError: raise Http404("No month specified") return month def get_next_month(self, date): """ Get the next valid month. """ first_day, last_day = _month_bounds(date) next = (last_day + datetime.timedelta(days=1)).replace(day=1) return _get_next_prev_month(self, next, is_previous=False, use_first_day=True) def get_previous_month(self, date): """ Get the previous valid month. """ first_day, last_day = _month_bounds(date) prev = (first_day - datetime.timedelta(days=1)) return _get_next_prev_month(self, prev, is_previous=True, use_first_day=True) class DayMixin(object): day_format = '%d' day = None def get_day_format(self): """ Get a day format string in strptime syntax to be used to parse the day from url variables. """ return self.day_format def get_day(self): "Return the day for which this view should display data" day = self.day if day is None: try: day = self.kwargs['day'] except KeyError: try: day = self.request.GET['day'] except KeyError: raise Http404("No day specified") return day def get_next_day(self, date): """ Get the next valid day. """ next = date + datetime.timedelta(days=1) return _get_next_prev_month(self, next, is_previous=False, use_first_day=False) def get_previous_day(self, date): """ Get the previous valid day. """ prev = date - datetime.timedelta(days=1) return _get_next_prev_month(self, prev, is_previous=True, use_first_day=False) class WeekMixin(object): week_format = '%U' week = None def get_week_format(self): """ Get a week format string in strptime syntax to be used to parse the week from url variables. """ return self.week_format def get_week(self): "Return the week for which this view should display data" week = self.week if week is None: try: week = self.kwargs['week'] except KeyError: try: week = self.request.GET['week'] except KeyError: raise Http404("No week specified") return week class DateMixin(object): """ Mixin class for views manipulating date-based data. """ date_field = None allow_future = False def get_date_field(self): """ Get the name of the date field to be used to filter by. """ if self.date_field is None: raise ImproperlyConfigured(u"%s.date_field is required." % self.__class__.__name__) return self.date_field def get_allow_future(self): """ Returns `True` if the view should be allowed to display objects from the future. """ return self.allow_future class BaseDateListView(MultipleObjectMixin, DateMixin, View): """ Abstract base class for date-based views display a list of objects. """ allow_empty = False def get(self, request, *args, **kwargs): self.date_list, self.object_list, extra_context = self.get_dated_items() context = self.get_context_data(object_list=self.object_list, date_list=self.date_list) context.update(extra_context) return self.render_to_response(context) def get_dated_items(self): """ Obtain the list of dates and itesm """ raise NotImplementedError('A DateView must provide an implementation of get_dated_items()') def get_dated_queryset(self, **lookup): """ Get a queryset properly filtered according to `allow_future` and any extra lookup kwargs. """ qs = self.get_queryset().filter(**lookup) date_field = self.get_date_field() allow_future = self.get_allow_future() allow_empty = self.get_allow_empty() if not allow_future: qs = qs.filter(**{'%s__lte' % date_field: datetime.datetime.now()}) if not allow_empty and not qs: raise Http404(u"No %s available" % unicode(qs.model._meta.verbose_name_plural)) return qs def get_date_list(self, queryset, date_type): """ Get a date list by calling `queryset.dates()`, checking along the way for empty lists that aren't allowed. """ date_field = self.get_date_field() allow_empty = self.get_allow_empty() date_list = queryset.dates(date_field, date_type)[::-1] if date_list is not None and not date_list and not allow_empty: raise Http404(u"No %s available" % unicode(qs.model._meta.verbose_name_plural)) return date_list def get_context_data(self, **kwargs): """ Get the context. Must return a Context (or subclass) instance. """ items = kwargs.pop('object_list') context = super(BaseDateListView, self).get_context_data(object_list=items) context.update(kwargs) return context class BaseArchiveIndexView(BaseDateListView): """ Base class for archives of date-based items. Requires a response mixin. """ context_object_name = 'latest' def get_dated_items(self): """ Return (date_list, items, extra_context) for this request. """ qs = self.get_dated_queryset() date_list = self.get_date_list(qs, 'year') if date_list: object_list = qs.order_by('-' + self.get_date_field()) else: object_list = qs.none() return (date_list, object_list, {}) class ArchiveIndexView(MultipleObjectTemplateResponseMixin, BaseArchiveIndexView): """ Top-level archive of date-based items. """ template_name_suffix = '_archive' class BaseYearArchiveView(YearMixin, BaseDateListView): """ List of objects published in a given year. """ make_object_list = False def get_dated_items(self): """ Return (date_list, items, extra_context) for this request. """ # Yes, no error checking: the URLpattern ought to validate this; it's # an error if it doesn't. year = self.get_year() date_field = self.get_date_field() qs = self.get_dated_queryset(**{date_field+'__year': year}) date_list = self.get_date_list(qs, 'month') if self.get_make_object_list(): object_list = qs.order_by('-'+date_field) else: # We need this to be a queryset since parent classes introspect it # to find information about the model. object_list = qs.none() return (date_list, object_list, {'year': year}) def get_make_object_list(self): """ Return `True` if this view should contain the full list of objects in the given year. """ return self.make_object_list class YearArchiveView(MultipleObjectTemplateResponseMixin, BaseYearArchiveView): """ List of objects published in a given year. """ template_name_suffix = '_archive_year' class BaseMonthArchiveView(YearMixin, MonthMixin, BaseDateListView): """ List of objects published in a given year. """ def get_dated_items(self): """ Return (date_list, items, extra_context) for this request. """ year = self.get_year() month = self.get_month() date_field = self.get_date_field() date = _date_from_string(year, self.get_year_format(), month, self.get_month_format()) # Construct a date-range lookup. first_day, last_day = _month_bounds(date) lookup_kwargs = { '%s__gte' % date_field: first_day, '%s__lt' % date_field: last_day, } qs = self.get_dated_queryset(**lookup_kwargs) date_list = self.get_date_list(qs, 'day') return (date_list, qs, { 'month': date, 'next_month': self.get_next_month(date), 'previous_month': self.get_previous_month(date), }) class MonthArchiveView(MultipleObjectTemplateResponseMixin, BaseMonthArchiveView): """ List of objects published in a given year. """ template_name_suffix = '_archive_month' class BaseWeekArchiveView(YearMixin, WeekMixin, BaseDateListView): """ List of objects published in a given week. """ def get_dated_items(self): """ Return (date_list, items, extra_context) for this request. """ year = self.get_year() week = self.get_week() date_field = self.get_date_field() week_format = self.get_week_format() week_start = { '%W': '1', '%U': '0', }[week_format] date = _date_from_string(year, self.get_year_format(), week_start, '%w', week, week_format) # Construct a date-range lookup. first_day = date last_day = date + datetime.timedelta(days=7) lookup_kwargs = { '%s__gte' % date_field: first_day, '%s__lt' % date_field: last_day, } qs = self.get_dated_queryset(**lookup_kwargs) return (None, qs, {'week': date}) class WeekArchiveView(MultipleObjectTemplateResponseMixin, BaseWeekArchiveView): """ List of objects published in a given week. """ template_name_suffix = '_archive_week' class BaseDayArchiveView(YearMixin, MonthMixin, DayMixin, BaseDateListView): """ List of objects published on a given day. """ def get_dated_items(self): """ Return (date_list, items, extra_context) for this request. """ year = self.get_year() month = self.get_month() day = self.get_day() date = _date_from_string(year, self.get_year_format(), month, self.get_month_format(), day, self.get_day_format()) return self._get_dated_items(date) def _get_dated_items(self, date): """ Do the actual heavy lifting of getting the dated items; this accepts a date object so that TodayArchiveView can be trivial. """ date_field = self.get_date_field() field = self.get_queryset().model._meta.get_field(date_field) lookup_kwargs = _date_lookup_for_field(field, date) qs = self.get_dated_queryset(**lookup_kwargs) return (None, qs, { 'day': date, 'previous_day': self.get_previous_day(date), 'next_day': self.get_next_day(date), 'previous_month': self.get_previous_month(date), 'next_month': self.get_next_month(date) }) class DayArchiveView(MultipleObjectTemplateResponseMixin, BaseDayArchiveView): """ List of objects published on a given day. """ template_name_suffix = "_archive_day" class BaseTodayArchiveView(BaseDayArchiveView): """ List of objects published today. """ def get_dated_items(self): """ Return (date_list, items, extra_context) for this request. """ return self._get_dated_items(datetime.date.today()) class TodayArchiveView(MultipleObjectTemplateResponseMixin, BaseTodayArchiveView): """ List of objects published today. """ template_name_suffix = "_archive_day" class BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView): """ Detail view of a single object on a single date; this differs from the standard DetailView by accepting a year/month/day in the URL. """ def get_object(self, queryset=None): """ Get the object this request displays. """ year = self.get_year() month = self.get_month() day = self.get_day() date = _date_from_string(year, self.get_year_format(), month, self.get_month_format(), day, self.get_day_format()) qs = self.get_queryset() if not self.get_allow_future() and date > datetime.date.today(): raise Http404("Future %s not available because %s.allow_future is False." % ( qs.model._meta.verbose_name_plural, self.__class__.__name__) ) # Filter down a queryset from self.queryset using the date from the # URL. This'll get passed as the queryset to DetailView.get_object, # which'll handle the 404 date_field = self.get_date_field() field = qs.model._meta.get_field(date_field) lookup = _date_lookup_for_field(field, date) qs = qs.filter(**lookup) return super(BaseDetailView, self).get_object(queryset=qs) class DateDetailView(SingleObjectTemplateResponseMixin, BaseDateDetailView): """ Detail view of a single object on a single date; this differs from the standard DetailView by accepting a year/month/day in the URL. """ template_name_suffix = '_detail' def _date_from_string(year, year_format, month, month_format, day='', day_format='', delim='__'): """ Helper: get a datetime.date object given a format string and a year, month, and possibly day; raise a 404 for an invalid date. """ format = delim.join((year_format, month_format, day_format)) datestr = delim.join((year, month, day)) try: return datetime.date(*time.strptime(datestr, format)[:3]) except ValueError: raise Http404(u"Invalid date string '%s' given format '%s'" % (datestr, format)) def _month_bounds(date): """ Helper: return the first and last days of the month for the given date. """ first_day = date.replace(day=1) if first_day.month == 12: last_day = first_day.replace(year=first_day.year + 1, month=1) else: last_day = first_day.replace(month=first_day.month + 1) return first_day, last_day def _get_next_prev_month(generic_view, naive_result, is_previous, use_first_day): """ Helper: Get the next or the previous valid date. The idea is to allow links on month/day views to never be 404s by never providing a date that'll be invalid for the given view. This is a bit complicated since it handles both next and previous months and days (for MonthArchiveView and DayArchiveView); hence the coupling to generic_view. However in essence the logic comes down to: * If allow_empty and allow_future are both true, this is easy: just return the naive result (just the next/previous day or month, reguardless of object existence.) * If allow_empty is true, allow_future is false, and the naive month isn't in the future, then return it; otherwise return None. * If allow_empty is false and allow_future is true, return the next date *that contains a valid object*, even if it's in the future. If there are no next objects, return None. * If allow_empty is false and allow_future is false, return the next date that contains a valid object. If that date is in the future, or if there are no next objects, return None. """ date_field = generic_view.get_date_field() allow_empty = generic_view.get_allow_empty() allow_future = generic_view.get_allow_future() # If allow_empty is True the naive value will be valid if allow_empty: result = naive_result # Otherwise, we'll need to go to the database to look for an object # whose date_field is at least (greater than/less than) the given # naive result else: # Construct a lookup and an ordering depending on whether we're doing # a previous date or a next date lookup. if is_previous: lookup = {'%s__lte' % date_field: naive_result} ordering = '-%s' % date_field else: lookup = {'%s__gte' % date_field: naive_result} ordering = date_field qs = generic_view.get_queryset().filter(**lookup).order_by(ordering) # Snag the first object from the queryset; if it doesn't exist that # means there's no next/previous link available. try: result = getattr(qs[0], date_field) except IndexError: result = None # Convert datetimes to a dates if hasattr(result, 'date'): result = result.date() # For month views, we always want to have a date that's the first of the # month for consistency's sake. if result and use_first_day: result = result.replace(day=1) # Check against future dates. if result and (allow_future or result < datetime.date.today()): return result else: return None def _date_lookup_for_field(field, date): """ Get the lookup kwargs for looking up a date against a given Field. If the date field is a DateTimeField, we can't just do filter(df=date) because that doesn't take the time into account. So we need to make a range lookup in those cases. """ if isinstance(field, models.DateTimeField): date_range = ( datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max) ) return {'%s__range' % field.name: date_range} else: return {field.name: date}
mit
emon10005/sympy
sympy/solvers/inequalities.py
25
17580
"""Tools for solving inequalities and systems of inequalities. """ from __future__ import print_function, division from sympy.core import Symbol, Dummy from sympy.core.compatibility import iterable, reduce from sympy.sets import Interval from sympy.core.relational import Relational, Eq, Ge, Lt from sympy.sets.sets import FiniteSet, Union from sympy.core.singleton import S from sympy.functions import Abs from sympy.logic import And from sympy.polys import Poly, PolynomialError, parallel_poly_from_expr from sympy.polys.polyutils import _nsort from sympy.utilities.misc import filldedent def solve_poly_inequality(poly, rel): """Solve a polynomial inequality with rational coefficients. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> from sympy.solvers.inequalities import solve_poly_inequality >>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==') [{0}] >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=') [(-oo, -1), (-1, 1), (1, oo)] >>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==') [{-1}, {1}] See Also ======== solve_poly_inequalities """ if not isinstance(poly, Poly): raise ValueError( 'For efficiency reasons, `poly` should be a Poly instance') if poly.is_number: t = Relational(poly.as_expr(), 0, rel) if t is S.true: return [S.Reals] elif t is S.false: return [S.EmptySet] else: raise NotImplementedError( "could not determine truth value of %s" % t) reals, intervals = poly.real_roots(multiple=False), [] if rel == '==': for root, _ in reals: interval = Interval(root, root) intervals.append(interval) elif rel == '!=': left = S.NegativeInfinity for right, _ in reals + [(S.Infinity, 1)]: interval = Interval(left, right, True, True) intervals.append(interval) left = right else: if poly.LC() > 0: sign = +1 else: sign = -1 eq_sign, equal = None, False if rel == '>': eq_sign = +1 elif rel == '<': eq_sign = -1 elif rel == '>=': eq_sign, equal = +1, True elif rel == '<=': eq_sign, equal = -1, True else: raise ValueError("'%s' is not a valid relation" % rel) right, right_open = S.Infinity, True for left, multiplicity in reversed(reals): if multiplicity % 2: if sign == eq_sign: intervals.insert( 0, Interval(left, right, not equal, right_open)) sign, right, right_open = -sign, left, not equal else: if sign == eq_sign and not equal: intervals.insert( 0, Interval(left, right, True, right_open)) right, right_open = left, True elif sign != eq_sign and equal: intervals.insert(0, Interval(left, left)) if sign == eq_sign: intervals.insert( 0, Interval(S.NegativeInfinity, right, True, right_open)) return intervals def solve_poly_inequalities(polys): """Solve polynomial inequalities with rational coefficients. Examples ======== >>> from sympy.solvers.inequalities import solve_poly_inequalities >>> from sympy.polys import Poly >>> from sympy.abc import x >>> solve_poly_inequalities((( ... Poly(x**2 - 3), ">"), ( ... Poly(-x**2 + 1), ">"))) (-oo, -sqrt(3)) U (-1, 1) U (sqrt(3), oo) """ from sympy import Union return Union(*[solve_poly_inequality(*p) for p in polys]) def solve_rational_inequalities(eqs): """Solve a system of rational inequalities with rational coefficients. Examples ======== >>> from sympy.abc import x >>> from sympy import Poly >>> from sympy.solvers.inequalities import solve_rational_inequalities >>> solve_rational_inequalities([[ ... ((Poly(-x + 1), Poly(1, x)), '>='), ... ((Poly(-x + 1), Poly(1, x)), '<=')]]) {1} >>> solve_rational_inequalities([[ ... ((Poly(x), Poly(1, x)), '!='), ... ((Poly(-x + 1), Poly(1, x)), '>=')]]) (-oo, 0) U (0, 1] See Also ======== solve_poly_inequality """ result = S.EmptySet for _eqs in eqs: if not _eqs: continue global_intervals = [Interval(S.NegativeInfinity, S.Infinity)] for (numer, denom), rel in _eqs: numer_intervals = solve_poly_inequality(numer*denom, rel) denom_intervals = solve_poly_inequality(denom, '==') intervals = [] for numer_interval in numer_intervals: for global_interval in global_intervals: interval = numer_interval.intersect(global_interval) if interval is not S.EmptySet: intervals.append(interval) global_intervals = intervals intervals = [] for global_interval in global_intervals: for denom_interval in denom_intervals: global_interval -= denom_interval if global_interval is not S.EmptySet: intervals.append(global_interval) global_intervals = intervals if not global_intervals: break for interval in global_intervals: result = result.union(interval) return result def reduce_rational_inequalities(exprs, gen, relational=True): """Reduce a system of rational inequalities with rational coefficients. Examples ======== >>> from sympy import Poly, Symbol >>> from sympy.solvers.inequalities import reduce_rational_inequalities >>> x = Symbol('x', real=True) >>> reduce_rational_inequalities([[x**2 <= 0]], x) Eq(x, 0) >>> reduce_rational_inequalities([[x + 2 > 0]], x) And(-2 < x, x < oo) >>> reduce_rational_inequalities([[(x + 2, ">")]], x) And(-2 < x, x < oo) >>> reduce_rational_inequalities([[x + 2]], x) Eq(x, -2) """ exact = True eqs = [] solution = S.EmptySet for _exprs in exprs: _eqs = [] for expr in _exprs: if isinstance(expr, tuple): expr, rel = expr else: if expr.is_Relational: expr, rel = expr.lhs - expr.rhs, expr.rel_op else: expr, rel = expr, '==' if expr is S.true: numer, denom, rel = S.Zero, S.One, '==' elif expr is S.false: numer, denom, rel = S.One, S.One, '==' else: numer, denom = expr.together().as_numer_denom() try: (numer, denom), opt = parallel_poly_from_expr( (numer, denom), gen) except PolynomialError: raise PolynomialError(filldedent(''' only polynomials and rational functions are supported in this context''')) if not opt.domain.is_Exact: numer, denom, exact = numer.to_exact(), denom.to_exact(), False domain = opt.domain.get_exact() if not (domain.is_ZZ or domain.is_QQ): expr = numer/denom expr = Relational(expr, 0, rel) solution = Union(solution, solve_univariate_inequality(expr, gen, relational=False)) else: _eqs.append(((numer, denom), rel)) eqs.append(_eqs) solution = Union(solution, solve_rational_inequalities(eqs)) if not exact: solution = solution.evalf() if relational: solution = solution.as_relational(gen) return solution def reduce_abs_inequality(expr, rel, gen): """Reduce an inequality with nested absolute values. Examples ======== >>> from sympy import Abs, Symbol >>> from sympy.solvers.inequalities import reduce_abs_inequality >>> x = Symbol('x', real=True) >>> reduce_abs_inequality(Abs(x - 5) - 3, '<', x) And(2 < x, x < 8) >>> reduce_abs_inequality(Abs(x + 2)*3 - 13, '<', x) And(-19/3 < x, x < 7/3) See Also ======== reduce_abs_inequalities """ if gen.is_real is False: raise TypeError(filldedent(''' can't solve inequalities with absolute values containing non-real variables''')) def _bottom_up_scan(expr): exprs = [] if expr.is_Add or expr.is_Mul: op = expr.func for arg in expr.args: _exprs = _bottom_up_scan(arg) if not exprs: exprs = _exprs else: args = [] for expr, conds in exprs: for _expr, _conds in _exprs: args.append((op(expr, _expr), conds + _conds)) exprs = args elif expr.is_Pow: n = expr.exp if not n.is_Integer or n < 0: raise ValueError( "only non-negative integer powers are allowed") _exprs = _bottom_up_scan(expr.base) for expr, conds in _exprs: exprs.append((expr**n, conds)) elif isinstance(expr, Abs): _exprs = _bottom_up_scan(expr.args[0]) for expr, conds in _exprs: exprs.append(( expr, conds + [Ge(expr, 0)])) exprs.append((-expr, conds + [Lt(expr, 0)])) else: exprs = [(expr, [])] return exprs exprs = _bottom_up_scan(expr) mapping = {'<': '>', '<=': '>='} inequalities = [] for expr, conds in exprs: if rel not in mapping.keys(): expr = Relational( expr, 0, rel) else: expr = Relational(-expr, 0, mapping[rel]) inequalities.append([expr] + conds) return reduce_rational_inequalities(inequalities, gen) def reduce_abs_inequalities(exprs, gen): """Reduce a system of inequalities with nested absolute values. Examples ======== >>> from sympy import Abs, Symbol >>> from sympy.abc import x >>> from sympy.solvers.inequalities import reduce_abs_inequalities >>> x = Symbol('x', real=True) >>> reduce_abs_inequalities([(Abs(3*x - 5) - 7, '<'), ... (Abs(x + 25) - 13, '>')], x) And(-2/3 < x, Or(And(-12 < x, x < oo), And(-oo < x, x < -38)), x < 4) >>> reduce_abs_inequalities([(Abs(x - 4) + Abs(3*x - 5) - 7, '<')], x) And(1/2 < x, x < 4) See Also ======== reduce_abs_inequality """ return And(*[ reduce_abs_inequality(expr, rel, gen) for expr, rel in exprs ]) def solve_univariate_inequality(expr, gen, relational=True): """Solves a real univariate inequality. Examples ======== >>> from sympy.solvers.inequalities import solve_univariate_inequality >>> from sympy.core.symbol import Symbol >>> x = Symbol('x') >>> solve_univariate_inequality(x**2 >= 4, x) Or(And(-oo < x, x <= -2), And(2 <= x, x < oo)) >>> solve_univariate_inequality(x**2 >= 4, x, relational=False) (-oo, -2] U [2, oo) """ from sympy.solvers.solvers import solve, denoms # This keeps the function independent of the assumptions about `gen`. # `solveset` makes sure this function is called only when the domain is # real. d = Dummy(real=True) expr = expr.subs(gen, d) _gen = gen gen = d e = expr.lhs - expr.rhs parts = n, d = e.as_numer_denom() if all(i.is_polynomial(gen) for i in parts): solns = solve(n, gen, check=False) singularities = solve(d, gen, check=False) else: solns = solve(e, gen, check=False) singularities = [] for d in denoms(e): singularities.extend(solve(d, gen)) include_x = expr.func(0, 0) def valid(x): v = e.subs(gen, x) try: r = expr.func(v, 0) except TypeError: r = S.false if r in (S.true, S.false): return r if v.is_real is False: return S.false else: v = v.n(2) if v.is_comparable: return expr.func(v, 0) return S.false start = S.NegativeInfinity sol_sets = [S.EmptySet] try: reals = _nsort(set(solns + singularities), separated=True)[0] except NotImplementedError: raise NotImplementedError('sorting of these roots is not supported') for x in reals: end = x if end in [S.NegativeInfinity, S.Infinity]: if valid(S(0)): sol_sets.append(Interval(start, S.Infinity, True, True)) break if valid((start + end)/2 if start != S.NegativeInfinity else end - 1): sol_sets.append(Interval(start, end, True, True)) if x in singularities: singularities.remove(x) elif include_x: sol_sets.append(FiniteSet(x)) start = end end = S.Infinity if valid(start + 1): sol_sets.append(Interval(start, end, True, True)) rv = Union(*sol_sets).subs(gen, _gen) return rv if not relational else rv.as_relational(_gen) def _solve_inequality(ie, s): """ A hacky replacement for solve, since the latter only works for univariate inequalities. """ if not ie.rel_op in ('>', '>=', '<', '<='): raise NotImplementedError expr = ie.lhs - ie.rhs try: p = Poly(expr, s) if p.degree() != 1: raise NotImplementedError except (PolynomialError, NotImplementedError): try: n, d = expr.as_numer_denom() return reduce_rational_inequalities([[ie]], s) except PolynomialError: return solve_univariate_inequality(ie, s) a, b = p.all_coeffs() if a.is_positive: return ie.func(s, -b/a) elif a.is_negative: return ie.func(-b/a, s) else: raise NotImplementedError def _reduce_inequalities(inequalities, symbols): # helper for reduce_inequalities poly_part, abs_part = {}, {} other = [] for inequality in inequalities: expr, rel = inequality.lhs, inequality.rel_op # rhs is 0 # check for gens using atoms which is more strict than free_symbols to # guard against EX domain which won't be handled by # reduce_rational_inequalities gens = expr.atoms(Symbol) if len(gens) == 1: gen = gens.pop() else: common = expr.free_symbols & symbols if len(common) == 1: gen = common.pop() other.append(_solve_inequality(Relational(expr, 0, rel), gen)) continue else: raise NotImplementedError(filldedent(''' inequality has more than one symbol of interest''')) if expr.is_polynomial(gen): poly_part.setdefault(gen, []).append((expr, rel)) else: components = expr.find(lambda u: u.has(gen) and ( u.is_Function or u.is_Pow and not u.exp.is_Integer)) if components and all(isinstance(i, Abs) for i in components): abs_part.setdefault(gen, []).append((expr, rel)) else: other.append(_solve_inequality(Relational(expr, 0, rel), gen)) poly_reduced = [] abs_reduced = [] for gen, exprs in poly_part.items(): poly_reduced.append(reduce_rational_inequalities([exprs], gen)) for gen, exprs in abs_part.items(): abs_reduced.append(reduce_abs_inequalities(exprs, gen)) return And(*(poly_reduced + abs_reduced + other)) def reduce_inequalities(inequalities, symbols=[]): """Reduce a system of inequalities with rational coefficients. Examples ======== >>> from sympy import sympify as S, Symbol >>> from sympy.abc import x, y >>> from sympy.solvers.inequalities import reduce_inequalities >>> reduce_inequalities(0 <= x + 3, []) And(-3 <= x, x < oo) >>> reduce_inequalities(0 <= x + y*2 - 1, [x]) x >= -2*y + 1 """ if not iterable(inequalities): inequalities = [inequalities] # prefilter keep = [] for i in inequalities: if isinstance(i, Relational): i = i.func(i.lhs.as_expr() - i.rhs.as_expr(), 0) elif i not in (True, False): i = Eq(i, 0) if i == True: continue elif i == False: return S.false if i.lhs.is_number: raise NotImplementedError( "could not determine truth value of %s" % i) keep.append(i) inequalities = keep del keep gens = reduce(set.union, [i.free_symbols for i in inequalities], set()) if not iterable(symbols): symbols = [symbols] symbols = set(symbols) or gens # make vanilla symbol real recast = dict([(i, Dummy(i.name, real=True)) for i in gens if i.is_real is None]) inequalities = [i.xreplace(recast) for i in inequalities] symbols = set([i.xreplace(recast) for i in symbols]) # solve system rv = _reduce_inequalities(inequalities, symbols) # restore original symbols and return return rv.xreplace(dict([(v, k) for k, v in recast.items()]))
bsd-3-clause
jmartinm/invenio
modules/websession/lib/webuser_regression_tests.py
16
11178
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # pylint: disable=E1102 """WebSession Regression Test Suite.""" __revision__ = \ "$Id$" from invenio.testutils import InvenioTestCase from mechanize import Browser from invenio.dbquery import run_sql from invenio.config import CFG_SITE_SECURE_URL from invenio.testutils import make_test_suite, run_test_suite from invenio import webuser class IsUserSuperAdminTests(InvenioTestCase): """Test functions related to the isUserSuperAdmin function.""" def setUp(self): self.id_admin = run_sql('SELECT id FROM user WHERE nickname="admin"')[0][0] self.id_hyde = run_sql('SELECT id FROM user WHERE nickname="hyde"')[0][0] def test_isUserSuperAdmin_admin(self): """webuser - isUserSuperAdmin with admin""" self.failUnless(webuser.isUserSuperAdmin(webuser.collect_user_info(self.id_admin))) def test_isUserSuperAdmin_hyde(self): """webuser - isUserSuperAdmin with hyde""" self.failIf(webuser.isUserSuperAdmin(webuser.collect_user_info(self.id_hyde))) class WebSessionYourSettingsTests(InvenioTestCase): """Check WebSession web pages whether they are up or not.""" def tearDown(self): run_sql('DELETE FROM user WHERE email="foo@cds.cern.ch"') run_sql('DELETE FROM user WHERE email="FOO@cds.cern.ch"') def test_password_setting(self): """webuser - check password settings""" browser = Browser() browser.open(CFG_SITE_SECURE_URL + "/youraccount/login") browser.select_form(nr=0) browser['p_un'] = 'admin' browser['p_pw'] = '' browser.submit() expected_response = "You are logged in as admin" login_response_body = browser.response().read() try: login_response_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, login_response_body)) # Going to set new password from "" to "123" browser.open(CFG_SITE_SECURE_URL + "/youraccount/edit") browser.select_form(name="edit_password") browser['old_password'] = "" browser['password'] = "123" browser['password2'] = "123" browser.submit() expected_response = "Password successfully edited" change_password_body = browser.response().read() try: change_password_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, change_password_body)) # Going to set a wrong old password browser.open(CFG_SITE_SECURE_URL + "/youraccount/edit") browser.select_form(name="edit_password") browser['old_password'] = "321" browser['password'] = "123" browser['password2'] = "123" browser.submit() expected_response = "Wrong old password inserted" change_password_body = browser.response().read() try: change_password_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, change_password_body)) # Going to put different new passwords browser.open(CFG_SITE_SECURE_URL + "/youraccount/edit") browser.select_form(name="edit_password") browser['old_password'] = "123" browser['password'] = "123" browser['password2'] = "321" browser.submit() expected_response = "Both passwords must match" change_password_body = browser.response().read() try: change_password_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, change_password_body)) # Reset the situation browser.open(CFG_SITE_SECURE_URL + "/youraccount/edit") browser.select_form(name="edit_password") browser['old_password'] = "123" browser['password'] = "" browser['password2'] = "" browser.submit() expected_response = "Password successfully edited" change_password_body = browser.response().read() try: change_password_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, change_password_body)) def test_email_caseless(self): """webuser - check email caseless""" browser = Browser() browser.open(CFG_SITE_SECURE_URL + "/youraccount/register") browser.select_form(nr=0) browser['p_email'] = 'foo@cds.cern.ch' browser['p_nickname'] = 'foobar' browser['p_pw'] = '' browser['p_pw2'] = '' browser.submit() expected_response = "Account created" login_response_body = browser.response().read() try: login_response_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, login_response_body)) browser = Browser() browser.open(CFG_SITE_SECURE_URL + "/youraccount/register") browser.select_form(nr=0) browser['p_email'] = 'foo@cds.cern.ch' browser['p_nickname'] = 'foobar2' browser['p_pw'] = '' browser['p_pw2'] = '' browser.submit() expected_response = "Registration failure" login_response_body = browser.response().read() try: login_response_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, login_response_body)) browser = Browser() browser.open(CFG_SITE_SECURE_URL + "/youraccount/register") browser.select_form(nr=0) browser['p_email'] = 'FOO@cds.cern.ch' browser['p_nickname'] = 'foobar2' browser['p_pw'] = '' browser['p_pw2'] = '' browser.submit() expected_response = "Registration failure" login_response_body = browser.response().read() try: login_response_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, login_response_body)) def test_select_records_per_group(self): """webuser - test of user preferences setting""" # logging in as admin browser = Browser() browser.open(CFG_SITE_SECURE_URL + "/youraccount/login") browser.select_form(nr=0) browser['p_un'] = 'admin' browser['p_pw'] = '' browser.submit() expected_response = "You are logged in as admin" login_response_body = browser.response().read() try: login_response_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, login_response_body)) # Going to edit page and setting records per group to 20 browser.open(CFG_SITE_SECURE_URL + "/youraccount/edit") browser.select_form(name="edit_websearch_settings") browser['group_records'] = ["25"] browser.submit() expected_response = "User settings saved correctly" changed_settings_body = browser.response().read() try: changed_settings_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, changed_settings_body)) # Going to the search page, making an empty search browser.open(CFG_SITE_SECURE_URL) browser.select_form(nr=0) browser.submit() expected_response = "1 - 25" records_found_body = browser.response().read() try: records_found_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, records_found_body)) # Going again to edit and setting records per group back to 10 browser.open(CFG_SITE_SECURE_URL + "/youraccount/edit") browser.select_form(name="edit_websearch_settings") browser['group_records'] = ["10"] browser.submit() expected_response = "User settings saved correctly" changed_settings_body = browser.response().read() try: changed_settings_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, changed_settings_body)) # Logging out! browser.open(CFG_SITE_SECURE_URL + "/youraccount/logout") expected_response = "You are no longer recognized" logout_response_body = browser.response().read() try: logout_response_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, logout_response_body)) # Logging in again browser.open(CFG_SITE_SECURE_URL + "/youraccount/login") browser.select_form(nr=0) browser['p_un'] = 'admin' browser['p_pw'] = '' browser.submit() expected_response = "You are logged in as admin" login_response_body = browser.response().read() try: login_response_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, login_response_body)) # Let's go to search and check that the setting is still there browser.open(CFG_SITE_SECURE_URL) browser.select_form(nr=0) browser.submit() expected_response = "1 - 10" records_found_body = browser.response().read() try: records_found_body.index(expected_response) except ValueError: self.fail("Expected to see %s, got %s." % \ (expected_response, records_found_body)) return TEST_SUITE = make_test_suite(WebSessionYourSettingsTests, IsUserSuperAdminTests) if __name__ == "__main__": run_test_suite(TEST_SUITE, warn_user=True)
gpl-2.0
arjunsinghy96/coala
tests/bearlib/spacing/SpacingHelperTest.py
34
4419
import unittest from coalib.bearlib.spacing.SpacingHelper import SpacingHelper from coalib.settings.Section import Section class SpacingHelperTest(unittest.TestCase): def setUp(self): self.uut = SpacingHelper() def test_needed_settings(self): self.assertEqual(list(self.uut.get_optional_settings()), ['tab_width']) self.assertEqual(list(self.uut.get_non_optional_settings()), []) def test_construction(self): section = Section('test section') self.assertRaises(TypeError, SpacingHelper, 'no integer') self.assertRaises(TypeError, self.uut.from_section, 5) self.assertEqual(self.uut.tab_width, self.uut.from_section(section).tab_width) # This is assumed in some tests. If you want to change this value, be # sure to change the tests too self.assertEqual(self.uut.DEFAULT_TAB_WIDTH, 4) self.assertEqual(self.uut.tab_width, self.uut.DEFAULT_TAB_WIDTH) def test_get_indentation(self): self.assertRaises(TypeError, self.uut.get_indentation, 5) self.assertEqual(self.uut.get_indentation('no indentation'), 0) self.assertEqual(self.uut.get_indentation(' indentation'), 1) self.assertEqual(self.uut.get_indentation(' indentation'), 2) self.assertEqual(self.uut.get_indentation('\tindentation'), self.uut.DEFAULT_TAB_WIDTH) # Having a space before the tab shouldn't make any difference self.assertEqual(self.uut.get_indentation(' \tindentation'), self.uut.DEFAULT_TAB_WIDTH) self.assertEqual(self.uut.get_indentation(' \t indentation'), self.uut.DEFAULT_TAB_WIDTH+1) self.assertEqual(self.uut.get_indentation('\t indentation'), self.uut.DEFAULT_TAB_WIDTH+1) # same tests but with indentation only self.assertEqual(self.uut.get_indentation('\t'), self.uut.DEFAULT_TAB_WIDTH) self.assertEqual(self.uut.get_indentation(' \t'), self.uut.DEFAULT_TAB_WIDTH) self.assertEqual(self.uut.get_indentation(' \t '), self.uut.DEFAULT_TAB_WIDTH+1) self.assertEqual(self.uut.get_indentation('\t '), self.uut.DEFAULT_TAB_WIDTH+1) self.assertEqual(self.uut.get_indentation('\t\t'), self.uut.DEFAULT_TAB_WIDTH*2) def test_replace_tabs_with_spaces(self): self.assertRaises(TypeError, self.uut.replace_tabs_with_spaces, 5) self.assertEqual(self.uut.replace_tabs_with_spaces(''), '') self.assertEqual(self.uut.replace_tabs_with_spaces(' '), ' ') self.assertEqual(self.uut.replace_tabs_with_spaces('\t'), ' '*self.uut.DEFAULT_TAB_WIDTH) self.assertEqual(self.uut.replace_tabs_with_spaces('\t\t'), ' '*self.uut.DEFAULT_TAB_WIDTH*2) self.assertEqual(self.uut.replace_tabs_with_spaces(' \t'), ' '*self.uut.DEFAULT_TAB_WIDTH) self.assertEqual(self.uut.replace_tabs_with_spaces(' \t'), ' '*self.uut.DEFAULT_TAB_WIDTH) self.assertEqual(self.uut.replace_tabs_with_spaces('d \t '), 'd' + ' '*self.uut.DEFAULT_TAB_WIDTH) def test_replace_spaces_with_tabs(self): self.assertRaises(TypeError, self.uut.replace_spaces_with_tabs, 5) self.assertEqual(self.uut.replace_spaces_with_tabs(''), '') self.assertEqual(self.uut.replace_spaces_with_tabs(' '), ' ') self.assertEqual(self.uut.replace_spaces_with_tabs(' '), '\t') self.assertEqual(self.uut.replace_spaces_with_tabs(' \t'), '\t') self.assertEqual(self.uut.replace_spaces_with_tabs(' dd '), ' dd ') self.assertEqual(self.uut.replace_spaces_with_tabs(' dd d '), ' dd d ') # One space shouldnt be replaced self.assertEqual(self.uut.replace_spaces_with_tabs(' dd '), ' dd\t') self.assertEqual( self.uut.replace_spaces_with_tabs(' \t a_text another'), '\t a_text\tanother') self.assertEqual(self.uut.replace_spaces_with_tabs('123\t'), '123\t') self.assertEqual(self.uut.replace_spaces_with_tabs('d d'), 'd d')
agpl-3.0
lorenzo-desantis/mne-python
examples/inverse/plot_make_inverse_operator.py
21
3232
""" =============================================================== Assemble inverse operator and compute MNE-dSPM inverse solution =============================================================== Assemble M/EEG, MEG, and EEG inverse operators and compute dSPM inverse solution on MNE evoked dataset and stores the solution in stc files for visualisation. """ # Author: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.minimum_norm import (make_inverse_operator, apply_inverse, write_inverse_operator) print(__doc__) data_path = sample.data_path() fname_fwd_meeg = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif' fname_fwd_eeg = data_path + '/MEG/sample/sample_audvis-eeg-oct-6-fwd.fif' fname_cov = data_path + '/MEG/sample/sample_audvis-shrunk-cov.fif' fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif' snr = 3.0 lambda2 = 1.0 / snr ** 2 # Load data evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0)) forward_meeg = mne.read_forward_solution(fname_fwd_meeg, surf_ori=True) noise_cov = mne.read_cov(fname_cov) # Restrict forward solution as necessary for MEG forward_meg = mne.pick_types_forward(forward_meeg, meg=True, eeg=False) # Alternatively, you can just load a forward solution that is restricted forward_eeg = mne.read_forward_solution(fname_fwd_eeg, surf_ori=True) # make an M/EEG, MEG-only, and EEG-only inverse operators info = evoked.info inverse_operator_meeg = make_inverse_operator(info, forward_meeg, noise_cov, loose=0.2, depth=0.8) inverse_operator_meg = make_inverse_operator(info, forward_meg, noise_cov, loose=0.2, depth=0.8) inverse_operator_eeg = make_inverse_operator(info, forward_eeg, noise_cov, loose=0.2, depth=0.8) write_inverse_operator('sample_audvis-meeg-oct-6-inv.fif', inverse_operator_meeg) write_inverse_operator('sample_audvis-meg-oct-6-inv.fif', inverse_operator_meg) write_inverse_operator('sample_audvis-eeg-oct-6-inv.fif', inverse_operator_eeg) # Compute inverse solution stcs = dict() stcs['meeg'] = apply_inverse(evoked, inverse_operator_meeg, lambda2, "dSPM", pick_ori=None) stcs['meg'] = apply_inverse(evoked, inverse_operator_meg, lambda2, "dSPM", pick_ori=None) stcs['eeg'] = apply_inverse(evoked, inverse_operator_eeg, lambda2, "dSPM", pick_ori=None) # Save result in stc files names = ['meeg', 'meg', 'eeg'] for name in names: stcs[name].save('mne_dSPM_inverse-%s' % name) ############################################################################### # View activation time-series plt.close('all') plt.figure(figsize=(8, 6)) for ii in range(len(stcs)): name = names[ii] stc = stcs[name] plt.subplot(len(stcs), 1, ii + 1) plt.plot(1e3 * stc.times, stc.data[::150, :].T) plt.ylabel('%s\ndSPM value' % str.upper(name)) plt.xlabel('time (ms)') plt.show()
bsd-3-clause
LLNL/spack
lib/spack/spack/pkgkit.py
2
2272
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) # flake8: noqa: F401 """pkgkit is a set of useful build tools and directives for packages. Everything in this module is automatically imported into Spack package files. """ import llnl.util.filesystem from llnl.util.filesystem import * from spack.package import \ Package, BundlePackage, \ run_before, run_after, on_package_attributes from spack.package import inject_flags, env_flags, build_system_flags from spack.build_systems.makefile import MakefilePackage from spack.build_systems.aspell_dict import AspellDictPackage from spack.build_systems.autotools import AutotoolsPackage from spack.build_systems.cmake import CMakePackage from spack.build_systems.cuda import CudaPackage from spack.build_systems.qmake import QMakePackage from spack.build_systems.scons import SConsPackage from spack.build_systems.waf import WafPackage from spack.build_systems.octave import OctavePackage from spack.build_systems.python import PythonPackage from spack.build_systems.r import RPackage from spack.build_systems.perl import PerlPackage from spack.build_systems.intel import IntelPackage from spack.build_systems.meson import MesonPackage from spack.build_systems.sip import SIPPackage from spack.build_systems.gnu import GNUMirrorPackage from spack.build_systems.sourceforge import SourceforgePackage from spack.build_systems.sourceware import SourcewarePackage from spack.build_systems.xorg import XorgPackage from spack.mixins import filter_compiler_wrappers from spack.version import Version, ver from spack.spec import Spec from spack.dependency import all_deptypes from spack.multimethod import when import spack.directives from spack.directives import * import spack.util.executable from spack.util.executable import * from spack.package import \ install_dependency_symlinks, flatten_dependencies, \ DependencyConflictError from spack.installer import \ ExternalPackageError, InstallError, InstallLockError, UpstreamPackageError from spack.variant import any_combination_of, auto_or_any_combination_of from spack.variant import disjoint_sets
lgpl-2.1
ProtractorNinja/qutebrowser
tests/unit/commands/test_runners.py
7
1488
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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. # # qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Tests for qutebrowser.commands.runners.""" import pytest from qutebrowser.commands import runners, cmdexc class TestCommandRunner: """Tests for CommandRunner.""" def test_parse_all(self, cmdline_test): """Test parsing of commands. See https://github.com/The-Compiler/qutebrowser/issues/615 Args: cmdline_test: A pytest fixture which provides testcases. """ cr = runners.CommandRunner(0) if cmdline_test.valid: list(cr.parse_all(cmdline_test.cmd, aliases=False)) else: with pytest.raises(cmdexc.NoSuchCommandError): list(cr.parse_all(cmdline_test.cmd, aliases=False))
gpl-3.0
jcpowermac/ansible
lib/ansible/modules/cloud/amazon/_ec2_ami_find.py
8
14002
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['deprecated'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: ec2_ami_find version_added: '2.0' short_description: Searches for AMIs to obtain the AMI ID and other information deprecated: Deprecated in 2.5. Use M(ec2_ami_facts) instead. description: - Returns list of matching AMIs with AMI ID, along with other useful information - Can search AMIs with different owners - Can search by matching tag(s), by AMI name and/or other criteria - Results can be sorted and sliced author: "Tom Bamford (@tombamford)" notes: - This module is not backwards compatible with the previous version of the ec2_search_ami module which worked only for Ubuntu AMIs listed on cloud-images.ubuntu.com. - See the example below for a suggestion of how to search by distro/release. options: region: description: - The AWS region to use. required: true aliases: [ 'aws_region', 'ec2_region' ] owner: description: - Search AMIs owned by the specified owner - Can specify an AWS account ID, or one of the special IDs 'self', 'amazon' or 'aws-marketplace' - If not specified, all EC2 AMIs in the specified region will be searched. - You can include wildcards in many of the search options. An asterisk (*) matches zero or more characters, and a question mark (?) matches exactly one character. You can escape special characters using a backslash (\) before the character. For example, a value of \*amazon\?\\ searches for the literal string *amazon?\. required: false default: null ami_id: description: - An AMI ID to match. default: null required: false ami_tags: description: - A hash/dictionary of tags to match for the AMI. default: null required: false architecture: description: - An architecture type to match (e.g. x86_64). default: null required: false hypervisor: description: - A hypervisor type type to match (e.g. xen). default: null required: false is_public: description: - Whether or not the image(s) are public. choices: ['yes', 'no'] default: null required: false name: description: - An AMI name to match. default: null required: false platform: description: - Platform type to match. default: null required: false product_code: description: - Marketplace product code to match. default: null required: false version_added: "2.3" sort: description: - Optional attribute which with to sort the results. - If specifying 'tag', the 'tag_name' parameter is required. - Starting at version 2.1, additional sort choices of architecture, block_device_mapping, creationDate, hypervisor, is_public, location, owner_id, platform, root_device_name, root_device_type, state, and virtualization_type are supported. choices: - 'name' - 'description' - 'tag' - 'architecture' - 'block_device_mapping' - 'creationDate' - 'hypervisor' - 'is_public' - 'location' - 'owner_id' - 'platform' - 'root_device_name' - 'root_device_type' - 'state' - 'virtualization_type' default: null required: false sort_tag: description: - Tag name with which to sort results. - Required when specifying 'sort=tag'. default: null required: false sort_order: description: - Order in which to sort results. - Only used when the 'sort' parameter is specified. choices: ['ascending', 'descending'] default: 'ascending' required: false sort_start: description: - Which result to start with (when sorting). - Corresponds to Python slice notation. default: null required: false sort_end: description: - Which result to end with (when sorting). - Corresponds to Python slice notation. default: null required: false state: description: - AMI state to match. default: 'available' required: false virtualization_type: description: - Virtualization type to match (e.g. hvm). default: null required: false root_device_type: description: - Root device type to match (e.g. ebs, instance-store). default: null required: false version_added: "2.5" no_result_action: description: - What to do when no results are found. - "'success' reports success and returns an empty array" - "'fail' causes the module to report failure" choices: ['success', 'fail'] default: 'success' required: false extends_documentation_fragment: - aws requirements: - "python >= 2.6" - boto ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Search for the AMI tagged "project:website" - ec2_ami_find: owner: self ami_tags: project: website no_result_action: fail register: ami_find # Search for the latest Ubuntu 14.04 AMI - ec2_ami_find: name: "ubuntu/images/ebs/ubuntu-trusty-14.04-amd64-server-*" owner: 099720109477 sort: name sort_order: descending sort_end: 1 register: ami_find # Launch an EC2 instance - ec2: image: "{{ ami_find.results[0].ami_id }}" instance_type: m3.medium key_name: mykey wait: yes ''' RETURN = ''' ami_id: description: id of found amazon image returned: when AMI found type: string sample: "ami-e9095e8c" architecture: description: architecture of image returned: when AMI found type: string sample: "x86_64" block_device_mapping: description: block device mapping associated with image returned: when AMI found type: dict sample: "{ '/dev/xvda': { 'delete_on_termination': true, 'encrypted': false, 'size': 8, 'snapshot_id': 'snap-ca0330b8', 'volume_type': 'gp2' }" creationDate: description: creation date of image returned: when AMI found type: string sample: "2015-10-15T22:43:44.000Z" description: description: description of image returned: when AMI found type: string sample: "test-server01" hypervisor: description: type of hypervisor returned: when AMI found type: string sample: "xen" is_public: description: whether image is public returned: when AMI found type: bool sample: false location: description: location of image returned: when AMI found type: string sample: "435210894375/test-server01-20151015-234343" name: description: ami name of image returned: when AMI found type: string sample: "test-server01-20151015-234343" owner_id: description: owner of image returned: when AMI found type: string sample: "435210894375" platform: description: platform of image returned: when AMI found type: string sample: null root_device_name: description: root device name of image returned: when AMI found type: string sample: "/dev/xvda" root_device_type: description: root device type of image returned: when AMI found type: string sample: "ebs" state: description: state of image returned: when AMI found type: string sample: "available" tags: description: tags assigned to image returned: when AMI found type: dict sample: "{ 'Environment': 'devel', 'Name': 'test-server01', 'Role': 'web' }" virtualization_type: description: image virtualization type returned: when AMI found type: string sample: "hvm" ''' import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import HAS_BOTO, ec2_argument_spec, ec2_connect def get_block_device_mapping(image): """ Retrieves block device mapping from AMI """ bdm_dict = dict() bdm = getattr(image, 'block_device_mapping') for device_name in bdm.keys(): bdm_dict[device_name] = { 'size': bdm[device_name].size, 'snapshot_id': bdm[device_name].snapshot_id, 'volume_type': bdm[device_name].volume_type, 'encrypted': bdm[device_name].encrypted, 'delete_on_termination': bdm[device_name].delete_on_termination } return bdm_dict def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( owner=dict(required=False, default=None), ami_id=dict(required=False), ami_tags=dict(required=False, type='dict', aliases=['search_tags', 'image_tags']), architecture=dict(required=False), hypervisor=dict(required=False), is_public=dict(required=False, type='bool'), name=dict(required=False), platform=dict(required=False), product_code=dict(required=False), sort=dict(required=False, default=None, choices=['name', 'description', 'tag', 'architecture', 'block_device_mapping', 'creationDate', 'hypervisor', 'is_public', 'location', 'owner_id', 'platform', 'root_device_name', 'root_device_type', 'state', 'virtualization_type']), sort_tag=dict(required=False), sort_order=dict(required=False, default='ascending', choices=['ascending', 'descending']), sort_start=dict(required=False), sort_end=dict(required=False), state=dict(required=False, default='available'), virtualization_type=dict(required=False), no_result_action=dict(required=False, default='success', choices=['success', 'fail']), ) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) module.deprecate("The 'ec2_ami_find' module has been deprecated. Use 'ec2_ami_facts' instead.", version=2.9) if not HAS_BOTO: module.fail_json(msg='boto required for this module, install via pip or your package manager') ami_id = module.params.get('ami_id') ami_tags = module.params.get('ami_tags') architecture = module.params.get('architecture') hypervisor = module.params.get('hypervisor') is_public = module.params.get('is_public') name = module.params.get('name') owner = module.params.get('owner') platform = module.params.get('platform') product_code = module.params.get('product_code') root_device_type = module.params.get('root_device_type') sort = module.params.get('sort') sort_tag = module.params.get('sort_tag') sort_order = module.params.get('sort_order') sort_start = module.params.get('sort_start') sort_end = module.params.get('sort_end') state = module.params.get('state') virtualization_type = module.params.get('virtualization_type') no_result_action = module.params.get('no_result_action') filter = {'state': state} if ami_id: filter['image_id'] = ami_id if ami_tags: for tag in ami_tags: filter['tag:' + tag] = ami_tags[tag] if architecture: filter['architecture'] = architecture if hypervisor: filter['hypervisor'] = hypervisor if is_public: filter['is_public'] = 'true' if name: filter['name'] = name if platform: filter['platform'] = platform if product_code: filter['product-code'] = product_code if root_device_type: filter['root_device_type'] = root_device_type if virtualization_type: filter['virtualization_type'] = virtualization_type ec2 = ec2_connect(module) images_result = ec2.get_all_images(owners=owner, filters=filter) if no_result_action == 'fail' and len(images_result) == 0: module.fail_json(msg="No AMIs matched the attributes: %s" % json.dumps(filter)) results = [] for image in images_result: data = { 'ami_id': image.id, 'architecture': image.architecture, 'block_device_mapping': get_block_device_mapping(image), 'creationDate': image.creationDate, 'description': image.description, 'hypervisor': image.hypervisor, 'is_public': image.is_public, 'location': image.location, 'name': image.name, 'owner_id': image.owner_id, 'platform': image.platform, 'root_device_name': image.root_device_name, 'root_device_type': image.root_device_type, 'state': image.state, 'tags': image.tags, 'virtualization_type': image.virtualization_type, } if image.kernel_id: data['kernel_id'] = image.kernel_id if image.ramdisk_id: data['ramdisk_id'] = image.ramdisk_id results.append(data) if sort == 'tag': if not sort_tag: module.fail_json(msg="'sort_tag' option must be given with 'sort=tag'") results.sort(key=lambda e: e['tags'][sort_tag], reverse=(sort_order == 'descending')) elif sort: results.sort(key=lambda e: e[sort], reverse=(sort_order == 'descending')) try: if sort and sort_start and sort_end: results = results[int(sort_start):int(sort_end)] elif sort and sort_start: results = results[int(sort_start):] elif sort and sort_end: results = results[:int(sort_end)] except TypeError: module.fail_json(msg="Please supply numeric values for sort_start and/or sort_end") module.exit_json(results=results) if __name__ == '__main__': main()
gpl-3.0
hozn/coilmq
coilmq/store/sa/__init__.py
3
7182
""" Queue storage module that uses SQLAlchemy to access queue information and frames in a database. """ import threading import logging import os import os.path import shelve from collections import deque from datetime import datetime, timedelta # try: # from configparser import ConfigParser # except ImportError: # from ConfigParser import ConfigParser from sqlalchemy import engine_from_config, MetaData from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.sql import select, func, distinct from coilmq.store import QueueStore from coilmq.config import config from coilmq.exception import ConfigError from coilmq.util.concurrency import synchronized from coilmq.store.sa import meta, model __authors__ = ['"Hans Lellelid" <hans@xmpl.org>'] __copyright__ = "Copyright 2009 Hans Lellelid" __license__ = """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.""" def make_sa(): """ Factory to creates a SQLAlchemy queue store, pulling config values from the CoilMQ configuration. """ configuration = dict(config.items('coilmq')) engine = engine_from_config(configuration, 'qstore.sqlalchemy.') init_model(engine) store = SAQueue() return store def init_model(engine, create=True, drop=False): """ Initializes the shared SQLAlchemy state in the L{coilmq.store.sa.model} module. @param engine: The SQLAlchemy engine instance. @type engine: C{sqlalchemy.Engine} @param create: Whether to create the tables (if they do not exist). @type create: C{bool} @param drop: Whether to drop the tables (if they exist). @type drop: C{bool} """ meta.engine = engine meta.metadata = MetaData(bind=meta.engine) meta.Session = scoped_session(sessionmaker(bind=meta.engine)) model.setup_tables(create=create, drop=drop) class SAQueue(QueueStore): """ A QueueStore implementation that stores messages in a database and uses SQLAlchemy to interface with the database. Note that this implementation does not actually use the ORM capabilities of SQLAlchemy, but simply uses SQLAlchemy for the DB abstraction for SQL building and DDL (table creation). This L{coilmq.store.sa.model.setup_tables} function is used to actually define (& create) the database tables. This class also depends on the L{init_model} method have been called to define the L{coilmq.store.sa.model.Session} class-like callable (and the engine & metadata). Finally, this class does not explicitly use shared data (db connections); a new Session is created in each method. The actual implementation is handled using SQLAlchemy scoped sessions, which provide thread-local Session class-like callables. As a result of deferring that to the SA layer, we don't need to use synchronization locks to guard calls to the methods in this store implementation. """ def enqueue(self, destination, frame): """ Store message (frame) for specified destinationination. @param destination: The destinationination queue name for this message (frame). @type destination: C{str} @param frame: The message (frame) to send to specified destinationination. @type frame: C{stompclient.frame.Frame} """ session = meta.Session() message_id = frame.headers.get('message-id') if not message_id: raise ValueError("Cannot queue a frame without message-id set.") ins = model.frames_table.insert().values( message_id=message_id, destination=destination, frame=frame) session.execute(ins) session.commit() def dequeue(self, destination): """ Removes and returns an item from the queue (or C{None} if no items in queue). @param destination: The queue name (destinationination). @type destination: C{str} @return: The first frame in the specified queue, or C{None} if there are none. @rtype: C{stompclient.frame.Frame} """ session = meta.Session() try: selstmt = select( [model.frames_table.c.message_id, model.frames_table.c.frame]) selstmt = selstmt.where( model.frames_table.c.destination == destination) selstmt = selstmt.order_by( model.frames_table.c.queued, model.frames_table.c.sequence) result = session.execute(selstmt) first = result.fetchone() if not first: return None delstmt = model.frames_table.delete().where(model.frames_table.c.message_id == first[model.frames_table.c.message_id]) session.execute(delstmt) frame = first[model.frames_table.c.frame] except: session.rollback() raise else: session.commit() return frame def has_frames(self, destination): """ Whether specified queue has any frames. @param destination: The queue name (destinationination). @type destination: C{str} @return: Whether there are any frames in the specified queue. @rtype: C{bool} """ session = meta.Session() sel = select([model.frames_table.c.message_id]).where( model.frames_table.c.destination == destination) result = session.execute(sel) first = result.fetchone() return first is not None def size(self, destination): """ Size of the queue for specified destination. @param destination: The queue destination (e.g. /queue/foo) @type destination: C{str} @return: The number of frames in specified queue. @rtype: C{int} """ session = meta.Session() sel = select([func.count(model.frames_table.c.message_id)]).where( model.frames_table.c.destination == destination) result = session.execute(sel) first = result.fetchone() if not first: return 0 else: return int(first[0]) def destinations(self): """ Provides a list of destinations (queue "addresses") available. @return: A list of the detinations available. @rtype: C{set} """ session = meta.Session() sel = select([distinct(model.frames_table.c.destination)]) result = session.execute(sel) return set([r[0] for r in result.fetchall()]) def close(self): """ Closes the databases, freeing any resources (and flushing any unsaved changes to disk). """ meta.Session.remove()
apache-2.0
nvoron23/statsmodels
statsmodels/base/_constraints.py
26
10377
# -*- coding: utf-8 -*- """ Created on Thu May 15 16:36:05 2014 Author: Josef Perktold License: BSD-3 """ import numpy as np class TransformRestriction(object): """Transformation for linear constraints `R params = q` Note, the transformation from the reduced to the full parameters is an affine and not a linear transformation if q is not zero. Parameters ---------- R : array_like Linear restriction matrix q : arraylike or None values of the linear restrictions Notes ----- The reduced parameters are not sorted with respect to constraints. TODO: error checking, eg. inconsistent constraints, how? Inconsistent constraints will raise an exception in the calculation of the constant or offset. However, homogeneous constraints, where q=0, will can have a solution where the relevant parameters are constraint to be zero, as in the following example:: b1 + b2 = 0 and b1 + 2*b2 = 0, implies that b2 = 0. The transformation applied from full to reduced parameter space does not raise and exception if the constraint doesn't hold. TODO: maybe change this, what's the behavior in this case? The `reduce` transform is applied to the array of explanatory variables, `exog`, when transforming a linear model to impose the constraints. """ def __init__(self, R, q=None): # The calculations are based on Stata manual for makecns R = self.R = np.atleast_2d(R) if q is not None: q = self.q = np.asarray(q) k_constr, k_vars = R.shape self.k_constr, self.k_vars = k_constr, k_vars self.k_unconstr = k_vars - k_constr m = np.eye(k_vars) - R.T.dot(np.linalg.pinv(R).T) evals, evecs = np.linalg.eigh(m) # This normalizes the transformation so the larges element is 1. # It makes it easier to interpret simple restrictions, e.g. b1 + b2 = 0 # TODO: make this work, there is something wrong, does not round-trip # need to adjust constant #evecs_maxabs = np.max(np.abs(evecs), 0) #evecs = evecs / evecs_maxabs self.evals = evals self.evecs = evecs # temporarily attach as attribute L = self.L = evecs[:, :k_constr] self.transf_mat = evecs[:, k_constr:] if q is not None: # use solve instead of inv #self.constant = q.T.dot(np.linalg.inv(L.T.dot(R.T)).dot(L.T)) try: self.constant = q.T.dot(np.linalg.solve(L.T.dot(R.T), L.T)) except np.linalg.linalg.LinAlgError as e: raise ValueError('possibly inconsistent constraints. error ' 'generated by\n%r' % (e, )) else: self.constant = 0 def expand(self, params_reduced): """transform from the reduced to the full parameter space Parameters ---------- params_reduced : array_like parameters in the transformed space Returns ------- params : array_like parameters in the original space Notes ----- If the restriction is not homogeneous, i.e. q is not equal to zero, then this is an affine transform. """ params_reduced = np.asarray(params_reduced) return self.transf_mat.dot(params_reduced.T).T + self.constant def reduce(self, params): """transform from the full to the reduced parameter space Parameters ---------- params : array_like parameters or data in the original space Returns ------- params_reduced : array_like parameters in the transformed space This transform can be applied to the original parameters as well as to the data. If params is 2-d, then each row is transformed. """ params = np.asarray(params) return params.dot(self.transf_mat) def transform_params_constraint(params, Sinv, R, q): """find the parameters that statisfy linear constraint from unconstraint The linear constraint R params = q is imposed. Parameters ---------- params : array_like unconstraint parameters Sinv : ndarray, 2d, symmetric covariance matrix of the parameter estimate R : ndarray, 2d constraint matrix q : ndarray, 1d values of the constraint Returns ------- params_constraint : ndarray parameters of the same length as params satisfying the constraint Notes ----- This is the exact formula for OLS and other linear models. It will be a local approximation for nonlinear models. TODO: Is Sinv always the covariance matrix? In the linear case it can be (X'X)^{-1} or sigmahat^2 (X'X)^{-1}. My guess is that this is the point in the subspace that satisfies the constraint that has minimum Mahalanobis distance. Proof ? """ rsr = R.dot(Sinv).dot(R.T) reduction = Sinv.dot(R.T).dot(np.linalg.solve(rsr, R.dot(params) - q)) return params - reduction def fit_constrained(model, constraint_matrix, constraint_values, start_params=None, fit_kwds=None): # note: self is model instance """fit model subject to linear equality constraints The constraints are of the form `R params = q` where R is the constraint_matrix and q is the vector of constraint_values. The estimation creates a new model with transformed design matrix, exog, and converts the results back to the original parameterization. Parameters ---------- model: model instance An instance of a model, see limitations in Notes section constraint_matrix : array_like, 2D This is R in the linear equality constraint `R params = q`. The number of columns needs to be the same as the number of columns in exog. constraint_values : This is `q` in the linear equality constraint `R params = q` If it is a tuple, then the constraint needs to be given by two arrays (constraint_matrix, constraint_value), i.e. (R, q). Otherwise, the constraints can be given as strings or list of strings. see t_test for details start_params : None or array_like starting values for the optimization. `start_params` needs to be given in the original parameter space and are internally transformed. **fit_kwds : keyword arguments fit_kwds are used in the optimization of the transformed model. Returns ------- params : ndarray ? estimated parameters (in the original parameterization cov_params : ndarray covariance matrix of the parameter estimates. This is a reverse transformation of the covariance matrix of the transformed model given by `cov_params()` Note: `fit_kwds` can affect the choice of covariance, e.g. by specifying `cov_type`, which will be reflected in the returned covariance. res_constr : results instance This is the results instance for the created transformed model. Notes ----- Limitations: Models where the number of parameters is different from the number of columns of exog are not yet supported. Requires a model that implement an offset option. """ self = model # internal alias, used for methods if fit_kwds is None: fit_kwds = {} R, q = constraint_matrix, constraint_values endog, exog = self.endog, self.exog transf = TransformRestriction(R, q) exogp_st = transf.reduce(exog) offset = exog.dot(transf.constant.squeeze()) if hasattr(self, 'offset'): offset += self.offset if start_params is not None: start_params = transf.reduce(start_params) #need copy, because we don't want to change it, we don't need deepcopy import copy init_kwds = copy.copy(self._get_init_kwds()) del init_kwds['offset'] # TODO: refactor to combine with above or offset_all # using offset as keywords is not supported in all modules mod_constr = self.__class__(endog, exogp_st, offset=offset, **init_kwds) res_constr = mod_constr.fit(start_params=start_params, **fit_kwds) params_orig = transf.expand(res_constr.params).squeeze() cov_params = transf.transf_mat.dot(res_constr.cov_params()).dot(transf.transf_mat.T) return params_orig, cov_params, res_constr def fit_constrained_wrap(model, constraints, start_params=None, **fit_kwds): """fit_constraint that returns a results instance This is a development version for fit_constrained methods or fit_constrained as standalone function. It will not work correctly for all models because creating a new results instance is not standardized for use outside the `fit` methods, and might need adjustements for this. This is the prototype for the fit_constrained method that has been added to Poisson and GLM. """ self = model # alias for use as method #constraints = (R, q) # TODO: temporary trailing underscore to not overwrite the monkey # patched version # TODO: decide whether to move the imports from patsy import DesignInfo # we need this import if we copy it to a different module #from statsmodels.base._constraints import fit_constrained # same pattern as in base.LikelihoodModel.t_test lc = DesignInfo(self.exog_names).linear_constraint(constraints) R, q = lc.coefs, lc.constants # TODO: add start_params option, need access to tranformation # fit_constrained needs to do the transformation params, cov, res_constr = fit_constrained(self, R, q, start_params=start_params, fit_kwds=fit_kwds) #create dummy results Instance, TODO: wire up properly res = self.fit(start_params=params, maxiter=0, warn_convergence=False) # we get a wrapper back res._results.params = params res._results.normalized_cov_params = cov k_constr = len(q) res._results.df_resid += k_constr res._results.df_model -= k_constr res._results.constraints = lc res._results.k_constr = k_constr res._results.results_constrained = res_constr return res
bsd-3-clause
galaxyproject/pulsar
pulsar/managers/util/external.py
6
1103
from re import search EXTERNAL_ID_TYPE_ANY = None EXTERNAL_ID_PATTERNS = [ ('condor', r'submitted to cluster (\d+)\.'), ('slurm', r'Submitted batch job (\w+)'), ('torque', r'(.+)'), # Default 'pattern' assumed by Galaxy code circa August 2013. ] def parse_external_id(output, type=EXTERNAL_ID_TYPE_ANY): """ Attempt to parse the output of job submission commands for an external id.__doc__ >>> parse_external_id("12345.pbsmanager") '12345.pbsmanager' >>> parse_external_id('Submitted batch job 185') '185' >>> parse_external_id('Submitted batch job 185', type='torque') 'Submitted batch job 185' >>> parse_external_id('submitted to cluster 125.') '125' >>> parse_external_id('submitted to cluster 125.', type='slurm') >>> """ external_id = None for pattern_type, pattern in EXTERNAL_ID_PATTERNS: if type != EXTERNAL_ID_TYPE_ANY and type != pattern_type: continue match = search(pattern, output) if match: external_id = match.group(1) break return external_id
apache-2.0
ptrendx/mxnet
example/neural-style/end_to_end/gen_v4.py
27
3955
# 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. # coding: utf-8 import mxnet as mx import numpy as np def Conv(data, num_filter, kernel=(5, 5), pad=(2, 2), stride=(2, 2)): sym = mx.sym.Convolution(data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, no_bias=False) sym = mx.sym.BatchNorm(sym, fix_gamma=False) sym = mx.sym.LeakyReLU(sym, act_type="leaky") return sym def Deconv(data, num_filter, kernel=(6, 6), pad=(2, 2), stride=(2, 2), out=False): sym = mx.sym.Deconvolution(data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, no_bias=True) sym = mx.sym.BatchNorm(sym, fix_gamma=False) if out == False: sym = mx.sym.LeakyReLU(sym, act_type="leaky") else: sym = mx.sym.Activation(sym, act_type="tanh") return sym def get_generator(prefix, im_hw): data = mx.sym.Variable("%s_data" % prefix) conv1_1 = mx.sym.Convolution(data, num_filter=48, kernel=(5, 5), pad=(2, 2), no_bias=False) conv1_1 = mx.sym.BatchNorm(conv1_1, fix_gamma=False) conv1_1 = mx.sym.LeakyReLU(conv1_1, act_type="leaky") conv2_1 = mx.sym.Convolution(conv1_1, num_filter=32, kernel=(5, 5), pad=(2, 2), no_bias=False) conv2_1 = mx.sym.BatchNorm(conv2_1, fix_gamma=False) conv2_1 = mx.sym.LeakyReLU(conv2_1, act_type="leaky") conv3_1 = mx.sym.Convolution(conv2_1, num_filter=64, kernel=(3, 3), pad=(1, 1), no_bias=False) conv3_1 = mx.sym.BatchNorm(conv3_1, fix_gamma=False) conv3_1 = mx.sym.LeakyReLU(conv3_1, act_type="leaky") conv4_1 = mx.sym.Convolution(conv3_1, num_filter=32, kernel=(5, 5), pad=(2, 2), no_bias=False) conv4_1 = mx.sym.BatchNorm(conv4_1, fix_gamma=False) conv4_1 = mx.sym.LeakyReLU(conv4_1, act_type="leaky") conv5_1 = mx.sym.Convolution(conv4_1, num_filter=48, kernel=(5, 5), pad=(2, 2), no_bias=False) conv5_1 = mx.sym.BatchNorm(conv5_1, fix_gamma=False) conv5_1 = mx.sym.LeakyReLU(conv5_1, act_type="leaky") conv6_1 = mx.sym.Convolution(conv5_1, num_filter=32, kernel=(5, 5), pad=(2, 2), no_bias=True) conv6_1 = mx.sym.BatchNorm(conv6_1, fix_gamma=False) conv6_1 = mx.sym.LeakyReLU(conv6_1, act_type="leaky") out = mx.sym.Convolution(conv6_1, num_filter=3, kernel=(3, 3), pad=(1, 1), no_bias=True) out = mx.sym.BatchNorm(out, fix_gamma=False) out = mx.sym.Activation(data=out, act_type="tanh") raw_out = (out * 128) + 128 norm = mx.sym.SliceChannel(raw_out, num_outputs=3) r_ch = norm[0] - 123.68 g_ch = norm[1] - 116.779 b_ch = norm[2] - 103.939 norm_out = 0.4 * mx.sym.Concat(*[r_ch, g_ch, b_ch]) + 0.6 * data return norm_out def get_module(prefix, dshape, ctx, is_train=True): sym = get_generator(prefix, dshape[-2:]) mod = mx.mod.Module(symbol=sym, data_names=("%s_data" % prefix,), label_names=None, context=ctx) if is_train: mod.bind(data_shapes=[("%s_data" % prefix, dshape)], for_training=True, inputs_need_grad=True) else: mod.bind(data_shapes=[("%s_data" % prefix, dshape)], for_training=False, inputs_need_grad=False) mod.init_params(initializer=mx.init.Xavier(magnitude=2.)) return mod
apache-2.0
PurrfectDream/notepad-plus-plus
scintilla/qt/ScintillaEditPy/sepbuild.py
54
11780
import distutils.sysconfig import getopt import glob import os import platform import shutil import subprocess import stat import sys sys.path.append(os.path.join("..", "ScintillaEdit")) import WidgetGen scintillaDirectory = "../.." scintillaScriptsDirectory = os.path.join(scintillaDirectory, "scripts") sys.path.append(scintillaScriptsDirectory) from FileGenerator import GenerateFile # Decide up front which platform, treat anything other than Windows or OS X as Linux PLAT_WINDOWS = platform.system() == "Windows" PLAT_DARWIN = platform.system() == "Darwin" PLAT_LINUX = not (PLAT_DARWIN or PLAT_WINDOWS) def IsFileNewer(name1, name2): """ Returns whether file with name1 is newer than file with name2. Returns 1 if name2 doesn't exist. """ if not os.path.exists(name1): return 0 if not os.path.exists(name2): return 1 mod_time1 = os.stat(name1)[stat.ST_MTIME] mod_time2 = os.stat(name2)[stat.ST_MTIME] return (mod_time1 > mod_time2) def textFromRun(args): proc = subprocess.Popen(args, shell=isinstance(args, str), stdout=subprocess.PIPE) (stdoutdata, stderrdata) = proc.communicate() if proc.returncode: raise OSError(proc.returncode) return stdoutdata def runProgram(args, exitOnFailure): print(" ".join(args)) retcode = subprocess.call(" ".join(args), shell=True, stderr=subprocess.STDOUT) if retcode: print("Failed in " + " ".join(args) + " return code = " + str(retcode)) if exitOnFailure: sys.exit() def usage(): print("sepbuild.py [-h|--help][-c|--clean][-u|--underscore-names]") print("") print("Generate PySide wappers and build them.") print("") print("options:") print("") print("-c --clean remove all object and generated files") print("-b --pyside-base Location of the PySide+Qt4 sandbox to use") print("-h --help display this text") print("-d --debug=yes|no force debug build (or non-debug build)") print("-u --underscore-names use method_names consistent with GTK+ standards") modifyFunctionElement = """ <modify-function signature="%s">%s </modify-function>""" injectCode = """ <inject-code class="target" position="beginning">%s </inject-code>""" injectCheckN = """ if (!cppArg%d) { PyErr_SetString(PyExc_ValueError, "Null string argument"); return 0; }""" def methodSignature(name, v, options): argTypes = "" p1Type = WidgetGen.cppAlias(v["Param1Type"]) if p1Type == "int": p1Type = "sptr_t" if p1Type: argTypes = argTypes + p1Type p2Type = WidgetGen.cppAlias(v["Param2Type"]) if p2Type == "int": p2Type = "sptr_t" if p2Type and v["Param2Type"] != "stringresult": if p1Type: argTypes = argTypes + ", " argTypes = argTypes + p2Type methodName = WidgetGen.normalisedName(name, options, v["FeatureType"]) constDeclarator = " const" if v["FeatureType"] == "get" else "" return methodName + "(" + argTypes + ")" + constDeclarator def printTypeSystemFile(f, options): out = [] for name in f.order: v = f.features[name] if v["Category"] != "Deprecated": feat = v["FeatureType"] if feat in ["fun", "get", "set"]: checks = "" if v["Param1Type"] == "string": checks = checks + (injectCheckN % 0) if v["Param2Type"] == "string": if v["Param1Type"] == "": # Only arg 2 -> treat as first checks = checks + (injectCheckN % 0) else: checks = checks + (injectCheckN % 1) if checks: inject = injectCode % checks out.append(modifyFunctionElement % (methodSignature(name, v, options), inject)) #if v["Param1Type"] == "string": # out.append("<string-xml>" + name + "</string-xml>\n") return out def doubleBackSlashes(s): # Quote backslashes so qmake does not produce warnings return s.replace("\\", "\\\\") class SepBuilder: def __init__(self): # Discover configuration parameters self.ScintillaEditIncludes = [".", "../ScintillaEdit", "../ScintillaEditBase", "../../include"] if PLAT_WINDOWS: self.MakeCommand = "nmake" self.MakeTarget = "release" else: self.MakeCommand = "make" self.MakeTarget = "" if PLAT_DARWIN: self.QMakeOptions = "-spec macx-g++" else: self.QMakeOptions = "" # Default to debug build if running in a debug build interpreter self.DebugBuild = hasattr(sys, 'getobjects') # Python self.PyVersion = "%d.%d" % sys.version_info[:2] self.PyVersionSuffix = distutils.sysconfig.get_config_var("VERSION") self.PyIncludes = distutils.sysconfig.get_python_inc() self.PyPrefix = distutils.sysconfig.get_config_var("prefix") self.PyLibDir = distutils.sysconfig.get_config_var( ("LIBDEST" if sys.platform == 'win32' else "LIBDIR")) # Scintilla with open("../../version.txt") as f: version = f.read() self.ScintillaVersion = version[0] + '.' + version[1] + '.' + version[2] # Find out what qmake is called self.QMakeCommand = "qmake" if not PLAT_WINDOWS: # On Unix qmake may not be present but qmake-qt4 may be so check pathToQMake = textFromRun("which qmake-qt4 || which qmake").rstrip() self.QMakeCommand = os.path.basename(pathToQMake) # Qt default location from qmake self._SetQtIncludeBase(textFromRun(self.QMakeCommand + " -query QT_INSTALL_HEADERS").rstrip()) # PySide default location # No standard for installing PySide development headers and libs on Windows so # choose /usr to be like Linux self._setPySideBase('\\usr' if PLAT_WINDOWS else '/usr') self.ProInclude = "sepbuild.pri" self.qtStyleInterface = True def _setPySideBase(self, base): self.PySideBase = base def _try_pkgconfig(var, package, *relpath): try: return textFromRun(["pkg-config", "--variable=" + var, package]).rstrip() except OSError: return os.path.join(self.PySideBase, *relpath) self.PySideTypeSystem = _try_pkgconfig("typesystemdir", "pyside", "share", "PySide", "typesystems") self.PySideIncludeBase = _try_pkgconfig("includedir", "pyside", "include", "PySide") self.ShibokenIncludeBase = _try_pkgconfig("includedir", "shiboken", "include", "shiboken") self.PySideIncludes = [ self.ShibokenIncludeBase, self.PySideIncludeBase, os.path.join(self.PySideIncludeBase, "QtCore"), os.path.join(self.PySideIncludeBase, "QtGui")] self.PySideLibDir = _try_pkgconfig("libdir", "pyside", "lib") self.ShibokenLibDir = _try_pkgconfig("libdir", "shiboken", "lib") self.AllIncludes = os.pathsep.join(self.QtIncludes + self.ScintillaEditIncludes + self.PySideIncludes) self.ShibokenGenerator = "shiboken" # Is this still needed? It doesn't work with latest shiboken sources #if PLAT_DARWIN: # # On OS X, can not automatically find Shiboken dylib so provide a full path # self.ShibokenGenerator = os.path.join(self.PySideLibDir, "generatorrunner", "shiboken") def generateAPI(self, args): os.chdir(os.path.join("..", "ScintillaEdit")) if not self.qtStyleInterface: args.insert(0, '--underscore-names') WidgetGen.main(args) f = WidgetGen.readInterface(False) os.chdir(os.path.join("..", "ScintillaEditPy")) options = {"qtStyle": self.qtStyleInterface} GenerateFile("typesystem_ScintillaEdit.xml.template", "typesystem_ScintillaEdit.xml", "<!-- ", True, printTypeSystemFile(f, options)) def runGenerator(self): generatorrunner = "shiboken" for name in ('shiboken', 'generatorrunner'): if PLAT_WINDOWS: name += '.exe' name = os.path.join(self.PySideBase, "bin", name) if os.path.exists(name): generatorrunner = name break args = [ generatorrunner, "--generator-set=" + self.ShibokenGenerator, "global.h ", "--avoid-protected-hack", "--enable-pyside-extensions", "--include-paths=" + self.AllIncludes, "--typesystem-paths=" + self.PySideTypeSystem, "--output-directory=.", "typesystem_ScintillaEdit.xml"] print(" ".join(args)) retcode = subprocess.call(" ".join(args), shell=True, stderr=subprocess.STDOUT) if retcode: print("Failed in generatorrunner", retcode) sys.exit() def writeVariables(self): # Write variables needed into file to be included from project so it does not have to discover much with open(self.ProInclude, "w") as f: f.write("SCINTILLA_VERSION=" + self.ScintillaVersion + "\n") f.write("PY_VERSION=" + self.PyVersion + "\n") f.write("PY_VERSION_SUFFIX=" + self.PyVersionSuffix + "\n") f.write("PY_PREFIX=" + doubleBackSlashes(self.PyPrefix) + "\n") f.write("PY_INCLUDES=" + doubleBackSlashes(self.PyIncludes) + "\n") f.write("PY_LIBDIR=" + doubleBackSlashes(self.PyLibDir) + "\n") f.write("PYSIDE_INCLUDES=" + doubleBackSlashes(self.PySideIncludeBase) + "\n") f.write("PYSIDE_LIB=" + doubleBackSlashes(self.PySideLibDir) + "\n") f.write("SHIBOKEN_INCLUDES=" + doubleBackSlashes(self.ShibokenIncludeBase) + "\n") f.write("SHIBOKEN_LIB=" + doubleBackSlashes(self.ShibokenLibDir) + "\n") if self.DebugBuild: f.write("CONFIG += debug\n") else: f.write("CONFIG += release\n") def make(self): runProgram([self.QMakeCommand, self.QMakeOptions], exitOnFailure=True) runProgram([self.MakeCommand, self.MakeTarget], exitOnFailure=True) def cleanEverything(self): self.generateAPI(["--clean"]) runProgram([self.MakeCommand, "distclean"], exitOnFailure=False) filesToRemove = [self.ProInclude, "typesystem_ScintillaEdit.xml", "../../bin/ScintillaEditPy.so", "../../bin/ScintillaConstants.py"] for file in filesToRemove: try: os.remove(file) except OSError: pass for logFile in glob.glob("*.log"): try: os.remove(logFile) except OSError: pass shutil.rmtree("debug", ignore_errors=True) shutil.rmtree("release", ignore_errors=True) shutil.rmtree("ScintillaEditPy", ignore_errors=True) def buildEverything(self): cleanGenerated = False opts, args = getopt.getopt(sys.argv[1:], "hcdub", ["help", "clean", "debug=", "underscore-names", "pyside-base="]) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-c", "--clean"): cleanGenerated = True elif opt in ("-d", "--debug"): self.DebugBuild = (arg == '' or arg.lower() == 'yes') if self.DebugBuild and sys.platform == 'win32': self.MakeTarget = 'debug' elif opt in ("-b", '--pyside-base'): self._SetQtIncludeBase(os.path.join(os.path.normpath(arg), 'include')) self._setPySideBase(os.path.normpath(arg)) elif opt in ("-u", "--underscore-names"): self.qtStyleInterface = False if cleanGenerated: self.cleanEverything() else: self.writeVariables() self.generateAPI([""]) self.runGenerator() self.make() self.copyScintillaConstants() def copyScintillaConstants(self): orig = 'ScintillaConstants.py' dest = '../../bin/' + orig if IsFileNewer(dest, orig): return f = open(orig, 'r') contents = f.read() f.close() f = open(dest, 'w') f.write(contents) f.close() def _SetQtIncludeBase(self, base): self.QtIncludeBase = base self.QtIncludes = [self.QtIncludeBase] + [os.path.join(self.QtIncludeBase, sub) for sub in ["QtCore", "QtGui"]] # Set path so correct qmake is found path = os.environ.get('PATH', '').split(os.pathsep) qt_bin_dir = os.path.join(os.path.dirname(base), 'bin') if qt_bin_dir not in path: path.insert(0, qt_bin_dir) os.environ['PATH'] = os.pathsep.join(path) if __name__ == "__main__": sepBuild = SepBuilder() sepBuild.buildEverything()
gpl-2.0
snap-stanford/ogb
examples/nodeproppred/products/node2vec.py
1
2074
import argparse import torch from torch_geometric.nn import Node2Vec from ogb.nodeproppred import PygNodePropPredDataset def save_embedding(model): torch.save(model.embedding.weight.data.cpu(), 'embedding.pt') def main(): parser = argparse.ArgumentParser(description='OGBN-Products (Node2Vec)') parser.add_argument('--device', type=int, default=0) parser.add_argument('--embedding_dim', type=int, default=128) parser.add_argument('--walk_length', type=int, default=40) parser.add_argument('--context_size', type=int, default=20) parser.add_argument('--walks_per_node', type=int, default=10) parser.add_argument('--batch_size', type=int, default=256) parser.add_argument('--lr', type=float, default=0.01) parser.add_argument('--epochs', type=int, default=1) parser.add_argument('--log_steps', type=int, default=1) args = parser.parse_args() device = f'cuda:{args.device}' if torch.cuda.is_available() else 'cpu' device = torch.device(device) dataset = PygNodePropPredDataset(name='ogbn-products') data = dataset[0] model = Node2Vec(data.edge_index, args.embedding_dim, args.walk_length, args.context_size, args.walks_per_node, sparse=True).to(device) loader = model.loader(batch_size=args.batch_size, shuffle=True, num_workers=4) optimizer = torch.optim.SparseAdam(list(model.parameters()), lr=args.lr) model.train() for epoch in range(1, args.epochs + 1): for i, (pos_rw, neg_rw) in enumerate(loader): optimizer.zero_grad() loss = model.loss(pos_rw.to(device), neg_rw.to(device)) loss.backward() optimizer.step() if (i + 1) % args.log_steps == 0: print(f'Epoch: {epoch:02d}, Step: {i+1:03d}/{len(loader)}, ' f'Loss: {loss:.4f}') if (i + 1) % 100 == 0: # Save model every 100 steps. save_embedding(model) save_embedding(model) if __name__ == "__main__": main()
mit
Cue/eventlet
examples/twisted/twisted_portforward.py
8
1158
"""Port forwarder USAGE: twisted_portforward.py local_port remote_host remote_port""" import sys from twisted.internet import reactor from eventlet.twistedutil import join_reactor from eventlet.twistedutil.protocol import GreenClientCreator, SpawnFactory, UnbufferedTransport from eventlet import proc def forward(source, dest): try: while True: x = source.recv() if not x: break print 'forwarding %s bytes' % len(x) dest.write(x) finally: dest.loseConnection() def handler(local): client = str(local.getHost()) print 'accepted connection from %s' % client remote = GreenClientCreator(reactor, UnbufferedTransport).connectTCP(remote_host, remote_port) a = proc.spawn(forward, remote, local) b = proc.spawn(forward, local, remote) proc.waitall([a, b], trap_errors=True) print 'closed connection to %s' % client try: local_port, remote_host, remote_port = sys.argv[1:] except ValueError: sys.exit(__doc__) local_port = int(local_port) remote_port = int(remote_port) reactor.listenTCP(local_port, SpawnFactory(handler)) reactor.run()
mit
migonzalvar/youtube-dl
youtube_dl/extractor/ted.py
115
10646
from __future__ import unicode_literals import json import re from .common import InfoExtractor from ..compat import compat_str from ..utils import int_or_none class TEDIE(InfoExtractor): IE_NAME = 'ted' _VALID_URL = r'''(?x) (?P<proto>https?://) (?P<type>www|embed(?:-ssl)?)(?P<urlmain>\.ted\.com/ ( (?P<type_playlist>playlists(?:/\d+)?) # We have a playlist | ((?P<type_talk>talks)) # We have a simple talk | (?P<type_watch>watch)/[^/]+/[^/]+ ) (/lang/(.*?))? # The url may contain the language /(?P<name>[\w-]+) # Here goes the name and then ".html" .*)$ ''' _TESTS = [{ 'url': 'http://www.ted.com/talks/dan_dennett_on_our_consciousness.html', 'md5': 'fc94ac279feebbce69f21c0c6ee82810', 'info_dict': { 'id': '102', 'ext': 'mp4', 'title': 'The illusion of consciousness', 'description': ('Philosopher Dan Dennett makes a compelling ' 'argument that not only don\'t we understand our own ' 'consciousness, but that half the time our brains are ' 'actively fooling us.'), 'uploader': 'Dan Dennett', 'width': 854, 'duration': 1308, } }, { 'url': 'http://www.ted.com/watch/ted-institute/ted-bcg/vishal-sikka-the-beauty-and-power-of-algorithms', 'md5': '226f4fb9c62380d11b7995efa4c87994', 'info_dict': { 'id': 'vishal-sikka-the-beauty-and-power-of-algorithms', 'ext': 'mp4', 'title': 'Vishal Sikka: The beauty and power of algorithms', 'thumbnail': 're:^https?://.+\.jpg', 'description': 'Adaptive, intelligent, and consistent, algorithms are emerging as the ultimate app for everything from matching consumers to products to assessing medical diagnoses. Vishal Sikka shares his appreciation for the algorithm, charting both its inherent beauty and its growing power.', } }, { 'url': 'http://www.ted.com/talks/gabby_giffords_and_mark_kelly_be_passionate_be_courageous_be_your_best', 'info_dict': { 'id': '1972', 'ext': 'mp4', 'title': 'Be passionate. Be courageous. Be your best.', 'uploader': 'Gabby Giffords and Mark Kelly', 'description': 'md5:5174aed4d0f16021b704120360f72b92', 'duration': 1128, }, }, { 'url': 'http://www.ted.com/playlists/who_are_the_hackers', 'info_dict': { 'id': '10', 'title': 'Who are the hackers?', }, 'playlist_mincount': 6, }, { # contains a youtube video 'url': 'https://www.ted.com/talks/douglas_adams_parrots_the_universe_and_everything', 'add_ie': ['Youtube'], 'info_dict': { 'id': '_ZG8HBuDjgc', 'ext': 'mp4', 'title': 'Douglas Adams: Parrots the Universe and Everything', 'description': 'md5:01ad1e199c49ac640cb1196c0e9016af', 'uploader': 'University of California Television (UCTV)', 'uploader_id': 'UCtelevision', 'upload_date': '20080522', }, 'params': { 'skip_download': True, }, }, { # YouTube video 'url': 'http://www.ted.com/talks/jeffrey_kluger_the_sibling_bond', 'add_ie': ['Youtube'], 'info_dict': { 'id': 'aFBIPO-P7LM', 'ext': 'mp4', 'title': 'The hidden power of siblings: Jeff Kluger at TEDxAsheville', 'description': 'md5:3d7a4f50d95ca5dd67104e2a20f43fe1', 'uploader': 'TEDx Talks', 'uploader_id': 'TEDxTalks', 'upload_date': '20111216', }, 'params': { 'skip_download': True, }, }] _NATIVE_FORMATS = { 'low': {'preference': 1, 'width': 320, 'height': 180}, 'medium': {'preference': 2, 'width': 512, 'height': 288}, 'high': {'preference': 3, 'width': 854, 'height': 480}, } def _extract_info(self, webpage): info_json = self._search_regex(r'q\("\w+.init",({.+})\)</script>', webpage, 'info json') return json.loads(info_json) def _real_extract(self, url): m = re.match(self._VALID_URL, url, re.VERBOSE) if m.group('type').startswith('embed'): desktop_url = m.group('proto') + 'www' + m.group('urlmain') return self.url_result(desktop_url, 'TED') name = m.group('name') if m.group('type_talk'): return self._talk_info(url, name) elif m.group('type_watch'): return self._watch_info(url, name) else: return self._playlist_videos_info(url, name) def _playlist_videos_info(self, url, name): '''Returns the videos of the playlist''' webpage = self._download_webpage(url, name, 'Downloading playlist webpage') info = self._extract_info(webpage) playlist_info = info['playlist'] playlist_entries = [ self.url_result('http://www.ted.com/talks/' + talk['slug'], self.ie_key()) for talk in info['talks'] ] return self.playlist_result( playlist_entries, playlist_id=compat_str(playlist_info['id']), playlist_title=playlist_info['title']) def _talk_info(self, url, video_name): webpage = self._download_webpage(url, video_name) self.report_extraction(video_name) talk_info = self._extract_info(webpage)['talks'][0] external = talk_info.get('external') if external: service = external['service'] self.to_screen('Found video from %s' % service) ext_url = None if service.lower() == 'youtube': ext_url = external.get('code') return { '_type': 'url', 'url': ext_url or external['uri'], } formats = [{ 'url': format_url, 'format_id': format_id, 'format': format_id, } for (format_id, format_url) in talk_info['nativeDownloads'].items() if format_url is not None] if formats: for f in formats: finfo = self._NATIVE_FORMATS.get(f['format_id']) if finfo: f.update(finfo) for format_id, resources in talk_info['resources'].items(): if format_id == 'h264': for resource in resources: bitrate = int_or_none(resource.get('bitrate')) formats.append({ 'url': resource['file'], 'format_id': '%s-%sk' % (format_id, bitrate), 'tbr': bitrate, }) elif format_id == 'rtmp': streamer = talk_info.get('streamer') if not streamer: continue for resource in resources: formats.append({ 'format_id': '%s-%s' % (format_id, resource.get('name')), 'url': streamer, 'play_path': resource['file'], 'ext': 'flv', 'width': int_or_none(resource.get('width')), 'height': int_or_none(resource.get('height')), 'tbr': int_or_none(resource.get('bitrate')), }) elif format_id == 'hls': hls_formats = self._extract_m3u8_formats( resources.get('stream'), video_name, 'mp4', m3u8_id=format_id) for f in hls_formats: if f.get('format_id') == 'hls-meta': continue if not f.get('height'): f['vcodec'] = 'none' else: f['acodec'] = 'none' formats.extend(hls_formats) audio_download = talk_info.get('audioDownload') if audio_download: formats.append({ 'url': audio_download, 'format_id': 'audio', 'vcodec': 'none', 'preference': -0.5, }) self._sort_formats(formats) video_id = compat_str(talk_info['id']) thumbnail = talk_info['thumb'] if not thumbnail.startswith('http'): thumbnail = 'http://' + thumbnail return { 'id': video_id, 'title': talk_info['title'].strip(), 'uploader': talk_info['speaker'], 'thumbnail': thumbnail, 'description': self._og_search_description(webpage), 'subtitles': self._get_subtitles(video_id, talk_info), 'formats': formats, 'duration': talk_info.get('duration'), } def _get_subtitles(self, video_id, talk_info): languages = [lang['languageCode'] for lang in talk_info.get('languages', [])] if languages: sub_lang_list = {} for l in languages: sub_lang_list[l] = [ { 'url': 'http://www.ted.com/talks/subtitles/id/%s/lang/%s/format/%s' % (video_id, l, ext), 'ext': ext, } for ext in ['ted', 'srt'] ] return sub_lang_list else: return {} def _watch_info(self, url, name): webpage = self._download_webpage(url, name) config_json = self._html_search_regex( r'"pages\.jwplayer"\s*,\s*({.+?})\s*\)\s*</script>', webpage, 'config') config = json.loads(config_json)['config'] video_url = config['video']['url'] thumbnail = config.get('image', {}).get('url') title = self._html_search_regex( r"(?s)<h1(?:\s+class='[^']+')?>(.+?)</h1>", webpage, 'title') description = self._html_search_regex( [ r'(?s)<h4 class="[^"]+" id="h3--about-this-talk">.*?</h4>(.*?)</div>', r'(?s)<p><strong>About this talk:</strong>\s+(.*?)</p>', ], webpage, 'description', fatal=False) return { 'id': name, 'url': video_url, 'title': title, 'thumbnail': thumbnail, 'description': description, }
unlicense
NeovaHealth/odoo
addons/board/board.py
175
6654
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2013 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from operator import itemgetter from textwrap import dedent from openerp import tools, SUPERUSER_ID from openerp.osv import fields, osv class board_board(osv.osv): _name = 'board.board' _description = "Board" _auto = False _columns = {} @tools.cache() def list(self, cr, uid, context=None): Actions = self.pool.get('ir.actions.act_window') Menus = self.pool.get('ir.ui.menu') IrValues = self.pool.get('ir.values') act_ids = Actions.search(cr, uid, [('res_model', '=', self._name)], context=context) refs = ['%s,%s' % (Actions._name, act_id) for act_id in act_ids] # cannot search "action" field on menu (non stored function field without search_fnct) irv_ids = IrValues.search(cr, uid, [ ('model', '=', 'ir.ui.menu'), ('key', '=', 'action'), ('key2', '=', 'tree_but_open'), ('value', 'in', refs), ], context=context) menu_ids = map(itemgetter('res_id'), IrValues.read(cr, uid, irv_ids, ['res_id'], context=context)) menu_names = Menus.name_get(cr, uid, menu_ids, context=context) return [dict(id=m[0], name=m[1]) for m in menu_names] def _clear_list_cache(self): self.list.clear_cache(self) def create(self, cr, user, vals, context=None): return 0 def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): """ Overrides orm field_view_get. @return: Dictionary of Fields, arch and toolbar. """ res = {} res = super(board_board, self).fields_view_get(cr, user, view_id, view_type, context=context, toolbar=toolbar, submenu=submenu) CustView = self.pool.get('ir.ui.view.custom') vids = CustView.search(cr, user, [('user_id', '=', user), ('ref_id', '=', view_id)], context=context) if vids: view_id = vids[0] arch = CustView.browse(cr, user, view_id, context=context) res['custom_view_id'] = view_id res['arch'] = arch.arch res['arch'] = self._arch_preprocessing(cr, user, res['arch'], context=context) res['toolbar'] = {'print': [], 'action': [], 'relate': []} return res def _arch_preprocessing(self, cr, user, arch, context=None): from lxml import etree def remove_unauthorized_children(node): for child in node.iterchildren(): if child.tag == 'action' and child.get('invisible'): node.remove(child) else: child = remove_unauthorized_children(child) return node def encode(s): if isinstance(s, unicode): return s.encode('utf8') return s archnode = etree.fromstring(encode(arch)) return etree.tostring(remove_unauthorized_children(archnode), pretty_print=True) class board_create(osv.osv_memory): def board_create(self, cr, uid, ids, context=None): assert len(ids) == 1 this = self.browse(cr, uid, ids[0], context=context) view_arch = dedent("""<?xml version="1.0"?> <form string="%s" version="7.0"> <board style="2-1"> <column/> <column/> </board> </form> """.strip() % (this.name,)) view_id = self.pool.get('ir.ui.view').create(cr, uid, { 'name': this.name, 'model': 'board.board', 'priority': 16, 'type': 'form', 'arch': view_arch, }, context=context) action_id = self.pool.get('ir.actions.act_window').create(cr, uid, { 'name': this.name, 'view_type': 'form', 'view_mode': 'form', 'res_model': 'board.board', 'usage': 'menu', 'view_id': view_id, 'help': dedent('''<div class="oe_empty_custom_dashboard"> <p> <b>This dashboard is empty.</b> </p><p> To add the first report into this dashboard, go to any menu, switch to list or graph view, and click <i>'Add to Dashboard'</i> in the extended search options. </p><p> You can filter and group data before inserting into the dashboard using the search options. </p> </div> ''') }, context=context) menu_id = self.pool.get('ir.ui.menu').create(cr, SUPERUSER_ID, { 'name': this.name, 'parent_id': this.menu_parent_id.id, 'action': 'ir.actions.act_window,%s' % (action_id,) }, context=context) self.pool.get('board.board')._clear_list_cache() return { 'type': 'ir.actions.client', 'tag': 'reload', 'params': { 'menu_id': menu_id }, } def _default_menu_parent_id(self, cr, uid, context=None): _, menu_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'menu_reporting_dashboard') return menu_id _name = "board.create" _description = "Board Creation" _columns = { 'name': fields.char('Board Name', required=True), 'menu_parent_id': fields.many2one('ir.ui.menu', 'Parent Menu', required=True), } _defaults = { 'menu_parent_id': _default_menu_parent_id, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
timchen86/ntulifeguardapp
gdata-2.0.18/samples/apps/multidomain_quick_start_example.py
22
13180
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'Gunjan Sharma <gunjansharma@google.com>' import getopt import getpass import sys import gdata.apps.multidomain.client SCOPE = 'https://apps-apis.google.com/a/feeds/user/' USER_AGENT = 'MultiDomainQuickStartExample' class UserData(object): """Data corresponding to a single user.""" def __init__(self): self.email = '' self.first_name = '' self.last_name = '' self.password = '' self.confirm_password = 'temp' self.is_admin = '' self.hash_function = '' self.suspended = '' self.change_password = '' self.ip_whitelisted = '' self.quota = '' class MultiDomainQuickStartExample(object): """Demonstrates all the functions of multidomain user provisioning.""" def __init__(self, client_id, client_secret, domain): """Constructor for the MultiDomainQuickStartExample object. Takes a client_id, client_secret and domain to create an object for multidomain user provisioning. Args: client_id: [string] The clientId of the developer. client_secret: [string] The clientSecret of the developer. domain: [string] The domain on which the functions are to be performed. """ self.client_id = client_id self.client_secret = client_secret self.domain = domain token = gdata.gauth.OAuth2Token( client_id=self.client_id, client_secret=self.client_secret, scope=SCOPE, user_agent=USER_AGENT) uri = token.generate_authorize_url() print 'Please visit this URL to authorize the application:' print uri # Get the verification code from the standard input. code = raw_input('What is the verification code? ').strip() token.get_access_token(code) self.multidomain_client = ( gdata.apps.multidomain.client.MultiDomainProvisioningClient( domain=self.domain, auth_token=token)) def _PrintUserDetails(self, entry): """Prints all the information for a user entry. Args: entry: [UserEntry] User entry corresponding to a user """ print 'First Name: %s' % (entry.first_name) print 'Last Name: %s' % (entry.last_name) print 'Email: %s' % (entry.email) print 'Is Admin: %s' % (entry.is_admin) print 'Is Suspended: %s' % (entry.suspended) print 'Change password at next login: %s' % ( entry.change_password_at_next_login) print '\n' def _PrintAliasDetails(self, entry): """Prints all the information for a user alias entry. Args: entry: [AliasEntry] Alias entry correspoding to an alias """ print 'User Email: %s' % (entry.user_email) print 'Alias Email: %s' % (entry.alias_email) print '\n' def _GetChoice(self, for_field): """Gets a choice for a field. Args: for_field: [string] The field for which input is to be taken. Return: True/False/None: Depending on the choice made by the user. """ choice = int(raw_input(('Enter a choice for %s\n' '1-True 2-False 3-Default/Skip: ') % (for_field))) if choice == 1: return True elif choice == 2: return False return None def _TakeUserData(self, function='create'): """Takes input data for _UpdateUser and _CreateUser functions. Args: function: [string] representing the kind of function (create/update) from where this function was called. Return: user_data: [UserData] All data for a user. """ extra_stmt = '' if function == 'update': extra_stmt = '. Press enter to not update the field' user_data = UserData() while not user_data.email: user_data.email = raw_input('Enter a valid email address' '(username@domain.com): ') while not user_data.first_name: user_data.first_name = raw_input(('Enter first name for the user%s: ') % (extra_stmt)) if function == 'update': break while not user_data.last_name: user_data.last_name = raw_input(('Enter last name for the user%s: ') % (extra_stmt)) if function == 'update': break while not user_data.password == user_data.confirm_password: user_data.password = '' while not user_data.password: sys.stdout.write(('Enter password for the user%s: ') % (extra_stmt)) user_data.password = getpass.getpass() if function == 'update' and user_data.password.__len__() == 0: break if user_data.password.__len__() < 8: print 'Password must be at least 8 characters long' user_data.password = '' if function == 'update' and user_data.password.__len__() == 0: break sys.stdout.write('Confirm password: ') user_data.confirm_password = getpass.getpass() user_data.is_admin = self._GetChoice('is_admin') user_data.hash_function = raw_input('Enter a hash function or None: ') user_data.suspended = self._GetChoice('suspended') user_data.change_password = self._GetChoice('change_password') user_data.ip_whitelisted = self._GetChoice('ip_whitelisted') user_data.quota = raw_input('Enter a quota or None: ') if user_data.quota == 'None' or not user_data.quota.isdigit(): user_data.quota = None if user_data.hash_function == 'None': user_data.hash_function = None return user_data def _CreateUser(self): """Creates a new user account.""" user_data = self._TakeUserData() self.multidomain_client.CreateUser( user_data.email, user_data.first_name, user_data.last_name, user_data.password, user_data.is_admin, hash_function=user_data.hash_function, suspended=user_data.suspended, change_password=user_data.change_password, ip_whitelisted=user_data.ip_whitelisted, quota=user_data.quota) def _UpdateUser(self): """Updates a user.""" user_data = self._TakeUserData('update') user_entry = self.multidomain_client.RetrieveUser(user_data.email) if user_data.first_name: user_entry.first_name = user_data.first_name if user_data.last_name: user_entry.last_name = user_data.last_name if user_data.password: user_entry.password = user_data.password if not user_data.hash_function is None: user_entry.hash_function = user_data.hash_function if not user_data.quota is None: user_entry.quota = user_entry.quota if not user_data.is_admin is None: user_entry.is_admin = (str(user_data.is_admin)).lower() if not user_data.suspended is None: user_entry.suspended = (str(user_data.suspended)).lower() if not user_data.change_password is None: user_entry.change_password = (str(user_data.change_password)).lower() if not user_data.ip_whitelisted is None: user_entry.ip_whitelisted = (str(user_data.ip_whitelisted)).lower() self.multidomain_client.UpdateUser(user_data.email, user_entry) def _RenameUser(self): """Renames username of a user.""" old_email = '' new_email = '' while not old_email: old_email = raw_input('Enter old email address(username@domain.com): ') while not new_email: new_email = raw_input('Enter new email address(username@domain.com): ') self.multidomain_client.RenameUser(old_email, new_email) def _RetrieveSingleUser(self): """Retrieves a single user.""" email = '' while not email: email = raw_input('Enter a valid email address(username@domain.com): ') response = self.multidomain_client.RetrieveUser(email) self._PrintUserDetails(response) def _RetrieveAllUsers(self): """Retrieves all users from all the domains.""" response = self.multidomain_client.RetrieveAllUsers() for entry in response.entry: self._PrintUserDetails(entry) def _DeleteUser(self): """Deletes a user.""" email = '' while not email: email = raw_input('Enter a valid email address(username@domain.com): ') self.multidomain_client.DeleteUser(email) def _CreateUserAlias(self): """Creates a user alias.""" email = '' alias = '' while not email: email = raw_input('Enter a valid email address(username@domain.com): ') while not alias: alias = raw_input('Enter a valid alias email address' '(username@domain.com): ') self.multidomain_client.CreateAlias(email, alias) def _RetrieveAlias(self): """Retrieves a user corresponding to an alias.""" alias = '' while not alias: alias = raw_input('Enter a valid alias email address' '(username@domain.com): ') response = self.multidomain_client.RetrieveAlias(alias) self._PrintAliasDetails(response) def _RetrieveAllAliases(self): """Retrieves all user aliases for all users.""" response = self.multidomain_client.RetrieveAllAliases() for entry in response.entry: self._PrintAliasDetails(entry) def _RetrieveAllUserAliases(self): """Retrieves all user aliases of a user.""" email = '' while not email: email = raw_input('Enter a valid email address(username@domain.com): ') response = self.multidomain_client.RetrieveAllUserAliases(email) for entry in response.entry: self._PrintAliasDetails(entry) def _DeleteAlias(self): """Deletes a user alias.""" alias = '' while not alias: alias = raw_input('Enter a valid alias email address' '(username@domain.com): ') self.multidomain_client.DeleteAlias(alias) def Run(self): """Runs the sample by getting user input and takin appropriate action.""" #List of all the function and there description functions_list = [ {'function': self._CreateUser, 'description': 'Create a user'}, {'function': self._UpdateUser, 'description': 'Updating a user'}, {'function': self._RenameUser, 'description': 'Renaming a user'}, {'function': self._RetrieveSingleUser, 'description': 'Retrieve a single user'}, {'function': self._RetrieveAllUsers, 'description': 'Retrieve all users in all domains'}, {'function': self._DeleteUser, 'description': 'Deleting a User from a domain'}, {'function': self._CreateUserAlias, 'description': 'Create a User Alias in a domain'}, {'function': self._RetrieveAlias, 'description': 'Retrieve a User Alias in a domain'}, {'function': self._RetrieveAllAliases, 'description': 'Retrieve all User Aliases in a Domain'}, {'function': self._RetrieveAllUserAliases, 'description': 'Retrieve all User Aliases for a User'}, {'function': self._DeleteAlias, 'description': 'Delete a user alias from a domain'} ] while True: print 'Choose an option:\n0 - to exit' for i in range (0, len(functions_list)): print '%d - %s' % ((i+1), functions_list[i]['description']) choice = int(raw_input()) if choice == 0: break if choice < 0 or choice > len(functions_list): print 'Not a valid option!' continue functions_list[choice-1]['function']() def main(): """Runs the sample using an instance of MultiDomainQuickStartExample.""" # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['client_id=', 'client_secret=', 'domain=']) except getopt.error, msg: print ('python multidomain_provisioning_quick_start_example.py' '--client_id [clientId] --client_secret [clientSecret]' '--domain [domain]') sys.exit(2) client_id = '' client_secret = '' domain = '' # Parse options for option, arg in opts: if option == '--client_id': client_id = arg elif option == '--client_secret': client_secret = arg elif option == '--domain': domain = arg while not client_id: client_id = raw_input('Please enter a clientId: ') while not client_secret: client_secret = raw_input('Please enter a clientSecret: ') while not domain: domain = raw_input('Please enter domain name (example.com): ') try: multidomain_quick_start_example = MultiDomainQuickStartExample( client_id, client_secret, domain) except gdata.service.BadAuthentication: print 'Invalid user credentials given.' return multidomain_quick_start_example.Run() if __name__ == '__main__': main()
apache-2.0
firebitsbr/infernal-twin
build/reportlab/build/lib.linux-i686-2.7/reportlab/lib/textsplit.py
32
9741
#Copyright ReportLab Europe Ltd. 2000-2012 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/textsplit.py """Helpers for text wrapping, hyphenation, Asian text splitting and kinsoku shori. How to split a 'big word' depends on the language and the writing system. This module works on a Unicode string. It ought to grow by allowing ore algoriths to be plugged in based on possible knowledge of the language and desirable 'niceness' of the algorithm. """ __version__=''' $Id$ ''' from unicodedata import category from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.rl_config import _FUZZ from reportlab.lib.utils import isUnicode CANNOT_START_LINE = [ #strongly prohibited e.g. end brackets, stop, exclamation... u'!\',.:;?!")]\u3001\u3002\u300d\u300f\u3011\u3015\uff3d\u3011\uff09', #middle priority e.g. continuation small vowels - wrapped on two lines but one string... u'\u3005\u2015\u3041\u3043\u3045\u3047\u3049\u3063\u3083\u3085\u3087\u308e\u30a1\u30a3' u'\u30a5\u30a7\u30a9\u30c3\u30e3\u30e5\u30e7\u30ee\u30fc\u30f5\u30f6', #weakly prohibited - continuations, celsius symbol etc. u'\u309b\u309c\u30fb\u30fd\u30fe\u309d\u309e\u2015\u2010\xb0\u2032\u2033\u2103\uffe0\uff05\u2030' ] ALL_CANNOT_START = u''.join(CANNOT_START_LINE) CANNOT_END_LINE = [ #strongly prohibited u'\u2018\u201c\uff08[{\uff08\u3014\uff3b\uff5b\u3008\u300a\u300c\u300e\u3010', #weaker - currency symbols, hash, postcode - prefixes u'$\u00a3@#\uffe5\uff04\uffe1\uff20\u3012\u00a7' ] ALL_CANNOT_END = u''.join(CANNOT_END_LINE) def is_multi_byte(ch): "Is this an Asian character?" return (ord(ch) >= 0x3000) def getCharWidths(word, fontName, fontSize): """Returns a list of glyph widths. >>> getCharWidths('Hello', 'Courier', 10) [6.0, 6.0, 6.0, 6.0, 6.0] >>> from reportlab.pdfbase.cidfonts import UnicodeCIDFont >>> from reportlab.pdfbase.pdfmetrics import registerFont >>> registerFont(UnicodeCIDFont('HeiseiMin-W3')) >>> getCharWidths(u'\u6771\u4EAC', 'HeiseiMin-W3', 10) #most kanji are 100 ems [10.0, 10.0] """ #character-level function call; the performance is going to SUCK return [stringWidth(uChar, fontName, fontSize) for uChar in word] def wordSplit(word, maxWidths, fontName, fontSize, encoding='utf8'): """Attempts to break a word which lacks spaces into two parts, the first of which fits in the remaining space. It is allowed to add hyphens or whatever it wishes. This is intended as a wrapper for some language- and user-choice-specific splitting algorithms. It should only be called after line breaking on spaces, which covers western languages and is highly optimised already. It works on the 'last unsplit word'. Presumably with further study one could write a Unicode splitting algorithm for text fragments whick was much faster. Courier characters should be 6 points wide. >>> wordSplit('HelloWorld', 30, 'Courier', 10) [[0.0, 'Hello'], [0.0, 'World']] >>> wordSplit('HelloWorld', 31, 'Courier', 10) [[1.0, 'Hello'], [1.0, 'World']] """ if not isUnicode(word): uword = word.decode(encoding) else: uword = word charWidths = getCharWidths(uword, fontName, fontSize) lines = dumbSplit(uword, charWidths, maxWidths) if not isUnicode(word): lines2 = [] #convert back for (extraSpace, text) in lines: lines2.append([extraSpace, text.encode(encoding)]) lines = lines2 return lines def dumbSplit(word, widths, maxWidths): """This function attempts to fit as many characters as possible into the available space, cutting "like a knife" between characters. This would do for Chinese. It returns a list of (text, extraSpace) items where text is a Unicode string, and extraSpace is the points of unused space available on the line. This is a structure which is fairly easy to display, and supports 'backtracking' approaches after the fact. Test cases assume each character is ten points wide... >>> dumbSplit(u'Hello', [10]*5, 60) [[10, u'Hello']] >>> dumbSplit(u'Hello', [10]*5, 50) [[0, u'Hello']] >>> dumbSplit(u'Hello', [10]*5, 40) [[0, u'Hell'], [30, u'o']] """ _more = """ #>>> dumbSplit(u'Hello', [10]*5, 4) # less than one character #(u'', u'Hello') # this says 'Nihongo wa muzukashii desu ne!' (Japanese is difficult isn't it?) in 12 characters >>> jtext = u'\u65e5\u672c\u8a9e\u306f\u96e3\u3057\u3044\u3067\u3059\u306d\uff01' >>> dumbSplit(jtext, [10]*11, 30) # (u'\u65e5\u672c\u8a9e', u'\u306f\u96e3\u3057\u3044\u3067\u3059\u306d\uff01') """ if not isinstance(maxWidths,(list,tuple)): maxWidths = [maxWidths] assert isUnicode(word) lines = [] i = widthUsed = lineStartPos = 0 maxWidth = maxWidths[0] nW = len(word) while i<nW: w = widths[i] c = word[i] widthUsed += w i += 1 if widthUsed > maxWidth + _FUZZ and widthUsed>0: extraSpace = maxWidth - widthUsed if ord(c)<0x3000: # we appear to be inside a non-Asian script section. # (this is a very crude test but quick to compute). # This is likely to be quite rare so the speed of the # code below is hopefully not a big issue. The main # situation requiring this is that a document title # with an english product name in it got cut. # we count back and look for # - a space-like character # - reversion to Kanji (which would be a good split point) # - in the worst case, roughly half way back along the line limitCheck = (lineStartPos+i)>>1 #(arbitrary taste issue) for j in range(i-1,limitCheck,-1): cj = word[j] if category(cj)=='Zs' or ord(cj)>=0x3000: k = j+1 if k<i: j = k+1 extraSpace += sum(widths[j:i]) w = widths[k] c = word[k] i = j break #end of English-within-Asian special case #we are pushing this character back, but #the most important of the Japanese typography rules #if this character cannot start a line, wrap it up to this line so it hangs #in the right margin. We won't do two or more though - that's unlikely and #would result in growing ugliness. #and increase the extra space #bug fix contributed by Alexander Vasilenko <alexs.vasilenko@gmail.com> if c not in ALL_CANNOT_START and i>lineStartPos+1: #otherwise we need to push the character back #the i>lineStart+1 condition ensures progress i -= 1 extraSpace += w #lines.append([maxWidth-sum(widths[lineStartPos:i]), word[lineStartPos:i].strip()]) lines.append([extraSpace, word[lineStartPos:i].strip()]) try: maxWidth = maxWidths[len(lines)] except IndexError: maxWidth = maxWidths[-1] # use the last one lineStartPos = i widthUsed = 0 #any characters left? if widthUsed > 0: lines.append([maxWidth - widthUsed, word[lineStartPos:]]) return lines def kinsokuShoriSplit(word, widths, availWidth): #NOT USED OR FINISHED YET! """Split according to Japanese rules according to CJKV (Lunde). Essentially look for "nice splits" so that we don't end a line with an open bracket, or start one with a full stop, or stuff like that. There is no attempt to try to split compound words into constituent kanji. It currently uses wrap-down: packs as much on a line as possible, then backtracks if needed This returns a number of words each of which should just about fit on a line. If you give it a whole paragraph at once, it will do all the splits. It's possible we might slightly step over the width limit if we do hanging punctuation marks in future (e.g. dangle a Japanese full stop in the right margin rather than using a whole character box. """ lines = [] assert len(word) == len(widths) curWidth = 0.0 curLine = [] i = 0 #character index - we backtrack at times so cannot use for loop while 1: ch = word[i] w = widths[i] if curWidth + w < availWidth: curLine.append(ch) curWidth += w else: #end of line. check legality if ch in CANNOT_END_LINE[0]: pass #to be completed # This recipe refers: # # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061 import re rx=re.compile("([\u2e80-\uffff])", re.UNICODE) def cjkwrap(text, width, encoding="utf8"): return reduce(lambda line, word, width=width: '%s%s%s' % (line, [' ','\n', ''][(len(line)-line.rfind('\n')-1 + len(word.split('\n',1)[0] ) >= width) or line[-1:] == '\0' and 2], word), rx.sub(r'\1\0 ', str(text,encoding)).split(' ') ).replace('\0', '').encode(encoding) if __name__=='__main__': import doctest from reportlab.lib import textsplit doctest.testmod(textsplit)
gpl-3.0
fredericlepied/ansible
lib/ansible/modules/network/avi/avi_serviceengine.py
8
5728
#!/usr/bin/python # # Created on Aug 25, 2016 # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_serviceengine author: Gaurav Rastogi (grastogi@avinetworks.com) short_description: Module for setup of ServiceEngine Avi RESTful Object description: - This module is used to configure ServiceEngine object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.4" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent","present"] availability_zone: description: - Availability_zone of serviceengine. cloud_ref: description: - It is a reference to an object of type cloud. container_mode: description: - Boolean flag to set container_mode. - Default value when not specified in API or module is interpreted by Avi Controller as False. container_type: description: - Enum options - container_type_bridge, container_type_host, container_type_host_dpdk. - Default value when not specified in API or module is interpreted by Avi Controller as CONTAINER_TYPE_HOST. controller_created: description: - Boolean flag to set controller_created. - Default value when not specified in API or module is interpreted by Avi Controller as False. controller_ip: description: - Controller_ip of serviceengine. data_vnics: description: - List of vnic. enable_state: description: - Inorder to disable se set this field appropriately. - Enum options - SE_STATE_ENABLED, SE_STATE_DISABLED_FOR_PLACEMENT, SE_STATE_DISABLED. - Default value when not specified in API or module is interpreted by Avi Controller as SE_STATE_ENABLED. flavor: description: - Flavor of serviceengine. host_ref: description: - It is a reference to an object of type vimgrhostruntime. hypervisor: description: - Enum options - default, vmware_esx, kvm, vmware_vsan, xen. mgmt_vnic: description: - Vnic settings for serviceengine. name: description: - Name of the object. - Default value when not specified in API or module is interpreted by Avi Controller as VM name unknown. resources: description: - Seresources settings for serviceengine. se_group_ref: description: - It is a reference to an object of type serviceenginegroup. tenant_ref: description: - It is a reference to an object of type tenant. url: description: - Avi controller URL of the object. uuid: description: - Unique object identifier of the object. extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Example to create ServiceEngine object avi_serviceengine: controller: 10.10.25.42 username: admin password: something state: present name: sample_serviceengine """ RETURN = ''' obj: description: ServiceEngine (api/serviceengine) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.avi import ( avi_common_argument_spec, HAS_AVI, avi_ansible_api) except ImportError: HAS_AVI = False def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), availability_zone=dict(type='str',), cloud_ref=dict(type='str',), container_mode=dict(type='bool',), container_type=dict(type='str',), controller_created=dict(type='bool',), controller_ip=dict(type='str',), data_vnics=dict(type='list',), enable_state=dict(type='str',), flavor=dict(type='str',), host_ref=dict(type='str',), hypervisor=dict(type='str',), mgmt_vnic=dict(type='dict',), name=dict(type='str',), resources=dict(type='dict',), se_group_ref=dict(type='str',), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'serviceengine', set([])) if __name__ == '__main__': main()
gpl-3.0
mkaluza/external_chromium_org
native_client_sdk/src/tools/tests/sel_ldr_test.py
104
2080
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys import unittest SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PARENT_DIR = os.path.dirname(SCRIPT_DIR) DATA_DIR = os.path.join(SCRIPT_DIR, 'data') CHROME_SRC = os.path.dirname(os.path.dirname(os.path.dirname(PARENT_DIR))) MOCK_DIR = os.path.join(CHROME_SRC, "third_party", "pymock") # For the mock library sys.path.append(MOCK_DIR) sys.path.append(PARENT_DIR) import sel_ldr import mock class TestSelLdr(unittest.TestCase): def testRequiresArg(self): with mock.patch('sys.stderr'): self.assertRaises(SystemExit, sel_ldr.main, []) def testUsesHelper(self): with mock.patch('subprocess.call') as call: with mock.patch('os.path.exists'): with mock.patch('os.path.isfile'): with mock.patch('create_nmf.ParseElfHeader') as parse_header: parse_header.return_value = ('x8-64', False) with mock.patch('getos.GetPlatform') as get_platform: # assert that when we are running on linux # the helper is used. get_platform.return_value = 'linux' sel_ldr.main(['foo.nexe']) parse_header.assert_called_once_with('foo.nexe') self.assertEqual(call.call_count, 1) cmd = call.call_args[0][0] self.assertTrue('helper_bootstrap' in cmd[0]) # assert that when not running on linux the # helper is not used. get_platform.reset_mock() parse_header.reset_mock() call.reset_mock() get_platform.return_value = 'win' sel_ldr.main(['foo.nexe']) parse_header.assert_called_once_with('foo.nexe') self.assertEqual(call.call_count, 1) cmd = call.call_args[0][0] self.assertTrue('helper_bootstrap' not in cmd[0]) if __name__ == '__main__': unittest.main()
bsd-3-clause
Yannig/ansible
lib/ansible/plugins/action/aireos.py
16
3267
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import copy from ansible import constants as C from ansible.plugins.action.normal import ActionModule as _ActionModule from ansible.module_utils.aireos import aireos_provider_spec from ansible.module_utils.network_common import load_provider try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() class ActionModule(_ActionModule): def run(self, tmp=None, task_vars=None): if self._play_context.connection != 'local': return dict( failed=True, msg='invalid connection specified, expected connection=local, ' 'got %s' % self._play_context.connection ) provider = load_provider(aireos_provider_spec, self._task.args) pc = copy.deepcopy(self._play_context) pc.connection = 'network_cli' pc.network_os = 'aireos' pc.remote_addr = provider['host'] or self._play_context.remote_addr pc.port = int(provider['port'] or self._play_context.port or 22) pc.remote_user = provider['username'] or self._play_context.connection_user pc.password = provider['password'] or self._play_context.password pc.timeout = int(provider['timeout'] or C.PERSISTENT_COMMAND_TIMEOUT) display.vvv('using connection plugin %s' % pc.connection, pc.remote_addr) connection = self._shared_loader_obj.connection_loader.get('persistent', pc, sys.stdin) socket_path = connection.run() display.vvvv('socket_path: %s' % socket_path, pc.remote_addr) if not socket_path: return {'failed': True, 'msg': 'unable to open shell. Please see: ' + 'https://docs.ansible.com/ansible/network_debug_troubleshooting.html#unable-to-open-shell'} # make sure we are in the right cli context which should be # enable mode and not config module rc, out, err = connection.exec_command('prompt()') if str(out).strip().endswith(')#'): display.vvvv('wrong context, sending exit to device', self._play_context.remote_addr) connection.exec_command('exit') task_vars['ansible_socket'] = socket_path if self._play_context.become_method == 'enable': self._play_context.become = False self._play_context.become_method = None result = super(ActionModule, self).run(tmp, task_vars) return result
gpl-3.0
GanjaNoel/pym2
wdt/wdteditor.py
2
11345
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui import sys if sys.version_info < (3,0): import ConfigParser as configparser #import _winreg as winreg else: import configparser #import winreg import os from wowfile import * from wdt import * class WDTEditor(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.setupUi(self) self.config = configparser.ConfigParser() try: self.config.read("WDTEditor.ini") except: print "WDTEditor.ini could not be read!" self.foundWoW = False self.wowDir = "" self.getLastDir() self.wdt = WDTFile() def setupUi(self, MainWindow): self.lastDir = QtCore.QDir.currentPath() MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.tabWidget = QtGui.QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QtCore.QRect(20, 0, 780, 570)) self.tabWidget.setObjectName("tabWidget") self.terrTab = QtGui.QWidget() self.terrTab.setObjectName("terrTab") self.scrollArea = QtGui.QScrollArea(self.terrTab) self.scrollArea.setGeometry(QtCore.QRect(10, 50, 700, 490)) #self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) #self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) #self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QtGui.QWidget(self.scrollArea) self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 970, 970)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.terrCheck = [] for x in xrange(64): for y in xrange(64): t = QtGui.QCheckBox(self.scrollAreaWidgetContents) t.setGeometry(QtCore.QRect(x*15, y*15, 15, 15)) t.setText("") t.setObjectName("terrainCheck "+str(x)+" "+str(y)) t.setToolTip(str(x)+"/"+str(y)) self.terrCheck.append(t) self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.vertexCheck = QtGui.QCheckBox(self.terrTab) self.vertexCheck.setGeometry(QtCore.QRect(10, 0, 121, 17)) self.vertexCheck.setObjectName("vertexCheck") self.alphaCheck = QtGui.QCheckBox(self.terrTab) self.alphaCheck.setGeometry(QtCore.QRect(10, 20, 91, 17)) self.alphaCheck.setObjectName("alphaCheck") self.tabWidget.addTab(self.terrTab, "") self.wmoTab = QtGui.QWidget() self.wmoTab.setObjectName("wmoTab") self.filenameEdit = QtGui.QLineEdit(self.wmoTab) self.filenameEdit.setGeometry(QtCore.QRect(10, 30, 531, 20)) self.filenameEdit.setObjectName("filenameEdit") self.label = QtGui.QLabel(self.wmoTab) self.label.setGeometry(QtCore.QRect(20, 10, 51, 16)) self.label.setObjectName("label") self.doodadBox = QtGui.QComboBox(self.wmoTab) self.doodadBox.setGeometry(QtCore.QRect(10, 80, 69, 22)) self.doodadBox.setObjectName("doodadBox") self.nameBox = QtGui.QComboBox(self.wmoTab) self.nameBox.setGeometry(QtCore.QRect(100, 80, 69, 22)) self.nameBox.setObjectName("nameBox") self.oriA = QtGui.QDoubleSpinBox(self.wmoTab) self.oriA.setGeometry(QtCore.QRect(10, 150, 62, 22)) self.oriA.setMaximum(360.0) self.oriA.setObjectName("oriA") self.oriA.setRange(-360, 360) self.oriB = QtGui.QDoubleSpinBox(self.wmoTab) self.oriB.setGeometry(QtCore.QRect(80, 150, 62, 22)) self.oriB.setMaximum(360.0) self.oriB.setObjectName("oriB") self.oriB.setRange(-360, 360) self.oriC = QtGui.QDoubleSpinBox(self.wmoTab) self.oriC.setGeometry(QtCore.QRect(150, 150, 62, 22)) self.oriC.setMaximum(360.0) self.oriC.setObjectName("oriC") self.oriC.setRange(-360, 360) self.label_2 = QtGui.QLabel(self.wmoTab) self.label_2.setGeometry(QtCore.QRect(10, 60, 61, 16)) self.label_2.setObjectName("label_2") self.label_3 = QtGui.QLabel(self.wmoTab) self.label_3.setGeometry(QtCore.QRect(100, 60, 61, 16)) self.label_3.setObjectName("label_3") self.label_4 = QtGui.QLabel(self.wmoTab) self.label_4.setGeometry(QtCore.QRect(10, 130, 71, 16)) self.label_4.setObjectName("label_4") self.xPos = QtGui.QLineEdit(self.wmoTab) self.xPos.setGeometry(QtCore.QRect(10, 210, 61, 20)) self.xPos.setObjectName("xPos") self.yPos = QtGui.QLineEdit(self.wmoTab) self.yPos.setGeometry(QtCore.QRect(80, 210, 61, 20)) self.yPos.setObjectName("yPos") self.zPos = QtGui.QLineEdit(self.wmoTab) self.zPos.setGeometry(QtCore.QRect(150, 210, 61, 20)) self.zPos.setObjectName("zPos") self.label_5 = QtGui.QLabel(self.wmoTab) self.label_5.setGeometry(QtCore.QRect(10, 190, 46, 13)) self.label_5.setObjectName("label_5") self.tabWidget.addTab(self.wmoTab, "") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 603, 21)) self.menubar.setObjectName("menubar") self.menuFile = QtGui.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") MainWindow.setMenuBar(self.menubar) self.actionNew = QtGui.QAction(MainWindow) self.actionNew.setObjectName("actionNew") self.actionOpen = QtGui.QAction(MainWindow) self.actionOpen.setObjectName("actionOpen") self.connect(self.actionOpen, QtCore.SIGNAL("triggered()"), self.openFile) self.actionSave = QtGui.QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.connect(self.actionSave, QtCore.SIGNAL("triggered()"), self.saveFile) self.actionClose = QtGui.QAction(MainWindow) self.actionClose.setObjectName("actionClose") self.menuFile.addAction(self.actionNew) self.menuFile.addAction(self.actionOpen) self.menuFile.addAction(self.actionSave) self.menuFile.addAction(self.actionClose) self.menubar.addAction(self.menuFile.menuAction()) self.tabWidget.setCurrentWidget(self.terrTab) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.MainWindow = MainWindow def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.vertexCheck.setText(QtGui.QApplication.translate("MainWindow", "Use Vertex Shading", None, QtGui.QApplication.UnicodeUTF8)) self.alphaCheck.setText(QtGui.QApplication.translate("MainWindow", "Has Big Alpha", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.terrTab), QtGui.QApplication.translate("MainWindow", "Terrain", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", "Filename:", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Doodadset:", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("MainWindow", "Nameset:", None, QtGui.QApplication.UnicodeUTF8)) self.label_4.setText(QtGui.QApplication.translate("MainWindow", "Orientation:", None, QtGui.QApplication.UnicodeUTF8)) self.label_5.setText(QtGui.QApplication.translate("MainWindow", "Position:", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.wmoTab), QtGui.QApplication.translate("MainWindow", "World Model Object", None, QtGui.QApplication.UnicodeUTF8)) self.menuFile.setTitle(QtGui.QApplication.translate("MainWindow", "File", None, QtGui.QApplication.UnicodeUTF8)) self.actionNew.setText(QtGui.QApplication.translate("MainWindow", "New", None, QtGui.QApplication.UnicodeUTF8)) self.actionOpen.setText(QtGui.QApplication.translate("MainWindow", "Open", None, QtGui.QApplication.UnicodeUTF8)) self.actionSave.setText(QtGui.QApplication.translate("MainWindow", "Save", None, QtGui.QApplication.UnicodeUTF8)) self.actionClose.setText(QtGui.QApplication.translate("MainWindow", "Close", None, QtGui.QApplication.UnicodeUTF8)) def getLastDir(self): try: self.lastDir = self.config.get("Path", "LastDir") except: self.lastDir = QtCore.QDir.currentPath() def saveLastDir(self): try: if self.config.has_section("Path"): self.config.set("Path", "LastDir", self.lastDir) else: self.config.add_section("Path") self.config.set("Path", "LastDir", self.lastDir) conf = open("WDTEditor.ini","w+") self.config.write(conf) conf.close() except: print "oO" def getWoWDir(self): try: self.wowDir = self.config.get("Path", "WoWDir") self.foundWoW = True except: if os.name == "nt": print "Could not get WoWDir :(" #toDo: read registry else: print "Could not get WoWDir :(" def openFile(self): filename = QtGui.QFileDialog().getOpenFileName(self,"Open File",self.lastDir) self.MainWindow.setWindowTitle(filename) self.wdt.read(filename) for x in xrange(64): for y in xrange(64): if self.wdt.main.hasADT(x,y): self.terrCheck[y+x*64].setCheckState(2) else: self.terrCheck[y+x*64].setCheckState(0) if self.wdt.mphd.hasBigAlpha(): self.alphaCheck.setCheckState(2) else: self.alphaCheck.setCheckState(0) if self.wdt.mphd.hasVertexShading(): self.vertexCheck.setCheckState(2) else: self.vertexCheck.setCheckState(0) self.filenameEdit.setText(self.wdt.getWMOName()) pos = self.wdt.getWMOPosition() self.xPos.setText(str(pos.x)) self.yPos.setText(str(pos.y)) self.zPos.setText(str(pos.y)) ori = self.wdt.getWMOOrientation() self.oriA.setValue(ori.x) self.oriB.setValue(ori.y) self.oriC.setValue(ori.z) filename = str(filename) last = filename.rfind("/") self.lastDir = filename[0:last] self.saveLastDir() def saveFile(self): filename = QtGui.QFileDialog().getSaveFileName(self,"Save File",self.lastDir) hasTerr = False for x in xrange(64): for y in xrange(64): if (self.terrCheck[y+x*64].checkState() == 2): self.wdt.checkTile(x,y) hasTerr = True else: self.wdt.uncheckTile(x,y) if (hasTerr == True): self.wdt.setTerrain() else: self.wdt.unsetTerrain() print self.alphaCheck.checkState() if (self.alphaCheck.checkState() == 2): self.wdt.setBigAlpha() else: self.wdt.unsetBigAlpha() if (self.vertexCheck.checkState() == 2): self.wdt.setVertexShading() else: self.wdt.unsetVertexShading() #if (hasTerr == False): name = str(self.filenameEdit.text()) name.encode("cp1252") self.wdt.setWMOName(name) pos = Vec3() pos.x = float(self.xPos.text()) pos.y = float(self.yPos.text()) pos.z = float(self.zPos.text()) self.wdt.setWMOPosition(pos) ori = Vec3() ori.x = self.oriA.value() ori.y = self.oriB.value() ori.z = self.oriC.value() self.wdt.setWMOOrientation(ori) self.wdt.write(filename) filename = str(filename) last = filename.rfind("/") self.lastDir = filename[0:last] self.saveLastDir() app = QtGui.QApplication(sys.argv) dialog = WDTEditor() dialog.show() sys.exit(app.exec_())
lgpl-3.0
snakeleon/YouCompleteMe-x86
third_party/ycmd/third_party/requests/requests/packages/chardet/eucjpprober.py
2919
3678
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import sys from . import constants from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import EUCJPDistributionAnalysis from .jpcntx import EUCJPContextAnalysis from .mbcssm import EUCJPSMModel class EUCJPProber(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(EUCJPSMModel) self._mDistributionAnalyzer = EUCJPDistributionAnalysis() self._mContextAnalyzer = EUCJPContextAnalysis() self.reset() def reset(self): MultiByteCharSetProber.reset(self) self._mContextAnalyzer.reset() def get_charset_name(self): return "EUC-JP" def feed(self, aBuf): aLen = len(aBuf) for i in range(0, aLen): # PY3K: aBuf is a byte array, so aBuf[i] is an int, not a byte codingState = self._mCodingSM.next_state(aBuf[i]) if codingState == constants.eError: if constants._debug: sys.stderr.write(self.get_charset_name() + ' prober hit error at byte ' + str(i) + '\n') self._mState = constants.eNotMe break elif codingState == constants.eItsMe: self._mState = constants.eFoundIt break elif codingState == constants.eStart: charLen = self._mCodingSM.get_current_charlen() if i == 0: self._mLastChar[1] = aBuf[0] self._mContextAnalyzer.feed(self._mLastChar, charLen) self._mDistributionAnalyzer.feed(self._mLastChar, charLen) else: self._mContextAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mLastChar[0] = aBuf[aLen - 1] if self.get_state() == constants.eDetecting: if (self._mContextAnalyzer.got_enough_data() and (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): self._mState = constants.eFoundIt return self.get_state() def get_confidence(self): contxtCf = self._mContextAnalyzer.get_confidence() distribCf = self._mDistributionAnalyzer.get_confidence() return max(contxtCf, distribCf)
gpl-3.0
pgarridounican/ns-3.20-NC
src/point-to-point-layout/bindings/modulegen__gcc_ILP32.py
14
468963
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.point_to_point_layout', 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') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class] module.add_class('AsciiTraceHelper', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class] module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True, import_from_module='ns.network') ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv4 [class] module.add_class('AsciiTraceHelperForIpv4', allow_subclassing=True, import_from_module='ns.internet') ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv6 [class] module.add_class('AsciiTraceHelperForIpv6', allow_subclassing=True, import_from_module='ns.internet') ## 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-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper [class] module.add_class('Ipv4AddressHelper', import_from_module='ns.internet') ## 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-interface-container.h (module 'internet'): ns3::Ipv4InterfaceContainer [class] module.add_class('Ipv4InterfaceContainer', import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6AddressHelper [class] module.add_class('Ipv6AddressHelper', import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress [class] module.add_class('Ipv6InterfaceAddress', import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e [enumeration] module.add_enum('State_e', ['TENTATIVE', 'DEPRECATED', 'PREFERRED', 'PERMANENT', 'HOMEADDRESS', 'TENTATIVE_OPTIMISTIC', 'INVALID'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e [enumeration] module.add_enum('Scope_e', ['HOST', 'LINKLOCAL', 'GLOBAL'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6InterfaceContainer [class] module.add_class('Ipv6InterfaceContainer', import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## 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') ## pcap-file.h (module 'network'): ns3::PcapFile [class] module.add_class('PcapFile', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelper [class] module.add_class('PcapHelper', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelper [enumeration] module.add_enum('', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO', 'DLT_IEEE802_15_4'], outer_class=root_module['ns3::PcapHelper'], import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class] module.add_class('PcapHelperForDevice', allow_subclassing=True, import_from_module='ns.network') ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv4 [class] module.add_class('PcapHelperForIpv4', allow_subclassing=True, import_from_module='ns.internet') ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv6 [class] module.add_class('PcapHelperForIpv6', allow_subclassing=True, import_from_module='ns.internet') ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::PointToPointDumbbellHelper [class] module.add_class('PointToPointDumbbellHelper') ## point-to-point-grid.h (module 'point-to-point-layout'): ns3::PointToPointGridHelper [class] module.add_class('PointToPointGridHelper') ## point-to-point-helper.h (module 'point-to-point'): ns3::PointToPointHelper [class] module.add_class('PointToPointHelper', import_from_module='ns.point_to_point', parent=[root_module['ns3::PcapHelperForDevice'], root_module['ns3::AsciiTraceHelperForDevice']]) ## point-to-point-star.h (module 'point-to-point-layout'): ns3::PointToPointStarHelper [class] module.add_class('PointToPointStarHelper') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## 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']) ## internet-stack-helper.h (module 'internet'): ns3::InternetStackHelper [class] module.add_class('InternetStackHelper', import_from_module='ns.internet', parent=[root_module['ns3::PcapHelperForIpv4'], root_module['ns3::PcapHelperForIpv6'], root_module['ns3::AsciiTraceHelperForIpv4'], root_module['ns3::AsciiTraceHelperForIpv6']]) ## 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') ## ipv6-header.h (module 'internet'): ns3::Ipv6Header [class] module.add_class('Ipv6Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::NextHeader_e [enumeration] module.add_enum('NextHeader_e', ['IPV6_EXT_HOP_BY_HOP', 'IPV6_IPV4', 'IPV6_TCP', 'IPV6_UDP', 'IPV6_IPV6', 'IPV6_EXT_ROUTING', 'IPV6_EXT_FRAGMENTATION', 'IPV6_EXT_CONFIDENTIALITY', 'IPV6_EXT_AUTHENTIFICATION', 'IPV6_ICMPV6', 'IPV6_EXT_END', 'IPV6_EXT_DESTINATION', 'IPV6_SCTP', 'IPV6_EXT_MOBILITY', 'IPV6_UDP_LITE'], outer_class=root_module['ns3::Ipv6Header'], import_from_module='ns.internet') ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class] module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=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::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketAddressTag [class] module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['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']) ## 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-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') ## 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.h (module 'internet'): ns3::Ipv6 [class] module.add_class('Ipv6', 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-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol [class] module.add_class('Ipv6L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv6']) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_UNKNOWN_PROTOCOL', 'DROP_UNKNOWN_OPTION', 'DROP_MALFORMED_HEADER', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv6L3Protocol'], import_from_module='ns.internet') ## ipv6-pmtu-cache.h (module 'internet'): ns3::Ipv6PmtuCache [class] module.add_class('Ipv6PmtuCache', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## 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']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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> >']) ## 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']) module.add_container('std::vector< bool >', 'bool', container_type=u'vector') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map') ## 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) 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_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper']) register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice']) register_Ns3AsciiTraceHelperForIpv4_methods(root_module, root_module['ns3::AsciiTraceHelperForIpv4']) register_Ns3AsciiTraceHelperForIpv6_methods(root_module, root_module['ns3::AsciiTraceHelperForIpv6']) 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_Ns3Ipv4AddressHelper_methods(root_module, root_module['ns3::Ipv4AddressHelper']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4InterfaceContainer_methods(root_module, root_module['ns3::Ipv4InterfaceContainer']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6AddressHelper_methods(root_module, root_module['ns3::Ipv6AddressHelper']) register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress']) register_Ns3Ipv6InterfaceContainer_methods(root_module, root_module['ns3::Ipv6InterfaceContainer']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile']) register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper']) register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice']) register_Ns3PcapHelperForIpv4_methods(root_module, root_module['ns3::PcapHelperForIpv4']) register_Ns3PcapHelperForIpv6_methods(root_module, root_module['ns3::PcapHelperForIpv6']) register_Ns3PointToPointDumbbellHelper_methods(root_module, root_module['ns3::PointToPointDumbbellHelper']) register_Ns3PointToPointGridHelper_methods(root_module, root_module['ns3::PointToPointGridHelper']) register_Ns3PointToPointHelper_methods(root_module, root_module['ns3::PointToPointHelper']) register_Ns3PointToPointStarHelper_methods(root_module, root_module['ns3::PointToPointStarHelper']) 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_Ns3InternetStackHelper_methods(root_module, root_module['ns3::InternetStackHelper']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_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_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_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) 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_Ns3Ipv6_methods(root_module, root_module['ns3::Ipv6']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6L3Protocol_methods(root_module, root_module['ns3::Ipv6L3Protocol']) register_Ns3Ipv6PmtuCache_methods(root_module, root_module['ns3::Ipv6PmtuCache']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) 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_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_Ns3AsciiTraceHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::_Ios_Openmode filemode=std::ios_base::out) [member function] cls.add_method('CreateFileStream', 'ns3::Ptr< ns3::OutputStreamWrapper >', [param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode', default_value='std::ios_base::out')]) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3AsciiTraceHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice(ns3::AsciiTraceHelperForDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::NetDevice> nd) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::NetDevice >', 'nd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, std::string ndName, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ndName) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ndName')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t deviceid) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(std::string prefix) [member function] cls.add_method('EnableAsciiAll', 'void', [param('std::string', 'prefix')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiAll', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function] cls.add_method('EnableAsciiInternal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3AsciiTraceHelperForIpv4_methods(root_module, cls): ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv4::AsciiTraceHelperForIpv4(ns3::AsciiTraceHelperForIpv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelperForIpv4 const &', 'arg0')]) ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv4::AsciiTraceHelperForIpv4() [constructor] cls.add_constructor([]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, std::string ipv4Name, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('std::string', 'ipv4Name'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ipv4Name, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ipv4Name'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, ns3::Ipv4InterfaceContainer c) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('ns3::Ipv4InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ipv4InterfaceContainer c) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ipv4InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4All(std::string prefix) [member function] cls.add_method('EnableAsciiIpv4All', 'void', [param('std::string', 'prefix')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4All(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiIpv4All', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4Internal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv4Internal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3AsciiTraceHelperForIpv6_methods(root_module, cls): ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv6::AsciiTraceHelperForIpv6(ns3::AsciiTraceHelperForIpv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelperForIpv6 const &', 'arg0')]) ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv6::AsciiTraceHelperForIpv6() [constructor] cls.add_constructor([]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, std::string ipv6Name, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('std::string', 'ipv6Name'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ipv6Name, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ipv6Name'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, ns3::Ipv6InterfaceContainer c) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('ns3::Ipv6InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ipv6InterfaceContainer c) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ipv6InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, uint32_t nodeid, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6All(std::string prefix) [member function] cls.add_method('EnableAsciiIpv6All', 'void', [param('std::string', 'prefix')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6All(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiIpv6All', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6Internal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv6Internal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): 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 adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_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'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4AddressHelper_methods(root_module, cls): ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper::Ipv4AddressHelper(ns3::Ipv4AddressHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressHelper const &', 'arg0')]) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper::Ipv4AddressHelper() [constructor] cls.add_constructor([]) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper::Ipv4AddressHelper(ns3::Ipv4Address network, ns3::Ipv4Mask mask, ns3::Ipv4Address base="0.0.0.1") [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'network'), param('ns3::Ipv4Mask', 'mask'), param('ns3::Ipv4Address', 'base', default_value='"0.0.0.1"')]) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4InterfaceContainer ns3::Ipv4AddressHelper::Assign(ns3::NetDeviceContainer const & c) [member function] cls.add_method('Assign', 'ns3::Ipv4InterfaceContainer', [param('ns3::NetDeviceContainer const &', 'c')]) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4AddressHelper::NewAddress() [member function] cls.add_method('NewAddress', 'ns3::Ipv4Address', []) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4AddressHelper::NewNetwork() [member function] cls.add_method('NewNetwork', 'ns3::Ipv4Address', []) ## ipv4-address-helper.h (module 'internet'): void ns3::Ipv4AddressHelper::SetBase(ns3::Ipv4Address network, ns3::Ipv4Mask mask, ns3::Ipv4Address base="0.0.0.1") [member function] cls.add_method('SetBase', 'void', [param('ns3::Ipv4Address', 'network'), param('ns3::Ipv4Mask', 'mask'), param('ns3::Ipv4Address', 'base', default_value='"0.0.0.1"')]) 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_Ns3Ipv4InterfaceContainer_methods(root_module, cls): ## ipv4-interface-container.h (module 'internet'): ns3::Ipv4InterfaceContainer::Ipv4InterfaceContainer(ns3::Ipv4InterfaceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceContainer const &', 'arg0')]) ## ipv4-interface-container.h (module 'internet'): ns3::Ipv4InterfaceContainer::Ipv4InterfaceContainer() [constructor] cls.add_constructor([]) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(ns3::Ipv4InterfaceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::Ipv4InterfaceContainer', 'other')]) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface')]) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(std::pair<ns3::Ptr<ns3::Ipv4>,unsigned int> ipInterfacePair) [member function] cls.add_method('Add', 'void', [param('std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int >', 'ipInterfacePair')]) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(std::string ipv4Name, uint32_t interface) [member function] cls.add_method('Add', 'void', [param('std::string', 'ipv4Name'), param('uint32_t', 'interface')]) ## ipv4-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int> > > > ns3::Ipv4InterfaceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > > >', [], is_const=True) ## ipv4-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int> > > > ns3::Ipv4InterfaceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > > >', [], is_const=True) ## ipv4-interface-container.h (module 'internet'): std::pair<ns3::Ptr<ns3::Ipv4>,unsigned int> ns3::Ipv4InterfaceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int >', [param('uint32_t', 'i')], is_const=True) ## ipv4-interface-container.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceContainer::GetAddress(uint32_t i, uint32_t j=0) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4Address', [param('uint32_t', 'i'), param('uint32_t', 'j', default_value='0')], is_const=True) ## ipv4-interface-container.h (module 'internet'): uint32_t ns3::Ipv4InterfaceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::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_Ns3Ipv6AddressHelper_methods(root_module, cls): ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6AddressHelper::Ipv6AddressHelper(ns3::Ipv6AddressHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressHelper const &', 'arg0')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6AddressHelper::Ipv6AddressHelper() [constructor] cls.add_constructor([]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6AddressHelper::Ipv6AddressHelper(ns3::Ipv6Address network, ns3::Ipv6Prefix prefix, ns3::Ipv6Address base=ns3::Ipv6Address(((const char*)"::1"))) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'prefix'), param('ns3::Ipv6Address', 'base', default_value='ns3::Ipv6Address(((const char*)"::1"))')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6InterfaceContainer ns3::Ipv6AddressHelper::Assign(ns3::NetDeviceContainer const & c) [member function] cls.add_method('Assign', 'ns3::Ipv6InterfaceContainer', [param('ns3::NetDeviceContainer const &', 'c')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6InterfaceContainer ns3::Ipv6AddressHelper::Assign(ns3::NetDeviceContainer const & c, std::vector<bool,std::allocator<bool> > withConfiguration) [member function] cls.add_method('Assign', 'ns3::Ipv6InterfaceContainer', [param('ns3::NetDeviceContainer const &', 'c'), param('std::vector< bool >', 'withConfiguration')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6InterfaceContainer ns3::Ipv6AddressHelper::AssignWithoutAddress(ns3::NetDeviceContainer const & c) [member function] cls.add_method('AssignWithoutAddress', 'ns3::Ipv6InterfaceContainer', [param('ns3::NetDeviceContainer const &', 'c')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6AddressHelper::NewAddress(ns3::Address addr) [member function] cls.add_method('NewAddress', 'ns3::Ipv6Address', [param('ns3::Address', 'addr')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6AddressHelper::NewAddress() [member function] cls.add_method('NewAddress', 'ns3::Ipv6Address', []) ## ipv6-address-helper.h (module 'internet'): void ns3::Ipv6AddressHelper::NewNetwork(ns3::Ipv6Address network, ns3::Ipv6Prefix prefix) [member function] cls.add_method('NewNetwork', 'void', [param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'prefix')], deprecated=True) ## ipv6-address-helper.h (module 'internet'): void ns3::Ipv6AddressHelper::NewNetwork() [member function] cls.add_method('NewNetwork', 'void', []) ## ipv6-address-helper.h (module 'internet'): void ns3::Ipv6AddressHelper::SetBase(ns3::Ipv6Address network, ns3::Ipv6Prefix prefix, ns3::Ipv6Address base=ns3::Ipv6Address(((const char*)"::1"))) [member function] cls.add_method('SetBase', 'void', [param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'prefix'), param('ns3::Ipv6Address', 'base', default_value='ns3::Ipv6Address(((const char*)"::1"))')]) return def register_Ns3Ipv6InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address, ns3::Ipv6Prefix prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'prefix')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv6InterfaceAddress const &', 'o')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceAddress::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): uint32_t ns3::Ipv6InterfaceAddress::GetNsDadUid() const [member function] cls.add_method('GetNsDadUid', 'uint32_t', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Prefix ns3::Ipv6InterfaceAddress::GetPrefix() const [member function] cls.add_method('GetPrefix', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e ns3::Ipv6InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv6InterfaceAddress::Scope_e', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e ns3::Ipv6InterfaceAddress::GetState() const [member function] cls.add_method('GetState', 'ns3::Ipv6InterfaceAddress::State_e', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): bool ns3::Ipv6InterfaceAddress::IsInSameSubnet(ns3::Ipv6Address b) const [member function] cls.add_method('IsInSameSubnet', 'bool', [param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetAddress(ns3::Ipv6Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetNsDadUid(uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('uint32_t', 'uid')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetScope(ns3::Ipv6InterfaceAddress::Scope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv6InterfaceAddress::Scope_e', 'scope')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetState(ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) return def register_Ns3Ipv6InterfaceContainer_methods(root_module, cls): ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6InterfaceContainer::Ipv6InterfaceContainer(ns3::Ipv6InterfaceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6InterfaceContainer const &', 'arg0')]) ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6InterfaceContainer::Ipv6InterfaceContainer() [constructor] cls.add_constructor([]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::Add(ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::Add(ns3::Ipv6InterfaceContainer & c) [member function] cls.add_method('Add', 'void', [param('ns3::Ipv6InterfaceContainer &', 'c')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::Add(std::string ipv6Name, uint32_t interface) [member function] cls.add_method('Add', 'void', [param('std::string', 'ipv6Name'), param('uint32_t', 'interface')]) ## ipv6-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int> > > > ns3::Ipv6InterfaceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv6 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv6 >, unsigned int > > >', [], is_const=True) ## ipv6-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int> > > > ns3::Ipv6InterfaceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv6 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv6 >, unsigned int > > >', [], is_const=True) ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceContainer::GetAddress(uint32_t i, uint32_t j) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6Address', [param('uint32_t', 'i'), param('uint32_t', 'j')], is_const=True) ## ipv6-interface-container.h (module 'internet'): uint32_t ns3::Ipv6InterfaceContainer::GetInterfaceIndex(uint32_t i) const [member function] cls.add_method('GetInterfaceIndex', 'uint32_t', [param('uint32_t', 'i')], is_const=True) ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceContainer::GetLinkLocalAddress(uint32_t i) [member function] cls.add_method('GetLinkLocalAddress', 'ns3::Ipv6Address', [param('uint32_t', 'i')]) ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceContainer::GetLinkLocalAddress(ns3::Ipv6Address address) [member function] cls.add_method('GetLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-container.h (module 'internet'): uint32_t ns3::Ipv6InterfaceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::SetDefaultRoute(uint32_t i, uint32_t router) [member function] cls.add_method('SetDefaultRoute', 'void', [param('uint32_t', 'i'), param('uint32_t', 'router')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::SetDefaultRoute(uint32_t i, ns3::Ipv6Address routerAddr) [member function] cls.add_method('SetDefaultRoute', 'void', [param('uint32_t', 'i'), param('ns3::Ipv6Address', 'routerAddr')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::SetDefaultRouteInAllNodes(uint32_t router) [member function] cls.add_method('SetDefaultRouteInAllNodes', 'void', [param('uint32_t', 'router')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::SetDefaultRouteInAllNodes(ns3::Ipv6Address routerAddr) [member function] cls.add_method('SetDefaultRouteInAllNodes', 'void', [param('ns3::Ipv6Address', 'routerAddr')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::SetForwarding(uint32_t i, bool state) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'state')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::SetRouter(uint32_t i, bool router) [member function] cls.add_method('SetRouter', 'void', [param('uint32_t', 'i'), param('bool', 'router')], deprecated=True) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## 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 [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PcapFile_methods(root_module, cls): ## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor] cls.add_constructor([]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT) [member function] cls.add_method('Diff', 'bool', [param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint32_t &', 'sec'), param('uint32_t &', 'usec'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT')], is_static=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file.h (module 'network'): bool ns3::PcapFile::GetSwapMode() [member function] cls.add_method('GetSwapMode', 'bool', []) ## pcap-file.h (module 'network'): int32_t ns3::PcapFile::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Init(uint32_t dataLinkType, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT, int32_t timeZoneCorrection=ns3::PcapFile::ZONE_DEFAULT, bool swapMode=false) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT'), param('int32_t', 'timeZoneCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT'), param('bool', 'swapMode', default_value='false')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Read(uint8_t * const data, uint32_t maxBytes, uint32_t & tsSec, uint32_t & tsUsec, uint32_t & inclLen, uint32_t & origLen, uint32_t & readLen) [member function] cls.add_method('Read', 'void', [param('uint8_t * const', 'data'), param('uint32_t', 'maxBytes'), param('uint32_t &', 'tsSec'), param('uint32_t &', 'tsUsec'), param('uint32_t &', 'inclLen'), param('uint32_t &', 'origLen'), param('uint32_t &', 'readLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, uint8_t const * const data, uint32_t totalLen) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('uint8_t const * const', 'data'), param('uint32_t', 'totalLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Header & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): ns3::PcapFile::SNAPLEN_DEFAULT [variable] cls.add_static_attribute('SNAPLEN_DEFAULT', 'uint32_t const', is_const=True) ## pcap-file.h (module 'network'): ns3::PcapFile::ZONE_DEFAULT [variable] cls.add_static_attribute('ZONE_DEFAULT', 'int32_t const', is_const=True) return def register_Ns3PcapHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper(ns3::PcapHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::PcapFileWrapper> ns3::PcapHelper::CreateFile(std::string filename, std::_Ios_Openmode filemode, uint32_t dataLinkType, uint32_t snapLen=65535, int32_t tzCorrection=0) [member function] cls.add_method('CreateFile', 'ns3::Ptr< ns3::PcapFileWrapper >', [param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode'), param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='65535'), param('int32_t', 'tzCorrection', default_value='0')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3PcapHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function] cls.add_method('EnablePcapAll', 'void', [param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3PcapHelperForIpv4_methods(root_module, cls): ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv4::PcapHelperForIpv4(ns3::PcapHelperForIpv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelperForIpv4 const &', 'arg0')]) ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv4::PcapHelperForIpv4() [constructor] cls.add_constructor([]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, std::string ipv4Name, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('std::string', 'ipv4Name'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, ns3::Ipv4InterfaceContainer c) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('ns3::Ipv4InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, uint32_t nodeid, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4All(std::string prefix) [member function] cls.add_method('EnablePcapIpv4All', 'void', [param('std::string', 'prefix')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4Internal(std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv4Internal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3PcapHelperForIpv6_methods(root_module, cls): ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv6::PcapHelperForIpv6(ns3::PcapHelperForIpv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelperForIpv6 const &', 'arg0')]) ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv6::PcapHelperForIpv6() [constructor] cls.add_constructor([]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, std::string ipv6Name, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('std::string', 'ipv6Name'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, ns3::Ipv6InterfaceContainer c) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('ns3::Ipv6InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, uint32_t nodeid, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6All(std::string prefix) [member function] cls.add_method('EnablePcapIpv6All', 'void', [param('std::string', 'prefix')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6Internal(std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv6Internal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3PointToPointDumbbellHelper_methods(root_module, cls): ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::PointToPointDumbbellHelper::PointToPointDumbbellHelper(ns3::PointToPointDumbbellHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PointToPointDumbbellHelper const &', 'arg0')]) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::PointToPointDumbbellHelper::PointToPointDumbbellHelper(uint32_t nLeftLeaf, ns3::PointToPointHelper leftHelper, uint32_t nRightLeaf, ns3::PointToPointHelper rightHelper, ns3::PointToPointHelper bottleneckHelper) [constructor] cls.add_constructor([param('uint32_t', 'nLeftLeaf'), param('ns3::PointToPointHelper', 'leftHelper'), param('uint32_t', 'nRightLeaf'), param('ns3::PointToPointHelper', 'rightHelper'), param('ns3::PointToPointHelper', 'bottleneckHelper')]) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): void ns3::PointToPointDumbbellHelper::AssignIpv4Addresses(ns3::Ipv4AddressHelper leftIp, ns3::Ipv4AddressHelper rightIp, ns3::Ipv4AddressHelper routerIp) [member function] cls.add_method('AssignIpv4Addresses', 'void', [param('ns3::Ipv4AddressHelper', 'leftIp'), param('ns3::Ipv4AddressHelper', 'rightIp'), param('ns3::Ipv4AddressHelper', 'routerIp')]) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): void ns3::PointToPointDumbbellHelper::AssignIpv6Addresses(ns3::Ipv6Address network, ns3::Ipv6Prefix prefix) [member function] cls.add_method('AssignIpv6Addresses', 'void', [param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'prefix')]) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): void ns3::PointToPointDumbbellHelper::BoundingBox(double ulx, double uly, double lrx, double lry) [member function] cls.add_method('BoundingBox', 'void', [param('double', 'ulx'), param('double', 'uly'), param('double', 'lrx'), param('double', 'lry')]) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::Ptr<ns3::Node> ns3::PointToPointDumbbellHelper::GetLeft() const [member function] cls.add_method('GetLeft', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::Ptr<ns3::Node> ns3::PointToPointDumbbellHelper::GetLeft(uint32_t i) const [member function] cls.add_method('GetLeft', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::Ipv4Address ns3::PointToPointDumbbellHelper::GetLeftIpv4Address(uint32_t i) const [member function] cls.add_method('GetLeftIpv4Address', 'ns3::Ipv4Address', [param('uint32_t', 'i')], is_const=True) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::Ipv6Address ns3::PointToPointDumbbellHelper::GetLeftIpv6Address(uint32_t i) const [member function] cls.add_method('GetLeftIpv6Address', 'ns3::Ipv6Address', [param('uint32_t', 'i')], is_const=True) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::Ptr<ns3::Node> ns3::PointToPointDumbbellHelper::GetRight() const [member function] cls.add_method('GetRight', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::Ptr<ns3::Node> ns3::PointToPointDumbbellHelper::GetRight(uint32_t i) const [member function] cls.add_method('GetRight', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::Ipv4Address ns3::PointToPointDumbbellHelper::GetRightIpv4Address(uint32_t i) const [member function] cls.add_method('GetRightIpv4Address', 'ns3::Ipv4Address', [param('uint32_t', 'i')], is_const=True) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): ns3::Ipv6Address ns3::PointToPointDumbbellHelper::GetRightIpv6Address(uint32_t i) const [member function] cls.add_method('GetRightIpv6Address', 'ns3::Ipv6Address', [param('uint32_t', 'i')], is_const=True) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): void ns3::PointToPointDumbbellHelper::InstallStack(ns3::InternetStackHelper stack) [member function] cls.add_method('InstallStack', 'void', [param('ns3::InternetStackHelper', 'stack')]) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): uint32_t ns3::PointToPointDumbbellHelper::LeftCount() const [member function] cls.add_method('LeftCount', 'uint32_t', [], is_const=True) ## point-to-point-dumbbell.h (module 'point-to-point-layout'): uint32_t ns3::PointToPointDumbbellHelper::RightCount() const [member function] cls.add_method('RightCount', 'uint32_t', [], is_const=True) return def register_Ns3PointToPointGridHelper_methods(root_module, cls): ## point-to-point-grid.h (module 'point-to-point-layout'): ns3::PointToPointGridHelper::PointToPointGridHelper(ns3::PointToPointGridHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PointToPointGridHelper const &', 'arg0')]) ## point-to-point-grid.h (module 'point-to-point-layout'): ns3::PointToPointGridHelper::PointToPointGridHelper(uint32_t nRows, uint32_t nCols, ns3::PointToPointHelper pointToPoint) [constructor] cls.add_constructor([param('uint32_t', 'nRows'), param('uint32_t', 'nCols'), param('ns3::PointToPointHelper', 'pointToPoint')]) ## point-to-point-grid.h (module 'point-to-point-layout'): void ns3::PointToPointGridHelper::AssignIpv4Addresses(ns3::Ipv4AddressHelper rowIp, ns3::Ipv4AddressHelper colIp) [member function] cls.add_method('AssignIpv4Addresses', 'void', [param('ns3::Ipv4AddressHelper', 'rowIp'), param('ns3::Ipv4AddressHelper', 'colIp')]) ## point-to-point-grid.h (module 'point-to-point-layout'): void ns3::PointToPointGridHelper::AssignIpv6Addresses(ns3::Ipv6Address network, ns3::Ipv6Prefix prefix) [member function] cls.add_method('AssignIpv6Addresses', 'void', [param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'prefix')]) ## point-to-point-grid.h (module 'point-to-point-layout'): void ns3::PointToPointGridHelper::BoundingBox(double ulx, double uly, double lrx, double lry) [member function] cls.add_method('BoundingBox', 'void', [param('double', 'ulx'), param('double', 'uly'), param('double', 'lrx'), param('double', 'lry')]) ## point-to-point-grid.h (module 'point-to-point-layout'): ns3::Ipv4Address ns3::PointToPointGridHelper::GetIpv4Address(uint32_t row, uint32_t col) [member function] cls.add_method('GetIpv4Address', 'ns3::Ipv4Address', [param('uint32_t', 'row'), param('uint32_t', 'col')]) ## point-to-point-grid.h (module 'point-to-point-layout'): ns3::Ipv6Address ns3::PointToPointGridHelper::GetIpv6Address(uint32_t row, uint32_t col) [member function] cls.add_method('GetIpv6Address', 'ns3::Ipv6Address', [param('uint32_t', 'row'), param('uint32_t', 'col')]) ## point-to-point-grid.h (module 'point-to-point-layout'): ns3::Ptr<ns3::Node> ns3::PointToPointGridHelper::GetNode(uint32_t row, uint32_t col) [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'row'), param('uint32_t', 'col')]) ## point-to-point-grid.h (module 'point-to-point-layout'): void ns3::PointToPointGridHelper::InstallStack(ns3::InternetStackHelper stack) [member function] cls.add_method('InstallStack', 'void', [param('ns3::InternetStackHelper', 'stack')]) return def register_Ns3PointToPointHelper_methods(root_module, cls): ## point-to-point-helper.h (module 'point-to-point'): ns3::PointToPointHelper::PointToPointHelper(ns3::PointToPointHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PointToPointHelper const &', 'arg0')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::PointToPointHelper::PointToPointHelper() [constructor] cls.add_constructor([]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(ns3::NodeContainer c) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(ns3::Ptr<ns3::Node> a, ns3::Ptr<ns3::Node> b) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'a'), param('ns3::Ptr< ns3::Node >', 'b')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(ns3::Ptr<ns3::Node> a, std::string bName) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'a'), param('std::string', 'bName')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(std::string aName, ns3::Ptr<ns3::Node> b) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'aName'), param('ns3::Ptr< ns3::Node >', 'b')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(std::string aNode, std::string bNode) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'aNode'), param('std::string', 'bNode')]) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::SetChannelAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetChannelAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::SetDeviceAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::SetQueue(std::string type, std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetQueue', 'void', [param('std::string', 'type'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()')]) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function] cls.add_method('EnableAsciiInternal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) return def register_Ns3PointToPointStarHelper_methods(root_module, cls): ## point-to-point-star.h (module 'point-to-point-layout'): ns3::PointToPointStarHelper::PointToPointStarHelper(ns3::PointToPointStarHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PointToPointStarHelper const &', 'arg0')]) ## point-to-point-star.h (module 'point-to-point-layout'): ns3::PointToPointStarHelper::PointToPointStarHelper(uint32_t numSpokes, ns3::PointToPointHelper p2pHelper) [constructor] cls.add_constructor([param('uint32_t', 'numSpokes'), param('ns3::PointToPointHelper', 'p2pHelper')]) ## point-to-point-star.h (module 'point-to-point-layout'): void ns3::PointToPointStarHelper::AssignIpv4Addresses(ns3::Ipv4AddressHelper address) [member function] cls.add_method('AssignIpv4Addresses', 'void', [param('ns3::Ipv4AddressHelper', 'address')]) ## point-to-point-star.h (module 'point-to-point-layout'): void ns3::PointToPointStarHelper::AssignIpv6Addresses(ns3::Ipv6Address network, ns3::Ipv6Prefix prefix) [member function] cls.add_method('AssignIpv6Addresses', 'void', [param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'prefix')]) ## point-to-point-star.h (module 'point-to-point-layout'): void ns3::PointToPointStarHelper::BoundingBox(double ulx, double uly, double lrx, double lry) [member function] cls.add_method('BoundingBox', 'void', [param('double', 'ulx'), param('double', 'uly'), param('double', 'lrx'), param('double', 'lry')]) ## point-to-point-star.h (module 'point-to-point-layout'): ns3::Ptr<ns3::Node> ns3::PointToPointStarHelper::GetHub() const [member function] cls.add_method('GetHub', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## point-to-point-star.h (module 'point-to-point-layout'): ns3::Ipv4Address ns3::PointToPointStarHelper::GetHubIpv4Address(uint32_t i) const [member function] cls.add_method('GetHubIpv4Address', 'ns3::Ipv4Address', [param('uint32_t', 'i')], is_const=True) ## point-to-point-star.h (module 'point-to-point-layout'): ns3::Ipv6Address ns3::PointToPointStarHelper::GetHubIpv6Address(uint32_t i) const [member function] cls.add_method('GetHubIpv6Address', 'ns3::Ipv6Address', [param('uint32_t', 'i')], is_const=True) ## point-to-point-star.h (module 'point-to-point-layout'): ns3::Ipv4Address ns3::PointToPointStarHelper::GetSpokeIpv4Address(uint32_t i) const [member function] cls.add_method('GetSpokeIpv4Address', 'ns3::Ipv4Address', [param('uint32_t', 'i')], is_const=True) ## point-to-point-star.h (module 'point-to-point-layout'): ns3::Ipv6Address ns3::PointToPointStarHelper::GetSpokeIpv6Address(uint32_t i) const [member function] cls.add_method('GetSpokeIpv6Address', 'ns3::Ipv6Address', [param('uint32_t', 'i')], is_const=True) ## point-to-point-star.h (module 'point-to-point-layout'): ns3::Ptr<ns3::Node> ns3::PointToPointStarHelper::GetSpokeNode(uint32_t i) const [member function] cls.add_method('GetSpokeNode', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## point-to-point-star.h (module 'point-to-point-layout'): void ns3::PointToPointStarHelper::InstallStack(ns3::InternetStackHelper stack) [member function] cls.add_method('InstallStack', 'void', [param('ns3::InternetStackHelper', 'stack')]) ## point-to-point-star.h (module 'point-to-point-layout'): uint32_t ns3::PointToPointStarHelper::SpokeCount() const [member function] cls.add_method('SpokeCount', 'uint32_t', [], is_const=True) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')], is_static=True) return def register_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')]) ## 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'): 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'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_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_Ns3InternetStackHelper_methods(root_module, cls): ## internet-stack-helper.h (module 'internet'): ns3::InternetStackHelper::InternetStackHelper() [constructor] cls.add_constructor([]) ## internet-stack-helper.h (module 'internet'): ns3::InternetStackHelper::InternetStackHelper(ns3::InternetStackHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::InternetStackHelper const &', 'arg0')]) ## internet-stack-helper.h (module 'internet'): int64_t ns3::InternetStackHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'void', [param('std::string', 'nodeName')], is_const=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'void', [param('ns3::NodeContainer', 'c')], is_const=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::InstallAll() const [member function] cls.add_method('InstallAll', 'void', [], is_const=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::Reset() [member function] cls.add_method('Reset', 'void', []) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetIpv4ArpJitter(bool enable) [member function] cls.add_method('SetIpv4ArpJitter', 'void', [param('bool', 'enable')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetIpv4StackInstall(bool enable) [member function] cls.add_method('SetIpv4StackInstall', 'void', [param('bool', 'enable')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetIpv6NsRsJitter(bool enable) [member function] cls.add_method('SetIpv6NsRsJitter', 'void', [param('bool', 'enable')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetIpv6StackInstall(bool enable) [member function] cls.add_method('SetIpv6StackInstall', 'void', [param('bool', 'enable')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetRoutingHelper(ns3::Ipv4RoutingHelper const & routing) [member function] cls.add_method('SetRoutingHelper', 'void', [param('ns3::Ipv4RoutingHelper const &', 'routing')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetRoutingHelper(ns3::Ipv6RoutingHelper const & routing) [member function] cls.add_method('SetRoutingHelper', 'void', [param('ns3::Ipv6RoutingHelper const &', 'routing')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetTcp(std::string tid) [member function] cls.add_method('SetTcp', 'void', [param('std::string', 'tid')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetTcp(std::string tid, std::string attr, ns3::AttributeValue const & val) [member function] cls.add_method('SetTcp', 'void', [param('std::string', 'tid'), param('std::string', 'attr'), param('ns3::AttributeValue const &', 'val')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::EnableAsciiIpv4Internal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv4Internal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::EnableAsciiIpv6Internal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv6Internal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::EnablePcapIpv4Internal(std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv4Internal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::EnablePcapIpv6Internal(std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv6Internal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], visibility='private', 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_Ns3Ipv6Header_methods(root_module, cls): ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header(ns3::Ipv6Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Header const &', 'arg0')]) ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header() [constructor] cls.add_constructor([]) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetDestinationAddress() const [member function] cls.add_method('GetDestinationAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetFlowLabel() const [member function] cls.add_method('GetFlowLabel', 'uint32_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): ns3::TypeId ns3::Ipv6Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetNextHeader() const [member function] cls.add_method('GetNextHeader', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint16_t ns3::Ipv6Header::GetPayloadLength() const [member function] cls.add_method('GetPayloadLength', 'uint16_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetSourceAddress() const [member function] cls.add_method('GetSourceAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetTrafficClass() const [member function] cls.add_method('GetTrafficClass', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): static ns3::TypeId ns3::Ipv6Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetDestinationAddress(ns3::Ipv6Address dst) [member function] cls.add_method('SetDestinationAddress', 'void', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetFlowLabel(uint32_t flow) [member function] cls.add_method('SetFlowLabel', 'void', [param('uint32_t', 'flow')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetHopLimit(uint8_t limit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'limit')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetNextHeader(uint8_t next) [member function] cls.add_method('SetNextHeader', 'void', [param('uint8_t', 'next')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetPayloadLength(uint16_t len) [member function] cls.add_method('SetPayloadLength', 'void', [param('uint16_t', 'len')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetSourceAddress(ns3::Ipv6Address src) [member function] cls.add_method('SetSourceAddress', 'void', [param('ns3::Ipv6Address', 'src')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetTrafficClass(uint8_t traffic) [member function] cls.add_method('SetTrafficClass', 'void', [param('uint8_t', 'traffic')]) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3PcapFileWrapper_methods(root_module, cls): ## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor] cls.add_constructor([]) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::_Ios_Openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Header & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')]) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) return def register_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__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTos() const [member function] cls.add_method('IsManualIpTos', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketAddressTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::Address ns3::SocketAddressTag::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::SetAddress(ns3::Address addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'addr')]) return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_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(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): 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 & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::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 timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_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::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'): 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'): 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::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_Ns3Ipv4L3Protocol_methods(root_module, cls): ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor] cls.add_constructor([]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv4Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUnicast(ns3::Ipv4Address ad) const [member function] cls.add_method('IsUnicast', 'bool', [param('ns3::Ipv4Address', 'ad')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::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_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::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_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::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_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], visibility='private', is_virtual=True) 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'): uint32_t ns3::Ipv4MulticastRoute::GetOutputTtl(uint32_t oif) [member function] cls.add_method('GetOutputTtl', 'uint32_t', [param('uint32_t', 'oif')], deprecated=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_Ns3Ipv6_methods(root_module, cls): ## ipv6.h (module 'internet'): ns3::Ipv6::Ipv6(ns3::Ipv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6 const &', 'arg0')]) ## ipv6.h (module 'internet'): ns3::Ipv6::Ipv6() [constructor] cls.add_constructor([]) ## ipv6.h (module 'internet'): bool ns3::Ipv6::AddAddress(uint32_t interface, ns3::Ipv6InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv6InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): uint32_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): int32_t ns3::Ipv6::GetInterfaceForAddress(ns3::Ipv6Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv6Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): int32_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): int32_t ns3::Ipv6::GetInterfaceForPrefix(ns3::Ipv6Address address, ns3::Ipv6Prefix mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): uint16_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): uint16_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): uint32_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): uint32_t ns3::Ipv6::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6::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) ## ipv6.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv6::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) ## ipv6.h (module 'internet'): ns3::Ptr<ns3::Ipv6RoutingProtocol> ns3::Ipv6::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv6RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): static ns3::TypeId ns3::Ipv6::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::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) ## ipv6.h (module 'internet'): bool ns3::Ipv6::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) ## ipv6.h (module 'internet'): void ns3::Ipv6::RegisterExtensions() [member function] cls.add_method('RegisterExtensions', 'void', [], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::RegisterOptions() [member function] cls.add_method('RegisterOptions', 'void', [], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::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) ## ipv6.h (module 'internet'): bool ns3::Ipv6::RemoveAddress(uint32_t interface, ns3::Ipv6Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::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) ## ipv6.h (module 'internet'): void ns3::Ipv6::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) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetPmtu(ns3::Ipv6Address dst, uint32_t pmtu) [member function] cls.add_method('SetPmtu', 'void', [param('ns3::Ipv6Address', 'dst'), param('uint32_t', 'pmtu')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetRoutingProtocol(ns3::Ptr<ns3::Ipv6RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv6RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6::SourceAddressSelection(uint32_t interface, ns3::Ipv6Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv6Address', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'dest')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ipv6::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::GetMtuDiscover() const [member function] cls.add_method('GetMtuDiscover', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetMtuDiscover(bool mtuDiscover) [member function] cls.add_method('SetMtuDiscover', 'void', [param('bool', 'mtuDiscover')], is_pure_virtual=True, visibility='private', 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_Ns3Ipv6L3Protocol_methods(root_module, cls): ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv6-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv6L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol::Ipv6L3Protocol() [constructor] cls.add_constructor([]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')]) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv6L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv6L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', []) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetDefaultTclass(uint8_t tclass) [member function] cls.add_method('SetDefaultTclass', 'void', [param('uint8_t', 'tclass')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv6Address source, ns3::Ipv6Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv6Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv6Address', 'source'), param('ns3::Ipv6Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv6Route >', 'route')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv6RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv6RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv6RoutingProtocol> ns3::Ipv6L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv6RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv6L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv6Interface> ns3::Ipv6L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv6Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv6-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv6L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): int32_t ns3::Ipv6L3Protocol::GetInterfaceForAddress(ns3::Ipv6Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): int32_t ns3::Ipv6L3Protocol::GetInterfaceForPrefix(ns3::Ipv6Address addr, ns3::Ipv6Prefix mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv6Address', 'addr'), param('ns3::Ipv6Prefix', 'mask')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): int32_t ns3::Ipv6L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::AddAddress(uint32_t i, ns3::Ipv6InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv6InterfaceAddress', 'address')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv6L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::RemoveAddress(uint32_t interfaceIndex, ns3::Ipv6Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('ns3::Ipv6Address', 'address')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv6L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv6L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetPmtu(ns3::Ipv6Address dst, uint32_t pmtu) [member function] cls.add_method('SetPmtu', 'void', [param('ns3::Ipv6Address', 'dst'), param('uint32_t', 'pmtu')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6L3Protocol::SourceAddressSelection(uint32_t interface, ns3::Ipv6Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv6Address', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'dest')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Icmpv6L4Protocol> ns3::Ipv6L3Protocol::GetIcmpv6() const [member function] cls.add_method('GetIcmpv6', 'ns3::Ptr< ns3::Icmpv6L4Protocol >', [], is_const=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::AddAutoconfiguredAddress(uint32_t interface, ns3::Ipv6Address network, ns3::Ipv6Prefix mask, uint8_t flags, uint32_t validTime, uint32_t preferredTime, ns3::Ipv6Address defaultRouter=ns3::Ipv6Address::GetZero( )) [member function] cls.add_method('AddAutoconfiguredAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'mask'), param('uint8_t', 'flags'), param('uint32_t', 'validTime'), param('uint32_t', 'preferredTime'), param('ns3::Ipv6Address', 'defaultRouter', default_value='ns3::Ipv6Address::GetZero( )')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RemoveAutoconfiguredAddress(uint32_t interface, ns3::Ipv6Address network, ns3::Ipv6Prefix mask, ns3::Ipv6Address defaultRouter) [member function] cls.add_method('RemoveAutoconfiguredAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'mask'), param('ns3::Ipv6Address', 'defaultRouter')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RegisterExtensions() [member function] cls.add_method('RegisterExtensions', 'void', [], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RegisterOptions() [member function] cls.add_method('RegisterOptions', 'void', [], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::ReportDrop(ns3::Ipv6Header ipHeader, ns3::Ptr<ns3::Packet> p, ns3::Ipv6L3Protocol::DropReason dropReason) [member function] cls.add_method('ReportDrop', 'void', [param('ns3::Ipv6Header', 'ipHeader'), param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6L3Protocol::DropReason', 'dropReason')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetMtuDiscover(bool mtuDiscover) [member function] cls.add_method('SetMtuDiscover', 'void', [param('bool', 'mtuDiscover')], visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::GetMtuDiscover() const [member function] cls.add_method('GetMtuDiscover', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetSendIcmpv6Redirect(bool sendIcmpv6Redirect) [member function] cls.add_method('SetSendIcmpv6Redirect', 'void', [param('bool', 'sendIcmpv6Redirect')], visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::GetSendIcmpv6Redirect() const [member function] cls.add_method('GetSendIcmpv6Redirect', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3Ipv6PmtuCache_methods(root_module, cls): ## ipv6-pmtu-cache.h (module 'internet'): ns3::Ipv6PmtuCache::Ipv6PmtuCache(ns3::Ipv6PmtuCache const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PmtuCache const &', 'arg0')]) ## ipv6-pmtu-cache.h (module 'internet'): ns3::Ipv6PmtuCache::Ipv6PmtuCache() [constructor] cls.add_constructor([]) ## ipv6-pmtu-cache.h (module 'internet'): void ns3::Ipv6PmtuCache::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## ipv6-pmtu-cache.h (module 'internet'): uint32_t ns3::Ipv6PmtuCache::GetPmtu(ns3::Ipv6Address dst) [member function] cls.add_method('GetPmtu', 'uint32_t', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-pmtu-cache.h (module 'internet'): ns3::Time ns3::Ipv6PmtuCache::GetPmtuValidityTime() const [member function] cls.add_method('GetPmtuValidityTime', 'ns3::Time', [], is_const=True) ## ipv6-pmtu-cache.h (module 'internet'): static ns3::TypeId ns3::Ipv6PmtuCache::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-pmtu-cache.h (module 'internet'): void ns3::Ipv6PmtuCache::SetPmtu(ns3::Ipv6Address dst, uint32_t pmtu) [member function] cls.add_method('SetPmtu', 'void', [param('ns3::Ipv6Address', 'dst'), param('uint32_t', 'pmtu')]) ## ipv6-pmtu-cache.h (module 'internet'): bool ns3::Ipv6PmtuCache::SetPmtuValidityTime(ns3::Time validity) [member function] cls.add_method('SetPmtuValidityTime', 'bool', [param('ns3::Time', 'validity')]) 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_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,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 >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_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'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): 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')]) 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_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) 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 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()
gpl-2.0
glwu/python-for-android
python-build/python-libs/gdata/src/gdata/Crypto/Protocol/Chaffing.py
226
9467
"""This file implements the chaffing algorithm. Winnowing and chaffing is a technique for enhancing privacy without requiring strong encryption. In short, the technique takes a set of authenticated message blocks (the wheat) and adds a number of chaff blocks which have randomly chosen data and MAC fields. This means that to an adversary, the chaff blocks look as valid as the wheat blocks, and so the authentication would have to be performed on every block. By tailoring the number of chaff blocks added to the message, the sender can make breaking the message computationally infeasible. There are many other interesting properties of the winnow/chaff technique. For example, say Alice is sending a message to Bob. She packetizes the message and performs an all-or-nothing transformation on the packets. Then she authenticates each packet with a message authentication code (MAC). The MAC is a hash of the data packet, and there is a secret key which she must share with Bob (key distribution is an exercise left to the reader). She then adds a serial number to each packet, and sends the packets to Bob. Bob receives the packets, and using the shared secret authentication key, authenticates the MACs for each packet. Those packets that have bad MACs are simply discarded. The remainder are sorted by serial number, and passed through the reverse all-or-nothing transform. The transform means that an eavesdropper (say Eve) must acquire all the packets before any of the data can be read. If even one packet is missing, the data is useless. There's one twist: by adding chaff packets, Alice and Bob can make Eve's job much harder, since Eve now has to break the shared secret key, or try every combination of wheat and chaff packet to read any of the message. The cool thing is that Bob doesn't need to add any additional code; the chaff packets are already filtered out because their MACs don't match (in all likelihood -- since the data and MACs for the chaff packets are randomly chosen it is possible, but very unlikely that a chaff MAC will match the chaff data). And Alice need not even be the party adding the chaff! She could be completely unaware that a third party, say Charles, is adding chaff packets to her messages as they are transmitted. For more information on winnowing and chaffing see this paper: Ronald L. Rivest, "Chaffing and Winnowing: Confidentiality without Encryption" http://theory.lcs.mit.edu/~rivest/chaffing.txt """ __revision__ = "$Id: Chaffing.py,v 1.7 2003/02/28 15:23:21 akuchling Exp $" from Crypto.Util.number import bytes_to_long class Chaff: """Class implementing the chaff adding algorithm. Methods for subclasses: _randnum(size): Returns a randomly generated number with a byte-length equal to size. Subclasses can use this to implement better random data and MAC generating algorithms. The default algorithm is probably not very cryptographically secure. It is most important that the chaff data does not contain any patterns that can be used to discern it from wheat data without running the MAC. """ def __init__(self, factor=1.0, blocksper=1): """Chaff(factor:float, blocksper:int) factor is the number of message blocks to add chaff to, expressed as a percentage between 0.0 and 1.0. blocksper is the number of chaff blocks to include for each block being chaffed. Thus the defaults add one chaff block to every message block. By changing the defaults, you can adjust how computationally difficult it could be for an adversary to brute-force crack the message. The difficulty is expressed as: pow(blocksper, int(factor * number-of-blocks)) For ease of implementation, when factor < 1.0, only the first int(factor*number-of-blocks) message blocks are chaffed. """ if not (0.0<=factor<=1.0): raise ValueError, "'factor' must be between 0.0 and 1.0" if blocksper < 0: raise ValueError, "'blocksper' must be zero or more" self.__factor = factor self.__blocksper = blocksper def chaff(self, blocks): """chaff( [(serial-number:int, data:string, MAC:string)] ) : [(int, string, string)] Add chaff to message blocks. blocks is a list of 3-tuples of the form (serial-number, data, MAC). Chaff is created by choosing a random number of the same byte-length as data, and another random number of the same byte-length as MAC. The message block's serial number is placed on the chaff block and all the packet's chaff blocks are randomly interspersed with the single wheat block. This method then returns a list of 3-tuples of the same form. Chaffed blocks will contain multiple instances of 3-tuples with the same serial number, but the only way to figure out which blocks are wheat and which are chaff is to perform the MAC hash and compare values. """ chaffedblocks = [] # count is the number of blocks to add chaff to. blocksper is the # number of chaff blocks to add per message block that is being # chaffed. count = len(blocks) * self.__factor blocksper = range(self.__blocksper) for i, wheat in map(None, range(len(blocks)), blocks): # it shouldn't matter which of the n blocks we add chaff to, so for # ease of implementation, we'll just add them to the first count # blocks if i < count: serial, data, mac = wheat datasize = len(data) macsize = len(mac) addwheat = 1 # add chaff to this block for j in blocksper: import sys chaffdata = self._randnum(datasize) chaffmac = self._randnum(macsize) chaff = (serial, chaffdata, chaffmac) # mix up the order, if the 5th bit is on then put the # wheat on the list if addwheat and bytes_to_long(self._randnum(16)) & 0x40: chaffedblocks.append(wheat) addwheat = 0 chaffedblocks.append(chaff) if addwheat: chaffedblocks.append(wheat) else: # just add the wheat chaffedblocks.append(wheat) return chaffedblocks def _randnum(self, size): # TBD: Not a very secure algorithm. # TBD: size * 2 to work around possible bug in RandomPool from Crypto.Util import randpool import time pool = randpool.RandomPool(size * 2) while size > pool.entropy: pass # we now have enough entropy in the pool to get size bytes of random # data... well, probably return pool.get_bytes(size) if __name__ == '__main__': text = """\ We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty, and the pursuit of Happiness. That to secure these rights, Governments are instituted among Men, deriving their just powers from the consent of the governed. That whenever any Form of Government becomes destructive of these ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their Safety and Happiness. """ print 'Original text:\n==========' print text print '==========' # first transform the text into packets blocks = [] ; size = 40 for i in range(0, len(text), size): blocks.append( text[i:i+size] ) # now get MACs for all the text blocks. The key is obvious... print 'Calculating MACs...' from Crypto.Hash import HMAC, SHA key = 'Jefferson' macs = [HMAC.new(key, block, digestmod=SHA).digest() for block in blocks] assert len(blocks) == len(macs) # put these into a form acceptable as input to the chaffing procedure source = [] m = map(None, range(len(blocks)), blocks, macs) print m for i, data, mac in m: source.append((i, data, mac)) # now chaff these print 'Adding chaff...' c = Chaff(factor=0.5, blocksper=2) chaffed = c.chaff(source) from base64 import encodestring # print the chaffed message blocks. meanwhile, separate the wheat from # the chaff wheat = [] print 'chaffed message blocks:' for i, data, mac in chaffed: # do the authentication h = HMAC.new(key, data, digestmod=SHA) pmac = h.digest() if pmac == mac: tag = '-->' wheat.append(data) else: tag = ' ' # base64 adds a trailing newline print tag, '%3d' % i, \ repr(data), encodestring(mac)[:-1] # now decode the message packets and check it against the original text print 'Undigesting wheat...' newtext = "".join(wheat) if newtext == text: print 'They match!' else: print 'They differ!'
apache-2.0
agry/NGECore2
scripts/mobiles/tatooine/tormented_bocatt.py
2
1713
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobileTemplate.setCreatureName('bocatt_tormented') mobileTemplate.setLevel(18) mobileTemplate.setDifficulty(Difficulty.NORMAL) mobileTemplate.setMinSpawnDistance(4) mobileTemplate.setMaxSpawnDistance(8) mobileTemplate.setDeathblow(False) mobileTemplate.setScale(1) mobileTemplate.setMeatType("Reptilian Meat") mobileTemplate.setMeatAmount(100) mobileTemplate.setHideType("Leathery Hide") mobileTemplate.setBoneAmount(60) mobileTemplate.setBoneType("Animal Bones") mobileTemplate.setHideAmount(35) mobileTemplate.setSocialGroup("bocatt") mobileTemplate.setAssistRange(10) mobileTemplate.setStalker(True) mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE) templates = Vector() templates.add('object/mobile/shared_bocatt.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/ranged/creature/shared_creature_spit_small_toxicgreen.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() attacks.add('bm_bite_1') attacks.add('bm_bolster_armor_1') attacks.add('bm_disease_1') attacks.add('bm_enfeeble_1') mobileTemplate.setDefaultAttack('creatureRangedAttack') mobileTemplate.setAttacks(attacks) core.spawnService.addMobileTemplate('tormented_bocatt', mobileTemplate) return
lgpl-3.0
daxxi13/CouchPotatoServer
libs/chardet/latin1prober.py
950
5241
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .charsetprober import CharSetProber from .constants import eNotMe from .compat import wrap_ord FREQ_CAT_NUM = 4 UDF = 0 # undefined OTH = 1 # other ASC = 2 # ascii capital letter ASS = 3 # ascii small letter ACV = 4 # accent capital vowel ACO = 5 # accent capital other ASV = 6 # accent small vowel ASO = 7 # accent small other CLASS_NUM = 8 # total classes Latin1_CharToClass = ( OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 00 - 07 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 08 - 0F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 10 - 17 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 18 - 1F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 20 - 27 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 28 - 2F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 30 - 37 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 38 - 3F OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 40 - 47 ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 48 - 4F ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 50 - 57 ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, # 58 - 5F OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 60 - 67 ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 68 - 6F ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 70 - 77 ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, # 78 - 7F OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, # 80 - 87 OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, # 88 - 8F UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 90 - 97 OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, # 98 - 9F OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A0 - A7 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A8 - AF OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B0 - B7 OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B8 - BF ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, # C0 - C7 ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, # C8 - CF ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, # D0 - D7 ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, # D8 - DF ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, # E0 - E7 ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, # E8 - EF ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, # F0 - F7 ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, # F8 - FF ) # 0 : illegal # 1 : very unlikely # 2 : normal # 3 : very likely Latin1ClassModel = ( # UDF OTH ASC ASS ACV ACO ASV ASO 0, 0, 0, 0, 0, 0, 0, 0, # UDF 0, 3, 3, 3, 3, 3, 3, 3, # OTH 0, 3, 3, 3, 3, 3, 3, 3, # ASC 0, 3, 3, 3, 1, 1, 3, 3, # ASS 0, 3, 3, 3, 1, 2, 1, 2, # ACV 0, 3, 3, 3, 3, 3, 3, 3, # ACO 0, 3, 1, 3, 1, 1, 1, 3, # ASV 0, 3, 1, 3, 1, 1, 3, 3, # ASO ) class Latin1Prober(CharSetProber): def __init__(self): CharSetProber.__init__(self) self.reset() def reset(self): self._mLastCharClass = OTH self._mFreqCounter = [0] * FREQ_CAT_NUM CharSetProber.reset(self) def get_charset_name(self): return "windows-1252" def feed(self, aBuf): aBuf = self.filter_with_english_letters(aBuf) for c in aBuf: charClass = Latin1_CharToClass[wrap_ord(c)] freq = Latin1ClassModel[(self._mLastCharClass * CLASS_NUM) + charClass] if freq == 0: self._mState = eNotMe break self._mFreqCounter[freq] += 1 self._mLastCharClass = charClass return self.get_state() def get_confidence(self): if self.get_state() == eNotMe: return 0.01 total = sum(self._mFreqCounter) if total < 0.01: confidence = 0.0 else: confidence = ((self._mFreqCounter[3] / total) - (self._mFreqCounter[1] * 20.0 / total)) if confidence < 0.0: confidence = 0.0 # lower the confidence of latin1 so that other more accurate # detector can take priority. confidence = confidence * 0.5 return confidence
gpl-3.0
fmarier/letsencrypt
letsencrypt-apache/letsencrypt_apache/configurator.py
14
47581
"""Apache Configuration based off of Augeas Configurator.""" # pylint: disable=too-many-lines import itertools import logging import os import re import shutil import socket import subprocess import zope.interface from acme import challenges from letsencrypt import achallenges from letsencrypt import errors from letsencrypt import interfaces from letsencrypt import le_util from letsencrypt.plugins import common from letsencrypt_apache import augeas_configurator from letsencrypt_apache import constants from letsencrypt_apache import display_ops from letsencrypt_apache import dvsni from letsencrypt_apache import obj from letsencrypt_apache import parser logger = logging.getLogger(__name__) # TODO: Augeas sections ie. <VirtualHost>, <IfModule> beginning and closing # tags need to be the same case, otherwise Augeas doesn't recognize them. # This is not able to be completely remedied by regular expressions because # Augeas views <VirtualHost> </Virtualhost> as an error. This will just # require another check_parsing_errors() after all files are included... # (after a find_directive search is executed currently). It can be a one # time check however because all of LE's transactions will ensure # only properly formed sections are added. # Note: This protocol works for filenames with spaces in it, the sites are # properly set up and directives are changed appropriately, but Apache won't # recognize names in sites-enabled that have spaces. These are not added to the # Apache configuration. It may be wise to warn the user if they are trying # to use vhost filenames that contain spaces and offer to change ' ' to '_' # Note: FILEPATHS and changes to files are transactional. They are copied # over before the updates are made to the existing files. NEW_FILES is # transactional due to the use of register_file_creation() # TODO: Verify permissions on configuration root... it is easier than # checking permissions on each of the relative directories and less error # prone. # TODO: Write a server protocol finder. Listen <port> <protocol> or # Protocol <protocol>. This can verify partial setups are correct # TODO: Add directives to sites-enabled... not sites-available. # sites-available doesn't allow immediate find_dir search even with save() # and load() class ApacheConfigurator(augeas_configurator.AugeasConfigurator): # pylint: disable=too-many-instance-attributes,too-many-public-methods """Apache configurator. State of Configurator: This code has been been tested and built for Ubuntu 14.04 Apache 2.4 and it works for Ubuntu 12.04 Apache 2.2 :ivar config: Configuration. :type config: :class:`~letsencrypt.interfaces.IConfig` :ivar parser: Handles low level parsing :type parser: :class:`~letsencrypt_apache.parser` :ivar tup version: version of Apache :ivar list vhosts: All vhosts found in the configuration (:class:`list` of :class:`~letsencrypt_apache.obj.VirtualHost`) :ivar dict assoc: Mapping between domains and vhosts """ zope.interface.implements(interfaces.IAuthenticator, interfaces.IInstaller) zope.interface.classProvides(interfaces.IPluginFactory) description = "Apache Web Server - Alpha" @classmethod def add_parser_arguments(cls, add): add("ctl", default=constants.CLI_DEFAULTS["ctl"], help="Path to the 'apache2ctl' binary, used for 'configtest', " "retrieving the Apache2 version number, and initialization " "parameters.") add("enmod", default=constants.CLI_DEFAULTS["enmod"], help="Path to the Apache 'a2enmod' binary.") add("dismod", default=constants.CLI_DEFAULTS["dismod"], help="Path to the Apache 'a2enmod' binary.") add("init-script", default=constants.CLI_DEFAULTS["init_script"], help="Path to the Apache init script (used for server " "reload/restart).") add("le-vhost-ext", default=constants.CLI_DEFAULTS["le_vhost_ext"], help="SSL vhost configuration extension.") add("server-root", default=constants.CLI_DEFAULTS["server_root"], help="Apache server root directory.") def __init__(self, *args, **kwargs): """Initialize an Apache Configurator. :param tup version: version of Apache as a tuple (2, 4, 7) (used mostly for unittesting) """ version = kwargs.pop("version", None) super(ApacheConfigurator, self).__init__(*args, **kwargs) # Add name_server association dict self.assoc = dict() # Outstanding challenges self._chall_out = set() # These will be set in the prepare function self.parser = None self.version = version self.vhosts = None self._enhance_func = {"redirect": self._enable_redirect} @property def mod_ssl_conf(self): """Full absolute path to SSL configuration file.""" return os.path.join(self.config.config_dir, constants.MOD_SSL_CONF_DEST) def prepare(self): """Prepare the authenticator/installer. :raises .errors.NoInstallationError: If Apache configs cannot be found :raises .errors.MisconfigurationError: If Apache is misconfigured :raises .errors.NotSupportedError: If Apache version is not supported :raises .errors.PluginError: If there is any other error """ # Make sure configuration is valid self.config_test() self.parser = parser.ApacheParser( self.aug, self.conf("server-root"), self.conf("ctl")) # Check for errors in parsing files with Augeas self.check_parsing_errors("httpd.aug") # Set Version if self.version is None: self.version = self.get_version() if self.version < (2, 2): raise errors.NotSupportedError( "Apache Version %s not supported.", str(self.version)) # Get all of the available vhosts self.vhosts = self.get_virtual_hosts() temp_install(self.mod_ssl_conf) def deploy_cert(self, domain, cert_path, key_path, chain_path=None): """Deploys certificate to specified virtual host. Currently tries to find the last directives to deploy the cert in the VHost associated with the given domain. If it can't find the directives, it searches the "included" confs. The function verifies that it has located the three directives and finally modifies them to point to the correct destination. After the certificate is installed, the VirtualHost is enabled if it isn't already. .. todo:: Might be nice to remove chain directive if none exists This shouldn't happen within letsencrypt though :raises errors.PluginError: When unable to deploy certificate due to a lack of directives """ vhost = self.choose_vhost(domain) # This is done first so that ssl module is enabled and cert_path, # cert_key... can all be parsed appropriately self.prepare_server_https("443") path = {} path["cert_path"] = self.parser.find_dir( "SSLCertificateFile", None, vhost.path) path["cert_key"] = self.parser.find_dir( "SSLCertificateKeyFile", None, vhost.path) # Only include if a certificate chain is specified if chain_path is not None: path["chain_path"] = self.parser.find_dir( "SSLCertificateChainFile", None, vhost.path) if not path["cert_path"] or not path["cert_key"]: # Throw some can't find all of the directives error" logger.warn( "Cannot find a cert or key directive in %s. " "VirtualHost was not modified", vhost.path) # Presumably break here so that the virtualhost is not modified raise errors.PluginError( "Unable to find cert and/or key directives") logger.info("Deploying Certificate to VirtualHost %s", vhost.filep) # Assign the final directives; order is maintained in find_dir self.aug.set(path["cert_path"][-1], cert_path) self.aug.set(path["cert_key"][-1], key_path) if chain_path is not None: if not path["chain_path"]: self.parser.add_dir( vhost.path, "SSLCertificateChainFile", chain_path) else: self.aug.set(path["chain_path"][-1], chain_path) # Save notes about the transaction that took place self.save_notes += ("Changed vhost at %s with addresses of %s\n" "\tSSLCertificateFile %s\n" "\tSSLCertificateKeyFile %s\n" % (vhost.filep, ", ".join(str(addr) for addr in vhost.addrs), cert_path, key_path)) if chain_path is not None: self.save_notes += "\tSSLCertificateChainFile %s\n" % chain_path # Make sure vhost is enabled if not vhost.enabled: self.enable_site(vhost) def choose_vhost(self, target_name): """Chooses a virtual host based on the given domain name. If there is no clear virtual host to be selected, the user is prompted with all available choices. :param str target_name: domain name :returns: ssl vhost associated with name :rtype: :class:`~letsencrypt_apache.obj.VirtualHost` :raises .errors.PluginError: If no vhost is available or chosen """ # Allows for domain names to be associated with a virtual host if target_name in self.assoc: return self.assoc[target_name] # Try to find a reasonable vhost vhost = self._find_best_vhost(target_name) if vhost is not None: if not vhost.ssl: vhost = self.make_vhost_ssl(vhost) self.assoc[target_name] = vhost return vhost return self._choose_vhost_from_list(target_name) def _choose_vhost_from_list(self, target_name): # Select a vhost from a list vhost = display_ops.select_vhost(target_name, self.vhosts) if vhost is None: logger.error( "No vhost exists with servername or alias of: %s. " "No vhost was selected. Please specify servernames " "in the Apache config", target_name) raise errors.PluginError("No vhost selected") elif not vhost.ssl: addrs = self._get_proposed_addrs(vhost, "443") # TODO: Conflicts is too conservative if not any(vhost.enabled and vhost.conflicts(addrs) for vhost in self.vhosts): vhost = self.make_vhost_ssl(vhost) else: logger.error( "The selected vhost would conflict with other HTTPS " "VirtualHosts within Apache. Please select another " "vhost or add ServerNames to your configuration.") raise errors.PluginError( "VirtualHost not able to be selected.") self.assoc[target_name] = vhost return vhost def _find_best_vhost(self, target_name): """Finds the best vhost for a target_name. This does not upgrade a vhost to HTTPS... it only finds the most appropriate vhost for the given target_name. :returns: VHost or None """ # Points 4 - Servername SSL # Points 3 - Address name with SSL # Points 2 - Servername no SSL # Points 1 - Address name with no SSL best_candidate = None best_points = 0 for vhost in self.vhosts: if target_name in vhost.get_names(): points = 2 elif any(addr.get_addr() == target_name for addr in vhost.addrs): points = 1 else: # No points given if names can't be found. # This gets hit but doesn't register continue # pragma: no cover if vhost.ssl: points += 2 if points > best_points: best_points = points best_candidate = vhost # No winners here... is there only one reasonable vhost? if best_candidate is None: # reasonable == Not all _default_ addrs reasonable_vhosts = self._non_default_vhosts() if len(reasonable_vhosts) == 1: best_candidate = reasonable_vhosts[0] return best_candidate def _non_default_vhosts(self): """Return all non _default_ only vhosts.""" return [vh for vh in self.vhosts if not all( addr.get_addr() == "_default_" for addr in vh.addrs )] def get_all_names(self): """Returns all names found in the Apache Configuration. :returns: All ServerNames, ServerAliases, and reverse DNS entries for virtual host addresses :rtype: set """ all_names = set() for vhost in self.vhosts: all_names.update(vhost.get_names()) for addr in vhost.addrs: if common.hostname_regex.match(addr.get_addr()): all_names.add(addr.get_addr()) else: name = self.get_name_from_ip(addr) if name: all_names.add(name) return all_names def get_name_from_ip(self, addr): # pylint: disable=no-self-use """Returns a reverse dns name if available. :param addr: IP Address :type addr: ~.common.Addr :returns: name or empty string if name cannot be determined :rtype: str """ # If it isn't a private IP, do a reverse DNS lookup if not common.private_ips_regex.match(addr.get_addr()): try: socket.inet_aton(addr.get_addr()) return socket.gethostbyaddr(addr.get_addr())[0] except (socket.error, socket.herror, socket.timeout): pass return "" def _add_servernames(self, host): """Helper function for get_virtual_hosts(). :param host: In progress vhost whose names will be added :type host: :class:`~letsencrypt_apache.obj.VirtualHost` """ # Take the final ServerName as each overrides the previous servername_match = self.parser.find_dir( "ServerName", None, start=host.path, exclude=False) serveralias_match = self.parser.find_dir( "ServerAlias", None, start=host.path, exclude=False) for alias in serveralias_match: host.aliases.add(self.parser.get_arg(alias)) if servername_match: # Get last ServerName as each overwrites the previous host.name = self.parser.get_arg(servername_match[-1]) def _create_vhost(self, path): """Used by get_virtual_hosts to create vhost objects :param str path: Augeas path to virtual host :returns: newly created vhost :rtype: :class:`~letsencrypt_apache.obj.VirtualHost` """ addrs = set() args = self.aug.match(path + "/arg") for arg in args: addrs.add(obj.Addr.fromstring(self.parser.get_arg(arg))) is_ssl = False if self.parser.find_dir("SSLEngine", "on", start=path, exclude=False): is_ssl = True filename = get_file_path(path) is_enabled = self.is_site_enabled(filename) vhost = obj.VirtualHost(filename, path, addrs, is_ssl, is_enabled) self._add_servernames(vhost) return vhost # TODO: make "sites-available" a configurable directory def get_virtual_hosts(self): """Returns list of virtual hosts found in the Apache configuration. :returns: List of :class:`~letsencrypt_apache.obj.VirtualHost` objects found in configuration :rtype: list """ # Search sites-available, httpd.conf for possible virtual hosts paths = self.aug.match( ("/files%s/sites-available//*[label()=~regexp('%s')]" % (self.parser.root, parser.case_i("VirtualHost")))) vhs = [] for path in paths: vhs.append(self._create_vhost(path)) return vhs def is_name_vhost(self, target_addr): """Returns if vhost is a name based vhost NameVirtualHost was deprecated in Apache 2.4 as all VirtualHosts are now NameVirtualHosts. If version is earlier than 2.4, check if addr has a NameVirtualHost directive in the Apache config :param letsencrypt_apache.obj.Addr target_addr: vhost address :returns: Success :rtype: bool """ # Mixed and matched wildcard NameVirtualHost with VirtualHost # behavior is undefined. Make sure that an exact match exists # search for NameVirtualHost directive for ip_addr # note ip_addr can be FQDN although Apache does not recommend it return (self.version >= (2, 4) or self.parser.find_dir("NameVirtualHost", str(target_addr))) def add_name_vhost(self, addr): """Adds NameVirtualHost directive for given address. :param addr: Address that will be added as NameVirtualHost directive :type addr: :class:`~letsencrypt_apache.obj.Addr` """ loc = parser.get_aug_path(self.parser.loc["name"]) if addr.get_port() == "443": path = self.parser.add_dir_to_ifmodssl( loc, "NameVirtualHost", [str(addr)]) else: path = self.parser.add_dir(loc, "NameVirtualHost", [str(addr)]) msg = ("Setting %s to be NameBasedVirtualHost\n" "\tDirective added to %s\n" % (addr, path)) logger.debug(msg) self.save_notes += msg def prepare_server_https(self, port, temp=False): """Prepare the server for HTTPS. Make sure that the ssl_module is loaded and that the server is appropriately listening on port. :param str port: Port to listen on """ if "ssl_module" not in self.parser.modules: self.enable_mod("ssl", temp=temp) # Check for Listen <port> # Note: This could be made to also look for ip:443 combo if not self.parser.find_dir("Listen", port): logger.debug("No Listen %s directive found. Setting the " "Apache Server to Listen on port %s", port, port) if port == "443": args = [port] else: # Non-standard ports should specify https protocol args = [port, "https"] self.parser.add_dir_to_ifmodssl( parser.get_aug_path( self.parser.loc["listen"]), "Listen", args) self.save_notes += "Added Listen %s directive to %s\n" % ( port, self.parser.loc["listen"]) def make_addrs_sni_ready(self, addrs): """Checks to see if the server is ready for SNI challenges. :param addrs: Addresses to check SNI compatibility :type addrs: :class:`~letsencrypt_apache.obj.Addr` """ # Version 2.4 and later are automatically SNI ready. if self.version >= (2, 4): return for addr in addrs: if not self.is_name_vhost(addr): logger.debug("Setting VirtualHost at %s to be a name " "based virtual host", addr) self.add_name_vhost(addr) def make_vhost_ssl(self, nonssl_vhost): # pylint: disable=too-many-locals """Makes an ssl_vhost version of a nonssl_vhost. Duplicates vhost and adds default ssl options New vhost will reside as (nonssl_vhost.path) + ``letsencrypt_apache.constants.CLI_DEFAULTS["le_vhost_ext"]`` .. note:: This function saves the configuration :param nonssl_vhost: Valid VH that doesn't have SSLEngine on :type nonssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :returns: SSL vhost :rtype: :class:`~letsencrypt_apache.obj.VirtualHost` :raises .errors.PluginError: If more than one virtual host is in the file or if plugin is unable to write/read vhost files. """ avail_fp = nonssl_vhost.filep ssl_fp = self._get_ssl_vhost_path(avail_fp) self._copy_create_ssl_vhost_skeleton(avail_fp, ssl_fp) # Reload augeas to take into account the new vhost self.aug.load() # Get Vhost augeas path for new vhost vh_p = self.aug.match("/files%s//* [label()=~regexp('%s')]" % (ssl_fp, parser.case_i("VirtualHost"))) if len(vh_p) != 1: logger.error("Error: should only be one vhost in %s", avail_fp) raise errors.PluginError("Only one vhost per file is allowed") else: # This simplifies the process vh_p = vh_p[0] # Update Addresses self._update_ssl_vhosts_addrs(vh_p) # Add directives self._add_dummy_ssl_directives(vh_p) # Log actions and create save notes logger.info("Created an SSL vhost at %s", ssl_fp) self.save_notes += "Created ssl vhost at %s\n" % ssl_fp self.save() # We know the length is one because of the assertion above # Create the Vhost object ssl_vhost = self._create_vhost(vh_p) self.vhosts.append(ssl_vhost) # NOTE: Searches through Augeas seem to ruin changes to directives # The configuration must also be saved before being searched # for the new directives; For these reasons... this is tacked # on after fully creating the new vhost # Now check if addresses need to be added as NameBasedVhost addrs # This is for compliance with versions of Apache < 2.4 self._add_name_vhost_if_necessary(ssl_vhost) return ssl_vhost def _get_ssl_vhost_path(self, non_ssl_vh_fp): # Get filepath of new ssl_vhost if non_ssl_vh_fp.endswith(".conf"): return non_ssl_vh_fp[:-(len(".conf"))] + self.conf("le_vhost_ext") else: return non_ssl_vh_fp + self.conf("le_vhost_ext") def _copy_create_ssl_vhost_skeleton(self, avail_fp, ssl_fp): """Copies over existing Vhost with IfModule mod_ssl.c> skeleton. :param str avail_fp: Pointer to the original available non-ssl vhost :param str ssl_fp: Full path where the new ssl_vhost will reside. A new file is created on the filesystem. """ # First register the creation so that it is properly removed if # configuration is rolled back self.reverter.register_file_creation(False, ssl_fp) try: with open(avail_fp, "r") as orig_file: with open(ssl_fp, "w") as new_file: new_file.write("<IfModule mod_ssl.c>\n") for line in orig_file: new_file.write(line) new_file.write("</IfModule>\n") except IOError: logger.fatal("Error writing/reading to file in make_vhost_ssl") raise errors.PluginError("Unable to write/read in make_vhost_ssl") def _update_ssl_vhosts_addrs(self, vh_path): ssl_addrs = set() ssl_addr_p = self.aug.match(vh_path + "/arg") for addr in ssl_addr_p: old_addr = obj.Addr.fromstring( str(self.parser.get_arg(addr))) ssl_addr = old_addr.get_addr_obj("443") self.aug.set(addr, str(ssl_addr)) ssl_addrs.add(ssl_addr) return ssl_addrs def _add_dummy_ssl_directives(self, vh_path): self.parser.add_dir(vh_path, "SSLCertificateFile", "insert_cert_file_path") self.parser.add_dir(vh_path, "SSLCertificateKeyFile", "insert_key_file_path") self.parser.add_dir(vh_path, "Include", self.mod_ssl_conf) def _add_name_vhost_if_necessary(self, vhost): """Add NameVirtualHost Directives if necessary for new vhost. NameVirtualHosts was a directive in Apache < 2.4 https://httpd.apache.org/docs/2.2/mod/core.html#namevirtualhost :param vhost: New virtual host that was recently created. :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` """ need_to_save = False # See if the exact address appears in any other vhost # Remember 1.1.1.1:* == 1.1.1.1 -> hence any() for addr in vhost.addrs: for test_vh in self.vhosts: if (vhost.filep != test_vh.filep and any(test_addr == addr for test_addr in test_vh.addrs) and not self.is_name_vhost(addr)): self.add_name_vhost(addr) logger.info("Enabling NameVirtualHosts on %s", addr) need_to_save = True if need_to_save: self.save() ############################################################################ # Enhancements ############################################################################ def supported_enhancements(self): # pylint: disable=no-self-use """Returns currently supported enhancements.""" return ["redirect"] def enhance(self, domain, enhancement, options=None): """Enhance configuration. :param str domain: domain to enhance :param str enhancement: enhancement type defined in :const:`~letsencrypt.constants.ENHANCEMENTS` :param options: options for the enhancement See :const:`~letsencrypt.constants.ENHANCEMENTS` documentation for appropriate parameter. :raises .errors.PluginError: If Enhancement is not supported, or if there is any other problem with the enhancement. """ try: func = self._enhance_func[enhancement] except KeyError: raise errors.PluginError( "Unsupported enhancement: {0}".format(enhancement)) try: func(self.choose_vhost(domain), options) except errors.PluginError: logger.warn("Failed %s for %s", enhancement, domain) raise def _enable_redirect(self, ssl_vhost, unused_options): """Redirect all equivalent HTTP traffic to ssl_vhost. .. todo:: This enhancement should be rewritten and will unfortunately require lots of debugging by hand. Adds Redirect directive to the port 80 equivalent of ssl_vhost First the function attempts to find the vhost with equivalent ip addresses that serves on non-ssl ports The function then adds the directive .. note:: This function saves the configuration :param ssl_vhost: Destination of traffic, an ssl enabled vhost :type ssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :param unused_options: Not currently used :type unused_options: Not Available :returns: Success, general_vhost (HTTP vhost) :rtype: (bool, :class:`~letsencrypt_apache.obj.VirtualHost`) :raises .errors.PluginError: If no viable HTTP host can be created or used for the redirect. """ if "rewrite_module" not in self.parser.modules: self.enable_mod("rewrite") general_vh = self._get_http_vhost(ssl_vhost) if general_vh is None: # Add virtual_server with redirect logger.debug("Did not find http version of ssl virtual host " "attempting to create") redirect_addrs = self._get_proposed_addrs(ssl_vhost) for vhost in self.vhosts: if vhost.enabled and vhost.conflicts(redirect_addrs): raise errors.PluginError( "Unable to find corresponding HTTP vhost; " "Unable to create one as intended addresses conflict; " "Current configuration does not support automated " "redirection") self._create_redirect_vhost(ssl_vhost) else: # Check if redirection already exists self._verify_no_redirects(general_vh) # Add directives to server # Note: These are not immediately searchable in sites-enabled # even with save() and load() self.parser.add_dir(general_vh.path, "RewriteEngine", "on") self.parser.add_dir(general_vh.path, "RewriteRule", constants.REWRITE_HTTPS_ARGS) self.save_notes += ("Redirecting host in %s to ssl vhost in %s\n" % (general_vh.filep, ssl_vhost.filep)) self.save() logger.info("Redirecting vhost in %s to ssl vhost in %s", general_vh.filep, ssl_vhost.filep) def _verify_no_redirects(self, vhost): """Checks to see if existing redirect is in place. Checks to see if virtualhost already contains a rewrite or redirect returns boolean, integer :param vhost: vhost to check :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :raises errors.PluginError: When another redirection exists """ rewrite_path = self.parser.find_dir( "RewriteRule", None, start=vhost.path) redirect_path = self.parser.find_dir("Redirect", None, start=vhost.path) if redirect_path: # "Existing Redirect directive for virtualhost" raise errors.PluginError("Existing Redirect present on HTTP vhost.") if rewrite_path: # "No existing redirection for virtualhost" if len(rewrite_path) != len(constants.REWRITE_HTTPS_ARGS): raise errors.PluginError("Unknown Existing RewriteRule") for match, arg in itertools.izip( rewrite_path, constants.REWRITE_HTTPS_ARGS): if self.aug.get(match) != arg: raise errors.PluginError("Unknown Existing RewriteRule") raise errors.PluginError( "Let's Encrypt has already enabled redirection") def _create_redirect_vhost(self, ssl_vhost): """Creates an http_vhost specifically to redirect for the ssl_vhost. :param ssl_vhost: ssl vhost :type ssl_vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :returns: tuple of the form (`success`, :class:`~letsencrypt_apache.obj.VirtualHost`) :rtype: tuple """ text = self._get_redirect_config_str(ssl_vhost) redirect_filepath = self._write_out_redirect(ssl_vhost, text) self.aug.load() # Make a new vhost data structure and add it to the lists new_vhost = self._create_vhost(parser.get_aug_path(redirect_filepath)) self.vhosts.append(new_vhost) # Finally create documentation for the change self.save_notes += ("Created a port 80 vhost, %s, for redirection to " "ssl vhost %s\n" % (new_vhost.filep, ssl_vhost.filep)) def _get_redirect_config_str(self, ssl_vhost): # get servernames and serveraliases serveralias = "" servername = "" if ssl_vhost.name is not None: servername = "ServerName " + ssl_vhost.name if ssl_vhost.aliases: serveralias = "ServerAlias " + " ".join(ssl_vhost.aliases) return ("<VirtualHost %s>\n" "%s \n" "%s \n" "ServerSignature Off\n" "\n" "RewriteEngine On\n" "RewriteRule %s\n" "\n" "ErrorLog /var/log/apache2/redirect.error.log\n" "LogLevel warn\n" "</VirtualHost>\n" % (" ".join(str(addr) for addr in self._get_proposed_addrs(ssl_vhost)), servername, serveralias, " ".join(constants.REWRITE_HTTPS_ARGS))) def _write_out_redirect(self, ssl_vhost, text): # This is the default name redirect_filename = "le-redirect.conf" # See if a more appropriate name can be applied if ssl_vhost.name is not None: # make sure servername doesn't exceed filename length restriction if len(ssl_vhost.name) < (255 - (len(redirect_filename) + 1)): redirect_filename = "le-redirect-%s.conf" % ssl_vhost.name redirect_filepath = os.path.join( self.parser.root, "sites-available", redirect_filename) # Register the new file that will be created # Note: always register the creation before writing to ensure file will # be removed in case of unexpected program exit self.reverter.register_file_creation(False, redirect_filepath) # Write out file with open(redirect_filepath, "w") as redirect_file: redirect_file.write(text) logger.info("Created redirect file: %s", redirect_filename) return redirect_filepath def _get_http_vhost(self, ssl_vhost): """Find appropriate HTTP vhost for ssl_vhost.""" # First candidate vhosts filter candidate_http_vhs = [ vhost for vhost in self.vhosts if not vhost.ssl ] # Second filter - check addresses for http_vh in candidate_http_vhs: if http_vh.same_server(ssl_vhost): return http_vh return None def _get_proposed_addrs(self, vhost, port="80"): # pylint: disable=no-self-use """Return all addrs of vhost with the port replaced with the specified. :param obj.VirtualHost ssl_vhost: Original Vhost :param str port: Desired port for new addresses :returns: `set` of :class:`~obj.Addr` """ redirects = set() for addr in vhost.addrs: redirects.add(addr.get_addr_obj(port)) return redirects def get_all_certs_keys(self): """Find all existing keys, certs from configuration. Retrieve all certs and keys set in VirtualHosts on the Apache server :returns: list of tuples with form [(cert, key, path)] cert - str path to certificate file key - str path to associated key file path - File path to configuration file. :rtype: list """ c_k = set() for vhost in self.vhosts: if vhost.ssl: cert_path = self.parser.find_dir( "SSLCertificateFile", None, start=vhost.path, exclude=False) key_path = self.parser.find_dir( "SSLCertificateKeyFile", None, start=vhost.path, exclude=False) if cert_path and key_path: cert = os.path.abspath(self.parser.get_arg(cert_path[-1])) key = os.path.abspath(self.parser.get_arg(key_path[-1])) c_k.add((cert, key, get_file_path(cert_path[-1]))) else: logger.warning( "Invalid VirtualHost configuration - %s", vhost.filep) return c_k def is_site_enabled(self, avail_fp): """Checks to see if the given site is enabled. .. todo:: fix hardcoded sites-enabled, check os.path.samefile :param str avail_fp: Complete file path of available site :returns: Success :rtype: bool """ enabled_dir = os.path.join(self.parser.root, "sites-enabled") for entry in os.listdir(enabled_dir): if os.path.realpath(os.path.join(enabled_dir, entry)) == avail_fp: return True return False def enable_site(self, vhost): """Enables an available site, Apache restart required. .. note:: Does not make sure that the site correctly works or that all modules are enabled appropriately. .. todo:: This function should number subdomains before the domain vhost .. todo:: Make sure link is not broken... :param vhost: vhost to enable :type vhost: :class:`~letsencrypt_apache.obj.VirtualHost` :raises .errors.NotSupportedError: If filesystem layout is not supported. """ if self.is_site_enabled(vhost.filep): return if "/sites-available/" in vhost.filep: enabled_path = ("%s/sites-enabled/%s" % (self.parser.root, os.path.basename(vhost.filep))) self.reverter.register_file_creation(False, enabled_path) os.symlink(vhost.filep, enabled_path) vhost.enabled = True logger.info("Enabling available site: %s", vhost.filep) self.save_notes += "Enabled site %s\n" % vhost.filep else: raise errors.NotSupportedError( "Unsupported filesystem layout. " "sites-available/enabled expected.") def enable_mod(self, mod_name, temp=False): """Enables module in Apache. Both enables and restarts Apache so module is active. :param str mod_name: Name of the module to enable. (e.g. 'ssl') :param bool temp: Whether or not this is a temporary action. :raises .errors.NotSupportedError: If the filesystem layout is not supported. :raises .errors.MisconfigurationError: If a2enmod or a2dismod cannot be run. """ # Support Debian specific setup avail_path = os.path.join(self.parser.root, "mods-available") enabled_path = os.path.join(self.parser.root, "mods-enabled") if not os.path.isdir(avail_path) or not os.path.isdir(enabled_path): raise errors.NotSupportedError( "Unsupported directory layout. You may try to enable mod %s " "and try again." % mod_name) deps = _get_mod_deps(mod_name) # Enable all dependencies for dep in deps: if (dep + "_module") not in self.parser.modules: self._enable_mod_debian(dep, temp) self._add_parser_mod(dep) note = "Enabled dependency of %s module - %s" % (mod_name, dep) if not temp: self.save_notes += note + os.linesep logger.debug(note) # Enable actual module self._enable_mod_debian(mod_name, temp) self._add_parser_mod(mod_name) if not temp: self.save_notes += "Enabled %s module in Apache\n" % mod_name logger.info("Enabled Apache %s module", mod_name) # Modules can enable additional config files. Variables may be defined # within these new configuration sections. # Restart is not necessary as DUMP_RUN_CFG uses latest config. self.parser.update_runtime_variables(self.conf("ctl")) def _add_parser_mod(self, mod_name): """Shortcut for updating parser modules.""" self.parser.modules.add(mod_name + "_module") self.parser.modules.add("mod_" + mod_name + ".c") def _enable_mod_debian(self, mod_name, temp): """Assumes mods-available, mods-enabled layout.""" # Generate reversal command. # Try to be safe here... check that we can probably reverse before # applying enmod command if not le_util.exe_exists(self.conf("dismod")): raise errors.MisconfigurationError( "Unable to find a2dismod, please make sure a2enmod and " "a2dismod are configured correctly for letsencrypt.") self.reverter.register_undo_command( temp, [self.conf("dismod"), mod_name]) le_util.run_script([self.conf("enmod"), mod_name]) def restart(self): """Restarts apache server. .. todo:: This function will be converted to using reload :raises .errors.MisconfigurationError: If unable to restart due to a configuration problem, or if the restart subprocess cannot be run. """ return apache_restart(self.conf("init-script")) def config_test(self): # pylint: disable=no-self-use """Check the configuration of Apache for errors. :raises .errors.MisconfigurationError: If config_test fails """ try: le_util.run_script([self.conf("ctl"), "configtest"]) except errors.SubprocessError as err: raise errors.MisconfigurationError(str(err)) def get_version(self): """Return version of Apache Server. Version is returned as tuple. (ie. 2.4.7 = (2, 4, 7)) :returns: version :rtype: tuple :raises .PluginError: if unable to find Apache version """ try: stdout, _ = le_util.run_script([self.conf("ctl"), "-v"]) except errors.SubprocessError: raise errors.PluginError( "Unable to run %s -v" % self.conf("ctl")) regex = re.compile(r"Apache/([0-9\.]*)", re.IGNORECASE) matches = regex.findall(stdout) if len(matches) != 1: raise errors.PluginError("Unable to find Apache version") return tuple([int(i) for i in matches[0].split(".")]) def more_info(self): """Human-readable string to help understand the module""" return ( "Configures Apache to authenticate and install HTTPS.{0}" "Server root: {root}{0}" "Version: {version}".format( os.linesep, root=self.parser.loc["root"], version=".".join(str(i) for i in self.version)) ) ########################################################################### # Challenges Section ########################################################################### def get_chall_pref(self, unused_domain): # pylint: disable=no-self-use """Return list of challenge preferences.""" return [challenges.DVSNI] def perform(self, achalls): """Perform the configuration related challenge. This function currently assumes all challenges will be fulfilled. If this turns out not to be the case in the future. Cleanup and outstanding challenges will have to be designed better. """ self._chall_out.update(achalls) responses = [None] * len(achalls) apache_dvsni = dvsni.ApacheDvsni(self) for i, achall in enumerate(achalls): if isinstance(achall, achallenges.DVSNI): # Currently also have dvsni hold associated index # of the challenge. This helps to put all of the responses back # together when they are all complete. apache_dvsni.add_chall(achall, i) sni_response = apache_dvsni.perform() if sni_response: # Must restart in order to activate the challenges. # Handled here because we may be able to load up other challenge # types self.restart() # Go through all of the challenges and assign them to the proper # place in the responses return value. All responses must be in the # same order as the original challenges. for i, resp in enumerate(sni_response): responses[apache_dvsni.indices[i]] = resp return responses def cleanup(self, achalls): """Revert all challenges.""" self._chall_out.difference_update(achalls) # If all of the challenges have been finished, clean up everything if not self._chall_out: self.revert_challenge_config() self.restart() self.parser.init_modules() def _get_mod_deps(mod_name): """Get known module dependencies. .. note:: This does not need to be accurate in order for the client to run. This simply keeps things clean if the user decides to revert changes. .. warning:: If all deps are not included, it may cause incorrect parsing behavior, due to enable_mod's shortcut for updating the parser's currently defined modules (:method:`.ApacheConfigurator._add_parser_mod`) This would only present a major problem in extremely atypical configs that use ifmod for the missing deps. """ deps = { "ssl": ["setenvif", "mime", "socache_shmcb"] } return deps.get(mod_name, []) def apache_restart(apache_init_script): """Restarts the Apache Server. :param str apache_init_script: Path to the Apache init script. .. todo:: Try to use reload instead. (This caused timing problems before) .. todo:: On failure, this should be a recovery_routine call with another restart. This will confuse and inhibit developers from testing code though. This change should happen after the ApacheConfigurator has been thoroughly tested. The function will need to be moved into the class again. Perhaps this version can live on... for testing purposes. :raises .errors.MisconfigurationError: If unable to restart due to a configuration problem, or if the restart subprocess cannot be run. """ try: proc = subprocess.Popen([apache_init_script, "restart"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) except (OSError, ValueError): logger.fatal( "Unable to restart the Apache process with %s", apache_init_script) raise errors.MisconfigurationError( "Unable to restart Apache process with %s" % apache_init_script) stdout, stderr = proc.communicate() if proc.returncode != 0: # Enter recovery routine... logger.error("Apache Restart Failed!\n%s\n%s", stdout, stderr) raise errors.MisconfigurationError( "Error while restarting Apache:\n%s\n%s" % (stdout, stderr)) def get_file_path(vhost_path): """Get file path from augeas_vhost_path. Takes in Augeas path and returns the file name :param str vhost_path: Augeas virtual host path :returns: filename of vhost :rtype: str """ # Strip off /files avail_fp = vhost_path[6:] # This can be optimized... while True: # Cast both to lowercase to be case insensitive find_if = avail_fp.lower().find("/ifmodule") if find_if != -1: avail_fp = avail_fp[:find_if] continue find_vh = avail_fp.lower().find("/virtualhost") if find_vh != -1: avail_fp = avail_fp[:find_vh] continue break return avail_fp def temp_install(options_ssl): """Temporary install for convenience.""" # WARNING: THIS IS A POTENTIAL SECURITY VULNERABILITY # THIS SHOULD BE HANDLED BY THE PACKAGE MANAGER # AND TAKEN OUT BEFORE RELEASE, INSTEAD # SHOWING A NICE ERROR MESSAGE ABOUT THE PROBLEM. # Check to make sure options-ssl.conf is installed if not os.path.isfile(options_ssl): shutil.copyfile(constants.MOD_SSL_CONF_SRC, options_ssl)
apache-2.0
GdZ/scriptfile
software/googleAppEngine/lib/django_1_4/tests/regressiontests/text/tests.py
25
4236
# coding: utf-8 from __future__ import with_statement from django.test import TestCase from django.utils.encoding import iri_to_uri from django.utils.http import (cookie_date, http_date, urlquote, urlquote_plus, urlunquote, urlunquote_plus) from django.utils.text import get_text_list, smart_split from django.utils.translation import override class TextTests(TestCase): """ Tests for stuff in django.utils.text and other text munging util functions. """ def test_get_text_list(self): self.assertEqual(get_text_list(['a', 'b', 'c', 'd']), u'a, b, c or d') self.assertEqual(get_text_list(['a', 'b', 'c'], 'and'), u'a, b and c') self.assertEqual(get_text_list(['a', 'b'], 'and'), u'a and b') self.assertEqual(get_text_list(['a']), u'a') self.assertEqual(get_text_list([]), u'') with override('ar'): self.assertEqual(get_text_list(['a', 'b', 'c']), u"a، b أو c") def test_smart_split(self): self.assertEqual(list(smart_split(r'''This is "a person" test.''')), [u'This', u'is', u'"a person"', u'test.']) self.assertEqual(list(smart_split(r'''This is "a person's" test.'''))[2], u'"a person\'s"') self.assertEqual(list(smart_split(r'''This is "a person\"s" test.'''))[2], u'"a person\\"s"') self.assertEqual(list(smart_split('''"a 'one''')), [u'"a', u"'one"]) self.assertEqual(list(smart_split(r'''all friends' tests'''))[1], "friends'") self.assertEqual(list(smart_split(u'url search_page words="something else"')), [u'url', u'search_page', u'words="something else"']) self.assertEqual(list(smart_split(u"url search_page words='something else'")), [u'url', u'search_page', u"words='something else'"]) self.assertEqual(list(smart_split(u'url search_page words "something else"')), [u'url', u'search_page', u'words', u'"something else"']) self.assertEqual(list(smart_split(u'url search_page words-"something else"')), [u'url', u'search_page', u'words-"something else"']) self.assertEqual(list(smart_split(u'url search_page words=hello')), [u'url', u'search_page', u'words=hello']) self.assertEqual(list(smart_split(u'url search_page words="something else')), [u'url', u'search_page', u'words="something', u'else']) self.assertEqual(list(smart_split("cut:','|cut:' '")), [u"cut:','|cut:' '"]) def test_urlquote(self): self.assertEqual(urlquote(u'Paris & Orl\xe9ans'), u'Paris%20%26%20Orl%C3%A9ans') self.assertEqual(urlquote(u'Paris & Orl\xe9ans', safe="&"), u'Paris%20&%20Orl%C3%A9ans') self.assertEqual( urlunquote(u'Paris%20%26%20Orl%C3%A9ans'), u'Paris & Orl\xe9ans') self.assertEqual( urlunquote(u'Paris%20&%20Orl%C3%A9ans'), u'Paris & Orl\xe9ans') self.assertEqual(urlquote_plus(u'Paris & Orl\xe9ans'), u'Paris+%26+Orl%C3%A9ans') self.assertEqual(urlquote_plus(u'Paris & Orl\xe9ans', safe="&"), u'Paris+&+Orl%C3%A9ans') self.assertEqual( urlunquote_plus(u'Paris+%26+Orl%C3%A9ans'), u'Paris & Orl\xe9ans') self.assertEqual( urlunquote_plus(u'Paris+&+Orl%C3%A9ans'), u'Paris & Orl\xe9ans') def test_cookie_date(self): t = 1167616461.0 self.assertEqual(cookie_date(t), 'Mon, 01-Jan-2007 01:54:21 GMT') def test_http_date(self): t = 1167616461.0 self.assertEqual(http_date(t), 'Mon, 01 Jan 2007 01:54:21 GMT') def test_iri_to_uri(self): self.assertEqual(iri_to_uri(u'red%09ros\xe9#red'), 'red%09ros%C3%A9#red') self.assertEqual(iri_to_uri(u'/blog/for/J\xfcrgen M\xfcnster/'), '/blog/for/J%C3%BCrgen%20M%C3%BCnster/') self.assertEqual(iri_to_uri(u'locations/%s' % urlquote_plus(u'Paris & Orl\xe9ans')), 'locations/Paris+%26+Orl%C3%A9ans') def test_iri_to_uri_idempotent(self): self.assertEqual(iri_to_uri(iri_to_uri(u'red%09ros\xe9#red')), 'red%09ros%C3%A9#red')
mit
eedf/jeito
booking/migrations/0007_payment.py
2
1047
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-18 16:46 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('booking', '0006_auto_20170118_1724'), ] operations = [ migrations.CreateModel( name='Payment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('mean', models.IntegerField(choices=[(1, 'Chèque'), (2, 'Virement'), (3, 'Espèces')], verbose_name='Moyen de paiement')), ('date', models.DateField(default=django.utils.timezone.now)), ('amount', models.DecimalField(decimal_places=2, max_digits=8, verbose_name='Montant')), ('booking', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='payments', to='booking.Booking')), ], ), ]
mit
miipl-naveen/optibizz
addons/crm/crm.py
267
7967
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv, fields from openerp.http import request AVAILABLE_PRIORITIES = [ ('0', 'Very Low'), ('1', 'Low'), ('2', 'Normal'), ('3', 'High'), ('4', 'Very High'), ] class crm_tracking_medium(osv.Model): # OLD crm.case.channel _name = "crm.tracking.medium" _description = "Channels" _order = 'name' _columns = { 'name': fields.char('Channel Name', required=True), 'active': fields.boolean('Active'), } _defaults = { 'active': lambda *a: 1, } class crm_tracking_campaign(osv.Model): # OLD crm.case.resource.type _name = "crm.tracking.campaign" _description = "Campaign" _rec_name = "name" _columns = { 'name': fields.char('Campaign Name', required=True, translate=True), 'section_id': fields.many2one('crm.case.section', 'Sales Team'), } class crm_tracking_source(osv.Model): _name = "crm.tracking.source" _description = "Source" _rec_name = "name" _columns = { 'name': fields.char('Source Name', required=True, translate=True), } class crm_tracking_mixin(osv.AbstractModel): """Mixin class for objects which can be tracked by marketing. """ _name = 'crm.tracking.mixin' _columns = { 'campaign_id': fields.many2one('crm.tracking.campaign', 'Campaign', # old domain ="['|',('section_id','=',section_id),('section_id','=',False)]" help="This is a name that helps you keep track of your different campaign efforts Ex: Fall_Drive, Christmas_Special"), 'source_id': fields.many2one('crm.tracking.source', 'Source', help="This is the source of the link Ex: Search Engine, another domain, or name of email list"), 'medium_id': fields.many2one('crm.tracking.medium', 'Channel', help="This is the method of delivery. Ex: Postcard, Email, or Banner Ad", oldname='channel_id'), } def tracking_fields(self): return [('utm_campaign', 'campaign_id'), ('utm_source', 'source_id'), ('utm_medium', 'medium_id')] def tracking_get_values(self, cr, uid, vals, context=None): for key, fname in self.tracking_fields(): field = self._fields[fname] value = vals.get(fname) or (request and request.httprequest.cookies.get(key)) # params.get should be always in session by the dispatch from ir_http if field.type == 'many2one' and isinstance(value, basestring): # if we receive a string for a many2one, we search/create the id if value: Model = self.pool[field.comodel_name] rel_id = Model.name_search(cr, uid, value, context=context) if rel_id: rel_id = rel_id[0][0] else: rel_id = Model.create(cr, uid, {'name': value}, context=context) vals[fname] = rel_id else: # Here the code for others cases that many2one vals[fname] = value return vals def _get_default_track(self, cr, uid, field, context=None): return self.tracking_get_values(cr, uid, {}, context=context).get(field) _defaults = { 'source_id': lambda self, cr, uid, ctx: self._get_default_track(cr, uid, 'source_id', ctx), 'campaign_id': lambda self, cr, uid, ctx: self._get_default_track(cr, uid, 'campaign_id', ctx), 'medium_id': lambda self, cr, uid, ctx: self._get_default_track(cr, uid, 'medium_id', ctx), } class crm_case_stage(osv.osv): """ Model for case stages. This models the main stages of a document management flow. Main CRM objects (leads, opportunities, project issues, ...) will now use only stages, instead of state and stages. Stages are for example used to display the kanban view of records. """ _name = "crm.case.stage" _description = "Stage of case" _rec_name = 'name' _order = "sequence" _columns = { 'name': fields.char('Stage Name', required=True, translate=True), 'sequence': fields.integer('Sequence', help="Used to order stages. Lower is better."), 'probability': fields.float('Probability (%)', required=True, help="This percentage depicts the default/average probability of the Case for this stage to be a success"), 'on_change': fields.boolean('Change Probability Automatically', help="Setting this stage will change the probability automatically on the opportunity."), 'requirements': fields.text('Requirements'), 'section_ids': fields.many2many('crm.case.section', 'section_stage_rel', 'stage_id', 'section_id', string='Sections', help="Link between stages and sales teams. When set, this limitate the current stage to the selected sales teams."), 'case_default': fields.boolean('Default to New Sales Team', help="If you check this field, this stage will be proposed by default on each sales team. It will not assign this stage to existing teams."), 'fold': fields.boolean('Folded in Kanban View', help='This stage is folded in the kanban view when' 'there are no records in that stage to display.'), 'type': fields.selection([('lead', 'Lead'), ('opportunity', 'Opportunity'), ('both', 'Both')], string='Type', required=True, help="This field is used to distinguish stages related to Leads from stages related to Opportunities, or to specify stages available for both types."), } _defaults = { 'sequence': 1, 'probability': 0.0, 'on_change': True, 'fold': False, 'type': 'both', 'case_default': True, } class crm_case_categ(osv.osv): """ Category of Case """ _name = "crm.case.categ" _description = "Category of Case" _columns = { 'name': fields.char('Name', required=True, translate=True), 'section_id': fields.many2one('crm.case.section', 'Sales Team'), 'object_id': fields.many2one('ir.model', 'Object Name'), } def _find_object_id(self, cr, uid, context=None): """Finds id for case object""" context = context or {} object_id = context.get('object_id', False) ids = self.pool.get('ir.model').search(cr, uid, ['|', ('id', '=', object_id), ('model', '=', context.get('object_name', False))]) return ids and ids[0] or False _defaults = { 'object_id': _find_object_id } class crm_payment_mode(osv.osv): """ Payment Mode for Fund """ _name = "crm.payment.mode" _description = "CRM Payment Mode" _columns = { 'name': fields.char('Name', required=True), 'section_id': fields.many2one('crm.case.section', 'Sales Team'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
google-code/android-scripting
python/src/Mac/Demo/applescript/Disk_Copy/Utility_Events.py
34
7685
"""Suite Utility Events: Commands that allow the user to select Disk Copy files Level 1, version 1 Generated from Macintosh HD:Hulpprogramma's:Disk Copy AETE/AEUT resource version 1/0, language 0, script 0 """ import aetools import MacOS _code = 'ddsk' class Utility_Events_Events: _argmap_select_disk_image = { 'with_prompt' : 'SELp', } def select_disk_image(self, _no_object=None, _attributes={}, **_arguments): """select disk image: Prompt the user to select a disk image Keyword argument with_prompt: the prompt string to be displayed Keyword argument _attributes: AppleEvent attribute dictionary Returns: a reference to a disk image """ _code = 'UTIL' _subcode = 'SEL1' aetools.keysubst(_arguments, self._argmap_select_disk_image) if _no_object is not None: raise TypeError, 'No direct arg expected' aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.has_key('errn'): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] _argmap_select_DiskScript = { 'with_prompt' : 'SELp', } def select_DiskScript(self, _no_object=None, _attributes={}, **_arguments): """select DiskScript: Prompt the user to select a DiskScript Keyword argument with_prompt: the prompt string to be displayed Keyword argument _attributes: AppleEvent attribute dictionary Returns: a reference to a DiskScript """ _code = 'UTIL' _subcode = 'SEL2' aetools.keysubst(_arguments, self._argmap_select_DiskScript) if _no_object is not None: raise TypeError, 'No direct arg expected' aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.has_key('errn'): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] _argmap_select_disk_image_or_DiskScript = { 'with_prompt' : 'SELp', } def select_disk_image_or_DiskScript(self, _no_object=None, _attributes={}, **_arguments): """select disk image or DiskScript: Prompt the user to select a disk image or DiskScript Keyword argument with_prompt: the prompt string to be displayed Keyword argument _attributes: AppleEvent attribute dictionary Returns: a reference to disk image or a DiskScript """ _code = 'UTIL' _subcode = 'SEL3' aetools.keysubst(_arguments, self._argmap_select_disk_image_or_DiskScript) if _no_object is not None: raise TypeError, 'No direct arg expected' aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.has_key('errn'): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] _argmap_select_floppy_disk_image = { 'with_prompt' : 'SELp', } def select_floppy_disk_image(self, _no_object=None, _attributes={}, **_arguments): """select floppy disk image: Prompt the user to select a floppy disk image Keyword argument with_prompt: the prompt string to be displayed Keyword argument _attributes: AppleEvent attribute dictionary Returns: a reference to a floppy disk image """ _code = 'UTIL' _subcode = 'SEL4' aetools.keysubst(_arguments, self._argmap_select_floppy_disk_image) if _no_object is not None: raise TypeError, 'No direct arg expected' aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.has_key('errn'): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] _argmap_select_disk = { 'with_prompt' : 'SELp', } def select_disk(self, _no_object=None, _attributes={}, **_arguments): """select disk: Prompt the user to select a disk volume Keyword argument with_prompt: the prompt string to be displayed Keyword argument _attributes: AppleEvent attribute dictionary Returns: a reference to the disk """ _code = 'UTIL' _subcode = 'SEL5' aetools.keysubst(_arguments, self._argmap_select_disk) if _no_object is not None: raise TypeError, 'No direct arg expected' aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.has_key('errn'): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] _argmap_select_folder = { 'with_prompt' : 'SELp', } def select_folder(self, _no_object=None, _attributes={}, **_arguments): """select folder: Prompt the user to select a folder Keyword argument with_prompt: the prompt string to be displayed Keyword argument _attributes: AppleEvent attribute dictionary Returns: a reference to the folder """ _code = 'UTIL' _subcode = 'SEL6' aetools.keysubst(_arguments, self._argmap_select_folder) if _no_object is not None: raise TypeError, 'No direct arg expected' aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.has_key('errn'): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] _argmap_log = { 'time_stamp' : 'TSMP', } def log(self, _object, _attributes={}, **_arguments): """log: Add a string to the log window Required argument: the string to add to the log window Keyword argument time_stamp: Should the log entry be time-stamped? (false if not supplied) Keyword argument _attributes: AppleEvent attribute dictionary """ _code = 'UTIL' _subcode = 'LOG ' aetools.keysubst(_arguments, self._argmap_log) _arguments['----'] = _object aetools.enumsubst(_arguments, 'TSMP', _Enum_bool) _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.has_key('errn'): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----'] _Enum_TEXT = None # XXXX enum TEXT not found!! _Enum_bool = None # XXXX enum bool not found!! # # Indices of types declared in this module # _classdeclarations = { } _propdeclarations = { } _compdeclarations = { } _enumdeclarations = { }
apache-2.0
NetApp/cinder
cinder/api/contrib/volume_actions.py
5
15292
# Copyright 2012 OpenStack 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. from oslo_config import cfg import oslo_messaging as messaging from oslo_utils import encodeutils from oslo_utils import strutils import six import webob from cinder.api import extensions from cinder.api.openstack import api_version_request from cinder.api.openstack import wsgi from cinder import exception from cinder.i18n import _ from cinder.image import image_utils from cinder import utils from cinder import volume CONF = cfg.CONF def authorize(context, action_name): action = 'volume_actions:%s' % action_name extensions.extension_authorizer('volume', action)(context) class VolumeActionsController(wsgi.Controller): def __init__(self, *args, **kwargs): super(VolumeActionsController, self).__init__(*args, **kwargs) self.volume_api = volume.API() @wsgi.action('os-attach') def _attach(self, req, id, body): """Add attachment metadata.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) # instance uuid is an option now instance_uuid = None if 'instance_uuid' in body['os-attach']: instance_uuid = body['os-attach']['instance_uuid'] host_name = None # Keep API backward compatibility if 'host_name' in body['os-attach']: host_name = body['os-attach']['host_name'] mountpoint = body['os-attach']['mountpoint'] if 'mode' in body['os-attach']: mode = body['os-attach']['mode'] else: mode = 'rw' if instance_uuid is None and host_name is None: msg = _("Invalid request to attach volume to an invalid target") raise webob.exc.HTTPBadRequest(explanation=msg) if mode not in ('rw', 'ro'): msg = _("Invalid request to attach volume with an invalid mode. " "Attaching mode should be 'rw' or 'ro'") raise webob.exc.HTTPBadRequest(explanation=msg) try: self.volume_api.attach(context, volume, instance_uuid, host_name, mountpoint, mode) except messaging.RemoteError as error: if error.exc_type in ['InvalidVolume', 'InvalidUUID', 'InvalidVolumeAttachMode']: msg = "Error attaching volume - %(err_type)s: %(err_msg)s" % { 'err_type': error.exc_type, 'err_msg': error.value} raise webob.exc.HTTPBadRequest(explanation=msg) else: # There are also few cases where attach call could fail due to # db or volume driver errors. These errors shouldn't be exposed # to the user and in such cases it should raise 500 error. raise return webob.Response(status_int=202) @wsgi.action('os-detach') def _detach(self, req, id, body): """Clear attachment metadata.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) attachment_id = None if body['os-detach']: attachment_id = body['os-detach'].get('attachment_id', None) try: self.volume_api.detach(context, volume, attachment_id) except messaging.RemoteError as error: if error.exc_type in ['VolumeAttachmentNotFound', 'InvalidVolume']: msg = "Error detaching volume - %(err_type)s: %(err_msg)s" % \ {'err_type': error.exc_type, 'err_msg': error.value} raise webob.exc.HTTPBadRequest(explanation=msg) else: # There are also few cases where detach call could fail due to # db or volume driver errors. These errors shouldn't be exposed # to the user and in such cases it should raise 500 error. raise return webob.Response(status_int=202) @wsgi.action('os-reserve') def _reserve(self, req, id, body): """Mark volume as reserved.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) self.volume_api.reserve_volume(context, volume) return webob.Response(status_int=202) @wsgi.action('os-unreserve') def _unreserve(self, req, id, body): """Unmark volume as reserved.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) self.volume_api.unreserve_volume(context, volume) return webob.Response(status_int=202) @wsgi.action('os-begin_detaching') def _begin_detaching(self, req, id, body): """Update volume status to 'detaching'.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) self.volume_api.begin_detaching(context, volume) return webob.Response(status_int=202) @wsgi.action('os-roll_detaching') def _roll_detaching(self, req, id, body): """Roll back volume status to 'in-use'.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) self.volume_api.roll_detaching(context, volume) return webob.Response(status_int=202) @wsgi.action('os-initialize_connection') def _initialize_connection(self, req, id, body): """Initialize volume attachment.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) try: connector = body['os-initialize_connection']['connector'] except KeyError: raise webob.exc.HTTPBadRequest( explanation=_("Must specify 'connector'")) try: info = self.volume_api.initialize_connection(context, volume, connector) except exception.InvalidInput as err: raise webob.exc.HTTPBadRequest( explanation=err) except exception.VolumeBackendAPIException: msg = _("Unable to fetch connection information from backend.") raise webob.exc.HTTPInternalServerError(explanation=msg) return {'connection_info': info} @wsgi.action('os-terminate_connection') def _terminate_connection(self, req, id, body): """Terminate volume attachment.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) try: connector = body['os-terminate_connection']['connector'] except KeyError: raise webob.exc.HTTPBadRequest( explanation=_("Must specify 'connector'")) try: self.volume_api.terminate_connection(context, volume, connector) except exception.VolumeBackendAPIException: msg = _("Unable to terminate volume connection from backend.") raise webob.exc.HTTPInternalServerError(explanation=msg) return webob.Response(status_int=202) @wsgi.response(202) @wsgi.action('os-volume_upload_image') def _volume_upload_image(self, req, id, body): """Uploads the specified volume to image service.""" context = req.environ['cinder.context'] params = body['os-volume_upload_image'] req_version = req.api_version_request if not params.get("image_name"): msg = _("No image_name was specified in request.") raise webob.exc.HTTPBadRequest(explanation=msg) force = params.get('force', 'False') try: force = strutils.bool_from_string(force, strict=True) except ValueError as error: err_msg = encodeutils.exception_to_unicode(error) msg = _("Invalid value for 'force': '%s'") % err_msg raise webob.exc.HTTPBadRequest(explanation=msg) # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) authorize(context, "upload_image") # check for valid disk-format disk_format = params.get("disk_format", "raw") if not image_utils.validate_disk_format(disk_format): msg = _("Invalid disk-format '%(disk_format)s' is specified. " "Allowed disk-formats are %(allowed_disk_formats)s.") % { "disk_format": disk_format, "allowed_disk_formats": ", ".join( image_utils.VALID_DISK_FORMATS) } raise webob.exc.HTTPBadRequest(explanation=msg) image_metadata = {"container_format": params.get( "container_format", "bare"), "disk_format": disk_format, "name": params["image_name"]} if req_version >= api_version_request.APIVersionRequest('3.1'): image_metadata['visibility'] = params.get('visibility', 'private') image_metadata['protected'] = params.get('protected', 'False') if image_metadata['visibility'] == 'public': authorize(context, 'upload_public') if CONF.glance_api_version != 2: # Replace visibility with is_public for Glance V1 image_metadata['is_public'] = ( image_metadata['visibility'] == 'public') image_metadata.pop('visibility', None) image_metadata['protected'] = ( utils.get_bool_param('protected', image_metadata)) try: response = self.volume_api.copy_volume_to_image(context, volume, image_metadata, force) except exception.InvalidVolume as error: raise webob.exc.HTTPBadRequest(explanation=error.msg) except ValueError as error: raise webob.exc.HTTPBadRequest(explanation=six.text_type(error)) except messaging.RemoteError as error: msg = "%(err_type)s: %(err_msg)s" % {'err_type': error.exc_type, 'err_msg': error.value} raise webob.exc.HTTPBadRequest(explanation=msg) except Exception as error: raise webob.exc.HTTPBadRequest(explanation=six.text_type(error)) return {'os-volume_upload_image': response} @wsgi.action('os-extend') def _extend(self, req, id, body): """Extend size of volume.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) try: size = int(body['os-extend']['new_size']) except (KeyError, ValueError, TypeError): msg = _("New volume size must be specified as an integer.") raise webob.exc.HTTPBadRequest(explanation=msg) try: self.volume_api.extend(context, volume, size) except exception.InvalidVolume as error: raise webob.exc.HTTPBadRequest(explanation=error.msg) return webob.Response(status_int=202) @wsgi.action('os-update_readonly_flag') def _volume_readonly_update(self, req, id, body): """Update volume readonly flag.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) try: readonly_flag = body['os-update_readonly_flag']['readonly'] except KeyError: msg = _("Must specify readonly in request.") raise webob.exc.HTTPBadRequest(explanation=msg) try: readonly_flag = strutils.bool_from_string(readonly_flag, strict=True) except ValueError as error: err_msg = encodeutils.exception_to_unicode(error) msg = _("Invalid value for 'readonly': '%s'") % err_msg raise webob.exc.HTTPBadRequest(explanation=msg) self.volume_api.update_readonly_flag(context, volume, readonly_flag) return webob.Response(status_int=202) @wsgi.action('os-retype') def _retype(self, req, id, body): """Change type of existing volume.""" context = req.environ['cinder.context'] volume = self.volume_api.get(context, id) try: new_type = body['os-retype']['new_type'] except KeyError: msg = _("New volume type must be specified.") raise webob.exc.HTTPBadRequest(explanation=msg) policy = body['os-retype'].get('migration_policy') self.volume_api.retype(context, volume, new_type, policy) return webob.Response(status_int=202) @wsgi.action('os-set_bootable') def _set_bootable(self, req, id, body): """Update bootable status of a volume.""" context = req.environ['cinder.context'] # Not found exception will be handled at the wsgi level volume = self.volume_api.get(context, id) try: bootable = body['os-set_bootable']['bootable'] except KeyError: msg = _("Must specify bootable in request.") raise webob.exc.HTTPBadRequest(explanation=msg) try: bootable = strutils.bool_from_string(bootable, strict=True) except ValueError as error: err_msg = encodeutils.exception_to_unicode(error) msg = _("Invalid value for 'bootable': '%s'") % err_msg raise webob.exc.HTTPBadRequest(explanation=msg) update_dict = {'bootable': bootable} self.volume_api.update(context, volume, update_dict) return webob.Response(status_int=200) class Volume_actions(extensions.ExtensionDescriptor): """Enable volume actions.""" name = "VolumeActions" alias = "os-volume-actions" updated = "2012-05-31T00:00:00+00:00" def get_controller_extensions(self): controller = VolumeActionsController() extension = extensions.ControllerExtension(self, 'volumes', controller) return [extension]
apache-2.0
buaazp/etcd
Godeps/_workspace/src/github.com/ugorji/go/codec/test.py
670
3808
#!/usr/bin/env python # This will create golden files in a directory passed to it. # A Test calls this internally to create the golden files # So it can process them (so we don't have to checkin the files). # Ensure msgpack-python and cbor are installed first, using: # pip install --user msgpack-python # pip install --user cbor import cbor, msgpack, msgpackrpc, sys, os, threading def get_test_data_list(): # get list with all primitive types, and a combo type l0 = [ -8, -1616, -32323232, -6464646464646464, 192, 1616, 32323232, 6464646464646464, 192, -3232.0, -6464646464.0, 3232.0, 6464646464.0, False, True, None, u"someday", u"", u"bytestring", 1328176922000002000, -2206187877999998000, 270, -2013855847999995777, #-6795364578871345152, ] l1 = [ { "true": True, "false": False }, { "true": "True", "false": False, "uint16(1616)": 1616 }, { "list": [1616, 32323232, True, -3232.0, {"TRUE":True, "FALSE":False}, [True, False] ], "int32":32323232, "bool": True, "LONG STRING": "123456789012345678901234567890123456789012345678901234567890", "SHORT STRING": "1234567890" }, { True: "true", 8: False, "false": 0 } ] l = [] l.extend(l0) l.append(l0) l.extend(l1) return l def build_test_data(destdir): l = get_test_data_list() for i in range(len(l)): # packer = msgpack.Packer() serialized = msgpack.dumps(l[i]) f = open(os.path.join(destdir, str(i) + '.msgpack.golden'), 'wb') f.write(serialized) f.close() serialized = cbor.dumps(l[i]) f = open(os.path.join(destdir, str(i) + '.cbor.golden'), 'wb') f.write(serialized) f.close() def doRpcServer(port, stopTimeSec): class EchoHandler(object): def Echo123(self, msg1, msg2, msg3): return ("1:%s 2:%s 3:%s" % (msg1, msg2, msg3)) def EchoStruct(self, msg): return ("%s" % msg) addr = msgpackrpc.Address('localhost', port) server = msgpackrpc.Server(EchoHandler()) server.listen(addr) # run thread to stop it after stopTimeSec seconds if > 0 if stopTimeSec > 0: def myStopRpcServer(): server.stop() t = threading.Timer(stopTimeSec, myStopRpcServer) t.start() server.start() def doRpcClientToPythonSvc(port): address = msgpackrpc.Address('localhost', port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print client.call("Echo123", "A1", "B2", "C3") print client.call("EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"}) def doRpcClientToGoSvc(port): # print ">>>> port: ", port, " <<<<<" address = msgpackrpc.Address('localhost', port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print client.call("TestRpcInt.Echo123", ["A1", "B2", "C3"]) print client.call("TestRpcInt.EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"}) def doMain(args): if len(args) == 2 and args[0] == "testdata": build_test_data(args[1]) elif len(args) == 3 and args[0] == "rpc-server": doRpcServer(int(args[1]), int(args[2])) elif len(args) == 2 and args[0] == "rpc-client-python-service": doRpcClientToPythonSvc(int(args[1])) elif len(args) == 2 and args[0] == "rpc-client-go-service": doRpcClientToGoSvc(int(args[1])) else: print("Usage: test.py " + "[testdata|rpc-server|rpc-client-python-service|rpc-client-go-service] ...") if __name__ == "__main__": doMain(sys.argv[1:])
apache-2.0
fener06/pyload
module/cli/Handler.py
42
1348
#!/usr/bin/env python # -*- coding: utf-8 -*- # #Copyright (C) 2011 RaNaN # #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/>. # ### class Handler: def __init__(self, cli): self.cli = cli self.init() client = property(lambda self: self.cli.client) input = property(lambda self: self.cli.input) def init(self): pass def onChar(self, char): pass def onBackSpace(self): pass def onEnter(self, inp): pass def setInput(self, inp=""): self.cli.setInput(inp) def backspace(self): self.cli.setInput(self.input[:-1]) def renderBody(self, line): """ gets the line where to render output and should return the line number below its content """ return line + 1
gpl-3.0
gisce/OCB
addons/l10n_be_coda/wizard/account_coda_import.py
8
28350
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2012 Noviat nv/sa (www.noviat.be). All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import base64 import time from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp import tools import logging _logger = logging.getLogger(__name__) class account_coda_import(osv.osv_memory): _name = 'account.coda.import' _description = 'Import CODA File' _columns = { 'coda_data': fields.binary('CODA File', required=True), 'coda_fname': fields.char('CODA Filename', size=128, required=True), 'note': fields.text('Log'), 'temporary_account_id': fields.many2one('account.account', 'Temporary Account', domain="[('type','!=','view')]", help="It acts as a temporary account for general amount", required=True), } def _get_default_tmp_account(self, cr, uid, context): tmp_accounts = self.pool.get('account.account').search(cr, uid, [('code', '=', '490000')]) if tmp_accounts and len(tmp_accounts) > 0: tmp_account_id = tmp_accounts[0] else: tmp_account_id = False return tmp_account_id _defaults = { 'coda_fname': 'coda.txt', 'temporary_account_id': _get_default_tmp_account, } def coda_parsing(self, cr, uid, ids, context=None, batch=False, codafile=None, codafilename=None): if context is None: context = {} if batch: codafile = str(codafile) codafilename = codafilename else: data = self.browse(cr, uid, ids)[0] try: codafile = data.coda_data codafilename = data.coda_fname temporaryaccount = data.temporary_account_id.id except: raise osv.except_osv(_('Error'), _('Wizard in incorrect state. Please hit the Cancel button')) return {} recordlist = unicode(base64.decodestring(codafile), 'windows-1252', 'strict').split('\n') statements = [] for line in recordlist: if not line: pass elif line[0] == '0': #Begin of a new Bank statement statement = {} statements.append(statement) statement['version'] = line[127] if statement['version'] not in ['1', '2']: raise osv.except_osv(_('Error') + ' R001', _('CODA V%s statements are not supported, please contact your bank') % statement['version']) statement['globalisation_stack'] = [] statement['lines'] = [] statement['date'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT, time.strptime(rmspaces(line[5:11]), '%d%m%y')) statement['separateApplication'] = rmspaces(line[83:88]) elif line[0] == '1': #Statement details if statement['version'] == '1': statement['acc_number'] = rmspaces(line[5:17]) statement['currency'] = rmspaces(line[18:21]) elif statement['version'] == '2': if line[1] == '0': # Belgian bank account BBAN structure statement['acc_number'] = rmspaces(line[5:17]) statement['currency'] = rmspaces(line[18:21]) elif line[1] == '1': # foreign bank account BBAN structure raise osv.except_osv(_('Error') + ' R1001', _('Foreign bank accounts with BBAN structure are not supported ')) elif line[1] == '2': # Belgian bank account IBAN structure statement['acc_number'] = rmspaces(line[5:21]) statement['currency'] = rmspaces(line[39:42]) elif line[1] == '3': # foreign bank account IBAN structure raise osv.except_osv(_('Error') + ' R1002', _('Foreign bank accounts with IBAN structure are not supported ')) else: # Something else, not supported raise osv.except_osv(_('Error') + ' R1003', _('Unsupported bank account structure ')) statement['journal_id'] = False statement['bank_account'] = False # Belgian Account Numbers are composed of 12 digits. # In OpenERP, the user can fill the bank number in any format: With or without IBan code, with or without spaces, with or without '-' # The two following sql requests handle those cases. if len(statement['acc_number']) >= 12: # If the Account Number is >= 12 digits, it is mostlikely a Belgian Account Number (With or without IBAN). # The following request try to find the Account Number using a 'like' operator. # So, if the Account Number is stored with IBAN code, it can be found thanks to this. cr.execute("select id from res_partner_bank where replace(replace(acc_number,' ',''),'-','') like %s", ('%' + statement['acc_number'] + '%',)) else: # This case is necessary to avoid cases like the Account Number in the CODA file is set to a single or few digits, # and so a 'like' operator would return the first account number in the database which matches. cr.execute("select id from res_partner_bank where replace(replace(acc_number,' ',''),'-','') = %s", (statement['acc_number'],)) bank_ids = [id[0] for id in cr.fetchall()] # Filter bank accounts which are not allowed bank_ids = self.pool.get('res.partner.bank').search(cr, uid, [('id', 'in', bank_ids)]) if bank_ids and len(bank_ids) > 0: bank_accs = self.pool.get('res.partner.bank').browse(cr, uid, bank_ids) for bank_acc in bank_accs: if bank_acc.journal_id.id and ((bank_acc.journal_id.currency.id and bank_acc.journal_id.currency.name == statement['currency']) or (not bank_acc.journal_id.currency.id and bank_acc.journal_id.company_id.currency_id.name == statement['currency'])): statement['journal_id'] = bank_acc.journal_id statement['bank_account'] = bank_acc break if not statement['bank_account']: raise osv.except_osv(_('Error') + ' R1004', _("No matching Bank Account (with Account Journal) found.\n\nPlease set-up a Bank Account with as Account Number '%s' and as Currency '%s' and an Account Journal.") % (statement['acc_number'], statement['currency'])) statement['description'] = rmspaces(line[90:125]) statement['balance_start'] = float(rmspaces(line[43:58])) / 1000 if line[42] == '1': #1 = Debit, the starting balance is negative statement['balance_start'] = - statement['balance_start'] statement['balance_start_date'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT, time.strptime(rmspaces(line[58:64]), '%d%m%y')) statement['accountHolder'] = rmspaces(line[64:90]) statement['paperSeqNumber'] = rmspaces(line[2:5]) statement['codaSeqNumber'] = rmspaces(line[125:128]) elif line[0] == '2': if line[1] == '1': #New statement line statementLine = {} statementLine['ref'] = rmspaces(line[2:10]) statementLine['ref_move'] = rmspaces(line[2:6]) statementLine['ref_move_detail'] = rmspaces(line[6:10]) statementLine['sequence'] = len(statement['lines']) + 1 statementLine['transactionRef'] = rmspaces(line[10:31]) statementLine['debit'] = line[31] # 0 = Credit, 1 = Debit statementLine['amount'] = float(rmspaces(line[32:47])) / 1000 if statementLine['debit'] == '1': statementLine['amount'] = - statementLine['amount'] statementLine['transaction_type'] = line[53] statementLine['transactionDate'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT, time.strptime(rmspaces(line[47:53]), '%d%m%y')) statementLine['transaction_family'] = rmspaces(line[54:56]) statementLine['transaction_code'] = rmspaces(line[56:58]) statementLine['transaction_category'] = rmspaces(line[58:61]) if line[61] == '1': #Structured communication statementLine['communication_struct'] = True statementLine['communication_type'] = line[62:65] statementLine['communication'] = '+++' + line[65:68] + '/' + line[68:72] + '/' + line[72:77] + '+++' else: #Non-structured communication statementLine['communication_struct'] = False statementLine['communication'] = rmspaces(line[62:115]) statementLine['entryDate'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT, time.strptime(rmspaces(line[115:121]), '%d%m%y')) statementLine['type'] = 'normal' statementLine['globalisation'] = int(line[124]) if len(statement['globalisation_stack']) > 0 and statementLine['communication'] != '': statementLine['communication'] = "\n".join([statement['globalisation_stack'][-1]['communication'], statementLine['communication']]) if statementLine['globalisation'] > 0: if len(statement['globalisation_stack']) > 0 and statement['globalisation_stack'][-1]['globalisation'] == statementLine['globalisation']: # Destack statement['globalisation_stack'].pop() else: #Stack statementLine['type'] = 'globalisation' statement['globalisation_stack'].append(statementLine) statement['lines'].append(statementLine) elif line[1] == '2': if statement['lines'][-1]['ref'][0:4] != line[2:6]: raise osv.except_osv(_('Error') + 'R2004', _('CODA parsing error on movement data record 2.2, seq nr %s! Please report this issue via your OpenERP support channel.') % line[2:10]) statement['lines'][-1]['communication'] += rmspaces(line[10:63]) statement['lines'][-1]['payment_reference'] = rmspaces(line[63:98]) statement['lines'][-1]['counterparty_bic'] = rmspaces(line[98:109]) elif line[1] == '3': if statement['lines'][-1]['ref'][0:4] != line[2:6]: raise osv.except_osv(_('Error') + 'R2005', _('CODA parsing error on movement data record 2.3, seq nr %s! Please report this issue via your OpenERP support channel.') % line[2:10]) if statement['version'] == '1': statement['lines'][-1]['counterpartyNumber'] = rmspaces(line[10:22]) statement['lines'][-1]['counterpartyName'] = rmspaces(line[47:73]) statement['lines'][-1]['counterpartyAddress'] = rmspaces(line[73:125]) statement['lines'][-1]['counterpartyCurrency'] = '' else: if line[22] == ' ': statement['lines'][-1]['counterpartyNumber'] = rmspaces(line[10:22]) statement['lines'][-1]['counterpartyCurrency'] = rmspaces(line[23:26]) else: statement['lines'][-1]['counterpartyNumber'] = rmspaces(line[10:44]) statement['lines'][-1]['counterpartyCurrency'] = rmspaces(line[44:47]) statement['lines'][-1]['counterpartyName'] = rmspaces(line[47:82]) statement['lines'][-1]['communication'] += rmspaces(line[82:125]) else: # movement data record 2.x (x != 1,2,3) raise osv.except_osv(_('Error') + 'R2006', _('\nMovement data records of type 2.%s are not supported ') % line[1]) elif line[0] == '3': if line[1] == '1': infoLine = {} infoLine['entryDate'] = statement['lines'][-1]['entryDate'] infoLine['type'] = 'information' infoLine['sequence'] = len(statement['lines']) + 1 infoLine['ref'] = rmspaces(line[2:10]) infoLine['transactionRef'] = rmspaces(line[10:31]) infoLine['transaction_type'] = line[31] infoLine['transaction_family'] = rmspaces(line[32:34]) infoLine['transaction_code'] = rmspaces(line[34:36]) infoLine['transaction_category'] = rmspaces(line[36:39]) infoLine['communication'] = rmspaces(line[40:113]) statement['lines'].append(infoLine) elif line[1] == '2': if infoLine['ref'] != rmspaces(line[2:10]): raise osv.except_osv(_('Error') + 'R3004', _('CODA parsing error on information data record 3.2, seq nr %s! Please report this issue via your OpenERP support channel.') % line[2:10]) statement['lines'][-1]['communication'] += rmspaces(line[10:100]) elif line[1] == '3': if infoLine['ref'] != rmspaces(line[2:10]): raise osv.except_osv(_('Error') + 'R3005', _('CODA parsing error on information data record 3.3, seq nr %s! Please report this issue via your OpenERP support channel.') % line[2:10]) statement['lines'][-1]['communication'] += rmspaces(line[10:100]) elif line[0] == '4': comm_line = {} comm_line['type'] = 'communication' comm_line['sequence'] = len(statement['lines']) + 1 comm_line['ref'] = rmspaces(line[2:10]) comm_line['communication'] = rmspaces(line[32:112]) statement['lines'].append(comm_line) elif line[0] == '8': # new balance record statement['debit'] = line[41] statement['paperSeqNumber'] = rmspaces(line[1:4]) statement['balance_end_real'] = float(rmspaces(line[42:57])) / 1000 statement['balance_end_realDate'] = time.strftime(tools.DEFAULT_SERVER_DATE_FORMAT, time.strptime(rmspaces(line[57:63]), '%d%m%y')) if statement['debit'] == '1': # 1=Debit statement['balance_end_real'] = - statement['balance_end_real'] if statement['balance_end_realDate']: period_id = self.pool.get('account.period').search(cr, uid, [('company_id', '=', statement['journal_id'].company_id.id), ('date_start', '<=', statement['balance_end_realDate']), ('date_stop', '>=', statement['balance_end_realDate'])]) else: period_id = self.pool.get('account.period').search(cr, uid, [('company_id', '=', statement['journal_id'].company_id.id), ('date_start', '<=', statement['date']), ('date_stop', '>=', statement['date'])]) if not period_id and len(period_id) == 0: raise osv.except_osv(_('Error') + 'R0002', _("The CODA Statement New Balance date doesn't fall within a defined Accounting Period! Please create the Accounting Period for date %s for the company %s.") % (statement['balance_end_realDate'], statement['journal_id'].company_id.name)) statement['period_id'] = period_id[0] elif line[0] == '9': statement['balanceMin'] = float(rmspaces(line[22:37])) / 1000 statement['balancePlus'] = float(rmspaces(line[37:52])) / 1000 if not statement.get('balance_end_real'): statement['balance_end_real'] = statement['balance_start'] + statement['balancePlus'] - statement['balanceMin'] for i, statement in enumerate(statements): statement['coda_note'] = '' balance_start_check_date = (len(statement['lines']) > 0 and statement['lines'][0]['entryDate']) or statement['date'] cr.execute('SELECT balance_end_real \ FROM account_bank_statement \ WHERE journal_id = %s and date <= %s \ ORDER BY date DESC,id DESC LIMIT 1', (statement['journal_id'].id, balance_start_check_date)) res = cr.fetchone() balance_start_check = res and res[0] if balance_start_check == None: if statement['journal_id'].default_debit_account_id and (statement['journal_id'].default_credit_account_id == statement['journal_id'].default_debit_account_id): balance_start_check = statement['journal_id'].default_debit_account_id.balance else: raise osv.except_osv(_('Error'), _("Configuration Error in journal %s!\nPlease verify the Default Debit and Credit Account settings.") % statement['journal_id'].name) if balance_start_check != statement['balance_start']: statement['coda_note'] = _("The CODA Statement %s Starting Balance (%.2f) does not correspond with the previous Closing Balance (%.2f) in journal %s!") % (statement['description'] + ' #' + statement['paperSeqNumber'], statement['balance_start'], balance_start_check, statement['journal_id'].name) if not(statement.get('period_id')): raise osv.except_osv(_('Error') + ' R3006', _(' No transactions or no period in coda file !')) data = { 'name': statement['paperSeqNumber'], 'date': statement['date'], 'journal_id': statement['journal_id'].id, 'period_id': statement['period_id'], 'balance_start': statement['balance_start'], 'balance_end_real': statement['balance_end_real'], } statement['id'] = self.pool.get('account.bank.statement').create(cr, uid, data, context=context) for line in statement['lines']: if line['type'] == 'information': statement['coda_note'] = "\n".join([statement['coda_note'], line['type'].title() + ' with Ref. ' + str(line['ref']), 'Date: ' + str(line['entryDate']), 'Communication: ' + line['communication'], '']) elif line['type'] == 'communication': statement['coda_note'] = "\n".join([statement['coda_note'], line['type'].title() + ' with Ref. ' + str(line['ref']), 'Ref: ', 'Communication: ' + line['communication'], '']) elif line['type'] == 'normal': note = [] if 'counterpartyName' in line and line['counterpartyName'] != '': note.append(_('Counter Party') + ': ' + line['counterpartyName']) else: line['counterpartyName'] = False if 'counterpartyNumber' in line and line['counterpartyNumber'] != '': try: if int(line['counterpartyNumber']) == 0: line['counterpartyNumber'] = False except: pass if line['counterpartyNumber']: note.append(_('Counter Party Account') + ': ' + line['counterpartyNumber']) else: line['counterpartyNumber'] = False if 'counterpartyAddress' in line and line['counterpartyAddress'] != '': note.append(_('Counter Party Address') + ': ' + line['counterpartyAddress']) line['name'] = "\n".join(filter(None, [line['counterpartyName'], line['communication']])) line['transaction_type'] = 'general' partner = None partner_id = None invoice = False if line['communication_struct'] and 'communication_type' in line and line['communication_type'] == '101': ids = self.pool.get('account.invoice').search(cr, uid, [('reference', '=', line['communication']), ('reference_type', '=', 'bba')]) if ids: invoice = self.pool.get('account.invoice').browse(cr, uid, ids[0]) partner = invoice.partner_id partner_id = partner.id if invoice.type in ['in_invoice', 'in_refund'] and line['debit'] == '1': line['transaction_type'] = 'supplier' elif invoice.type in ['out_invoice', 'out_refund'] and line['debit'] == '0': line['transaction_type'] = 'customer' line['account'] = invoice.account_id.id line['reconcile'] = False if invoice.type in ['in_invoice', 'out_invoice']: iml_ids = self.pool.get('account.move.line').search(cr, uid, [('move_id', '=', invoice.move_id.id), ('reconcile_id', '=', False), ('account_id.reconcile', '=', True)]) if iml_ids: line['reconcile'] = iml_ids[0] if line['reconcile']: voucher_vals = { 'type': line['transaction_type'] == 'supplier' and 'payment' or 'receipt', 'name': line['name'], 'partner_id': partner_id, 'journal_id': statement['journal_id'].id, 'account_id': statement['journal_id'].default_credit_account_id.id, 'company_id': statement['journal_id'].company_id.id, 'currency_id': statement['journal_id'].company_id.currency_id.id, 'date': line['entryDate'], 'amount': abs(line['amount']), 'period_id': statement['period_id'], 'invoice_id': invoice.id, } context['invoice_id'] = invoice.id voucher_vals.update(self.pool.get('account.voucher').onchange_partner_id(cr, uid, [], partner_id=partner_id, journal_id=statement['journal_id'].id, amount=abs(line['amount']), currency_id=statement['journal_id'].company_id.currency_id.id, ttype=line['transaction_type'] == 'supplier' and 'payment' or 'receipt', date=line['transactionDate'], context=context )['value']) line_drs = [] for line_dr in voucher_vals['line_dr_ids']: line_drs.append((0, 0, line_dr)) voucher_vals['line_dr_ids'] = line_drs line_crs = [] for line_cr in voucher_vals['line_cr_ids']: line_crs.append((0, 0, line_cr)) voucher_vals['line_cr_ids'] = line_crs line['voucher_id'] = self.pool.get('account.voucher').create(cr, uid, voucher_vals, context=context) if 'counterpartyNumber' in line and line['counterpartyNumber']: ids = self.pool.get('res.partner.bank').search(cr, uid, [('acc_number', '=', str(line['counterpartyNumber']))]) if ids and len(ids) > 0: partner = self.pool.get('res.partner.bank').browse(cr, uid, ids[0], context=context).partner_id partner_id = partner.id if not invoice: if line['debit'] == '0': line['account'] = partner.property_account_receivable.id if partner.customer: line['transaction_type'] = 'customer' elif line['debit'] == '1': line['account'] = partner.property_account_payable.id if partner.supplier: line['transaction_type'] = 'supplier' if not partner and not invoice: line['account'] = temporaryaccount if 'communication' in line and line['communication'] != '': note.append(_('Communication') + ': ' + line['communication']) if 'voucher_id' not in line: line['voucher_id'] = None data = { 'name': line['name'], 'note': "\n".join(note), 'date': line['entryDate'], 'amount': line['amount'], 'type': line['transaction_type'], 'partner_id': partner_id, 'account_id': line['account'], 'statement_id': statement['id'], 'ref': line['ref'], 'sequence': line['sequence'], 'voucher_id': line['voucher_id'], 'coda_account_number': line['counterpartyNumber'], } self.pool.get('account.bank.statement.line').create(cr, uid, data, context=context) if statement['coda_note'] != '': self.pool.get('account.bank.statement').write(cr, uid, [statement['id']], {'coda_note': statement['coda_note']}, context=context) model, action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'account', 'action_bank_statement_tree') action = self.pool.get(model).browse(cr, uid, action_id, context=context) return { 'name': action.name, 'view_type': action.view_type, 'view_mode': action.view_mode, 'res_model': action.res_model, 'domain': action.domain, 'context': action.context, 'type': 'ir.actions.act_window', 'search_view_id': action.search_view_id.id, 'views': [(v.view_id.id, v.view_mode) for v in action.view_ids] } def rmspaces(s): return " ".join(s.split()) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
DucQuang1/youtube-dl
youtube_dl/extractor/shared.py
40
1876
from __future__ import unicode_literals import base64 from .common import InfoExtractor from ..compat import ( compat_urllib_parse, compat_urllib_request, ) from ..utils import ( ExtractorError, int_or_none, ) class SharedIE(InfoExtractor): _VALID_URL = r'http://shared\.sx/(?P<id>[\da-z]{10})' _TEST = { 'url': 'http://shared.sx/0060718775', 'md5': '106fefed92a8a2adb8c98e6a0652f49b', 'info_dict': { 'id': '0060718775', 'ext': 'mp4', 'title': 'Bmp4', }, } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) if '>File does not exist<' in webpage: raise ExtractorError( 'Video %s does not exist' % video_id, expected=True) download_form = self._hidden_inputs(webpage) request = compat_urllib_request.Request( url, compat_urllib_parse.urlencode(download_form)) request.add_header('Content-Type', 'application/x-www-form-urlencoded') video_page = self._download_webpage( request, video_id, 'Downloading video page') video_url = self._html_search_regex( r'data-url="([^"]+)"', video_page, 'video URL') title = base64.b64decode(self._html_search_meta( 'full:title', webpage, 'title').encode('utf-8')).decode('utf-8') filesize = int_or_none(self._html_search_meta( 'full:size', webpage, 'file size', fatal=False)) thumbnail = self._html_search_regex( r'data-poster="([^"]+)"', video_page, 'thumbnail', default=None) return { 'id': video_id, 'url': video_url, 'ext': 'mp4', 'filesize': filesize, 'title': title, 'thumbnail': thumbnail, }
unlicense
goyoregalado/OMSTD
examples/cracking/ch-001/omstd_ch_001/api.py
2
3383
# -*- coding: utf-8 -*- """ Project name: Open Methodology for Security Tool Developers Project URL: https://github.com/cr0hn/OMSTD Copyright (c) 2014, cr0hn<-AT->cr0hn.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ """ API file """ __author__ = 'cr0hn - cr0hn<-at->cr0hn.com (@ggdaniel)' __all__ = ["check_md5", "run_check_md5_hash"] # Import data from .lib.data import * from .lib.check_md5 import check_md5 # ---------------------------------------------------------------------- def run_check_md5_hash(input_parameters): """ Checks MD5 hash and return an Results object. :param input_parameters: Parameters object with config :type input_parameters: Parameters :return: Results object :rtype: Results :raises: TypeError """ if not isinstance(input_parameters, Parameters): raise TypeError("Expected Parameters, got '%s' instead" % type(input_parameters)) try: r = check_md5(input_parameters) return Results(plain_password=r, is_hash_found=True) except HashNotFound as e: return Results(plain_password=None, is_hash_found=False) # ---------------------------------------------------------------------- def run_console(input_parameters): """ Run for command line interface. It's make all steps of tool: - Looking find - Get password - Display into screen :param input_parameters: Parameters object with config :type input_parameters: Parameters :raises: TypeError """ try: result = run_check_md5_hash(input_parameters) # Display plain text print("[**] Plain text FOUND!!!. Decoded password is ----> %s <----." % result.plain_password) except InvalidHashFormat as e: print("\n[!] An error was found while try to get password: %s\n" % e) except HashNotFound as e: print("\n[-] Plain text not found for hash '%s'" % input_parameters.md5_hash)
bsd-2-clause
bcroq/kansha
kansha/user/view.py
2
8283
# -*- coding:utf-8 -*- #-- # Copyright (c) 2012-2014 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- from nagare.i18n import _ from nagare import presentation, component, ajax, var from kansha import validator from kansha.toolbox import overlay, remote from .usermanager import NewMember from .comp import User, PendingUser @presentation.render_for(User) def render_User(self, h, comp, *args): """Default view, render avatar and fullname""" h << comp.render(h, "avatar") with h.div(class_="name"): h << comp.render(h, model="fullname") h << h.span(self.data.email or self.data.email_to_confirm, class_="email") return h.root @presentation.render_for(User, model='avatar') def render_User_avatar(self, h, comp, model, *args): """Render a user's avatar""" with h.span(class_='avatar', title='%s' % (self.data.fullname)): avatar = self.get_avatar() if avatar: h << h.img(src=avatar) else: h << h.i(class_='ico-btn icon-user') return h.root @presentation.render_for(User, model='fullname') def render_User_fullname(self, h, comp, model, *args): """Render a user's avatar""" return h.span(self.data.fullname, class_="fullname") @presentation.render_for(User, model='search') def render_User_search(self, h, comp, *args): """Serach result view""" return h.div(comp) @presentation.render_for(User, model='overlay-member') @presentation.render_for(User, model='overlay-manager') @presentation.render_for(User, model='overlay-remove') @presentation.render_for(User, model='overlay-last_manager') @presentation.render_for(PendingUser, model='overlay-pending') def render_User_overlay_remove(self, h, comp, model): sub_model = model[8:] h << component.Component( overlay.Overlay( lambda r: ( comp.render(r, "avatar"), {'class': 'miniavatar'} ), lambda r: comp.render(r, sub_model), dynamic=False, cls='card-overlay' if model == 'remove' else 'board-labels-overlay' ) ) return h.root @presentation.render_for(User, "remove") def render_User_remove(self, h, comp, *args): """Render for search result""" with h.div(class_='member'): h << comp.render(h, None) with h.span(class_="actions"): with h.form: h << h.input(value=_("Remove"), type="submit", class_="btn btn-primary delete").action(ajax.Update(action=lambda: comp.answer(self.username))) return h.root @presentation.render_for(User, "member") @presentation.render_for(User, "manager") def render_User_manager(self, h, comp, model): """Render for search result""" with h.div(class_='member'): h << comp.render(h, None) with h.span(class_="actions"): with h.form: h << h.input( value=_("Manager"), type="submit", class_=("btn btn-primary toggle" if model == 'manager' else "btn btn-primary") ).action(ajax.Update(action=lambda: comp.answer('toggle_role'))) h << h.input( value=_("Remove"), type="submit", class_="btn btn-primary delete" ).action(ajax.Update(action=lambda: comp.answer('remove'))) return h.root @presentation.render_for(User, "last_manager") def render_User_last_manager(self, h, comp, *args): """Render for search result""" with h.div(class_='member'): h << comp.render(h, None) with h.span(class_="actions last-manager"): h << _("You are the last manager, you can't leave this board.") return h.root @presentation.render_for(User, model="menu") def render_User_menu(self, h, comp, *args): """Render user menu""" h << h.li(h.a(h.i(class_='icon-home'), _("Home"), class_="home").action(lambda: comp.answer(self))) h << h.li(h.a(h.i(class_='icon-switch'), _("Logout"), class_="logout").action(comp.answer)) return h.root @presentation.render_for(User, model="detailed") def render_User_detailed(self, h, comp, *args): """Render user detailed view""" h << h.h3(self.data.fullname) h << h.div(comp.render(h, model='avatar')) return h.root @presentation.render_for(User, model="friend") def render_User_friend(self, h, comp, *args): h << h.a(comp.render(h, "avatar")).action( remote.Action(lambda: comp.answer([self.data.email or self.data.email_to_confirm]))) return h.root @presentation.render_for(NewMember, model='add_members') def render_AddMembers(self, h, comp, *args): value = var.Var('') submit_id = h.generate_id('form') hidden_id = h.generate_id('hidden') with h.form: h << h.input(type='text', id=self.text_id) h << h.input(type='hidden', id=hidden_id).action(value) h << self.autocomplete h << h.script( u"%(ac_id)s.itemSelectEvent.subscribe(function(sType, aArgs) {" u"var value = aArgs[2][0];" u"YAHOO.util.Dom.setAttribute(%(hidden_id)s, 'value', value);" u"YAHOO.util.Dom.get(%(submit_id)s).click();" u"});" % { 'ac_id': self.autocomplete().var, 'hidden_id': ajax.py2js(hidden_id), 'submit_id': ajax.py2js(submit_id) } ) h << h.script( "document.getElementById(%s).focus()" % ajax.py2js(self.text_id) ) h << h.button(id=submit_id, style='display:none').action(remote.Action(lambda: comp.answer([] if not value() else [value()]))) return h.root @presentation.render_for(NewMember) def render_NewMember(self, h, comp, *args): """Render the title of the associated card""" with h.form: members_to_add = var.Var() def get_emails(): emails = [] for email in members_to_add().split(','): try: email = email.strip() email = validator.validate_email(email) emails.append(email) except ValueError: continue return emails h << h.input(type='text', id=self.text_id,).action(members_to_add) mail_input = h.input(value=_("Add"), type="submit", class_="btn btn-primary" ).action(remote.Action(lambda: comp.answer(get_emails()))) # Sending mail synchronously can take a long time mail_input.set('onclick', 'YAHOO.kansha.app.showWaiter();' + mail_input.get('onclick')) h << mail_input h << self.autocomplete h << h.script( "document.getElementById(%s).focus()" % ajax.py2js(self.text_id) ) return h.root # Pending User @presentation.render_for(PendingUser) def render_PendingUser(self, h, comp, *args): """Default view, render avatar and fullname""" h << comp.render(h, "avatar") with h.div(class_="name"): h << h.span(self.username, class_="fullname") h << h.span(self.username, class_="email") return h.root @presentation.render_for(PendingUser, model='avatar') def render_PendingUser_avatar(self, h, comp, model, *args): """Render a user's avatar""" with h.span(class_='avatar', title='%s' % (self.username)): h << h.i(class_='ico-btn icon-mail2') return h.root @presentation.render_for(PendingUser, "pending") def render_PendingUser_pending(self, h, comp, *args): """Render for search result""" with h.div(class_='member'): h << comp.render(h, None) with h.span(class_="actions"): with h.form: h << h.input(value=_("Resend invitation"), type="submit", class_="btn btn-primary").action(ajax.Update(action=lambda: comp.answer('resend'))) h << h.input(value=_("Remove"), type="submit", class_="btn btn-primary delete").action(ajax.Update(action=(lambda: comp.answer('remove')))) return h.root
bsd-3-clause
SelvorWhim/competitive
Bloomberg_codecon/General_challenger_problems/mug_color.py
1
1927
### INSTRUCTIONS ### ''' Jay S. has got himself in trouble! He had borrowed a friend's coffee mug and somehow lost it. As his friend will be extremely angry when he finds out about it, Jay has decided to buy his friend a replacement mug to try to control the damage. Unfortunately, Jay does not remember the color of the mug he had borrowed. He only knows that the color was one of White, Black, Blue, Red or Yellow. Jay goes around his office asking his colleagues if they are able to recall the color but his friends don't seem to remember the color of the mug either. What they do know is what color the mug definitely was not. Based on this information, help Jay figure out what the color of the mug was. > Input Specifications Your program will take An input N (1 <= N <= 1,000,000) which denotes the number of people Jay questions regarding the mug. This will be followed by N strings S[1],S[2]...S[N] where S[I] denotes the response of person I to Jay's question which is what color the mug definitely was not. S[I] will also be only one of the 5 colors namely White, Black, Blue, Red or Yellow. > Output Specifications Based on the input, print out the color of the mug. The color of the mug can only be one of the 5 colors namely White, Black, Blue, Red or Yellow. You can safely assume that there always exists only one unique color that the mug can have. ''' ### MY SOLUTION (accepted) ### #Problem : Mug Color #Language : Python 3 #Compiled Using : py_compile #Version : Python 3.4.3 #Input for your program will be provided from STDIN #Print out all output from your program to STDOUT import sys colors=['White', 'Black', 'Blue', 'Red', 'Yellow'] data = sys.stdin.read().splitlines() N = int(data[0]) for color in data[1:] : if color in colors: colors.remove(color) print(colors[0]) # assumed exactly one remains. If more, will be first available. If none, error.
unlicense
christianurich/DynaMind-ToolBox
DynaMind-Extensions/unit-tests/gtest-1.6.0/scripts/fuse_gtest_files.py
2577
8813
#!/usr/bin/env python # # Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """fuse_gtest_files.py v0.2.0 Fuses Google Test source code into a .h file and a .cc file. SYNOPSIS fuse_gtest_files.py [GTEST_ROOT_DIR] OUTPUT_DIR Scans GTEST_ROOT_DIR for Google Test source code, and generates two files: OUTPUT_DIR/gtest/gtest.h and OUTPUT_DIR/gtest/gtest-all.cc. Then you can build your tests by adding OUTPUT_DIR to the include search path and linking with OUTPUT_DIR/gtest/gtest-all.cc. These two files contain everything you need to use Google Test. Hence you can "install" Google Test by copying them to wherever you want. GTEST_ROOT_DIR can be omitted and defaults to the parent directory of the directory holding this script. EXAMPLES ./fuse_gtest_files.py fused_gtest ./fuse_gtest_files.py path/to/unpacked/gtest fused_gtest This tool is experimental. In particular, it assumes that there is no conditional inclusion of Google Test headers. Please report any problems to googletestframework@googlegroups.com. You can read http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide for more information. """ __author__ = 'wan@google.com (Zhanyong Wan)' import os import re import sets import sys # We assume that this file is in the scripts/ directory in the Google # Test root directory. DEFAULT_GTEST_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..') # Regex for matching '#include "gtest/..."'. INCLUDE_GTEST_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gtest/.+)"') # Regex for matching '#include "src/..."'. INCLUDE_SRC_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(src/.+)"') # Where to find the source seed files. GTEST_H_SEED = 'include/gtest/gtest.h' GTEST_SPI_H_SEED = 'include/gtest/gtest-spi.h' GTEST_ALL_CC_SEED = 'src/gtest-all.cc' # Where to put the generated files. GTEST_H_OUTPUT = 'gtest/gtest.h' GTEST_ALL_CC_OUTPUT = 'gtest/gtest-all.cc' def VerifyFileExists(directory, relative_path): """Verifies that the given file exists; aborts on failure. relative_path is the file path relative to the given directory. """ if not os.path.isfile(os.path.join(directory, relative_path)): print 'ERROR: Cannot find %s in directory %s.' % (relative_path, directory) print ('Please either specify a valid project root directory ' 'or omit it on the command line.') sys.exit(1) def ValidateGTestRootDir(gtest_root): """Makes sure gtest_root points to a valid gtest root directory. The function aborts the program on failure. """ VerifyFileExists(gtest_root, GTEST_H_SEED) VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED) def VerifyOutputFile(output_dir, relative_path): """Verifies that the given output file path is valid. relative_path is relative to the output_dir directory. """ # Makes sure the output file either doesn't exist or can be overwritten. output_file = os.path.join(output_dir, relative_path) if os.path.exists(output_file): # TODO(wan@google.com): The following user-interaction doesn't # work with automated processes. We should provide a way for the # Makefile to force overwriting the files. print ('%s already exists in directory %s - overwrite it? (y/N) ' % (relative_path, output_dir)) answer = sys.stdin.readline().strip() if answer not in ['y', 'Y']: print 'ABORTED.' sys.exit(1) # Makes sure the directory holding the output file exists; creates # it and all its ancestors if necessary. parent_directory = os.path.dirname(output_file) if not os.path.isdir(parent_directory): os.makedirs(parent_directory) def ValidateOutputDir(output_dir): """Makes sure output_dir points to a valid output directory. The function aborts the program on failure. """ VerifyOutputFile(output_dir, GTEST_H_OUTPUT) VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT) def FuseGTestH(gtest_root, output_dir): """Scans folder gtest_root to generate gtest/gtest.h in output_dir.""" output_file = file(os.path.join(output_dir, GTEST_H_OUTPUT), 'w') processed_files = sets.Set() # Holds all gtest headers we've processed. def ProcessFile(gtest_header_path): """Processes the given gtest header file.""" # We don't process the same header twice. if gtest_header_path in processed_files: return processed_files.add(gtest_header_path) # Reads each line in the given gtest header. for line in file(os.path.join(gtest_root, gtest_header_path), 'r'): m = INCLUDE_GTEST_FILE_REGEX.match(line) if m: # It's '#include "gtest/..."' - let's process it recursively. ProcessFile('include/' + m.group(1)) else: # Otherwise we copy the line unchanged to the output file. output_file.write(line) ProcessFile(GTEST_H_SEED) output_file.close() def FuseGTestAllCcToFile(gtest_root, output_file): """Scans folder gtest_root to generate gtest/gtest-all.cc in output_file.""" processed_files = sets.Set() def ProcessFile(gtest_source_file): """Processes the given gtest source file.""" # We don't process the same #included file twice. if gtest_source_file in processed_files: return processed_files.add(gtest_source_file) # Reads each line in the given gtest source file. for line in file(os.path.join(gtest_root, gtest_source_file), 'r'): m = INCLUDE_GTEST_FILE_REGEX.match(line) if m: if 'include/' + m.group(1) == GTEST_SPI_H_SEED: # It's '#include "gtest/gtest-spi.h"'. This file is not # #included by "gtest/gtest.h", so we need to process it. ProcessFile(GTEST_SPI_H_SEED) else: # It's '#include "gtest/foo.h"' where foo is not gtest-spi. # We treat it as '#include "gtest/gtest.h"', as all other # gtest headers are being fused into gtest.h and cannot be # #included directly. # There is no need to #include "gtest/gtest.h" more than once. if not GTEST_H_SEED in processed_files: processed_files.add(GTEST_H_SEED) output_file.write('#include "%s"\n' % (GTEST_H_OUTPUT,)) else: m = INCLUDE_SRC_FILE_REGEX.match(line) if m: # It's '#include "src/foo"' - let's process it recursively. ProcessFile(m.group(1)) else: output_file.write(line) ProcessFile(GTEST_ALL_CC_SEED) def FuseGTestAllCc(gtest_root, output_dir): """Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir.""" output_file = file(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w') FuseGTestAllCcToFile(gtest_root, output_file) output_file.close() def FuseGTest(gtest_root, output_dir): """Fuses gtest.h and gtest-all.cc.""" ValidateGTestRootDir(gtest_root) ValidateOutputDir(output_dir) FuseGTestH(gtest_root, output_dir) FuseGTestAllCc(gtest_root, output_dir) def main(): argc = len(sys.argv) if argc == 2: # fuse_gtest_files.py OUTPUT_DIR FuseGTest(DEFAULT_GTEST_ROOT_DIR, sys.argv[1]) elif argc == 3: # fuse_gtest_files.py GTEST_ROOT_DIR OUTPUT_DIR FuseGTest(sys.argv[1], sys.argv[2]) else: print __doc__ sys.exit(1) if __name__ == '__main__': main()
gpl-2.0
DoWhatILove/turtle
programming/python/design/swampy/World.py
1
7842
#!/usr/bin/python """ This module is part of Swampy, a suite of programs available from allendowney.com/swampy. Copyright 2005 Allen B. Downey Distributed under the GNU General Public License at gnu.org/licenses/gpl.html. """ import math import random import time import threading import sys import tkinter from .Gui import Gui class World(Gui): """Represents the environment where Animals live. A World usually includes a canvas, where animals are drawn, and sometimes a control panel. """ current_world = None def __init__(self, delay=0.5, *args, **kwds): Gui.__init__(self, *args, **kwds) self.delay = delay self.title('World') # keep track of the most recent world World.current_world = self # set to False when the user presses quit. self.exists = True # list of animals that live in this world. self.animals = [] # if the user closes the window, shut down cleanly self.protocol("WM_DELETE_WINDOW", self.quit) def wait_for_user(self): """Waits for user events and processes them.""" try: self.mainloop() except KeyboardInterrupt: print('KeyboardInterrupt') def quit(self): """Shuts down the World.""" # tell other threads that the world is gone self.exists = False # destroy closes the window self.destroy() # quit terminates mainloop (but since mainloop can get called # recursively, quitting once might not be enough!) Gui.quit(self) def sleep(self): """Updates the GUI and sleeps. Calling Tk.update from a function that might be invoked by an event handler is generally considered a bad idea. For a discussion, see http://wiki.tcl.tk/1255 However, in this case: 1) It is by far the simplest option, and I want to keep this code readable. 2) It is generally the last thing that happens in an event handler. So any changes that happen during the update won't cause problems when it returns. Sleeping is also a potential problem, since the GUI is unresponsive while sleeping. So it is probably a good idea to keep delay less than about 0.5 seconds. """ self.update() time.sleep(self.delay) def register(self, animal): """Adds a new animal to the world.""" self.animals.append(animal) def unregister(self, animal): """Removes an animal from the world.""" self.animals.remove(animal) def clear(self): """Undraws and removes all the animals. And deletes anything else on the canvas. """ for animal in self.animals: animal.undraw() self.animals = [] try: self.canvas.delete('all') except AttributeError: print('Warning: World.clear: World must have a canvas.') def step(self): """Invoke the step method on every animal.""" for animal in self.animals: animal.step() def run(self): """Invoke step intermittently until the user presses Quit or Stop.""" self.running = True while self.exists and self.running: self.step() self.update() def stop(self): """Stops running.""" self.running = False def map_animals(self, callable): """Apply the given callable to all animals. Args: callable: any callable object, including Gui.Callable """ return list(map(callable, self.animals)) def make_interpreter(self, gs=None): """Makes an interpreter for this world. Creates an attribute named inter. """ self.inter = Interpreter(self, gs) def run_text(self): """Executes the code from the TextEntry in the control panel. Precondition: self must have an Interpreter and a text entry. """ source = self.te_code.get(1.0, tkinter.END) self.inter.run_code(source, '<user-provided code>') def run_file(self): """Read the code from the filename in the entry and runs it. Precondition: self must have an Interpreter and a filename entry. """ filename = self.en_file.get() fp = open(filename) source = fp.read() self.inter.run_code(source, filename) class Interpreter(object): """Encapsulates the environment where user-provided code executes.""" def __init__(self, world, gs=None): self.world = world # if the caller didn't provide globals, use the current env if gs == None: self.globals = globals() else: self.globals = gs def run_code_thread(self, *args): """Runs the given code in a new thread.""" return MyThread(self.run_code, *args) def run_code(self, source, filename): """Runs the given code in the saved environment.""" code = compile(source, filename, 'exec') try: exec(code, self.globals) except KeyboardInterrupt: self.world.quit() except tkinter.TclError: pass class MyThread(threading.Thread): """Wrapper for threading.Thread. Improves the syntax for creating and starting threads. """ def __init__(self, target, *args): threading.Thread.__init__(self, target=target, args=args) self.start() class Animal(object): """Abstract class, defines the methods child classes need to provide. Attributes: world: reference to the World the animal lives in. x: location in Canvas coordinates y: location in Canvas coordinates """ def __init__(self, world=None): self.world = world or World.current_world if self.world: self.world.register(self) self.x = 0 self.y = 0 def set_delay(self, delay): """Sets delay for this animal's world. delay is made available as an animal attribute for backward compatibility; ideally it should be considered an attribute of the world, not an animal. Args: delay: float delay in seconds """ self.world.delay = delay delay = property(lambda self: self.world.delay, set_delay) def step(self): """Takes one step. Subclasses should override this method. """ pass def draw(self): """Draws the animal. Subclasses should override this method. """ pass def undraw(self): """Undraws the animal.""" if self.world.exists and hasattr(self, 'tag'): self.world.canvas.delete(self.tag) def die(self): """Removes the animal from the world and undraws it.""" self.world.unregister(self) self.undraw() def redraw(self): """Undraws and then redraws the animal.""" if self.world.exists: self.undraw() self.draw() def polar(self, x, y, r, theta): """Converts polar coordinates to cartesian. Args: x, y: location of the origin r: radius theta: angle in degrees Returns: tuple of x, y coordinates """ rad = theta * math.pi / 180 s = math.sin(rad) c = math.cos(rad) return [x + r * c, y + r * s] def wait_for_user(): """Invokes wait_for_user on the most recent World.""" World.current_world.wait_for_user() if __name__ == '__main__': # make a generic world world = World() # create a canvas and put a text item on it ca = world.ca() ca.text([0, 0], 'hello') # wait for the user wait_for_user()
mit
Fusion-Rom/android_external_chromium_org
tools/valgrind/browser_wrapper_win.py
44
1638
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import glob import os import re import sys import subprocess # TODO(timurrrr): we may use it on POSIX too to avoid code duplication once we # support layout_tests, remove Dr. Memory specific code and verify it works # on a "clean" Mac. testcase_name = None for arg in sys.argv: m = re.match("\-\-gtest_filter=(.*)", arg) if m: assert testcase_name is None testcase_name = m.groups()[0] # arg #0 is the path to this python script cmd_to_run = sys.argv[1:] # TODO(timurrrr): this is Dr. Memory-specific # Usually, we pass "-logdir" "foo\bar\spam path" args to Dr. Memory. # To group reports per UI test, we want to put the reports for each test into a # separate directory. This code can be simplified when we have # http://code.google.com/p/drmemory/issues/detail?id=684 fixed. logdir_idx = cmd_to_run.index("-logdir") old_logdir = cmd_to_run[logdir_idx + 1] wrapper_pid = str(os.getpid()) # On Windows, there is a chance of PID collision. We avoid it by appending the # number of entries in the logdir at the end of wrapper_pid. # This number is monotonic and we can't have two simultaneously running wrappers # with the same PID. wrapper_pid += "_%d" % len(glob.glob(old_logdir + "\\*")) cmd_to_run[logdir_idx + 1] += "\\testcase.%s.logs" % wrapper_pid os.makedirs(cmd_to_run[logdir_idx + 1]) if testcase_name: f = open(old_logdir + "\\testcase.%s.name" % wrapper_pid, "w") print >>f, testcase_name f.close() exit(subprocess.call(cmd_to_run))
bsd-3-clause
Eyepea/FrameworkBenchmarks
toolset/benchmark/test_types/framework_test_type.py
27
4710
import copy import sys import subprocess from subprocess import PIPE import requests # Requests is built ontop of urllib3, # here we prevent general request logging import logging logging.getLogger('urllib3').setLevel(logging.CRITICAL) from pprint import pprint class FrameworkTestType: ''' Interface between a test type (json, query, plaintext, etc) and the rest of TFB. A test type defines a number of keys it expects to find in the benchmark_config.json, and this base class handles extracting those keys and injecting them into the test. For example, if benchmark_config.json contains a line `"spam" : "foobar"` and a subclasses X passes an argument list of ['spam'], then after parsing there will exist a member `X.spam = 'foobar'`. ''' def __init__(self, name, requires_db=False, accept_header=None, args=[]): self.name = name self.requires_db = requires_db self.args = args self.out = sys.stdout self.err = sys.stderr if accept_header is None: self.accept_header = self.accept('json') else: self.accept_header = accept_header self.passed = None self.failed = None self.warned = None def accept(self, content_type): return { 'json': 'application/json,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7', 'html': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'plaintext': 'text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7' }[content_type] def setup_out(self, out): ''' Sets up file-like objects for logging. Used in cases where it is hard just return the output. Any output sent to these file objects is also printed to the console NOTE: I detest this. It would be much better to use logging like it's intended ''' self.out = out def parse(self, test_keys): ''' Takes the dict of key/value pairs describing a FrameworkTest and collects all variables needed by this FrameworkTestType Raises AttributeError if required keys are missing ''' if all(arg in test_keys for arg in self.args): self.__dict__.update({arg: test_keys[arg] for arg in self.args}) return self else: # This is quite common - most tests don't support all types raise AttributeError( "A %s requires the benchmark_config.json to contain %s" % (self.name, self.args)) def request_headers_and_body(self, url): ''' Downloads a URL and returns the HTTP response headers and body content as a tuple ''' print "Accessing URL %s:" % url self.out.write("Accessing URL %s \n" % url) headers = {'Accept': self.accept_header} r = requests.get(url, timeout=15, headers=headers) headers = r.headers body = r.content self.out.write(str(headers)) self.out.write(body) b = 40 print " Response (trimmed to %d bytes): \"%s\"" % (b, body.strip()[:b]) return headers, body def verify(self, base_url): ''' Accesses URL used by this test type and checks the return values for correctness. Most test types run multiple checks, so this returns a list of results. Each result is a 3-tuple of (String result, String reason, String urlTested). - result : 'pass','warn','fail' - reason : Short human-readable reason if result was warn or fail. Please do not print the response as part of this, other parts of TFB will do that based upon the current logging settings if this method indicates a failure happened - urlTested: The exact URL that was queried Subclasses should make a best-effort attempt to report as many failures and warnings as they can to help users avoid needing to run TFB repeatedly while debugging ''' # TODO make String result into an enum to enforce raise NotImplementedError("Subclasses must provide verify") def get_url(self): '''Returns the URL for this test, like '/json''' # This is a method because each test type uses a different key # for their URL so the base class can't know which arg is the URL raise NotImplementedError("Subclasses must provide get_url") def copy(self): ''' Returns a copy that can be safely modified. Use before calling parse ''' return copy.copy(self)
bsd-3-clause
CforED/Machine-Learning
examples/semi_supervised/plot_label_propagation_structure.py
45
2433
""" ============================================== Label Propagation learning a complex structure ============================================== Example of LabelPropagation learning a complex internal structure to demonstrate "manifold learning". The outer circle should be labeled "red" and the inner circle "blue". Because both label groups lie inside their own distinct shape, we can see that the labels propagate correctly around the circle. """ print(__doc__) # Authors: Clay Woolam <clay@woolam.org> # Andreas Mueller <amueller@ais.uni-bonn.de> # Licence: BSD import numpy as np import matplotlib.pyplot as plt from sklearn.semi_supervised import label_propagation from sklearn.datasets import make_circles # generate ring with inner box n_samples = 200 X, y = make_circles(n_samples=n_samples, shuffle=False) outer, inner = 0, 1 labels = -np.ones(n_samples) labels[0] = outer labels[-1] = inner ############################################################################### # Learn with LabelSpreading label_spread = label_propagation.LabelSpreading(kernel='knn', alpha=1.0) label_spread.fit(X, labels) ############################################################################### # Plot output labels output_labels = label_spread.transduction_ plt.figure(figsize=(8.5, 4)) plt.subplot(1, 2, 1) plt.scatter(X[labels == outer, 0], X[labels == outer, 1], color='navy', marker='s', lw=0, label="outer labeled", s=10) plt.scatter(X[labels == inner, 0], X[labels == inner, 1], color='c', marker='s', lw=0, label='inner labeled', s=10) plt.scatter(X[labels == -1, 0], X[labels == -1, 1], color='darkorange', marker='.', label='unlabeled') plt.legend(scatterpoints=1, shadow=False, loc='upper right') plt.title("Raw data (2 classes=outer and inner)") plt.subplot(1, 2, 2) output_label_array = np.asarray(output_labels) outer_numbers = np.where(output_label_array == outer)[0] inner_numbers = np.where(output_label_array == inner)[0] plt.scatter(X[outer_numbers, 0], X[outer_numbers, 1], color='navy', marker='s', lw=0, s=10, label="outer learned") plt.scatter(X[inner_numbers, 0], X[inner_numbers, 1], color='c', marker='s', lw=0, s=10, label="inner learned") plt.legend(scatterpoints=1, shadow=False, loc='upper right') plt.title("Labels learned with Label Spreading (KNN)") plt.subplots_adjust(left=0.07, bottom=0.07, right=0.93, top=0.92) plt.show()
bsd-3-clause
jonyroda97/redbot-amigosprovaveis
lib/raven/middleware.py
3
3675
""" raven.middleware ~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from contextlib import contextmanager from raven._compat import Iterator, next from raven.utils.wsgi import ( get_current_url, get_headers, get_environ) @contextmanager def common_exception_handling(environ, client): try: yield except (StopIteration, GeneratorExit): # Make sure we do this explicitly here. At least GeneratorExit # is handled implicitly by the rest of the logic but we want # to make sure this does not regress raise except Exception: client.handle_exception(environ) raise except KeyboardInterrupt: client.handle_exception(environ) raise except SystemExit as e: if e.code != 0: client.handle_exception(environ) raise class ClosingIterator(Iterator): """ An iterator that is implements a ``close`` method as-per WSGI recommendation. """ def __init__(self, sentry, iterable, environ): self.sentry = sentry self.environ = environ self._close = getattr(iterable, 'close', None) self.iterable = iter(iterable) self.closed = False def __iter__(self): return self def __next__(self): try: with common_exception_handling(self.environ, self.sentry): return next(self.iterable) except StopIteration: # We auto close here if we reach the end because some WSGI # middleware does not really like to close things. To avoid # massive leaks we just close automatically at the end of # iteration. self.close() raise def close(self): if self.closed: return try: if self._close is not None: with common_exception_handling(self.environ, self.sentry): self._close() finally: self.sentry.client.context.clear() self.sentry.client.transaction.clear() self.closed = True class Sentry(object): """ A WSGI middleware which will attempt to capture any uncaught exceptions and send them to Sentry. >>> from raven.base import Client >>> application = Sentry(application, Client()) """ def __init__(self, application, client=None): self.application = application if client is None: from raven.base import Client client = Client() self.client = client def __call__(self, environ, start_response): # TODO(dcramer): ideally this is lazy, but the context helpers must # support callbacks first self.client.http_context(self.get_http_context(environ)) with common_exception_handling(environ, self): iterable = self.application(environ, start_response) return ClosingIterator(self, iterable, environ) def get_http_context(self, environ): return { 'method': environ.get('REQUEST_METHOD'), 'url': get_current_url(environ, strip_querystring=True), 'query_string': environ.get('QUERY_STRING'), # TODO # 'data': environ.get('wsgi.input'), 'headers': dict(get_headers(environ)), 'env': dict(get_environ(environ)), } def process_response(self, request, response): self.client.context.clear() def handle_exception(self, environ=None): return self.client.captureException()
gpl-3.0
JasonCormie/ansible-modules-extras
cloud/vmware/vmware_vmkernel.py
75
7458
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Joseph Callen <jcallen () csc.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' --- module: vmware_vmkernel short_description: Create a VMware VMkernel Interface description: - Create a VMware VMkernel Interface version_added: 2.0 author: "Joseph Callen (@jcpowermac), Russell Teague (@mtnbikenc)" notes: - Tested on vSphere 5.5 requirements: - "python >= 2.6" - PyVmomi options: vswitch_name: description: - The name of the vswitch where to add the VMK interface required: True portgroup_name: description: - The name of the portgroup for the VMK interface required: True ip_address: description: - The IP Address for the VMK interface required: True subnet_mask: description: - The Subnet Mask for the VMK interface required: True vland_id: description: - The VLAN ID for the VMK interface required: True mtu: description: - The MTU for the VMK interface required: False enable_vsan: description: - Enable the VMK interface for VSAN traffic required: False enable_vmotion: description: - Enable the VMK interface for vMotion traffic required: False enable_mgmt: description: - Enable the VMK interface for Management traffic required: False enable_ft: description: - Enable the VMK interface for Fault Tolerance traffic required: False extends_documentation_fragment: vmware.documentation ''' EXAMPLES = ''' # Example command from Ansible Playbook - name: Add Management vmkernel port (vmk1) local_action: module: vmware_vmkernel hostname: esxi_hostname username: esxi_username password: esxi_password vswitch_name: vswitch_name portgroup_name: portgroup_name vlan_id: vlan_id ip_address: ip_address subnet_mask: subnet_mask enable_mgmt: True ''' try: from pyVmomi import vim, vmodl HAS_PYVMOMI = True except ImportError: HAS_PYVMOMI = False def create_vmkernel_adapter(host_system, port_group_name, vlan_id, vswitch_name, ip_address, subnet_mask, mtu, enable_vsan, enable_vmotion, enable_mgmt, enable_ft): host_config_manager = host_system.configManager host_network_system = host_config_manager.networkSystem host_virtual_vic_manager = host_config_manager.virtualNicManager config = vim.host.NetworkConfig() config.portgroup = [vim.host.PortGroup.Config()] config.portgroup[0].changeOperation = "add" config.portgroup[0].spec = vim.host.PortGroup.Specification() config.portgroup[0].spec.name = port_group_name config.portgroup[0].spec.vlanId = vlan_id config.portgroup[0].spec.vswitchName = vswitch_name config.portgroup[0].spec.policy = vim.host.NetworkPolicy() config.vnic = [vim.host.VirtualNic.Config()] config.vnic[0].changeOperation = "add" config.vnic[0].portgroup = port_group_name config.vnic[0].spec = vim.host.VirtualNic.Specification() config.vnic[0].spec.ip = vim.host.IpConfig() config.vnic[0].spec.ip.dhcp = False config.vnic[0].spec.ip.ipAddress = ip_address config.vnic[0].spec.ip.subnetMask = subnet_mask if mtu: config.vnic[0].spec.mtu = mtu host_network_config_result = host_network_system.UpdateNetworkConfig(config, "modify") for vnic_device in host_network_config_result.vnicDevice: if enable_vsan: vsan_system = host_config_manager.vsanSystem vsan_config = vim.vsan.host.ConfigInfo() vsan_config.networkInfo = vim.vsan.host.ConfigInfo.NetworkInfo() vsan_config.networkInfo.port = [vim.vsan.host.ConfigInfo.NetworkInfo.PortConfig()] vsan_config.networkInfo.port[0].device = vnic_device host_vsan_config_result = vsan_system.UpdateVsan_Task(vsan_config) if enable_vmotion: host_virtual_vic_manager.SelectVnicForNicType("vmotion", vnic_device) if enable_mgmt: host_virtual_vic_manager.SelectVnicForNicType("management", vnic_device) if enable_ft: host_virtual_vic_manager.SelectVnicForNicType("faultToleranceLogging", vnic_device) return True def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(portgroup_name=dict(required=True, type='str'), ip_address=dict(required=True, type='str'), subnet_mask=dict(required=True, type='str'), mtu=dict(required=False, type='int'), enable_vsan=dict(required=False, type='bool'), enable_vmotion=dict(required=False, type='bool'), enable_mgmt=dict(required=False, type='bool'), enable_ft=dict(required=False, type='bool'), vswitch_name=dict(required=True, type='str'), vlan_id=dict(required=True, type='int'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') port_group_name = module.params['portgroup_name'] ip_address = module.params['ip_address'] subnet_mask = module.params['subnet_mask'] mtu = module.params['mtu'] enable_vsan = module.params['enable_vsan'] enable_vmotion = module.params['enable_vmotion'] enable_mgmt = module.params['enable_mgmt'] enable_ft = module.params['enable_ft'] vswitch_name = module.params['vswitch_name'] vlan_id = module.params['vlan_id'] try: content = connect_to_api(module) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = host.keys()[0] changed = create_vmkernel_adapter(host_system, port_group_name, vlan_id, vswitch_name, ip_address, subnet_mask, mtu, enable_vsan, enable_vmotion, enable_mgmt, enable_ft) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e)) from ansible.module_utils.vmware import * from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
pottzer/home-assistant
homeassistant/components/modbus.py
10
2759
""" homeassistant.components.modbus ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Modbus component, using pymodbus (python3 branch). Configuration: To use the Modbus component you will need to add something like the following to your configuration.yaml file. #Modbus TCP modbus: type: tcp host: 127.0.0.1 port: 2020 #Modbus RTU modbus: type: serial method: rtu port: /dev/ttyUSB0 baudrate: 9600 stopbits: 1 bytesize: 8 parity: N """ import logging from homeassistant.const import (EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) DOMAIN = "modbus" DEPENDENCIES = [] REQUIREMENTS = ['https://github.com/bashwork/pymodbus/archive/' 'd7fc4f1cc975631e0a9011390e8017f64b612661.zip#pymodbus==1.2.0'] # Type of network MEDIUM = "type" # if MEDIUM == "serial" METHOD = "method" SERIAL_PORT = "port" BAUDRATE = "baudrate" STOPBITS = "stopbits" BYTESIZE = "bytesize" PARITY = "parity" # if MEDIUM == "tcp" or "udp" HOST = "host" IP_PORT = "port" _LOGGER = logging.getLogger(__name__) NETWORK = None TYPE = None def setup(hass, config): """ Setup Modbus component. """ # Modbus connection type # pylint: disable=global-statement, import-error global TYPE TYPE = config[DOMAIN][MEDIUM] # Connect to Modbus network # pylint: disable=global-statement, import-error global NETWORK if TYPE == "serial": from pymodbus.client.sync import ModbusSerialClient as ModbusClient NETWORK = ModbusClient(method=config[DOMAIN][METHOD], port=config[DOMAIN][SERIAL_PORT], baudrate=config[DOMAIN][BAUDRATE], stopbits=config[DOMAIN][STOPBITS], bytesize=config[DOMAIN][BYTESIZE], parity=config[DOMAIN][PARITY]) elif TYPE == "tcp": from pymodbus.client.sync import ModbusTcpClient as ModbusClient NETWORK = ModbusClient(host=config[DOMAIN][HOST], port=config[DOMAIN][IP_PORT]) elif TYPE == "udp": from pymodbus.client.sync import ModbusUdpClient as ModbusClient NETWORK = ModbusClient(host=config[DOMAIN][HOST], port=config[DOMAIN][IP_PORT]) else: return False def stop_modbus(event): """ Stop Modbus service. """ NETWORK.close() def start_modbus(event): """ Start Modbus service. """ NETWORK.connect() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_modbus) hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_modbus) # Tells the bootstrapper that the component was successfully initialized return True
mit
lude-ma/python-ivi
ivi/agilent/agilentDSAX92804A.py
7
1691
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-2014 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .agilent90000 import * class agilentDSAX92804A(agilent90000): "Agilent Infiniium DSAX92804A IVI oscilloscope driver" def __init__(self, *args, **kwargs): self.__dict__.setdefault('_instrument_id', 'DSAX92804A') super(agilentDSAX92804A, self).__init__(*args, **kwargs) self._analog_channel_count = 4 self._digital_channel_count = 0 self._channel_count = self._analog_channel_count + self._digital_channel_count self._bandwidth = 28e9 self._init_channels()
mit
theflofly/tensorflow
tensorflow/contrib/distributions/python/ops/vector_student_t.py
22
10470
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Vector Student's t distribution classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.distributions.python.ops import bijectors from tensorflow.contrib.distributions.python.ops import distribution_util from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops.distributions import student_t from tensorflow.python.ops.distributions import transformed_distribution from tensorflow.python.util import deprecation class _VectorStudentT(transformed_distribution.TransformedDistribution): """A vector version of Student's t-distribution on `R^k`. #### Mathematical details The probability density function (pdf) is, ```none pdf(x; df, mu, Sigma) = (1 + ||y||**2 / df)**(-0.5 (df + 1)) / Z where, y = inv(Sigma) (x - mu) Z = abs(det(Sigma)) ( sqrt(df pi) Gamma(0.5 df) / Gamma(0.5 (df + 1)) )**k ``` where: * `loc = mu`; a vector in `R^k`, * `scale = Sigma`; a lower-triangular matrix in `R^{k x k}`, * `Z` denotes the normalization constant, and, * `Gamma` is the [gamma function]( https://en.wikipedia.org/wiki/Gamma_function), and, * `||y||**2` denotes the [squared Euclidean norm]( https://en.wikipedia.org/wiki/Norm_(mathematics)#Euclidean_norm) of `y`. The VectorStudentT distribution is a member of the [location-scale family]( https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be constructed as, ```none X ~ StudentT(df, loc=0, scale=1) Y = loc + scale * X ``` Notice that the `scale` matrix has semantics closer to std. deviation than covariance (but it is not std. deviation). This distribution is an Affine transformation of iid [Student's t-distributions]( https://en.wikipedia.org/wiki/Student%27s_t-distribution) and should not be confused with the [Multivariate Student's t-distribution]( https://en.wikipedia.org/wiki/Multivariate_t-distribution). The traditional Multivariate Student's t-distribution is type of [elliptical distribution]( https://en.wikipedia.org/wiki/Elliptical_distribution); it has PDF: ```none pdf(x; df, mu, Sigma) = (1 + ||y||**2 / df)**(-0.5 (df + k)) / Z where, y = inv(Sigma) (x - mu) Z = abs(det(Sigma)) sqrt(df pi)**k Gamma(0.5 df) / Gamma(0.5 (df + k)) ``` Notice that the Multivariate Student's t-distribution uses `k` where the Vector Student's t-distribution has a `1`. Conversely the Vector version has a broader application of the power-`k` in the normalization constant. #### Examples A single instance of a "Vector Student's t-distribution" is defined by a mean vector of length `k` and a scale matrix of shape `k x k`. Extra leading dimensions, if provided, allow for batches. ```python import tensorflow_probability as tfp tfd = tfp.distributions # Initialize a single 3-variate vector Student's t-distribution. mu = [1., 2, 3] chol = [[1., 0, 0.], [1, 3, 0], [1, 2, 3]] vt = tfd.VectorStudentT(df=2, loc=mu, scale_tril=chol) # Evaluate this on an observation in R^3, returning a scalar. vt.prob([-1., 0, 1]) # Initialize a batch of two 3-variate vector Student's t-distributions. mu = [[1., 2, 3], [11, 22, 33]] chol = ... # shape 2 x 3 x 3, lower triangular, positive diagonal. vt = tfd.VectorStudentT(loc=mu, scale_tril=chol) # Evaluate this on a two observations, each in R^3, returning a length two # tensor. x = [[-1, 0, 1], [-11, 0, 11]] vt.prob(x) ``` For more examples of how to construct the `scale` matrix, see the `tf.contrib.distributions.bijectors.Affine` docstring. """ @deprecation.deprecated( "2018-10-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.contrib.distributions`.", warn_once=True) def __init__(self, df, loc=None, scale_identity_multiplier=None, scale_diag=None, scale_tril=None, scale_perturb_factor=None, scale_perturb_diag=None, validate_args=False, allow_nan_stats=True, name="VectorStudentT"): """Instantiates the vector Student's t-distributions on `R^k`. The `batch_shape` is the broadcast between `df.batch_shape` and `Affine.batch_shape` where `Affine` is constructed from `loc` and `scale_*` arguments. The `event_shape` is the event shape of `Affine.event_shape`. Args: df: Floating-point `Tensor`. The degrees of freedom of the distribution(s). `df` must contain only positive values. Must be scalar if `loc`, `scale_*` imply non-scalar batch_shape or must have the same `batch_shape` implied by `loc`, `scale_*`. loc: Floating-point `Tensor`. If this is set to `None`, no `loc` is applied. scale_identity_multiplier: floating point rank 0 `Tensor` representing a scaling done to the identity matrix. When `scale_identity_multiplier = scale_diag=scale_tril = None` then `scale += IdentityMatrix`. Otherwise no scaled-identity-matrix is added to `scale`. scale_diag: Floating-point `Tensor` representing the diagonal matrix. `scale_diag` has shape [N1, N2, ..., k], which represents a k x k diagonal matrix. When `None` no diagonal term is added to `scale`. scale_tril: Floating-point `Tensor` representing the diagonal matrix. `scale_diag` has shape [N1, N2, ..., k, k], which represents a k x k lower triangular matrix. When `None` no `scale_tril` term is added to `scale`. The upper triangular elements above the diagonal are ignored. scale_perturb_factor: Floating-point `Tensor` representing factor matrix with last two dimensions of shape `(k, r)`. When `None`, no rank-r update is added to `scale`. scale_perturb_diag: Floating-point `Tensor` representing the diagonal matrix. `scale_perturb_diag` has shape [N1, N2, ..., r], which represents an r x r Diagonal matrix. When `None` low rank updates will take the form `scale_perturb_factor * scale_perturb_factor.T`. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. """ parameters = dict(locals()) graph_parents = [df, loc, scale_identity_multiplier, scale_diag, scale_tril, scale_perturb_factor, scale_perturb_diag] with ops.name_scope(name) as name: with ops.name_scope("init", values=graph_parents): # The shape of the _VectorStudentT distribution is governed by the # relationship between df.batch_shape and affine.batch_shape. In # pseudocode the basic procedure is: # if df.batch_shape is scalar: # if affine.batch_shape is not scalar: # # broadcast distribution.sample so # # it has affine.batch_shape. # self.batch_shape = affine.batch_shape # else: # if affine.batch_shape is scalar: # # let affine broadcasting do its thing. # self.batch_shape = df.batch_shape # All of the above magic is actually handled by TransformedDistribution. # Here we really only need to collect the affine.batch_shape and decide # what we're going to pass in to TransformedDistribution's # (override) batch_shape arg. affine = bijectors.Affine( shift=loc, scale_identity_multiplier=scale_identity_multiplier, scale_diag=scale_diag, scale_tril=scale_tril, scale_perturb_factor=scale_perturb_factor, scale_perturb_diag=scale_perturb_diag, validate_args=validate_args) distribution = student_t.StudentT( df=df, loc=array_ops.zeros([], dtype=affine.dtype), scale=array_ops.ones([], dtype=affine.dtype)) batch_shape, override_event_shape = ( distribution_util.shapes_from_loc_and_scale( affine.shift, affine.scale)) override_batch_shape = distribution_util.pick_vector( distribution.is_scalar_batch(), batch_shape, constant_op.constant([], dtype=dtypes.int32)) super(_VectorStudentT, self).__init__( distribution=distribution, bijector=affine, batch_shape=override_batch_shape, event_shape=override_event_shape, validate_args=validate_args, name=name) self._parameters = parameters @property def df(self): """Degrees of freedom in these Student's t distribution(s).""" return self.distribution.df @property def loc(self): """Locations of these Student's t distribution(s).""" return self.bijector.shift @property def scale(self): """Dense (batch) covariance matrix, if available.""" return self.bijector.scale
apache-2.0
mjnowen/mjnowen-anim-studio-tools
sherman/www/lib/template.py
5
1571
import os import cherrypy from genshi.core import Stream from genshi.output import encode, get_serializer from genshi.template import Context, TemplateLoader from lib import ajax loader = TemplateLoader( os.path.join(os.path.dirname(__file__), '..', 'templates'), auto_reload=True ) def output(filename, method='html', encoding='utf-8', **options): """Decorator for exposed methods to specify what template they should use for rendering, and which serialization method and options should be applied. """ def decorate(func): def wrapper(*args, **kwargs): cherrypy.thread_data.template = loader.load(filename) opt = options.copy() if not ajax.is_xhr() and method == 'html': opt.setdefault('doctype', 'html') serializer = get_serializer(method, **opt) stream = func(*args, **kwargs) if not isinstance(stream, Stream): return stream return encode(serializer(stream), method=serializer, encoding=encoding) return wrapper return decorate def render(*args, **kwargs): """Function to render the given data to the template specified via the ``@output`` decorator. """ if args: assert len(args) == 1, \ 'Expected exactly one argument, but got %r' % (args,) template = loader.load(args[0]) else: template = cherrypy.thread_data.template ctxt = Context(url=cherrypy.url) ctxt.push(kwargs) return template.generate(ctxt)
gpl-3.0
lmr/autotest
database_legacy/migrations/058_drone_management.py
16
1979
UP_SQL = """ CREATE TABLE afe_drones ( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, hostname VARCHAR(255) NOT NULL ) ENGINE=InnoDB; ALTER TABLE afe_drones ADD CONSTRAINT afe_drones_unique UNIQUE KEY (hostname); CREATE TABLE afe_drone_sets ( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, name VARCHAR(255) NOT NULL ) ENGINE=InnoDB; ALTER TABLE afe_drone_sets ADD CONSTRAINT afe_drone_sets_unique UNIQUE KEY (name); CREATE TABLE afe_drone_sets_drones ( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, droneset_id INT NOT NULL, drone_id INT NOT NULL ) ENGINE=InnoDB; ALTER TABLE afe_drone_sets_drones ADD CONSTRAINT afe_drone_sets_drones_droneset_ibfk FOREIGN KEY (droneset_id) REFERENCES afe_drone_sets (id); ALTER TABLE afe_drone_sets_drones ADD CONSTRAINT afe_drone_sets_drones_drone_ibfk FOREIGN KEY (drone_id) REFERENCES afe_drones (id); ALTER TABLE afe_drone_sets_drones ADD CONSTRAINT afe_drone_sets_drones_unique UNIQUE KEY (droneset_id, drone_id); ALTER TABLE afe_jobs ADD COLUMN drone_set_id INT; ALTER TABLE afe_jobs ADD CONSTRAINT afe_jobs_drone_set_ibfk FOREIGN KEY (drone_set_id) REFERENCES afe_drone_sets (id); ALTER TABLE afe_users ADD COLUMN drone_set_id INT; ALTER TABLE afe_users ADD CONSTRAINT afe_users_drone_set_ibfk FOREIGN KEY (drone_set_id) REFERENCES afe_drone_sets (id); UPDATE afe_special_tasks SET requested_by_id = ( SELECT id FROM afe_users WHERE login = 'autotest_system') WHERE requested_by_id IS NULL; ALTER TABLE afe_special_tasks MODIFY COLUMN requested_by_id INT NOT NULL; """ DOWN_SQL = """ ALTER TABLE afe_special_tasks MODIFY COLUMN requested_by_id INT DEFAULT NULL; ALTER TABLE afe_users DROP FOREIGN KEY afe_users_drone_set_ibfk; ALTER TABLE afe_users DROP COLUMN drone_set_id; ALTER TABLE afe_jobs DROP FOREIGN KEY afe_jobs_drone_set_ibfk; ALTER TABLE afe_jobs DROP COLUMN drone_set_id; DROP TABLE IF EXISTS afe_drone_sets_drones; DROP TABLE IF EXISTS afe_drone_sets; DROP TABLE IF EXISTS afe_drones; """
gpl-2.0
yoseforb/lollypop
src/pop_infos.py
1
5999
#!/usr/bin/python # Copyright (c) 2014-2015 Cedric Bellegarde <cedric.bellegarde@adishatz.org> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gtk, GLib, Gio, GdkPixbuf from _thread import start_new_thread import urllib.request from gettext import gettext as _ from lollypop.define import Lp # Show ArtistInfos in a popover class InfosPopover(Gtk.Popover): """ Init popover @param artist id as int @param track id as int """ def __init__(self, artist_id, track_id=None): Gtk.Popover.__init__(self) self._infos = ArtistInfos(artist_id, track_id) self._infos.show() self.add(self._infos) """ Populate view """ def populate(self): self._infos.populate() """ Resize popover and set signals callback """ def do_show(self): size_setting = Lp.settings.get_value('window-size') if isinstance(size_setting[1], int): self.set_size_request(700, size_setting[1]*0.5) else: self.set_size_request(700, 400) Gtk.Popover.do_show(self) """ Preferred width """ def do_get_preferred_width(self): return (700, 700) # Show artist informations from lastfm class ArtistInfos(Gtk.Bin): """ Init artist infos @param artist as str @param title as str """ def __init__(self, artist, title=None): Gtk.Bin.__init__(self) self._artist = artist self._title = title self._stack = Gtk.Stack() self._stack.set_property('expand', True) self._stack.show() builder = Gtk.Builder() builder.add_from_resource('/org/gnome/Lollypop/ArtistInfos.ui') builder.connect_signals(self) widget = builder.get_object('widget') widget.attach(self._stack, 0, 2, 4, 1) if title is not None and Lp.lastfm.is_auth(): builder.get_object('love_btn').show() builder.get_object('unlove_btn').show() self._url_btn = builder.get_object('lastfm') self._image = builder.get_object('image') self._content = builder.get_object('content') self._label = builder.get_object('label') self._label.set_text(_("Please wait...")) self._scrolled = builder.get_object('scrolled') self._spinner = builder.get_object('spinner') self._not_found = builder.get_object('notfound') self._stack.add(self._spinner) self._stack.add(self._not_found) self._stack.add(self._scrolled) self._stack.set_visible_child(self._spinner) self.add(widget) """ Populate informations and artist image """ def populate(self): start_new_thread(self._populate, ()) ####################### # PRIVATE # ####################### """ Same as _populate() @thread safe """ def _populate(self): (url, image_url, content) = Lp.lastfm.get_artist_infos(self._artist) stream = None try: response = None if image_url is not None: response = urllib.request.urlopen(image_url) if response is not None: stream = Gio.MemoryInputStream.new_from_data(response.read(), None) except Exception as e: print("PopArtistInfos::_populate: %s" % e) content = None GLib.idle_add(self._set_content, content, url, stream) """ Set content on view @param content as str @param url as str @param stream as Gio.MemoryInputStream """ def _set_content(self, content, url, stream): if content is not None: self._stack.set_visible_child(self._scrolled) self._label.set_text(self._artist) self._url_btn.set_uri(url) self._content.set_text(content) else: self._stack.set_visible_child(self._not_found) self._label.set_text(_("No information for this artist...")) if stream is not None: pixbuf = GdkPixbuf.Pixbuf.new_from_stream(stream, None) self._image.set_from_pixbuf(pixbuf) del pixbuf """ Love a track @param btn as Gtk.Button """ def _on_love_btn_clicked(self, btn): if Gio.NetworkMonitor.get_default().get_network_available() and\ Lp.lastfm.is_auth(): start_new_thread(self._love_track, ()) btn.set_sensitive(False) """ Love a track """ def _love_track(self): track = Lp.lastfm.get_track(self._artist, self._title) try: track.love() except: GLib.idle_add(Lp.notify.send, _("Wrong Last.fm credentials")) """ Unlove a track @param btn as Gtk.Button """ def _on_unlove_btn_clicked(self, btn): if Gio.NetworkMonitor.get_default().get_network_available() and\ Lp.lastfm.is_auth(): start_new_thread(self._unlove_track, ()) btn.set_sensitive(False) """ Unlove a track """ def _unlove_track(self): track = Lp.lastfm.get_track(self._artist, self._title) try: track.unlove() except: GLib.idle_add(Lp.notify.send, _("Wrong Last.fm credentials"))
gpl-3.0
normtown/SickRage
lib/fanart/core.py
60
1256
import requests import fanart from fanart.errors import RequestFanartError, ResponseFanartError class Request(object): def __init__(self, apikey, id, ws, type=None, sort=None, limit=None): self._apikey = apikey self._id = id self._ws = ws self._type = type or fanart.TYPE.ALL self._sort = sort or fanart.SORT.POPULAR self._limit = limit or fanart.LIMIT.ALL self.validate() self._response = None def validate(self): for attribute_name in ('ws', 'type', 'sort', 'limit'): attribute = getattr(self, '_' + attribute_name) choices = getattr(fanart, attribute_name.upper() + '_LIST') if attribute not in choices: raise RequestFanartError('Not allowed {0}: {1} [{2}]'.format(attribute_name, attribute, ', '.join(choices))) def __str__(self): return fanart.BASEURL % (self._ws, self._id, self._apikey) def response(self): try: response = requests.get(str(self)) rjson = response.json() if not isinstance(rjson, dict): raise Exception(response.text) return rjson except Exception as e: raise ResponseFanartError(str(e))
gpl-3.0
hellysmile/aiohttp
aiohttp/web_app.py
2
10119
import asyncio import warnings from collections import MutableMapping from functools import partial from . import hdrs from .abc import AbstractAccessLogger, AbstractMatchInfo, AbstractRouter from .frozenlist import FrozenList from .helpers import AccessLogger from .log import web_logger from .signals import Signal from .web_middlewares import _fix_request_current_app from .web_request import Request from .web_response import StreamResponse from .web_server import Server from .web_urldispatcher import PrefixedSubAppResource, UrlDispatcher __all__ = ('Application',) class Application(MutableMapping): ATTRS = frozenset([ 'logger', '_debug', '_router', '_loop', '_handler_args', '_middlewares', '_middlewares_handlers', '_run_middlewares', '_state', '_frozen', '_subapps', '_on_response_prepare', '_on_startup', '_on_shutdown', '_on_cleanup', '_client_max_size']) def __init__(self, *, logger=web_logger, router=None, middlewares=(), handler_args=None, client_max_size=1024**2, loop=None, debug=...): if router is None: router = UrlDispatcher() assert isinstance(router, AbstractRouter), router if loop is not None: warnings.warn("loop argument is deprecated", DeprecationWarning, stacklevel=2) self._debug = debug self._router = router self._loop = loop self._handler_args = handler_args self.logger = logger self._middlewares = FrozenList(middlewares) self._middlewares_handlers = None # initialized on freezing self._run_middlewares = None # initialized on freezing self._state = {} self._frozen = False self._subapps = [] self._on_response_prepare = Signal(self) self._on_startup = Signal(self) self._on_shutdown = Signal(self) self._on_cleanup = Signal(self) self._client_max_size = client_max_size def __init_subclass__(cls): warnings.warn("Inheritance class {} from web.Application " "is discouraged".format(cls.__name__), DeprecationWarning, stacklevel=2) def __setattr__(self, name, val): if name not in self.ATTRS: warnings.warn("Setting custom web.Application.{} attribute " "is discouraged".format(name), DeprecationWarning, stacklevel=2) super().__setattr__(name, val) # MutableMapping API def __eq__(self, other): return self is other def __getitem__(self, key): return self._state[key] def _check_frozen(self): if self._frozen: warnings.warn("Changing state of started or joined " "application is deprecated", DeprecationWarning, stacklevel=3) def __setitem__(self, key, value): self._check_frozen() self._state[key] = value def __delitem__(self, key): self._check_frozen() del self._state[key] def __len__(self): return len(self._state) def __iter__(self): return iter(self._state) ######## @property def loop(self): return self._loop def _set_loop(self, loop): if loop is None: loop = asyncio.get_event_loop() if self._loop is not None and self._loop is not loop: raise RuntimeError( "web.Application instance initialized with different loop") self._loop = loop # set loop debug if self._debug is ...: self._debug = loop.get_debug() # set loop to sub applications for subapp in self._subapps: subapp._set_loop(loop) @property def frozen(self): return self._frozen def freeze(self): if self._frozen: return self._frozen = True self._middlewares.freeze() self._router.freeze() self._on_response_prepare.freeze() self._on_startup.freeze() self._on_shutdown.freeze() self._on_cleanup.freeze() self._middlewares_handlers = tuple(self._prepare_middleware()) # If current app and any subapp do not have middlewares avoid run all # of the code footprint that it implies, which have a middleware # hardcoded per app that sets up the current_app attribute. If no # middlewares are configured the handler will receive the proper # current_app without needing all of this code. self._run_middlewares = True if self.middlewares else False for subapp in self._subapps: subapp.freeze() self._run_middlewares =\ self._run_middlewares or subapp._run_middlewares @property def debug(self): return self._debug def _reg_subapp_signals(self, subapp): def reg_handler(signame): subsig = getattr(subapp, signame) async def handler(app): await subsig.send(subapp) appsig = getattr(self, signame) appsig.append(handler) reg_handler('on_startup') reg_handler('on_shutdown') reg_handler('on_cleanup') def add_subapp(self, prefix, subapp): if self.frozen: raise RuntimeError( "Cannot add sub application to frozen application") if subapp.frozen: raise RuntimeError("Cannot add frozen application") if prefix.endswith('/'): prefix = prefix[:-1] if prefix in ('', '/'): raise ValueError("Prefix cannot be empty") resource = PrefixedSubAppResource(prefix, subapp) self.router.register_resource(resource) self._reg_subapp_signals(subapp) self._subapps.append(subapp) subapp.freeze() if self._loop is not None: subapp._set_loop(self._loop) return resource @property def on_response_prepare(self): return self._on_response_prepare @property def on_startup(self): return self._on_startup @property def on_shutdown(self): return self._on_shutdown @property def on_cleanup(self): return self._on_cleanup @property def router(self): return self._router @property def middlewares(self): return self._middlewares def make_handler(self, *, loop=None, access_log_class=AccessLogger, **kwargs): if not issubclass(access_log_class, AbstractAccessLogger): raise TypeError( 'access_log_class must be subclass of ' 'aiohttp.abc.AbstractAccessLogger, got {}'.format( access_log_class)) self._set_loop(loop) self.freeze() kwargs['debug'] = self.debug if self._handler_args: for k, v in self._handler_args.items(): kwargs[k] = v return Server(self._handle, request_factory=self._make_request, access_log_class=access_log_class, loop=self.loop, **kwargs) async def startup(self): """Causes on_startup signal Should be called in the event loop along with the request handler. """ await self.on_startup.send(self) async def shutdown(self): """Causes on_shutdown signal Should be called before cleanup() """ await self.on_shutdown.send(self) async def cleanup(self): """Causes on_cleanup signal Should be called after shutdown() """ await self.on_cleanup.send(self) def _make_request(self, message, payload, protocol, writer, task, _cls=Request): return _cls( message, payload, protocol, writer, task, self._loop, client_max_size=self._client_max_size) def _prepare_middleware(self): for m in reversed(self._middlewares): if getattr(m, '__middleware_version__', None) == 1: yield m, True else: warnings.warn('old-style middleware "{!r}" deprecated, ' 'see #2252'.format(m), DeprecationWarning, stacklevel=2) yield m, False yield _fix_request_current_app(self), True async def _handle(self, request): match_info = await self._router.resolve(request) assert isinstance(match_info, AbstractMatchInfo), match_info match_info.add_app(self) if __debug__: match_info.freeze() resp = None request._match_info = match_info expect = request.headers.get(hdrs.EXPECT) if expect: resp = await match_info.expect_handler(request) await request.writer.drain() if resp is None: handler = match_info.handler if self._run_middlewares: for app in match_info.apps[::-1]: for m, new_style in app._middlewares_handlers: if new_style: handler = partial(m, handler=handler) else: handler = await m(app, handler) resp = await handler(request) assert isinstance(resp, StreamResponse), \ ("Handler {!r} should return response instance, " "got {!r} [middlewares {!r}]").format( match_info.handler, type(resp), [middleware for app in match_info.apps for middleware in app.middlewares]) return resp def __call__(self): """gunicorn compatibility""" return self def __repr__(self): return "<Application 0x{:x}>".format(id(self))
apache-2.0
Fireblend/scikit-learn
sklearn/feature_extraction/tests/test_dict_vectorizer.py
276
3790
# Authors: Lars Buitinck <L.J.Buitinck@uva.nl> # Dan Blanchard <dblanchard@ets.org> # License: BSD 3 clause from random import Random import numpy as np import scipy.sparse as sp from numpy.testing import assert_array_equal from sklearn.utils.testing import (assert_equal, assert_in, assert_false, assert_true) from sklearn.feature_extraction import DictVectorizer from sklearn.feature_selection import SelectKBest, chi2 def test_dictvectorizer(): D = [{"foo": 1, "bar": 3}, {"bar": 4, "baz": 2}, {"bar": 1, "quux": 1, "quuux": 2}] for sparse in (True, False): for dtype in (int, np.float32, np.int16): for sort in (True, False): for iterable in (True, False): v = DictVectorizer(sparse=sparse, dtype=dtype, sort=sort) X = v.fit_transform(iter(D) if iterable else D) assert_equal(sp.issparse(X), sparse) assert_equal(X.shape, (3, 5)) assert_equal(X.sum(), 14) assert_equal(v.inverse_transform(X), D) if sparse: # CSR matrices can't be compared for equality assert_array_equal(X.A, v.transform(iter(D) if iterable else D).A) else: assert_array_equal(X, v.transform(iter(D) if iterable else D)) if sort: assert_equal(v.feature_names_, sorted(v.feature_names_)) def test_feature_selection(): # make two feature dicts with two useful features and a bunch of useless # ones, in terms of chi2 d1 = dict([("useless%d" % i, 10) for i in range(20)], useful1=1, useful2=20) d2 = dict([("useless%d" % i, 10) for i in range(20)], useful1=20, useful2=1) for indices in (True, False): v = DictVectorizer().fit([d1, d2]) X = v.transform([d1, d2]) sel = SelectKBest(chi2, k=2).fit(X, [0, 1]) v.restrict(sel.get_support(indices=indices), indices=indices) assert_equal(v.get_feature_names(), ["useful1", "useful2"]) def test_one_of_k(): D_in = [{"version": "1", "ham": 2}, {"version": "2", "spam": .3}, {"version=3": True, "spam": -1}] v = DictVectorizer() X = v.fit_transform(D_in) assert_equal(X.shape, (3, 5)) D_out = v.inverse_transform(X) assert_equal(D_out[0], {"version=1": 1, "ham": 2}) names = v.get_feature_names() assert_true("version=2" in names) assert_false("version" in names) def test_unseen_or_no_features(): D = [{"camelot": 0, "spamalot": 1}] for sparse in [True, False]: v = DictVectorizer(sparse=sparse).fit(D) X = v.transform({"push the pram a lot": 2}) if sparse: X = X.toarray() assert_array_equal(X, np.zeros((1, 2))) X = v.transform({}) if sparse: X = X.toarray() assert_array_equal(X, np.zeros((1, 2))) try: v.transform([]) except ValueError as e: assert_in("empty", str(e)) def test_deterministic_vocabulary(): # Generate equal dictionaries with different memory layouts items = [("%03d" % i, i) for i in range(1000)] rng = Random(42) d_sorted = dict(items) rng.shuffle(items) d_shuffled = dict(items) # check that the memory layout does not impact the resulting vocabulary v_1 = DictVectorizer().fit([d_sorted]) v_2 = DictVectorizer().fit([d_shuffled]) assert_equal(v_1.vocabulary_, v_2.vocabulary_)
bsd-3-clause
nanolearningllc/edx-platform-cypress-2
common/lib/xmodule/xmodule/library_tools.py
154
7784
""" XBlock runtime services for LibraryContentModule """ from django.core.exceptions import PermissionDenied from opaque_keys.edx.locator import LibraryLocator, LibraryUsageLocator from search.search_engine_base import SearchEngine from xmodule.library_content_module import ANY_CAPA_TYPE_VALUE from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.capa_module import CapaDescriptor def normalize_key_for_search(library_key): """ Normalizes library key for use with search indexing """ return library_key.replace(version_guid=None, branch=None) class LibraryToolsService(object): """ Service that allows LibraryContentModule to interact with libraries in the modulestore. """ def __init__(self, modulestore): self.store = modulestore def _get_library(self, library_key): """ Given a library key like "library-v1:ProblemX+PR0B", return the 'library' XBlock with meta-information about the library. A specific version may be specified. Returns None on error. """ if not isinstance(library_key, LibraryLocator): library_key = LibraryLocator.from_string(library_key) try: return self.store.get_library( library_key, remove_version=False, remove_branch=False, head_validation=False ) except ItemNotFoundError: return None def get_library_version(self, lib_key): """ Get the version (an ObjectID) of the given library. Returns None if the library does not exist. """ library = self._get_library(lib_key) if library: # We need to know the library's version so ensure it's set in library.location.library_key.version_guid assert library.location.library_key.version_guid is not None return library.location.library_key.version_guid return None def create_block_analytics_summary(self, course_key, block_keys): """ Given a CourseKey and a list of (block_type, block_id) pairs, prepare the JSON-ready metadata needed for analytics logging. This is [ {"usage_key": x, "original_usage_key": y, "original_usage_version": z, "descendants": [...]} ] where the main list contains all top-level blocks, and descendants contains a *flat* list of all descendants of the top level blocks, if any. """ def summarize_block(usage_key): """ Basic information about the given block """ orig_key, orig_version = self.store.get_block_original_usage(usage_key) return { "usage_key": unicode(usage_key), "original_usage_key": unicode(orig_key) if orig_key else None, "original_usage_version": unicode(orig_version) if orig_version else None, } result_json = [] for block_key in block_keys: key = course_key.make_usage_key(*block_key) info = summarize_block(key) info['descendants'] = [] try: block = self.store.get_item(key, depth=None) # Load the item and all descendants children = list(getattr(block, "children", [])) while children: child_key = children.pop() child = self.store.get_item(child_key) info['descendants'].append(summarize_block(child_key)) children.extend(getattr(child, "children", [])) except ItemNotFoundError: pass # The block has been deleted result_json.append(info) return result_json def _problem_type_filter(self, library, capa_type): """ Filters library children by capa type""" search_engine = SearchEngine.get_search_engine(index="library_index") if search_engine: filter_clause = { "library": unicode(normalize_key_for_search(library.location.library_key)), "content_type": CapaDescriptor.INDEX_CONTENT_TYPE, "problem_types": capa_type } search_result = search_engine.search(field_dictionary=filter_clause) results = search_result.get('results', []) return [LibraryUsageLocator.from_string(item['data']['id']) for item in results] else: return [key for key in library.children if self._filter_child(key, capa_type)] def _filter_child(self, usage_key, capa_type): """ Filters children by CAPA problem type, if configured """ if usage_key.block_type != "problem": return False descriptor = self.store.get_item(usage_key, depth=0) assert isinstance(descriptor, CapaDescriptor) return capa_type in descriptor.problem_types def can_use_library_content(self, block): """ Determines whether a modulestore holding a course_id supports libraries. """ return self.store.check_supports(block.location.course_key, 'copy_from_template') def update_children(self, dest_block, user_id, user_perms=None, version=None): """ This method is to be used when the library that a LibraryContentModule references has been updated. It will re-fetch all matching blocks from the libraries, and copy them as children of dest_block. The children will be given new block_ids, but the definition ID used should be the exact same definition ID used in the library. This method will update dest_block's 'source_library_version' field to store the version number of the libraries used, so we easily determine if dest_block is up to date or not. """ if user_perms and not user_perms.can_write(dest_block.location.course_key): raise PermissionDenied() if not dest_block.source_library_id: dest_block.source_library_version = "" return source_blocks = [] library_key = dest_block.source_library_key if version: library_key = library_key.replace(branch=ModuleStoreEnum.BranchName.library, version_guid=version) library = self._get_library(library_key) if library is None: raise ValueError("Requested library not found.") if user_perms and not user_perms.can_read(library_key): raise PermissionDenied() filter_children = (dest_block.capa_type != ANY_CAPA_TYPE_VALUE) if filter_children: # Apply simple filtering based on CAPA problem types: source_blocks.extend(self._problem_type_filter(library, dest_block.capa_type)) else: source_blocks.extend(library.children) with self.store.bulk_operations(dest_block.location.course_key): dest_block.source_library_version = unicode(library.location.library_key.version_guid) self.store.update_item(dest_block, user_id) head_validation = not version dest_block.children = self.store.copy_from_template( source_blocks, dest_block.location, user_id, head_validation=head_validation ) # ^-- copy_from_template updates the children in the DB # but we must also set .children here to avoid overwriting the DB again def list_available_libraries(self): """ List all known libraries. Returns tuples of (LibraryLocator, display_name) """ return [ (lib.location.library_key.replace(version_guid=None, branch=None), lib.display_name) for lib in self.store.get_libraries() ]
agpl-3.0
timm/timmnix
pypy3-v5.5.0-linux64/lib-python/3/ipaddress.py
2
70303
# Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. """A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ __version__ = '1.0' import functools IPV4LENGTH = 32 IPV6LENGTH = 128 class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A Value Error related to the netmask.""" def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address) def ip_network(address, strict=True): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set. """ try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address) def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address) def v4_int_to_packed(address): """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an IPv4 IP address. """ try: return address.to_bytes(4, 'big') except: raise ValueError("Address negative or too large for IPv4") def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return address.to_bytes(16, 'big') except: raise ValueError("Address negative or too large for IPv6") def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr def _find_address_range(addresses): """Find a sequence of IPv#Address. Args: addresses: a list of IPv#Address objects. Returns: A tuple containing the first and last IP addresses in the sequence. """ first = last = addresses[0] for ip in addresses[1:]: if ip._ip == last._ip + 1: last = ip else: break return (first, last) def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits for i in range(bits): if (number >> i) & 1: return i # All bits of interest were zero, even if there are more in the number return bits def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')] Args: first: the first IPv4Address or IPv6Address in the range. last: the last IPv4Address or IPv6Address in the range. Returns: An iterator of the summarized IPv(4|6) network objects. Raise: TypeError: If the first and last objects are not IP addresses. If the first and last objects are not the same version. ValueError: If the last object is not greater than the first. If the version of the first address is not 4 or 6. """ if (not (isinstance(first, _BaseAddress) and isinstance(last, _BaseAddress))): raise TypeError('first and last must be IP addresses, not networks') if first.version != last.version: raise TypeError("%s and %s are not of the same version" % ( first, last)) if first > last: raise ValueError('last IP address must be greater than first') if first.version == 4: ip = IPv4Network elif first.version == 6: ip = IPv6Network else: raise ValueError('unknown IP version') ip_bits = first._max_prefixlen first_int = first._ip last_int = last._ip while first_int <= last_int: nbits = min(_count_righthand_zero_bits(first_int, ip_bits), (last_int - first_int + 1).bit_length() - 1) net = ip('%s/%d' % (first, ip_bits - nbits)) yield net first_int += 1 << nbits if first_int - 1 == ip._ALL_ONES: break first = first.__class__(first_int) def _collapse_addresses_recursive(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ while True: last_addr = None ret_array = [] optimized = False for cur_addr in addresses: if not ret_array: last_addr = cur_addr ret_array.append(cur_addr) elif (cur_addr.network_address >= last_addr.network_address and cur_addr.broadcast_address <= last_addr.broadcast_address): optimized = True elif cur_addr == list(last_addr.supernet().subnets())[1]: ret_array[-1] = last_addr = last_addr.supernet() optimized = True else: last_addr = cur_addr ret_array.append(cur_addr) addresses = ret_array if not optimized: return addresses def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects. """ i = 0 addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) nets = sorted(set(nets)) while i < len(ips): (first, last) = _find_address_range(ips[i:]) i = ips.index(last) + 1 addrs.extend(summarize_address_range(first, last)) return iter(_collapse_addresses_recursive(sorted( addrs + nets, key=_BaseNetwork._get_networks_key))) def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented class _TotalOrderingMixin: # Helper that derives the other comparison operations from # __lt__ and __eq__ # We avoid functools.total_ordering because it doesn't handle # NotImplemented correctly yet (http://bugs.python.org/issue10042) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not equal def __lt__(self, other): raise NotImplementedError def __le__(self, other): less = self.__lt__(other) if less is NotImplemented or not less: return self.__eq__(other) return less def __gt__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not (less or equal) def __ge__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented return not less class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return str(self) @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = "%r (len %d != %d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, address_len, expected_len, self._version)) def _ip_int_from_prefix(self, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen) def _prefix_from_ip_int(self, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in axpanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, self._max_prefixlen) prefixlen = self._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = self._max_prefixlen // 8 details = ip_int.to_bytes(byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen def _report_invalid_netmask(self, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) from None def _prefix_from_prefix_string(self, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): self._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: self._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= self._max_prefixlen): self._report_invalid_netmask(prefixlen_str) return prefixlen def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: self._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except ValueError: self._report_invalid_netmask(ip_str) class _BaseAddress(_IPAddressBase): """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. """ def __init__(self, address): if (not isinstance(address, bytes) and '/' in str(address)): raise AddressValueError("Unexpected '/' in %r" % address) def __int__(self): return self._ip def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except AttributeError: return NotImplemented def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseAddress): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self._ip != other._ip: return self._ip < other._ip return False # Shorthand for Integer addition and subtraction. This is not # meant to ever support addition/subtraction of addresses. def __add__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) + other) def __sub__(self, other): if not isinstance(other, int): return NotImplemented return self.__class__(int(self) - other) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return str(self._string_from_ip_int(self._ip)) def __hash__(self): return hash(hex(int(self._ip))) def _get_address_key(self): return (self._version, self) class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address): raise ValueError('%s not contained in %s' % (other, self)) if other == self: raise StopIteration # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if (other.network_address >= s1.network_address and other.broadcast_address <= s1.broadcast_address): yield s2 s1, s2 = s1.subnets() elif (other.network_address >= s2.network_address and other.broadcast_address <= s2.broadcast_address): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) first = self.__class__('%s/%s' % (self.network_address, self._prefixlen + prefixlen_diff)) yield first current = first while True: broadcast = current.broadcast_address if broadcast == self.broadcast_address: return new_addr = self._address_class(int(broadcast) + 1) current = self.__class__('%s/%s' % (new_addr, new_prefixlen)) yield current def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix if self.prefixlen - prefixlen_diff < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) # TODO (pmoody): optimize this. t = self.__class__('%s/%d' % (self.network_address, self.prefixlen - prefixlen_diff), strict=False) return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 4193. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback) class _BaseV4: """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2**IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0)) def __init__(self, address): self._version = 4 self._max_prefixlen = IPV4LENGTH def _explode_shorthand_ip_string(self): return str(self) def _ip_int_from_string(self, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return int.from_bytes(map(self._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) from None def _parse_octet(self, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int def _string_from_ip_int(self, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(map(str, ip_int.to_bytes(4, 'big'))) def _is_valid_netmask(self, netmask): """Verify that the netmask is valid. Args: netmask: A string, either a prefix or dotted decimal netmask. Returns: A boolean, True if the prefix represents a valid IPv4 netmask. """ mask = netmask.split('.') if len(mask) == 4: try: for x in mask: if int(x) not in self._valid_mask_octets: return False except ValueError: # Found something that isn't an integer or isn't valid return False for idx, y in enumerate(mask): if idx > 0 and y > mask[idx - 1]: return False return True try: netmask = int(netmask) except ValueError: return False return 0 <= netmask <= self._max_prefixlen def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv4Address(_BaseV4, _BaseAddress): """Represent and manipulate single IPv4 Addresses.""" def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ _BaseAddress.__init__(self, address) _BaseV4.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) self._ip = int.from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ reserved_network = IPv4Network('240.0.0.0/4') return self in reserved_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 1918. """ private_10 = IPv4Network('10.0.0.0/8') private_172 = IPv4Network('172.16.0.0/12') private_192 = IPv4Network('192.168.0.0/16') return (self in private_10 or self in private_172 or self in private_192) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details. """ multicast_network = IPv4Network('224.0.0.0/4') return self in multicast_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3. """ unspecified_address = IPv4Address('0.0.0.0') return self == unspecified_address @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. """ loopback_network = IPv4Network('127.0.0.0/8') return self in loopback_network @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. """ linklocal_network = IPv4Network('169.254.0.0/16') return self in linklocal_network class IPv4Interface(IPv4Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv4Address.__init__(self, address) self.network = IPv4Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv4Address.__init__(self, addr[0]) self.network = IPv4Network(address, strict=False) self._prefixlen = self.network._prefixlen self.netmask = self.network.netmask self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv4Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv4Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv4Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) class IPv4Network(_BaseV4, _BaseNetwork): """This class represents and manipulates 32-bit IPv4 network + addresses.. Attributes: [examples for IPv4Network('192.0.2.0/27')] .network_address: IPv4Address('192.0.2.0') .hostmask: IPv4Address('0.0.0.31') .broadcast_address: IPv4Address('192.0.2.32') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27 """ # Class to use when creating address objects _address_class = IPv4Address def __init__(self, address, strict=True): """Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. '192.0.2.0/24' '192.0.2.0/255.255.255.0' '192.0.0.2/0.0.0.255' are all functionally the same in IPv4. Similarly, '192.0.2.1' '192.0.2.1/255.255.255.255' '192.0.2.1/32' are also functionally equivalent. That is to say, failing to provide a subnetmask will create an object with a mask of /32. If the mask (portion after the / in the argument) is given in dotted quad form, it is treated as a netmask if it starts with a non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it starts with a zero field (e.g. 0.255.255.255 == /8), with the single exception of an all-zero mask which is treated as a netmask == /0. If no mask is given, a default of /32 is used. Additionally, an integer can be passed, so IPv4Network('192.0.2.1') == IPv4Network(3221225985) or, more generally IPv4Interface(int(IPv4Interface('192.0.2.1'))) == IPv4Interface('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict is True and a network address is not supplied. """ _BaseV4.__init__(self, address) _BaseNetwork.__init__(self, address) # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here return # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv4Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ALL_ONES) #fixme: address/network test here. return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: try: # Check for a netmask in prefix length form self._prefixlen = self._prefix_from_prefix_string(addr[1]) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. self._prefixlen = self._prefix_from_ip_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv4Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv4Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ class _BaseV6: """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. """ _ALL_ONES = (2**IPV6LENGTH) - 1 _HEXTET_COUNT = 8 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') def __init__(self, address): self._version = 6 self._max_prefixlen = IPV6LENGTH def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) from None parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = self._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != self._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= self._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) from None def _parse_hextet(self, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not self._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16) def _compress_hextets(self, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets def _string_from_ip_int(self, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(self._ip) if ip_int > self._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)] hextets = self._compress_hextets(hextets) return ':'.join(hextets) def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, IPv6Network): ip_str = str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = str(self.ip) else: ip_str = str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x+4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts) @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv6Address(_BaseV6, _BaseAddress): """Represent and manipulate single IPv6 Addresses.""" def __init__(self, address): """Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. """ _BaseAddress.__init__(self, address) _BaseV6.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 16) self._ip = int.from_bytes(address, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = str(address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v6_int_to_packed(self._ip) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ multicast_network = IPv6Network('ff00::/8') return self in multicast_network @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'), IPv6Network('200::/7'), IPv6Network('400::/6'), IPv6Network('800::/5'), IPv6Network('1000::/4'), IPv6Network('4000::/3'), IPv6Network('6000::/3'), IPv6Network('8000::/3'), IPv6Network('A000::/3'), IPv6Network('C000::/3'), IPv6Network('E000::/4'), IPv6Network('F000::/5'), IPv6Network('F800::/6'), IPv6Network('FE00::/9')] return any(self in x for x in reserved_networks) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ linklocal_network = IPv6Network('fe80::/10') return self in linklocal_network @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ sitelocal_network = IPv6Network('fec0::/10') return self in sitelocal_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 4193. """ private_network = IPv6Network('fc00::/7') return self in private_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0 @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return self._ip == 1 @property def ipv4_mapped(self): """Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise. """ if (self._ip >> 32) != 0xFFFF: return None return IPv4Address(self._ip & 0xFFFFFFFF) @property def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF)) @property def sixtofour(self): """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address. """ if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) class IPv6Interface(IPv6Address): def __init__(self, address): if isinstance(address, (bytes, int)): IPv6Address.__init__(self, address) self.network = IPv6Network(self._ip) self._prefixlen = self._max_prefixlen return addr = _split_optional_netmask(address) IPv6Address.__init__(self, addr[0]) self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self._prefixlen = self.network._prefixlen self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv6Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv6Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) @property def ip(self): return IPv6Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) @property def is_unspecified(self): return self._ip == 0 and self.network.is_unspecified @property def is_loopback(self): return self._ip == 1 and self.network.is_loopback class IPv6Network(_BaseV6, _BaseNetwork): """This class represents and manipulates 128-bit IPv6 networks. Attributes: [examples for IPv6('2001:db8::1000/124')] .network_address: IPv6Address('2001:db8::1000') .hostmask: IPv6Address('::f') .broadcast_address: IPv6Address('2001:db8::100f') .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') .prefixlen: 124 """ # Class to use when creating address objects _address_class = IPv6Address def __init__(self, address, strict=True): """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied. """ _BaseV6.__init__(self, address) _BaseNetwork.__init__(self, address) # Efficient constructor from integer. if isinstance(address, int): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Constructing from a packed address if isinstance(address, bytes): self.network_address = IPv6Address(address) self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ALL_ONES) return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: # This may raise NetmaskValueError self._prefixlen = self._prefix_from_prefix_string(addr[1]) else: self._prefixlen = self._max_prefixlen self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen)) if strict: if (IPv6Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv6Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
mit
Chilledheart/vbox
src/VBox/ValidationKit/tests/selftests/tdSelfTest1.py
4
1441
#!/usr/bin/env python # -*- coding: utf-8 -*- # $Id$ """ Test Manager Self Test - Dummy Test Driver. """ __copyright__ = \ """ Copyright (C) 2012-2014 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation, in version 2 as it comes in the "COPYING" file of the VirtualBox OSE distribution. VirtualBox OSE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. The contents of this file may alternatively be used under the terms of the Common Development and Distribution License Version 1.0 (CDDL) only, as it comes in the "COPYING.CDDL" file of the VirtualBox OSE distribution, in which case the provisions of the CDDL are applicable instead of those of the GPL. You may elect to license modified versions of this file under the terms and conditions of either the GPL or the CDDL or both. """ __version__ = "$Revision$" import sys; print('dummydriver.py: hello world!'); print('dummydriver.py: args: %s' % (sys.argv,)); if sys.argv[-1] in [ 'all', 'execute' ]: import time; for i in range(10, 1, -1): print('dummydriver.py: %u...', i); sys.stdout.flush(); time.sleep(1); print('dummydriver.py: ...0! done'); sys.exit(0);
gpl-2.0
realsystem/CloudFerry
cloudferrylib/os/actions/map_compute_info.py
6
1797
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an AS IS BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and# # limitations under the License. from cloudferrylib.base.action import action from cloudferrylib.utils import utils as utl import copy INSTANCES = 'instances' DIFF = 'diff' PATH_DST = 'path_dst' HOST_DST = 'host_dst' class MapComputeInfo(action.Action): def run(self, info=None, **kwargs): new_compute_info = copy.deepcopy(info) src_compute = self.src_cloud.resources[utl.COMPUTE_RESOURCE] dst_compute = self.dst_cloud.resources[utl.COMPUTE_RESOURCE] src_flavors_dict = \ {flavor.id: flavor.name for flavor in src_compute.get_flavor_list()} dst_flavors_dict = \ {flavor.name: flavor.id for flavor in dst_compute.get_flavor_list()} for instance_id, instance in new_compute_info[utl.INSTANCES_TYPE].iteritems(): _instance = instance['instance'] flavor_name = src_flavors_dict[_instance['flavor_id']] _instance['flavor_id'] = dst_flavors_dict[flavor_name] path_dst = "%s/%s" % (self.dst_cloud.cloud_config.cloud.temp, "temp%s_base" % instance_id) instance[DIFF][PATH_DST] = path_dst instance[DIFF][HOST_DST] = self.dst_cloud.getIpSsh() return { 'info': new_compute_info }
apache-2.0
egabancho/invenio-collections
invenio_collections/admin.py
4
1973
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Admin interface for managin collections.""" from __future__ import absolute_import from invenio.ext.admin.views import ModelView from invenio.ext.sqlalchemy import db from wtforms import TextField from .models import Collection, Collectionname class CollectionAdmin(ModelView): """Configuration of collection admin interface.""" _can_create = True _can_edit = True _can_delete = True acc_view_action = 'cfgwebsearch' acc_edit_action = 'cfgwebsearch' acc_delete_action = 'cfgwebsearch' column_list = ( 'name', 'dbquery', ) column_searchable_list = ('name', 'dbquery') form_columns = ('name', 'dbquery') form_overrides = dict(dbquery=TextField) page_size = 100 def __init__(self, model, session, **kwargs): super(CollectionAdmin, self).__init__( model, session, **kwargs ) def register_admin(app, admin): """Called on app initialization to register administration interface.""" category = "Collections" admin.category_icon_classes[category] = "fa fa-th-list" admin.add_view(CollectionAdmin( Collection, db.session, name='Collections', category=category ))
gpl-2.0
akhilaananthram/cortipy
setup.py
5
1291
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup sdict = {} execfile('cortipy/version.py', {}, sdict) def findRequirements(): """ Read the requirements.txt file and parse into requirements for setup's install_requirements option. """ return [ line.strip() for line in open("requirements.txt").readlines() if not line.startswith("#") ] sdict.update({ 'name' : 'cortipy', 'description' : 'Python client for REST API', 'url': 'http://github.com/numenta/cortipy', 'download_url' : 'https://pypi.python.org/packages/source/g/cortipy/cortipy-%s.tar.gz' % sdict['version'], 'author' : 'Alexander Lavin', 'author_email' : 'alavin@numenta.com', 'keywords' : ['sdr', 'nlp', 'rest', 'htm', 'cortical.io'], 'license' : 'MIT', 'install_requires': findRequirements(), 'test_suite': 'tests.unit', 'packages' : ['cortipy'], 'classifiers' : [ 'Development Status :: 1 - Planning', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python'], }) setup(**sdict)
mit
bonitadecker77/python-for-android
python3-alpha/python3-src/Lib/lib2to3/tests/data/py3_test_grammar.py
266
30362
# Python test set -- part 1, grammar. # This just tests whether the parser accepts them all. # NOTE: When you run this test as a script from the command line, you # get warnings about certain hex/oct constants. Since those are # issued by the parser, you can't suppress them by adding a # filterwarnings() call to this module. Therefore, to shut up the # regression test, the filterwarnings() call has been added to # regrtest.py. from test.support import run_unittest, check_syntax_error import unittest import sys # testing import * from sys import * class TokenTests(unittest.TestCase): def testBackslash(self): # Backslash means line continuation: x = 1 \ + 1 self.assertEquals(x, 2, 'backslash for line continuation') # Backslash does not means continuation in comments :\ x = 0 self.assertEquals(x, 0, 'backslash ending comment') def testPlainIntegers(self): self.assertEquals(type(000), type(0)) self.assertEquals(0xff, 255) self.assertEquals(0o377, 255) self.assertEquals(2147483647, 0o17777777777) self.assertEquals(0b1001, 9) # "0x" is not a valid literal self.assertRaises(SyntaxError, eval, "0x") from sys import maxsize if maxsize == 2147483647: self.assertEquals(-2147483647-1, -0o20000000000) # XXX -2147483648 self.assert_(0o37777777777 > 0) self.assert_(0xffffffff > 0) self.assert_(0b1111111111111111111111111111111 > 0) for s in ('2147483648', '0o40000000000', '0x100000000', '0b10000000000000000000000000000000'): try: x = eval(s) except OverflowError: self.fail("OverflowError on huge integer literal %r" % s) elif maxsize == 9223372036854775807: self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000) self.assert_(0o1777777777777777777777 > 0) self.assert_(0xffffffffffffffff > 0) self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0) for s in '9223372036854775808', '0o2000000000000000000000', \ '0x10000000000000000', \ '0b100000000000000000000000000000000000000000000000000000000000000': try: x = eval(s) except OverflowError: self.fail("OverflowError on huge integer literal %r" % s) else: self.fail('Weird maxsize value %r' % maxsize) def testLongIntegers(self): x = 0 x = 0xffffffffffffffff x = 0Xffffffffffffffff x = 0o77777777777777777 x = 0O77777777777777777 x = 123456789012345678901234567890 x = 0b100000000000000000000000000000000000000000000000000000000000000000000 x = 0B111111111111111111111111111111111111111111111111111111111111111111111 def testFloats(self): x = 3.14 x = 314. x = 0.314 # XXX x = 000.314 x = .314 x = 3e14 x = 3E14 x = 3e-14 x = 3e+14 x = 3.e14 x = .3e14 x = 3.1e4 def testStringLiterals(self): x = ''; y = ""; self.assert_(len(x) == 0 and x == y) x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39) x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34) x = "doesn't \"shrink\" does it" y = 'doesn\'t "shrink" does it' self.assert_(len(x) == 24 and x == y) x = "does \"shrink\" doesn't it" y = 'does "shrink" doesn\'t it' self.assert_(len(x) == 24 and x == y) x = """ The "quick" brown fox jumps over the 'lazy' dog. """ y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' self.assertEquals(x, y) y = ''' The "quick" brown fox jumps over the 'lazy' dog. ''' self.assertEquals(x, y) y = "\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the 'lazy' dog.\n\ " self.assertEquals(x, y) y = '\n\ The \"quick\"\n\ brown fox\n\ jumps over\n\ the \'lazy\' dog.\n\ ' self.assertEquals(x, y) def testEllipsis(self): x = ... self.assert_(x is Ellipsis) self.assertRaises(SyntaxError, eval, ".. .") class GrammarTests(unittest.TestCase): # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE # XXX can't test in a script -- this rule is only used when interactive # file_input: (NEWLINE | stmt)* ENDMARKER # Being tested as this very moment this very module # expr_input: testlist NEWLINE # XXX Hard to test -- used only in calls to input() def testEvalInput(self): # testlist ENDMARKER x = eval('1, 0 or 1') def testFuncdef(self): ### [decorators] 'def' NAME parameters ['->' test] ':' suite ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE ### decorators: decorator+ ### parameters: '(' [typedargslist] ')' ### typedargslist: ((tfpdef ['=' test] ',')* ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [',']) ### tfpdef: NAME [':' test] ### varargslist: ((vfpdef ['=' test] ',')* ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [',']) ### vfpdef: NAME def f1(): pass f1() f1(*()) f1(*(), **{}) def f2(one_argument): pass def f3(two, arguments): pass self.assertEquals(f2.__code__.co_varnames, ('one_argument',)) self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments')) def a1(one_arg,): pass def a2(two, args,): pass def v0(*rest): pass def v1(a, *rest): pass def v2(a, b, *rest): pass f1() f2(1) f2(1,) f3(1, 2) f3(1, 2,) v0() v0(1) v0(1,) v0(1,2) v0(1,2,3,4,5,6,7,8,9,0) v1(1) v1(1,) v1(1,2) v1(1,2,3) v1(1,2,3,4,5,6,7,8,9,0) v2(1,2) v2(1,2,3) v2(1,2,3,4) v2(1,2,3,4,5,6,7,8,9,0) def d01(a=1): pass d01() d01(1) d01(*(1,)) d01(**{'a':2}) def d11(a, b=1): pass d11(1) d11(1, 2) d11(1, **{'b':2}) def d21(a, b, c=1): pass d21(1, 2) d21(1, 2, 3) d21(*(1, 2, 3)) d21(1, *(2, 3)) d21(1, 2, *(3,)) d21(1, 2, **{'c':3}) def d02(a=1, b=2): pass d02() d02(1) d02(1, 2) d02(*(1, 2)) d02(1, *(2,)) d02(1, **{'b':2}) d02(**{'a': 1, 'b': 2}) def d12(a, b=1, c=2): pass d12(1) d12(1, 2) d12(1, 2, 3) def d22(a, b, c=1, d=2): pass d22(1, 2) d22(1, 2, 3) d22(1, 2, 3, 4) def d01v(a=1, *rest): pass d01v() d01v(1) d01v(1, 2) d01v(*(1, 2, 3, 4)) d01v(*(1,)) d01v(**{'a':2}) def d11v(a, b=1, *rest): pass d11v(1) d11v(1, 2) d11v(1, 2, 3) def d21v(a, b, c=1, *rest): pass d21v(1, 2) d21v(1, 2, 3) d21v(1, 2, 3, 4) d21v(*(1, 2, 3, 4)) d21v(1, 2, **{'c': 3}) def d02v(a=1, b=2, *rest): pass d02v() d02v(1) d02v(1, 2) d02v(1, 2, 3) d02v(1, *(2, 3, 4)) d02v(**{'a': 1, 'b': 2}) def d12v(a, b=1, c=2, *rest): pass d12v(1) d12v(1, 2) d12v(1, 2, 3) d12v(1, 2, 3, 4) d12v(*(1, 2, 3, 4)) d12v(1, 2, *(3, 4, 5)) d12v(1, *(2,), **{'c': 3}) def d22v(a, b, c=1, d=2, *rest): pass d22v(1, 2) d22v(1, 2, 3) d22v(1, 2, 3, 4) d22v(1, 2, 3, 4, 5) d22v(*(1, 2, 3, 4)) d22v(1, 2, *(3, 4, 5)) d22v(1, *(2, 3), **{'d': 4}) # keyword argument type tests try: str('x', **{b'foo':1 }) except TypeError: pass else: self.fail('Bytes should not work as keyword argument names') # keyword only argument tests def pos0key1(*, key): return key pos0key1(key=100) def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2 pos2key2(1, 2, k1=100) pos2key2(1, 2, k1=100, k2=200) pos2key2(1, 2, k2=100, k1=200) def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200) pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100) # keyword arguments after *arglist def f(*args, **kwargs): return args, kwargs self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), {'x':2, 'y':5})) self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)") self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") # argument annotation tests def f(x) -> list: pass self.assertEquals(f.__annotations__, {'return': list}) def f(x:int): pass self.assertEquals(f.__annotations__, {'x': int}) def f(*x:str): pass self.assertEquals(f.__annotations__, {'x': str}) def f(**x:float): pass self.assertEquals(f.__annotations__, {'x': float}) def f(x, y:1+2): pass self.assertEquals(f.__annotations__, {'y': 3}) def f(a, b:1, c:2, d): pass self.assertEquals(f.__annotations__, {'b': 1, 'c': 2}) def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass self.assertEquals(f.__annotations__, {'b': 1, 'c': 2, 'e': 3, 'g': 6}) def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass self.assertEquals(f.__annotations__, {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, 'k': 11, 'return': 12}) # Check for SF Bug #1697248 - mixing decorators and a return annotation def null(x): return x @null def f(x) -> list: pass self.assertEquals(f.__annotations__, {'return': list}) # test MAKE_CLOSURE with a variety of oparg's closure = 1 def f(): return closure def f(x=1): return closure def f(*, k=1): return closure def f() -> int: return closure # Check ast errors in *args and *kwargs check_syntax_error(self, "f(*g(1=2))") check_syntax_error(self, "f(**g(1=2))") def testLambdef(self): ### lambdef: 'lambda' [varargslist] ':' test l1 = lambda : 0 self.assertEquals(l1(), 0) l2 = lambda : a[d] # XXX just testing the expression l3 = lambda : [2 < x for x in [-1, 3, 0]] self.assertEquals(l3(), [0, 1, 0]) l4 = lambda x = lambda y = lambda z=1 : z : y() : x() self.assertEquals(l4(), 1) l5 = lambda x, y, z=2: x + y + z self.assertEquals(l5(1, 2), 5) self.assertEquals(l5(1, 2, 3), 6) check_syntax_error(self, "lambda x: x = 2") check_syntax_error(self, "lambda (None,): None") l6 = lambda x, y, *, k=20: x+y+k self.assertEquals(l6(1,2), 1+2+20) self.assertEquals(l6(1,2,k=10), 1+2+10) ### stmt: simple_stmt | compound_stmt # Tested below def testSimpleStmt(self): ### simple_stmt: small_stmt (';' small_stmt)* [';'] x = 1; pass; del x def foo(): # verify statements that end with semi-colons x = 1; pass; del x; foo() ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt # Tested below def testExprStmt(self): # (exprlist '=')* exprlist 1 1, 2, 3 x = 1 x = 1, 2, 3 x = y = z = 1, 2, 3 x, y, z = 1, 2, 3 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4) check_syntax_error(self, "x + 1 = 1") check_syntax_error(self, "a + 1 = b + 2") def testDelStmt(self): # 'del' exprlist abc = [1,2,3] x, y, z = abc xyz = x, y, z del abc del x, y, (z, xyz) def testPassStmt(self): # 'pass' pass # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt # Tested below def testBreakStmt(self): # 'break' while 1: break def testContinueStmt(self): # 'continue' i = 1 while i: i = 0; continue msg = "" while not msg: msg = "ok" try: continue msg = "continue failed to continue inside try" except: msg = "continue inside try called except block" if msg != "ok": self.fail(msg) msg = "" while not msg: msg = "finally block not called" try: continue finally: msg = "ok" if msg != "ok": self.fail(msg) def test_break_continue_loop(self): # This test warrants an explanation. It is a test specifically for SF bugs # #463359 and #462937. The bug is that a 'break' statement executed or # exception raised inside a try/except inside a loop, *after* a continue # statement has been executed in that loop, will cause the wrong number of # arguments to be popped off the stack and the instruction pointer reset to # a very small number (usually 0.) Because of this, the following test # *must* written as a function, and the tracking vars *must* be function # arguments with default values. Otherwise, the test will loop and loop. def test_inner(extra_burning_oil = 1, count=0): big_hippo = 2 while big_hippo: count += 1 try: if extra_burning_oil and big_hippo == 1: extra_burning_oil -= 1 break big_hippo -= 1 continue except: raise if count > 2 or big_hippo != 1: self.fail("continue then break in try/except in loop broken!") test_inner() def testReturn(self): # 'return' [testlist] def g1(): return def g2(): return 1 g1() x = g2() check_syntax_error(self, "class foo:return 1") def testYield(self): check_syntax_error(self, "class foo:yield 1") def testRaise(self): # 'raise' test [',' test] try: raise RuntimeError('just testing') except RuntimeError: pass try: raise KeyboardInterrupt except KeyboardInterrupt: pass def testImport(self): # 'import' dotted_as_names import sys import time, sys # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names) from time import time from time import (time) # not testable inside a function, but already done at top of the module # from sys import * from sys import path, argv from sys import (path, argv) from sys import (path, argv,) def testGlobal(self): # 'global' NAME (',' NAME)* global a global a, b global one, two, three, four, five, six, seven, eight, nine, ten def testNonlocal(self): # 'nonlocal' NAME (',' NAME)* x = 0 y = 0 def f(): nonlocal x nonlocal x, y def testAssert(self): # assert_stmt: 'assert' test [',' test] assert 1 assert 1, 1 assert lambda x:x assert 1, lambda x:x+1 try: assert 0, "msg" except AssertionError as e: self.assertEquals(e.args[0], "msg") else: if __debug__: self.fail("AssertionError not raised by assert 0") ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef # Tested below def testIf(self): # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] if 1: pass if 1: pass else: pass if 0: pass elif 0: pass if 0: pass elif 0: pass elif 0: pass elif 0: pass else: pass def testWhile(self): # 'while' test ':' suite ['else' ':' suite] while 0: pass while 0: pass else: pass # Issue1920: "while 0" is optimized away, # ensure that the "else" clause is still present. x = 0 while 0: x = 1 else: x = 2 self.assertEquals(x, 2) def testFor(self): # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] for i in 1, 2, 3: pass for i, j, k in (): pass else: pass class Squares: def __init__(self, max): self.max = max self.sofar = [] def __len__(self): return len(self.sofar) def __getitem__(self, i): if not 0 <= i < self.max: raise IndexError n = len(self.sofar) while n <= i: self.sofar.append(n*n) n = n+1 return self.sofar[i] n = 0 for x in Squares(10): n = n+x if n != 285: self.fail('for over growing sequence') result = [] for x, in [(1,), (2,), (3,)]: result.append(x) self.assertEqual(result, [1, 2, 3]) def testTry(self): ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite] ### | 'try' ':' suite 'finally' ':' suite ### except_clause: 'except' [expr ['as' expr]] try: 1/0 except ZeroDivisionError: pass else: pass try: 1/0 except EOFError: pass except TypeError as msg: pass except RuntimeError as msg: pass except: pass else: pass try: 1/0 except (EOFError, TypeError, ZeroDivisionError): pass try: 1/0 except (EOFError, TypeError, ZeroDivisionError) as msg: pass try: pass finally: pass def testSuite(self): # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT if 1: pass if 1: pass if 1: # # # pass pass # pass # def testTest(self): ### and_test ('or' and_test)* ### and_test: not_test ('and' not_test)* ### not_test: 'not' not_test | comparison if not 1: pass if 1 and 1: pass if 1 or 1: pass if not not not 1: pass if not 1 and 1 and 1: pass if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass def testComparison(self): ### comparison: expr (comp_op expr)* ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not' if 1: pass x = (1 == 1) if 1 == 1: pass if 1 != 1: pass if 1 < 1: pass if 1 > 1: pass if 1 <= 1: pass if 1 >= 1: pass if 1 is 1: pass if 1 is not 1: pass if 1 in (): pass if 1 not in (): pass if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass def testBinaryMaskOps(self): x = 1 & 1 x = 1 ^ 1 x = 1 | 1 def testShiftOps(self): x = 1 << 1 x = 1 >> 1 x = 1 << 1 >> 1 def testAdditiveOps(self): x = 1 x = 1 + 1 x = 1 - 1 - 1 x = 1 - 1 + 1 - 1 + 1 def testMultiplicativeOps(self): x = 1 * 1 x = 1 / 1 x = 1 % 1 x = 1 / 1 * 1 % 1 def testUnaryOps(self): x = +1 x = -1 x = ~1 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 x = -1*1/1 + 1*1 - ---1*1 def testSelectors(self): ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME ### subscript: expr | [expr] ':' [expr] import sys, time c = sys.path[0] x = time.time() x = sys.modules['time'].time() a = '01234' c = a[0] c = a[-1] s = a[0:5] s = a[:5] s = a[0:] s = a[:] s = a[-5:] s = a[:-1] s = a[-4:-3] # A rough test of SF bug 1333982. http://python.org/sf/1333982 # The testing here is fairly incomplete. # Test cases should include: commas with 1 and 2 colons d = {} d[1] = 1 d[1,] = 2 d[1,2] = 3 d[1,2,3] = 4 L = list(d) L.sort(key=lambda x: x if isinstance(x, tuple) else ()) self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') def testAtoms(self): ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [',']) x = (1) x = (1 or 2 or 3) x = (1 or 2 or 3, 2, 3) x = [] x = [1] x = [1 or 2 or 3] x = [1 or 2 or 3, 2, 3] x = [] x = {} x = {'one': 1} x = {'one': 1,} x = {'one' or 'two': 1 or 2} x = {'one': 1, 'two': 2} x = {'one': 1, 'two': 2,} x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} x = {'one'} x = {'one', 1,} x = {'one', 'two', 'three'} x = {2, 3, 4,} x = x x = 'x' x = 123 ### exprlist: expr (',' expr)* [','] ### testlist: test (',' test)* [','] # These have been exercised enough above def testClassdef(self): # 'class' NAME ['(' [testlist] ')'] ':' suite class B: pass class B2(): pass class C1(B): pass class C2(B): pass class D(C1, C2, B): pass class C: def meth1(self): pass def meth2(self, arg): pass def meth3(self, a1, a2): pass # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE # decorators: decorator+ # decorated: decorators (classdef | funcdef) def class_decorator(x): return x @class_decorator class G: pass def testDictcomps(self): # dictorsetmaker: ( (test ':' test (comp_for | # (',' test ':' test)* [','])) | # (test (comp_for | (',' test)* [','])) ) nums = [1, 2, 3] self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4}) def testListcomps(self): # list comprehension tests nums = [1, 2, 3, 4, 5] strs = ["Apple", "Banana", "Coconut"] spcs = [" Apple", " Banana ", "Coco nut "] self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut']) self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15]) self.assertEqual([x for x in nums if x > 2], [3, 4, 5]) self.assertEqual([(i, s) for i in nums for s in strs], [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'), (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'), (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'), (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'), (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')]) self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]], [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'), (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'), (5, 'Banana'), (5, 'Coconut')]) self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)], [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]]) def test_in_func(l): return [0 < x < 3 for x in l if x > 2] self.assertEqual(test_in_func(nums), [False, False, False]) def test_nested_front(): self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]], [[1, 2], [3, 4], [5, 6]]) test_nested_front() check_syntax_error(self, "[i, s for i in nums for s in strs]") check_syntax_error(self, "[x if y]") suppliers = [ (1, "Boeing"), (2, "Ford"), (3, "Macdonalds") ] parts = [ (10, "Airliner"), (20, "Engine"), (30, "Cheeseburger") ] suppart = [ (1, 10), (1, 20), (2, 20), (3, 30) ] x = [ (sname, pname) for (sno, sname) in suppliers for (pno, pname) in parts for (sp_sno, sp_pno) in suppart if sno == sp_sno and pno == sp_pno ] self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'), ('Macdonalds', 'Cheeseburger')]) def testGenexps(self): # generator expression tests g = ([x for x in range(10)] for x in range(1)) self.assertEqual(next(g), [x for x in range(10)]) try: next(g) self.fail('should produce StopIteration exception') except StopIteration: pass a = 1 try: g = (a for d in a) next(g) self.fail('should produce TypeError') except TypeError: pass self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd']) self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy']) a = [x for x in range(10)] b = (x for x in (y for y in a)) self.assertEqual(sum(b), sum([x for x in range(10)])) self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)])) self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2])) self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)])) self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)])) self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)])) self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)])) self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0) check_syntax_error(self, "foo(x for x in range(10), 100)") check_syntax_error(self, "foo(100, x for x in range(10))") def testComprehensionSpecials(self): # test for outmost iterable precomputation x = 10; g = (i for i in range(x)); x = 5 self.assertEqual(len(list(g)), 10) # This should hold, since we're only precomputing outmost iterable. x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x)) x = 5; t = True; self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g)) # Grammar allows multiple adjacent 'if's in listcomps and genexps, # even though it's silly. Make sure it works (ifelse broke this.) self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7]) self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7]) # verify unpacking single element tuples in listcomp/genexp. self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6]) self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9]) def test_with_statement(self): class manager(object): def __enter__(self): return (1, 2) def __exit__(self, *args): pass with manager(): pass with manager() as x: pass with manager() as (x, y): pass with manager(), manager(): pass with manager() as x, manager() as y: pass with manager() as x, manager(): pass def testIfElseExpr(self): # Test ifelse expressions in various cases def _checkeval(msg, ret): "helper to check that evaluation of expressions is done correctly" print(x) return ret # the next line is not allowed anymore #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True]) self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True]) self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True]) self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5) self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5) self.assertEqual((5 and 6 if 0 else 1), 1) self.assertEqual(((5 and 6) if 0 else 1), 1) self.assertEqual((5 and (6 if 1 else 1)), 6) self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3) self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1) self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5) self.assertEqual((not 5 if 1 else 1), False) self.assertEqual((not 5 if 0 else 1), 1) self.assertEqual((6 + 1 if 1 else 2), 7) self.assertEqual((6 - 1 if 1 else 2), 5) self.assertEqual((6 * 2 if 1 else 4), 12) self.assertEqual((6 / 2 if 1 else 3), 3) self.assertEqual((6 < 4 if 0 else 2), 2) def test_main(): run_unittest(TokenTests, GrammarTests) if __name__ == '__main__': test_main()
apache-2.0
aebrahim/ome
ome/settings.py
1
5475
"""retrive local user settings""" from ConfigParser import SafeConfigParser, NoOptionError import os as os from os.path import join, split, abspath, isfile, expanduser from sys import modules self = modules[__name__] # define various filepaths omelib_directory = join(split(abspath(__file__))[0], "") ome_directory = join(abspath(join(omelib_directory, "..")), "") def which(program): """returns path to an executable if it is found in the path""" fpath, fname = split(program) if fpath: if isfile(program) and os.access(program, os.X_OK): return program else: paths_to_search = os.environ["PATH"].split(os.pathsep) paths_to_search.extend((omelib_directory, ome_directory)) for path in paths_to_search: exe_file = join(path, program) if isfile(exe_file) and os.access(exe_file, os.X_OK): return exe_file if os.name == "nt" and not program.endswith(".exe"): return which(program + ".exe") return None def _escape_space(program): """escape spaces in for windows""" if os.name == "nt" and ' ' in program: return '"' + program + '"' else: return program config = SafeConfigParser() # set the default settings config.add_section("DATABASE") config.set("DATABASE", "postgres_host", "localhost") config.set("DATABASE", "postgres_port", "5432") config.set("DATABASE", "postgres_database", "ome_stage_2") config.set("DATABASE", "postgres_user", "dbuser") config.set("DATABASE", "postgres_password", "") config.set("DATABASE", "postgres_test_database", "ome_test") config.add_section("DATA") config.add_section("EXECUTABLES") # overwrite defaults settings with settings from the file def load_settings_from_file(filepath="settings.ini", in_omelib=True): """Reload settings from a different settings file. Arguments --------- filepath: The path to the settings file to use. in_omelib: Whether or not the path given is a relative path from the omelib directory. """ if in_omelib: filepath = join(omelib_directory, filepath) config.read(filepath) # attempt to intellegently determine more difficult settings if not config.has_option("DATABASE", "user"): if "USERNAME" in os.environ: # windows user = os.environ["USERNAME"] elif "USER" in os.environ: # unix user = os.environ["USER"] config.set("DATABASE", "user", user) # executables if not config.has_option("EXECUTABLES", "psql"): psql = which("psql91") if psql is None: psql = which("psql") config.set("EXECUTABLES", "psql", psql) if not config.has_option("EXECUTABLES", "R"): R = which("R") config.set("EXECUTABLES", "R", R) if not config.has_option("EXECUTABLES", "Rscript"): Rscript = which("Rscript") config.set("EXECUTABLES", "Rscript", Rscript) if not config.has_option("EXECUTABLES", "primer3"): primer3 = which("primer3_core") config.set("EXECUTABLES", "primer3", primer3) if not config.has_option("EXECUTABLES", "cufflinks"): cufflinks = which("cufflinks") config.set("EXECUTABLES", "cufflinks", cufflinks) if not config.has_option("EXECUTABLES", "java"): java = which("java") config.set("EXECUTABLES", "java", java) # save options as variables self.postgres_user = config.get("DATABASE", "postgres_user") self.postgres_password = config.get("DATABASE", "postgres_password") if len(self.postgres_password) > 0: os.environ["PGPASSWORD"] = self.postgres_password self.postgres_database = config.get("DATABASE", "postgres_database") self.postgres_host = config.get("DATABASE", "postgres_host") self.postgres_port = config.get("DATABASE", "postgres_port") self.postgres_test_database = config.get("DATABASE", "postgres_test_database") self.psql = _escape_space(config.get("EXECUTABLES", "psql")) self.R = _escape_space(config.get("EXECUTABLES", "R")) self.Rscript = _escape_space(config.get("EXECUTABLES", "Rscript")) self.primer3 = _escape_space(config.get("EXECUTABLES", "primer3")) self.cufflinks = config.get("EXECUTABLES", "cufflinks") self.java = config.get("EXECUTABLES", "java") # make a psql string with the database options included self.psql_full = "%s --host=%s --username=%s --port=%s " % \ (self.psql, self.postgres_host, self.postgres_user, self.postgres_port) try: self.data_directory = expanduser(config.get('DATA', 'data_directory')) except NoOptionError: raise Exception('data_directory was not supplied in settings.ini') # set default here, after getting the data directory try: self.model_genome = expanduser(config.get('DATA', 'model_genome')) except NoOptionError: raise Exception('model_genome path was not supplied in settings.ini') # these are optional for data_pref in ['compartment_names', 'reaction_id_prefs', 'reaction_hash_prefs', 'gene_reaction_rule_prefs', 'data_source_preferences', 'model_dump_directory', 'model_published_directory', 'model_polished_directory']: try: setattr(self, data_pref, expanduser(config.get('DATA', data_pref))) except NoOptionError: setattr(self, data_pref, None) load_settings_from_file() del SafeConfigParser, modules
mit
marlboromoo/miniboa
miniboa/telnet.py
18
24890
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # miniboa/telnet.py # Copyright 2009 Jim Storch # 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. #------------------------------------------------------------------------------ """ Manage one Telnet client connected via a TCP/IP socket. """ import socket import time from miniboa.error import BogConnectionLost from miniboa.xterm import colorize from miniboa.xterm import word_wrap #---[ Telnet Notes ]----------------------------------------------------------- # (See RFC 854 for more information) # # Negotiating a Local Option # -------------------------- # # Side A begins with: # # "IAC WILL/WONT XX" Meaning "I would like to [use|not use] option XX." # # Side B replies with either: # # "IAC DO XX" Meaning "OK, you may use option XX." # "IAC DONT XX" Meaning "No, you cannot use option XX." # # # Negotiating a Remote Option # ---------------------------- # # Side A begins with: # # "IAC DO/DONT XX" Meaning "I would like YOU to [use|not use] option XX." # # Side B replies with either: # # "IAC WILL XX" Meaning "I will begin using option XX" # "IAC WONT XX" Meaning "I will not begin using option XX" # # # The syntax is designed so that if both parties receive simultaneous requests # for the same option, each will see the other's request as a positive # acknowledgement of it's own. # # If a party receives a request to enter a mode that it is already in, the # request should not be acknowledged. ## Where you see DE in my comments I mean 'Distant End', e.g. the client. UNKNOWN = -1 #--[ Telnet Commands ]--------------------------------------------------------- SE = chr(240) # End of subnegotiation parameters NOP = chr(241) # No operation DATMK = chr(242) # Data stream portion of a sync. BREAK = chr(243) # NVT Character BRK IP = chr(244) # Interrupt Process AO = chr(245) # Abort Output AYT = chr(246) # Are you there EC = chr(247) # Erase Character EL = chr(248) # Erase Line GA = chr(249) # The Go Ahead Signal SB = chr(250) # Sub-option to follow WILL = chr(251) # Will; request or confirm option begin WONT = chr(252) # Wont; deny option request DO = chr(253) # Do = Request or confirm remote option DONT = chr(254) # Don't = Demand or confirm option halt IAC = chr(255) # Interpret as Command SEND = chr(001) # Sub-process negotiation SEND command IS = chr(000) # Sub-process negotiation IS command #--[ Telnet Options ]---------------------------------------------------------- BINARY = chr( 0) # Transmit Binary ECHO = chr( 1) # Echo characters back to sender RECON = chr( 2) # Reconnection SGA = chr( 3) # Suppress Go-Ahead TTYPE = chr( 24) # Terminal Type NAWS = chr( 31) # Negotiate About Window Size LINEMO = chr( 34) # Line Mode #-----------------------------------------------------------------Telnet Option class TelnetOption(object): """ Simple class used to track the status of an extended Telnet option. """ def __init__(self): self.local_option = UNKNOWN # Local state of an option self.remote_option = UNKNOWN # Remote state of an option self.reply_pending = False # Are we expecting a reply? #------------------------------------------------------------------------Telnet class TelnetClient(object): """ Represents a client connection via Telnet. First argument is the socket discovered by the Telnet Server. Second argument is the tuple (ip address, port number). """ def __init__(self, sock, addr_tup): self.protocol = 'telnet' self.active = True # Turns False when the connection is lost self.sock = sock # The connection's socket self.fileno = sock.fileno() # The socket's file descriptor self.address = addr_tup[0] # The client's remote TCP/IP address self.port = addr_tup[1] # The client's remote port self.terminal_type = 'unknown client' # set via request_terminal_type() self.use_ansi = True self.columns = 80 self.rows = 24 self.send_pending = False self.send_buffer = '' self.recv_buffer = '' self.bytes_sent = 0 self.bytes_received = 0 self.cmd_ready = False self.command_list = [] self.connect_time = time.time() self.last_input_time = time.time() ## State variables for interpreting incoming telnet commands self.telnet_got_iac = False # Are we inside an IAC sequence? self.telnet_got_cmd = None # Did we get a telnet command? self.telnet_got_sb = False # Are we inside a subnegotiation? self.telnet_opt_dict = {} # Mapping for up to 256 TelnetOptions self.telnet_echo = False # Echo input back to the client? self.telnet_echo_password = False # Echo back '*' for passwords? self.telnet_sb_buffer = '' # Buffer for sub-negotiations # def __del__(self): # print "Telnet destructor called" # pass def get_command(self): """ Get a line of text that was received from the DE. The class's cmd_ready attribute will be true if lines are available. """ cmd = None count = len(self.command_list) if count > 0: cmd = self.command_list.pop(0) ## If that was the last line, turn off lines_pending if count == 1: self.cmd_ready = False return cmd def send(self, text): """ Send raw text to the distant end. """ if text: self.send_buffer += text.replace('\n', '\r\n') self.send_pending = True def send_cc(self, text): """ Send text with caret codes converted to ansi. """ self.send(colorize(text, self.use_ansi)) def send_wrapped(self, text): """ Send text padded and wrapped to the user's screen width. """ lines = word_wrap(text, self.columns) for line in lines: self.send_cc(line + '\n') def deactivate(self): """ Set the client to disconnect on the next server poll. """ self.active = False def addrport(self): """ Return the DE's IP address and port number as a string. """ return "%s:%s" % (self.address, self.port) def idle(self): """ Returns the number of seconds that have elasped since the DE last sent us some input. """ return time.time() - self.last_input_time def duration(self): """ Returns the number of seconds the DE has been connected. """ return time.time() - self.connect_time def request_do_sga(self): """ Request DE to Suppress Go-Ahead. See RFC 858. """ self._iac_do(SGA) self._note_reply_pending(SGA, True) def request_will_echo(self): """ Tell the DE that we would like to echo their text. See RFC 857. """ self._iac_will(ECHO) self._note_reply_pending(ECHO, True) self.telnet_echo = True def request_wont_echo(self): """ Tell the DE that we would like to stop echoing their text. See RFC 857. """ self._iac_wont(ECHO) self._note_reply_pending(ECHO, True) self.telnet_echo = False def password_mode_on(self): """ Tell DE we will echo (but don't) so typed passwords don't show. """ self._iac_will(ECHO) self._note_reply_pending(ECHO, True) def password_mode_off(self): """ Tell DE we are done echoing (we lied) and show typing again. """ self._iac_wont(ECHO) self._note_reply_pending(ECHO, True) def request_naws(self): """ Request to Negotiate About Window Size. See RFC 1073. """ self._iac_do(NAWS) self._note_reply_pending(NAWS, True) def request_terminal_type(self): """ Begins the Telnet negotiations to request the terminal type from the client. See RFC 779. """ self._iac_do(TTYPE) self._note_reply_pending(TTYPE, True) def socket_send(self): """ Called by TelnetServer when send data is ready. """ if len(self.send_buffer): try: sent = self.sock.send(self.send_buffer) except socket.error, err: print("!! SEND error '%d:%s' from %s" % (err[0], err[1], self.addrport())) self.active = False return self.bytes_sent += sent self.send_buffer = self.send_buffer[sent:] else: self.send_pending = False def socket_recv(self): """ Called by TelnetServer when recv data is ready. """ try: data = self.sock.recv(2048) except socket.error, ex: print ("?? socket.recv() error '%d:%s' from %s" % (ex[0], ex[1], self.addrport())) raise BogConnectionLost() ## Did they close the connection? size = len(data) if size == 0: raise BogConnectionLost() ## Update some trackers self.last_input_time = time.time() self.bytes_received += size ## Test for telnet commands for byte in data: self._iac_sniffer(byte) ## Look for newline characters to get whole lines from the buffer while True: mark = self.recv_buffer.find('\n') if mark == -1: break cmd = self.recv_buffer[:mark].strip() self.command_list.append(cmd) self.cmd_ready = True self.recv_buffer = self.recv_buffer[mark+1:] def _recv_byte(self, byte): """ Non-printable filtering currently disabled because it did not play well with extended character sets. """ ## Filter out non-printing characters #if (byte >= ' ' and byte <= '~') or byte == '\n': if self.telnet_echo: self._echo_byte(byte) self.recv_buffer += byte def _echo_byte(self, byte): """ Echo a character back to the client and convert LF into CR\LF. """ if byte == '\n': self.send_buffer += '\r' if self.telnet_echo_password: self.send_buffer += '*' else: self.send_buffer += byte def _iac_sniffer(self, byte): """ Watches incomming data for Telnet IAC sequences. Passes the data, if any, with the IAC commands stripped to _recv_byte(). """ ## Are we not currently in an IAC sequence coming from the DE? if self.telnet_got_iac is False: if byte == IAC: ## Well, we are now self.telnet_got_iac = True return ## Are we currenty in a sub-negotion? elif self.telnet_got_sb is True: ## Sanity check on length if len(self.telnet_sb_buffer) < 64: self.telnet_sb_buffer += byte else: self.telnet_got_sb = False self.telnet_sb_buffer = "" return else: ## Just a normal NVT character self._recv_byte(byte) return ## Byte handling when already in an IAC sequence sent from the DE else: ## Did we get sent a second IAC? if byte == IAC and self.telnet_got_sb is True: ## Must be an escaped 255 (IAC + IAC) self.telnet_sb_buffer += byte self.telnet_got_iac = False return ## Do we already have an IAC + CMD? elif self.telnet_got_cmd: ## Yes, so handle the option self._three_byte_cmd(byte) return ## We have IAC but no CMD else: ## Is this the middle byte of a three-byte command? if byte == DO: self.telnet_got_cmd = DO return elif byte == DONT: self.telnet_got_cmd = DONT return elif byte == WILL: self.telnet_got_cmd = WILL return elif byte == WONT: self.telnet_got_cmd = WONT return else: ## Nope, must be a two-byte command self._two_byte_cmd(byte) def _two_byte_cmd(self, cmd): """ Handle incoming Telnet commands that are two bytes long. """ #print "got two byte cmd %d" % ord(cmd) if cmd == SB: ## Begin capturing a sub-negotiation string self.telnet_got_sb = True self.telnet_sb_buffer = '' elif cmd == SE: ## Stop capturing a sub-negotiation string self.telnet_got_sb = False self._sb_decoder() elif cmd == NOP: pass elif cmd == DATMK: pass elif cmd == IP: pass elif cmd == AO: pass elif cmd == AYT: pass elif cmd == EC: pass elif cmd == EL: pass elif cmd == GA: pass else: print "2BC: Should not be here." self.telnet_got_iac = False self.telnet_got_cmd = None def _three_byte_cmd(self, option): """ Handle incoming Telnet commmands that are three bytes long. """ cmd = self.telnet_got_cmd #print "got three byte cmd %d:%d" % (ord(cmd), ord(option)) ## Incoming DO's and DONT's refer to the status of this end #---[ DO ]------------------------------------------------------------- if cmd == DO: if option == BINARY: if self._check_reply_pending(BINARY): self._note_reply_pending(BINARY, False) self._note_local_option(BINARY, True) elif (self._check_local_option(BINARY) is False or self._check_local_option(BINARY) is UNKNOWN): self._note_local_option(BINARY, True) self._iac_will(BINARY) ## Just nod elif option == ECHO: if self._check_reply_pending(ECHO): self._note_reply_pending(ECHO, False) self._note_local_option(ECHO, True) elif (self._check_local_option(ECHO) is False or self._check_local_option(ECHO) is UNKNOWN): self._note_local_option(ECHO, True) self._iac_will(ECHO) self.telnet_echo = True elif option == SGA: if self._check_reply_pending(SGA): self._note_reply_pending(SGA, False) self._note_local_option(SGA, True) elif (self._check_local_option(SGA) is False or self._check_local_option(SGA) is UNKNOWN): self._note_local_option(SGA, True) self._iac_will(SGA) ## Just nod else: ## ALL OTHER OTHERS = Default to refusing once if self._check_local_option(option) is UNKNOWN: self._note_local_option(option, False) self._iac_wont(option) #---[ DONT ]----------------------------------------------------------- elif cmd == DONT: if option == BINARY: if self._check_reply_pending(BINARY): self._note_reply_pending(BINARY, False) self._note_local_option(BINARY, False) elif (self._check_local_option(BINARY) is True or self._check_local_option(BINARY) is UNKNOWN): self._note_local_option(BINARY, False) self._iac_wont(BINARY) ## Just nod elif option == ECHO: if self._check_reply_pending(ECHO): self._note_reply_pending(ECHO, False) self._note_local_option(ECHO, True) self.telnet_echo = False elif (self._check_local_option(BINARY) is True or self._check_local_option(BINARY) is UNKNOWN): self._note_local_option(ECHO, False) self._iac_wont(ECHO) self.telnet_echo = False elif option == SGA: if self._check_reply_pending(SGA): self._note_reply_pending(SGA, False) self._note_local_option(SGA, False) elif (self._check_remote_option(SGA) is True or self._check_remote_option(SGA) is UNKNOWN): self._note_local_option(SGA, False) self._iac_will(SGA) ## Just nod else: ## ALL OTHER OPTIONS = Default to ignoring pass ## Incoming WILL's and WONT's refer to the status of the DE #---[ WILL ]----------------------------------------------------------- elif cmd == WILL: if option == ECHO: ## Nutjob DE offering to echo the server... if self._check_remote_option(ECHO) is UNKNOWN: self._note_remote_option(ECHO, False) # No no, bad DE! self._iac_dont(ECHO) elif option == NAWS: if self._check_reply_pending(NAWS): self._note_reply_pending(NAWS, False) self._note_remote_option(NAWS, True) ## Nothing else to do, client follow with SB elif (self._check_remote_option(NAWS) is False or self._check_remote_option(NAWS) is UNKNOWN): self._note_remote_option(NAWS, True) self._iac_do(NAWS) ## Client should respond with SB elif option == SGA: if self._check_reply_pending(SGA): self._note_reply_pending(SGA, False) self._note_remote_option(SGA, True) elif (self._check_remote_option(SGA) is False or self._check_remote_option(SGA) is UNKNOWN): self._note_remote_option(SGA, True) self._iac_do(SGA) ## Just nod elif option == TTYPE: if self._check_reply_pending(TTYPE): self._note_reply_pending(TTYPE, False) self._note_remote_option(TTYPE, True) ## Tell them to send their terminal type self.send('%c%c%c%c%c%c' % (IAC, SB, TTYPE, SEND, IAC, SE)) elif (self._check_remote_option(TTYPE) is False or self._check_remote_option(TTYPE) is UNKNOWN): self._note_remote_option(TTYPE, True) self._iac_do(TTYPE) #---[ WONT ]----------------------------------------------------------- elif cmd == WONT: if option == ECHO: ## DE states it wont echo us -- good, they're not suppose to. if self._check_remote_option(ECHO) is UNKNOWN: self._note_remote_option(ECHO, False) self._iac_dont(ECHO) elif option == SGA: if self._check_reply_pending(SGA): self._note_reply_pending(SGA, False) self._note_remote_option(SGA, False) elif (self._check_remote_option(SGA) is True or self._check_remote_option(SGA) is UNKNOWN): self._note_remote_option(SGA, False) self._iac_dont(SGA) if self._check_reply_pending(TTYPE): self._note_reply_pending(TTYPE, False) self._note_remote_option(TTYPE, False) elif (self._check_remote_option(TTYPE) is True or self._check_remote_option(TTYPE) is UNKNOWN): self._note_remote_option(TTYPE, False) self._iac_dont(TTYPE) else: print "3BC: Should not be here." self.telnet_got_iac = False self.telnet_got_cmd = None def _sb_decoder(self): """ Figures out what to do with a received sub-negotiation block. """ #print "at decoder" bloc = self.telnet_sb_buffer if len(bloc) > 2: if bloc[0] == TTYPE and bloc[1] == IS: self.terminal_type = bloc[2:] #print "Terminal type = '%s'" % self.terminal_type if bloc[0] == NAWS: if len(bloc) != 5: print "Bad length on NAWS SB:", len(bloc) else: self.columns = (256 * ord(bloc[1])) + ord(bloc[2]) self.rows = (256 * ord(bloc[3])) + ord(bloc[4]) #print "Screen is %d x %d" % (self.columns, self.rows) self.telnet_sb_buffer = '' #---[ State Juggling for Telnet Options ]---------------------------------- ## Sometimes verbiage is tricky. I use 'note' rather than 'set' here ## because (to me) set infers something happened. def _check_local_option(self, option): """Test the status of local negotiated Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() return self.telnet_opt_dict[option].local_option def _note_local_option(self, option, state): """Record the status of local negotiated Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() self.telnet_opt_dict[option].local_option = state def _check_remote_option(self, option): """Test the status of remote negotiated Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() return self.telnet_opt_dict[option].remote_option def _note_remote_option(self, option, state): """Record the status of local negotiated Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() self.telnet_opt_dict[option].remote_option = state def _check_reply_pending(self, option): """Test the status of requested Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() return self.telnet_opt_dict[option].reply_pending def _note_reply_pending(self, option, state): """Record the status of requested Telnet options.""" if not self.telnet_opt_dict.has_key(option): self.telnet_opt_dict[option] = TelnetOption() self.telnet_opt_dict[option].reply_pending = state #---[ Telnet Command Shortcuts ]------------------------------------------- def _iac_do(self, option): """Send a Telnet IAC "DO" sequence.""" self.send('%c%c%c' % (IAC, DO, option)) def _iac_dont(self, option): """Send a Telnet IAC "DONT" sequence.""" self.send('%c%c%c' % (IAC, DONT, option)) def _iac_will(self, option): """Send a Telnet IAC "WILL" sequence.""" self.send('%c%c%c' % (IAC, WILL, option)) def _iac_wont(self, option): """Send a Telnet IAC "WONT" sequence.""" self.send('%c%c%c' % (IAC, WONT, option))
apache-2.0
anpingli/openshift-ansible
roles/lib_openshift/src/test/unit/test_oc_serviceaccount_secret.py
82
13262
''' Unit tests for oc secret add ''' import os import six import sys import unittest import mock # Removing invalid variable names for tests so that I can # keep them brief # pylint: disable=invalid-name,no-name-in-module # Disable import-error b/c our libraries aren't loaded in jenkins # pylint: disable=import-error,wrong-import-position # place class in our python path module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library') # noqa: E501 sys.path.insert(0, module_path) from oc_serviceaccount_secret import OCServiceAccountSecret, locate_oc_binary # noqa: E402 try: import ruamel.yaml as yaml # noqa: EF401 YAML_TYPE = 'ruamel' except ImportError: YAML_TYPE = 'pyyaml' class OCServiceAccountSecretTest(unittest.TestCase): ''' Test class for OCServiceAccountSecret ''' @mock.patch('oc_serviceaccount_secret.locate_oc_binary') @mock.patch('oc_serviceaccount_secret.Utils.create_tmpfile_copy') @mock.patch('oc_serviceaccount_secret.Yedit._write') @mock.patch('oc_serviceaccount_secret.OCServiceAccountSecret._run') def test_adding_a_secret_to_a_serviceaccount(self, mock_cmd, mock_write, mock_tmpfile_copy, mock_oc_binary): ''' Testing adding a secret to a service account ''' # Arrange # run_ansible input parameters params = { 'state': 'present', 'namespace': 'default', 'secret': 'newsecret', 'service_account': 'builder', 'kubeconfig': '/etc/origin/master/admin.kubeconfig', 'debug': False, } oc_get_sa_before = '''{ "apiVersion": "v1", "imagePullSecrets": [ { "name": "builder-dockercfg-rsrua" } ], "kind": "ServiceAccount", "metadata": { "name": "builder", "namespace": "default", "selfLink": "/api/v1/namespaces/default/serviceaccounts/builder", "uid": "cf47bca7-ebc4-11e6-b041-0ed9df7abc38", "resourceVersion": "302879", "creationTimestamp": "2017-02-05T17:02:00Z" }, "secrets": [ { "name": "builder-dockercfg-rsrua" }, { "name": "builder-token-akqxi" } ] } ''' oc_get_sa_after = '''{ "apiVersion": "v1", "imagePullSecrets": [ { "name": "builder-dockercfg-rsrua" } ], "kind": "ServiceAccount", "metadata": { "name": "builder", "namespace": "default", "selfLink": "/api/v1/namespaces/default/serviceaccounts/builder", "uid": "cf47bca7-ebc4-11e6-b041-0ed9df7abc38", "resourceVersion": "302879", "creationTimestamp": "2017-02-05T17:02:00Z" }, "secrets": [ { "name": "builder-dockercfg-rsrua" }, { "name": "builder-token-akqxi" }, { "name": "newsecret" } ] } ''' builder_ryaml_file = '''\ secrets: - name: builder-dockercfg-rsrua - name: builder-token-akqxi - name: newsecret kind: ServiceAccount imagePullSecrets: - name: builder-dockercfg-rsrua apiVersion: v1 metadata: name: builder namespace: default resourceVersion: '302879' creationTimestamp: '2017-02-05T17:02:00Z' selfLink: /api/v1/namespaces/default/serviceaccounts/builder uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 ''' builder_pyyaml_file = '''\ apiVersion: v1 imagePullSecrets: - name: builder-dockercfg-rsrua kind: ServiceAccount metadata: creationTimestamp: '2017-02-05T17:02:00Z' name: builder namespace: default resourceVersion: '302879' selfLink: /api/v1/namespaces/default/serviceaccounts/builder uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 secrets: - name: builder-dockercfg-rsrua - name: builder-token-akqxi - name: newsecret ''' # Return values of our mocked function call. These get returned once per call. mock_cmd.side_effect = [ (0, oc_get_sa_before, ''), # First call to the mock (0, oc_get_sa_before, ''), # Second call to the mock (0, 'serviceaccount "builder" replaced', ''), # Third call to the mock (0, oc_get_sa_after, ''), # Fourth call to the mock ] mock_oc_binary.side_effect = [ 'oc' ] mock_tmpfile_copy.side_effect = [ '/tmp/mocked_kubeconfig', ] # Act results = OCServiceAccountSecret.run_ansible(params, False) # Assert self.assertTrue(results['changed']) self.assertEqual(results['results']['returncode'], 0) self.assertEqual(results['state'], 'present') # Making sure our mocks were called as we expected mock_cmd.assert_has_calls([ mock.call(['oc', 'get', 'sa', 'builder', '-o', 'json', '-n', 'default'], None), mock.call(['oc', 'get', 'sa', 'builder', '-o', 'json', '-n', 'default'], None), mock.call(['oc', 'replace', '-f', mock.ANY, '-n', 'default'], None), mock.call(['oc', 'get', 'sa', 'builder', '-o', 'json', '-n', 'default'], None) ]) yaml_file = builder_pyyaml_file if YAML_TYPE == 'ruamel': yaml_file = builder_ryaml_file mock_write.assert_has_calls([ mock.call(mock.ANY, yaml_file) ]) @mock.patch('oc_serviceaccount_secret.locate_oc_binary') @mock.patch('oc_serviceaccount_secret.Utils.create_tmpfile_copy') @mock.patch('oc_serviceaccount_secret.Yedit._write') @mock.patch('oc_serviceaccount_secret.OCServiceAccountSecret._run') def test_removing_a_secret_to_a_serviceaccount(self, mock_cmd, mock_write, mock_tmpfile_copy, mock_oc_binary): ''' Testing removing a secret to a service account ''' # Arrange # run_ansible input parameters params = { 'state': 'absent', 'namespace': 'default', 'secret': 'newsecret', 'service_account': 'builder', 'kubeconfig': '/etc/origin/master/admin.kubeconfig', 'debug': False, } oc_get_sa_before = '''{ "apiVersion": "v1", "imagePullSecrets": [ { "name": "builder-dockercfg-rsrua" } ], "kind": "ServiceAccount", "metadata": { "name": "builder", "namespace": "default", "selfLink": "/api/v1/namespaces/default/serviceaccounts/builder", "uid": "cf47bca7-ebc4-11e6-b041-0ed9df7abc38", "resourceVersion": "302879", "creationTimestamp": "2017-02-05T17:02:00Z" }, "secrets": [ { "name": "builder-dockercfg-rsrua" }, { "name": "builder-token-akqxi" }, { "name": "newsecret" } ] } ''' builder_ryaml_file = '''\ secrets: - name: builder-dockercfg-rsrua - name: builder-token-akqxi kind: ServiceAccount imagePullSecrets: - name: builder-dockercfg-rsrua apiVersion: v1 metadata: name: builder namespace: default resourceVersion: '302879' creationTimestamp: '2017-02-05T17:02:00Z' selfLink: /api/v1/namespaces/default/serviceaccounts/builder uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 ''' builder_pyyaml_file = '''\ apiVersion: v1 imagePullSecrets: - name: builder-dockercfg-rsrua kind: ServiceAccount metadata: creationTimestamp: '2017-02-05T17:02:00Z' name: builder namespace: default resourceVersion: '302879' selfLink: /api/v1/namespaces/default/serviceaccounts/builder uid: cf47bca7-ebc4-11e6-b041-0ed9df7abc38 secrets: - name: builder-dockercfg-rsrua - name: builder-token-akqxi ''' # Return values of our mocked function call. These get returned once per call. mock_cmd.side_effect = [ (0, oc_get_sa_before, ''), # First call to the mock (0, oc_get_sa_before, ''), # Second call to the mock (0, 'serviceaccount "builder" replaced', ''), # Third call to the mock ] mock_oc_binary.side_effect = [ 'oc' ] mock_tmpfile_copy.side_effect = [ '/tmp/mocked_kubeconfig', ] # Act results = OCServiceAccountSecret.run_ansible(params, False) # Assert self.assertTrue(results['changed']) self.assertEqual(results['results']['returncode'], 0) self.assertEqual(results['state'], 'absent') # Making sure our mocks were called as we expected mock_cmd.assert_has_calls([ mock.call(['oc', 'get', 'sa', 'builder', '-o', 'json', '-n', 'default'], None), mock.call(['oc', 'get', 'sa', 'builder', '-o', 'json', '-n', 'default'], None), mock.call(['oc', 'replace', '-f', mock.ANY, '-n', 'default'], None), ]) yaml_file = builder_pyyaml_file if YAML_TYPE == 'ruamel': yaml_file = builder_ryaml_file mock_write.assert_has_calls([ mock.call(mock.ANY, yaml_file) ]) @unittest.skipIf(six.PY3, 'py2 test only') @mock.patch('os.path.exists') @mock.patch('os.environ.get') def test_binary_lookup_fallback(self, mock_env_get, mock_path_exists): ''' Testing binary lookup fallback ''' mock_env_get.side_effect = lambda _v, _d: '' mock_path_exists.side_effect = lambda _: False self.assertEqual(locate_oc_binary(), 'oc') @unittest.skipIf(six.PY3, 'py2 test only') @mock.patch('os.path.exists') @mock.patch('os.environ.get') def test_binary_lookup_in_path(self, mock_env_get, mock_path_exists): ''' Testing binary lookup in path ''' oc_bin = '/usr/bin/oc' mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' mock_path_exists.side_effect = lambda f: f == oc_bin self.assertEqual(locate_oc_binary(), oc_bin) @unittest.skipIf(six.PY3, 'py2 test only') @mock.patch('os.path.exists') @mock.patch('os.environ.get') def test_binary_lookup_in_usr_local(self, mock_env_get, mock_path_exists): ''' Testing binary lookup in /usr/local/bin ''' oc_bin = '/usr/local/bin/oc' mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' mock_path_exists.side_effect = lambda f: f == oc_bin self.assertEqual(locate_oc_binary(), oc_bin) @unittest.skipIf(six.PY3, 'py2 test only') @mock.patch('os.path.exists') @mock.patch('os.environ.get') def test_binary_lookup_in_home(self, mock_env_get, mock_path_exists): ''' Testing binary lookup in ~/bin ''' oc_bin = os.path.expanduser('~/bin/oc') mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' mock_path_exists.side_effect = lambda f: f == oc_bin self.assertEqual(locate_oc_binary(), oc_bin) @unittest.skipIf(six.PY2, 'py3 test only') @mock.patch('shutil.which') @mock.patch('os.environ.get') def test_binary_lookup_fallback_py3(self, mock_env_get, mock_shutil_which): ''' Testing binary lookup fallback ''' mock_env_get.side_effect = lambda _v, _d: '' mock_shutil_which.side_effect = lambda _f, path=None: None self.assertEqual(locate_oc_binary(), 'oc') @unittest.skipIf(six.PY2, 'py3 test only') @mock.patch('shutil.which') @mock.patch('os.environ.get') def test_binary_lookup_in_path_py3(self, mock_env_get, mock_shutil_which): ''' Testing binary lookup in path ''' oc_bin = '/usr/bin/oc' mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' mock_shutil_which.side_effect = lambda _f, path=None: oc_bin self.assertEqual(locate_oc_binary(), oc_bin) @unittest.skipIf(six.PY2, 'py3 test only') @mock.patch('shutil.which') @mock.patch('os.environ.get') def test_binary_lookup_in_usr_local_py3(self, mock_env_get, mock_shutil_which): ''' Testing binary lookup in /usr/local/bin ''' oc_bin = '/usr/local/bin/oc' mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' mock_shutil_which.side_effect = lambda _f, path=None: oc_bin self.assertEqual(locate_oc_binary(), oc_bin) @unittest.skipIf(six.PY2, 'py3 test only') @mock.patch('shutil.which') @mock.patch('os.environ.get') def test_binary_lookup_in_home_py3(self, mock_env_get, mock_shutil_which): ''' Testing binary lookup in ~/bin ''' oc_bin = os.path.expanduser('~/bin/oc') mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin' mock_shutil_which.side_effect = lambda _f, path=None: oc_bin self.assertEqual(locate_oc_binary(), oc_bin)
apache-2.0
jkenn99/phantomjs
src/qt/qtwebkit/Tools/QueueStatusServer/model/queuestatus.py
121
2109
# Copyright (C) 2013 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from config import messages from google.appengine.ext import db from model.queuepropertymixin import QueuePropertyMixin class QueueStatus(db.Model, QueuePropertyMixin): author = db.UserProperty() queue_name = db.StringProperty() bot_id = db.StringProperty() active_bug_id = db.IntegerProperty() active_patch_id = db.IntegerProperty() message = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) results_file = db.BlobProperty() def is_retry_request(self): return self.message == messages.retry_status
bsd-3-clause
wangjun/CaoLiuDownloader
catch.py
2
6767
import sys import logging import os import os.path import requests import re import ConfigParser def success(val): return val,None def error(why): return None,why def get_val(m_val): return m_val[0] def get_error(m_val): return m_val[1] class GetCaoliuPic(object): """docstring for ClassName""" def __init__(self): super(GetCaoliuPic, self).__init__() self.ImgRegex = r'<input\s*type=\'image\'\s*src\s*=\s*["\']?([^\'" >]+?)[ \'"]' self.ThreadsRegex = r'<h3><a\s*href\s*=\s*["\']?([^\'">]+?)[ \'"][^>]*?>(?:<font color=green>)?[^<]*(?:</font>)?</a></h3>' self._isUrlFormat = re.compile(r'https?://([\w-]+\.)+[\w-]+(/[\w\- ./?%&=]*)?'); self._path = self.DealDir("Images") self.currentDir = "" self.cf = ConfigParser.ConfigParser() self.pageNum = 1 self.isMono = True self.numToDownload = -1 self.loggingFile = 'log.txt' self.retryTimes = 5 self.caoliudomain = 'example.com' if not os.path.exists('config'): print('No config file. Creating a default one.') self.SetDefaultConfig(); self.LoadConfig() #init logging file logging.basicConfig(filename = os.path.join(os.getcwd(), self.loggingFile), level = logging.WARN, filemode = 'w', format = '%(asctime)s - %(levelname)s: %(message)s') print("=============== start ==============="); i = self.pageNum print("=============== loading page {0} ===============".format(i)) res = self.DoFetch(i) if get_error(res): print(get_error(res)) print("=============== end ===============") def LoadConfig(self): self.cf.read("config") self.pageNum = self.cf.getint('web','page') self.isMono = self.cf.getboolean('file','mono') self.numToDownload = self.cf.getint('web','num_to_download') self.loggingFile = self.cf.get('basic','log_file') self.retryTimes = self.cf.getint('web','retry_times') self.caoliudomain = self.cf.get('web','domain') def SetDefaultConfig(self): self.cf.add_section('basic') self.cf.set('basic','log_file','log.txt') self.cf.add_section('web') self.cf.set('web','page','1') self.cf.set('web','num_to_download','-1') self.cf.set('web','retry_times','5') self.cf.set('web','domain','example.com') self.cf.add_section('file') self.cf.set('file','mono','true') with open('config', 'wb') as configfile: self.cf.write(configfile) def DealDir(self, path): if not os.path.exists(path): os.mkdir(path); return path; def FetchHtml(self, url): retry = 0 while True: try: response = requests.get(url) if response.status_code != 200: return error("Failed to fetch html. CODE:%i" % response.status_code) elif (response.text) == 0: return error("Empty html.") else: return success(response.text) except requests.ConnectionError: if retry<self.retryTimes: retry+=1 print('Can\'t retrive html. retry %i' % retry) continue logging.error('Can not connect to %s' % url) return error("The server is not responding.") def DoFetch(self, pageNum): res = self.FetchHtml("http://"+self.caoliudomain+"/thread0806.php?fid=16&search=&page={0}".format(pageNum)) if get_error(res): return res html = get_val(res) self.FetchThreadsLinks(html); return success(0) def FetchThreadsLinks(self, htmlSource): prog = re.compile(self.ThreadsRegex, re.IGNORECASE) matchesThreads = prog.findall(htmlSource) num = 0 for href in matchesThreads: if self.CheckThreadsValid(href) is True: #print href threadurl = 'http://'+self.caoliudomain+'/' + href print('Thread '+str(num + 1)+':'+threadurl) self.currentDir = href.split('/')[-3] + href.split('/')[-2] + href.split('/')[-1] self.currentDir = self.currentDir.split('.')[-2] print(self.currentDir+'/') res = self.FetchImageLinks(threadurl) if(get_error(res)): print(get_error(res)) num+=1 if self.numToDownload>0 and num>=self.numToDownload: break def CheckThreadsValid(self, href): return href[0:8] == "htm_data" def FetchImageLinks(self, threadurl): res = self.FetchHtml(threadurl) if get_error(res): return res html = get_val(res) self.FetchLinksFromSource(html); return success(0) def FetchLinksFromSource(self, htmlSource): prog = re.compile(self.ImgRegex, re.IGNORECASE) matchesImgSrc = prog.findall(htmlSource) for href in matchesImgSrc: if not self.CheckIsUrlFormat(href): continue; res = self.download_file(href) if get_error(res): print(get_error(res)) def CheckIsUrlFormat(self, value): return self._isUrlFormat.match(value) is not None def download_file(self, url): local_filename = "" if self.isMono: local_filename = "Images/"+ url.split('/')[-1] else: self.DealDir("Images/" + self.currentDir) local_filename = "Images/" + self.currentDir + '/' + url.split('/')[-1] if os.path.exists(local_filename): return error('\t skip '+local_filename) else: print('\t=>'+local_filename) # NOTE the stream=True parameter retry = 0 while True: try: r = requests.get(url, stream=True) break except requests.ConnectionError: if retry<self.retryTimes: retry+=1 print('\tCan\'t retrive image. retry %i' % retry) continue logging.error('Can not connect to %s' % url) return error('The server is not responding.') with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() return success(local_filename) if __name__ == '__main__': g = GetCaoliuPic()
mit
bottompawn/kbengine
kbe/src/lib/python/Lib/plat-darwin/IN.py
109
13954
# Generated by h2py from /usr/include/netinet/in.h # Included from sys/appleapiopts.h # Included from sys/_types.h # Included from sys/cdefs.h def __P(protos): return protos def __STRING(x): return #x def __P(protos): return () def __STRING(x): return "x" def __attribute__(x): return def __COPYRIGHT(s): return __IDSTRING(copyright,s) def __RCSID(s): return __IDSTRING(rcsid,s) def __SCCSID(s): return __IDSTRING(sccsid,s) def __PROJECT_VERSION(s): return __IDSTRING(project_version,s) __DARWIN_UNIX03 = 1 __DARWIN_UNIX03 = 0 __DARWIN_UNIX03 = 0 __DARWIN_UNIX03 = 1 __DARWIN_64_BIT_INO_T = 1 __DARWIN_64_BIT_INO_T = 0 __DARWIN_64_BIT_INO_T = 0 __DARWIN_NON_CANCELABLE = 0 __DARWIN_VERS_1050 = 1 __DARWIN_VERS_1050 = 0 __DARWIN_SUF_UNIX03 = "$UNIX2003" __DARWIN_SUF_UNIX03_SET = 1 __DARWIN_SUF_UNIX03_SET = 0 __DARWIN_SUF_64_BIT_INO_T = "$INODE64" __DARWIN_SUF_NON_CANCELABLE = "$NOCANCEL" __DARWIN_SUF_1050 = "$1050" __DARWIN_SUF_UNIX03_SET = 0 __DARWIN_SUF_EXTSN = "$DARWIN_EXTSN" __DARWIN_LONG_DOUBLE_IS_DOUBLE = 0 def __DARWIN_LDBL_COMPAT(x): return def __DARWIN_LDBL_COMPAT2(x): return __DARWIN_LONG_DOUBLE_IS_DOUBLE = 1 def __DARWIN_LDBL_COMPAT(x): return def __DARWIN_LDBL_COMPAT2(x): return __DARWIN_LONG_DOUBLE_IS_DOUBLE = 0 _DARWIN_FEATURE_LONG_DOUBLE_IS_DOUBLE = 1 _DARWIN_FEATURE_UNIX_CONFORMANCE = 3 _DARWIN_FEATURE_64_BIT_INODE = 1 # Included from machine/_types.h __PTHREAD_SIZE__ = 1168 __PTHREAD_ATTR_SIZE__ = 56 __PTHREAD_MUTEXATTR_SIZE__ = 8 __PTHREAD_MUTEX_SIZE__ = 56 __PTHREAD_CONDATTR_SIZE__ = 8 __PTHREAD_COND_SIZE__ = 40 __PTHREAD_ONCE_SIZE__ = 8 __PTHREAD_RWLOCK_SIZE__ = 192 __PTHREAD_RWLOCKATTR_SIZE__ = 16 __PTHREAD_SIZE__ = 596 __PTHREAD_ATTR_SIZE__ = 36 __PTHREAD_MUTEXATTR_SIZE__ = 8 __PTHREAD_MUTEX_SIZE__ = 40 __PTHREAD_CONDATTR_SIZE__ = 4 __PTHREAD_COND_SIZE__ = 24 __PTHREAD_ONCE_SIZE__ = 4 __PTHREAD_RWLOCK_SIZE__ = 124 __PTHREAD_RWLOCKATTR_SIZE__ = 12 __DARWIN_NULL = 0 # Included from stdint.h __WORDSIZE = 64 __WORDSIZE = 32 INT8_MAX = 127 INT16_MAX = 32767 INT32_MAX = 2147483647 INT8_MIN = -128 INT16_MIN = -32768 INT32_MIN = (-INT32_MAX-1) UINT8_MAX = 255 UINT16_MAX = 65535 INT_LEAST8_MIN = INT8_MIN INT_LEAST16_MIN = INT16_MIN INT_LEAST32_MIN = INT32_MIN INT_LEAST8_MAX = INT8_MAX INT_LEAST16_MAX = INT16_MAX INT_LEAST32_MAX = INT32_MAX UINT_LEAST8_MAX = UINT8_MAX UINT_LEAST16_MAX = UINT16_MAX INT_FAST8_MIN = INT8_MIN INT_FAST16_MIN = INT16_MIN INT_FAST32_MIN = INT32_MIN INT_FAST8_MAX = INT8_MAX INT_FAST16_MAX = INT16_MAX INT_FAST32_MAX = INT32_MAX UINT_FAST8_MAX = UINT8_MAX UINT_FAST16_MAX = UINT16_MAX INTPTR_MIN = INT32_MIN INTPTR_MAX = INT32_MAX PTRDIFF_MIN = INT32_MIN PTRDIFF_MAX = INT32_MAX WCHAR_MAX = 0x7fffffff WCHAR_MIN = 0 WCHAR_MIN = (-WCHAR_MAX-1) WINT_MIN = INT32_MIN WINT_MAX = INT32_MAX SIG_ATOMIC_MIN = INT32_MIN SIG_ATOMIC_MAX = INT32_MAX def INT8_C(v): return (v) def INT16_C(v): return (v) def INT32_C(v): return (v) # Included from sys/socket.h # Included from machine/_param.h SOCK_STREAM = 1 SOCK_DGRAM = 2 SOCK_RAW = 3 SOCK_RDM = 4 SOCK_SEQPACKET = 5 SO_DEBUG = 0x0001 SO_ACCEPTCONN = 0x0002 SO_REUSEADDR = 0x0004 SO_KEEPALIVE = 0x0008 SO_DONTROUTE = 0x0010 SO_BROADCAST = 0x0020 SO_USELOOPBACK = 0x0040 SO_LINGER = 0x0080 SO_LINGER = 0x1080 SO_OOBINLINE = 0x0100 SO_REUSEPORT = 0x0200 SO_TIMESTAMP = 0x0400 SO_ACCEPTFILTER = 0x1000 SO_DONTTRUNC = 0x2000 SO_WANTMORE = 0x4000 SO_WANTOOBFLAG = 0x8000 SO_SNDBUF = 0x1001 SO_RCVBUF = 0x1002 SO_SNDLOWAT = 0x1003 SO_RCVLOWAT = 0x1004 SO_SNDTIMEO = 0x1005 SO_RCVTIMEO = 0x1006 SO_ERROR = 0x1007 SO_TYPE = 0x1008 SO_NREAD = 0x1020 SO_NKE = 0x1021 SO_NOSIGPIPE = 0x1022 SO_NOADDRERR = 0x1023 SO_NWRITE = 0x1024 SO_REUSESHAREUID = 0x1025 SO_NOTIFYCONFLICT = 0x1026 SO_LINGER_SEC = 0x1080 SO_RESTRICTIONS = 0x1081 SO_RESTRICT_DENYIN = 0x00000001 SO_RESTRICT_DENYOUT = 0x00000002 SO_RESTRICT_DENYSET = (-2147483648) SO_LABEL = 0x1010 SO_PEERLABEL = 0x1011 SOL_SOCKET = 0xffff AF_UNSPEC = 0 AF_UNIX = 1 AF_LOCAL = AF_UNIX AF_INET = 2 AF_IMPLINK = 3 AF_PUP = 4 AF_CHAOS = 5 AF_NS = 6 AF_ISO = 7 AF_OSI = AF_ISO AF_ECMA = 8 AF_DATAKIT = 9 AF_CCITT = 10 AF_SNA = 11 AF_DECnet = 12 AF_DLI = 13 AF_LAT = 14 AF_HYLINK = 15 AF_APPLETALK = 16 AF_ROUTE = 17 AF_LINK = 18 pseudo_AF_XTP = 19 AF_COIP = 20 AF_CNT = 21 pseudo_AF_RTIP = 22 AF_IPX = 23 AF_SIP = 24 pseudo_AF_PIP = 25 AF_NDRV = 27 AF_ISDN = 28 AF_E164 = AF_ISDN pseudo_AF_KEY = 29 AF_INET6 = 30 AF_NATM = 31 AF_SYSTEM = 32 AF_NETBIOS = 33 AF_PPP = 34 AF_ATM = 30 pseudo_AF_HDRCMPLT = 35 AF_RESERVED_36 = 36 AF_NETGRAPH = 32 AF_MAX = 37 SOCK_MAXADDRLEN = 255 _SS_MAXSIZE = 128 PF_UNSPEC = AF_UNSPEC PF_LOCAL = AF_LOCAL PF_UNIX = PF_LOCAL PF_INET = AF_INET PF_IMPLINK = AF_IMPLINK PF_PUP = AF_PUP PF_CHAOS = AF_CHAOS PF_NS = AF_NS PF_ISO = AF_ISO PF_OSI = AF_ISO PF_ECMA = AF_ECMA PF_DATAKIT = AF_DATAKIT PF_CCITT = AF_CCITT PF_SNA = AF_SNA PF_DECnet = AF_DECnet PF_DLI = AF_DLI PF_LAT = AF_LAT PF_HYLINK = AF_HYLINK PF_APPLETALK = AF_APPLETALK PF_ROUTE = AF_ROUTE PF_LINK = AF_LINK PF_XTP = pseudo_AF_XTP PF_COIP = AF_COIP PF_CNT = AF_CNT PF_SIP = AF_SIP PF_IPX = AF_IPX PF_RTIP = pseudo_AF_RTIP PF_PIP = pseudo_AF_PIP PF_NDRV = AF_NDRV PF_ISDN = AF_ISDN PF_KEY = pseudo_AF_KEY PF_INET6 = AF_INET6 PF_NATM = AF_NATM PF_SYSTEM = AF_SYSTEM PF_NETBIOS = AF_NETBIOS PF_PPP = AF_PPP PF_RESERVED_36 = AF_RESERVED_36 PF_ATM = AF_ATM PF_NETGRAPH = AF_NETGRAPH PF_MAX = AF_MAX NET_MAXID = AF_MAX NET_RT_DUMP = 1 NET_RT_FLAGS = 2 NET_RT_IFLIST = 3 NET_RT_STAT = 4 NET_RT_TRASH = 5 NET_RT_IFLIST2 = 6 NET_RT_DUMP2 = 7 NET_RT_MAXID = 8 SOMAXCONN = 128 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_DONTROUTE = 0x4 MSG_EOR = 0x8 MSG_TRUNC = 0x10 MSG_CTRUNC = 0x20 MSG_WAITALL = 0x40 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_WAITSTREAM = 0x200 MSG_FLUSH = 0x400 MSG_HOLD = 0x800 MSG_SEND = 0x1000 MSG_HAVEMORE = 0x2000 MSG_RCVMORE = 0x4000 MSG_NEEDSA = 0x10000 CMGROUP_MAX = 16 SCM_RIGHTS = 0x01 SCM_TIMESTAMP = 0x02 SCM_CREDS = 0x03 SHUT_RD = 0 SHUT_WR = 1 SHUT_RDWR = 2 # Included from machine/endian.h # Included from sys/_endian.h def ntohl(x): return (x) def ntohs(x): return (x) def htonl(x): return (x) def htons(x): return (x) def NTOHL(x): return (x) def NTOHS(x): return (x) def HTONL(x): return (x) def HTONS(x): return (x) # Included from libkern/_OSByteOrder.h def __DARWIN_OSSwapConstInt16(x): return \ def __DARWIN_OSSwapConstInt32(x): return \ def __DARWIN_OSSwapConstInt64(x): return \ # Included from libkern/i386/_OSByteOrder.h def __DARWIN_OSSwapInt16(x): return \ def __DARWIN_OSSwapInt32(x): return \ def __DARWIN_OSSwapInt64(x): return \ def __DARWIN_OSSwapInt16(x): return _OSSwapInt16(x) def __DARWIN_OSSwapInt32(x): return _OSSwapInt32(x) def __DARWIN_OSSwapInt64(x): return _OSSwapInt64(x) def ntohs(x): return __DARWIN_OSSwapInt16(x) def htons(x): return __DARWIN_OSSwapInt16(x) def ntohl(x): return __DARWIN_OSSwapInt32(x) def htonl(x): return __DARWIN_OSSwapInt32(x) IPPROTO_IP = 0 IPPROTO_HOPOPTS = 0 IPPROTO_ICMP = 1 IPPROTO_IGMP = 2 IPPROTO_GGP = 3 IPPROTO_IPV4 = 4 IPPROTO_IPIP = IPPROTO_IPV4 IPPROTO_TCP = 6 IPPROTO_ST = 7 IPPROTO_EGP = 8 IPPROTO_PIGP = 9 IPPROTO_RCCMON = 10 IPPROTO_NVPII = 11 IPPROTO_PUP = 12 IPPROTO_ARGUS = 13 IPPROTO_EMCON = 14 IPPROTO_XNET = 15 IPPROTO_CHAOS = 16 IPPROTO_UDP = 17 IPPROTO_MUX = 18 IPPROTO_MEAS = 19 IPPROTO_HMP = 20 IPPROTO_PRM = 21 IPPROTO_IDP = 22 IPPROTO_TRUNK1 = 23 IPPROTO_TRUNK2 = 24 IPPROTO_LEAF1 = 25 IPPROTO_LEAF2 = 26 IPPROTO_RDP = 27 IPPROTO_IRTP = 28 IPPROTO_TP = 29 IPPROTO_BLT = 30 IPPROTO_NSP = 31 IPPROTO_INP = 32 IPPROTO_SEP = 33 IPPROTO_3PC = 34 IPPROTO_IDPR = 35 IPPROTO_XTP = 36 IPPROTO_DDP = 37 IPPROTO_CMTP = 38 IPPROTO_TPXX = 39 IPPROTO_IL = 40 IPPROTO_IPV6 = 41 IPPROTO_SDRP = 42 IPPROTO_ROUTING = 43 IPPROTO_FRAGMENT = 44 IPPROTO_IDRP = 45 IPPROTO_RSVP = 46 IPPROTO_GRE = 47 IPPROTO_MHRP = 48 IPPROTO_BHA = 49 IPPROTO_ESP = 50 IPPROTO_AH = 51 IPPROTO_INLSP = 52 IPPROTO_SWIPE = 53 IPPROTO_NHRP = 54 IPPROTO_ICMPV6 = 58 IPPROTO_NONE = 59 IPPROTO_DSTOPTS = 60 IPPROTO_AHIP = 61 IPPROTO_CFTP = 62 IPPROTO_HELLO = 63 IPPROTO_SATEXPAK = 64 IPPROTO_KRYPTOLAN = 65 IPPROTO_RVD = 66 IPPROTO_IPPC = 67 IPPROTO_ADFS = 68 IPPROTO_SATMON = 69 IPPROTO_VISA = 70 IPPROTO_IPCV = 71 IPPROTO_CPNX = 72 IPPROTO_CPHB = 73 IPPROTO_WSN = 74 IPPROTO_PVP = 75 IPPROTO_BRSATMON = 76 IPPROTO_ND = 77 IPPROTO_WBMON = 78 IPPROTO_WBEXPAK = 79 IPPROTO_EON = 80 IPPROTO_VMTP = 81 IPPROTO_SVMTP = 82 IPPROTO_VINES = 83 IPPROTO_TTP = 84 IPPROTO_IGP = 85 IPPROTO_DGP = 86 IPPROTO_TCF = 87 IPPROTO_IGRP = 88 IPPROTO_OSPFIGP = 89 IPPROTO_SRPC = 90 IPPROTO_LARP = 91 IPPROTO_MTP = 92 IPPROTO_AX25 = 93 IPPROTO_IPEIP = 94 IPPROTO_MICP = 95 IPPROTO_SCCSP = 96 IPPROTO_ETHERIP = 97 IPPROTO_ENCAP = 98 IPPROTO_APES = 99 IPPROTO_GMTP = 100 IPPROTO_IPCOMP = 108 IPPROTO_PIM = 103 IPPROTO_PGM = 113 IPPROTO_DIVERT = 254 IPPROTO_RAW = 255 IPPROTO_MAX = 256 IPPROTO_DONE = 257 __DARWIN_IPPORT_RESERVED = 1024 IPPORT_RESERVED = __DARWIN_IPPORT_RESERVED IPPORT_USERRESERVED = 5000 IPPORT_HIFIRSTAUTO = 49152 IPPORT_HILASTAUTO = 65535 IPPORT_RESERVEDSTART = 600 def IN_CLASSA(i): return (((u_int32_t)(i) & (-2147483648)) == 0) IN_CLASSA_NET = (-16777216) IN_CLASSA_NSHIFT = 24 IN_CLASSA_HOST = 0x00ffffff IN_CLASSA_MAX = 128 def IN_CLASSB(i): return (((u_int32_t)(i) & (-1073741824)) == (-2147483648)) IN_CLASSB_NET = (-65536) IN_CLASSB_NSHIFT = 16 IN_CLASSB_HOST = 0x0000ffff IN_CLASSB_MAX = 65536 def IN_CLASSC(i): return (((u_int32_t)(i) & (-536870912)) == (-1073741824)) IN_CLASSC_NET = (-256) IN_CLASSC_NSHIFT = 8 IN_CLASSC_HOST = 0x000000ff def IN_CLASSD(i): return (((u_int32_t)(i) & (-268435456)) == (-536870912)) IN_CLASSD_NET = (-268435456) IN_CLASSD_NSHIFT = 28 IN_CLASSD_HOST = 0x0fffffff def IN_MULTICAST(i): return IN_CLASSD(i) def IN_EXPERIMENTAL(i): return (((u_int32_t)(i) & (-268435456)) == (-268435456)) def IN_BADCLASS(i): return (((u_int32_t)(i) & (-268435456)) == (-268435456)) INADDR_NONE = (-1) def IN_LINKLOCAL(i): return (((u_int32_t)(i) & IN_CLASSB_NET) == IN_LINKLOCALNETNUM) IN_LOOPBACKNET = 127 INET_ADDRSTRLEN = 16 IP_OPTIONS = 1 IP_HDRINCL = 2 IP_TOS = 3 IP_TTL = 4 IP_RECVOPTS = 5 IP_RECVRETOPTS = 6 IP_RECVDSTADDR = 7 IP_RETOPTS = 8 IP_MULTICAST_IF = 9 IP_MULTICAST_TTL = 10 IP_MULTICAST_LOOP = 11 IP_ADD_MEMBERSHIP = 12 IP_DROP_MEMBERSHIP = 13 IP_MULTICAST_VIF = 14 IP_RSVP_ON = 15 IP_RSVP_OFF = 16 IP_RSVP_VIF_ON = 17 IP_RSVP_VIF_OFF = 18 IP_PORTRANGE = 19 IP_RECVIF = 20 IP_IPSEC_POLICY = 21 IP_FAITH = 22 IP_STRIPHDR = 23 IP_RECVTTL = 24 IP_FW_ADD = 40 IP_FW_DEL = 41 IP_FW_FLUSH = 42 IP_FW_ZERO = 43 IP_FW_GET = 44 IP_FW_RESETLOG = 45 IP_OLD_FW_ADD = 50 IP_OLD_FW_DEL = 51 IP_OLD_FW_FLUSH = 52 IP_OLD_FW_ZERO = 53 IP_OLD_FW_GET = 54 IP_NAT__XXX = 55 IP_OLD_FW_RESETLOG = 56 IP_DUMMYNET_CONFIGURE = 60 IP_DUMMYNET_DEL = 61 IP_DUMMYNET_FLUSH = 62 IP_DUMMYNET_GET = 64 IP_TRAFFIC_MGT_BACKGROUND = 65 IP_FORCE_OUT_IFP = 69 TRAFFIC_MGT_SO_BACKGROUND = 0x0001 TRAFFIC_MGT_SO_BG_SUPPRESSED = 0x0002 IP_DEFAULT_MULTICAST_TTL = 1 IP_DEFAULT_MULTICAST_LOOP = 1 IP_MAX_MEMBERSHIPS = 20 IP_PORTRANGE_DEFAULT = 0 IP_PORTRANGE_HIGH = 1 IP_PORTRANGE_LOW = 2 IPPROTO_MAXID = (IPPROTO_AH + 1) IPCTL_FORWARDING = 1 IPCTL_SENDREDIRECTS = 2 IPCTL_DEFTTL = 3 IPCTL_DEFMTU = 4 IPCTL_RTEXPIRE = 5 IPCTL_RTMINEXPIRE = 6 IPCTL_RTMAXCACHE = 7 IPCTL_SOURCEROUTE = 8 IPCTL_DIRECTEDBROADCAST = 9 IPCTL_INTRQMAXLEN = 10 IPCTL_INTRQDROPS = 11 IPCTL_STATS = 12 IPCTL_ACCEPTSOURCEROUTE = 13 IPCTL_FASTFORWARDING = 14 IPCTL_KEEPFAITH = 15 IPCTL_GIF_TTL = 16 IPCTL_MAXID = 17 # Included from netinet6/in6.h __KAME_VERSION = "20010528/apple-darwin" IPV6PORT_RESERVED = 1024 IPV6PORT_ANONMIN = 49152 IPV6PORT_ANONMAX = 65535 IPV6PORT_RESERVEDMIN = 600 IPV6PORT_RESERVEDMAX = (IPV6PORT_RESERVED-1) INET6_ADDRSTRLEN = 46 def IN6_IS_ADDR_UNSPECIFIED(a): return \ def IN6_IS_ADDR_LOOPBACK(a): return \ def IN6_IS_ADDR_V4COMPAT(a): return \ def IN6_IS_ADDR_V4MAPPED(a): return \ __IPV6_ADDR_SCOPE_NODELOCAL = 0x01 __IPV6_ADDR_SCOPE_LINKLOCAL = 0x02 __IPV6_ADDR_SCOPE_SITELOCAL = 0x05 __IPV6_ADDR_SCOPE_ORGLOCAL = 0x08 __IPV6_ADDR_SCOPE_GLOBAL = 0x0e def IN6_IS_ADDR_LINKLOCAL(a): return \ def IN6_IS_ADDR_SITELOCAL(a): return \ def IN6_IS_ADDR_MC_NODELOCAL(a): return \ def IN6_IS_ADDR_MC_LINKLOCAL(a): return \ def IN6_IS_ADDR_MC_SITELOCAL(a): return \ def IN6_IS_ADDR_MC_ORGLOCAL(a): return \ def IN6_IS_ADDR_MC_GLOBAL(a): return \ IPV6_OPTIONS = 1 IPV6_RECVOPTS = 5 IPV6_RECVRETOPTS = 6 IPV6_RECVDSTADDR = 7 IPV6_RETOPTS = 8 IPV6_SOCKOPT_RESERVED1 = 3 IPV6_UNICAST_HOPS = 4 IPV6_MULTICAST_IF = 9 IPV6_MULTICAST_HOPS = 10 IPV6_MULTICAST_LOOP = 11 IPV6_JOIN_GROUP = 12 IPV6_LEAVE_GROUP = 13 IPV6_PORTRANGE = 14 ICMP6_FILTER = 18 IPV6_PKTINFO = 19 IPV6_HOPLIMIT = 20 IPV6_NEXTHOP = 21 IPV6_HOPOPTS = 22 IPV6_DSTOPTS = 23 IPV6_RTHDR = 24 IPV6_PKTOPTIONS = 25 IPV6_CHECKSUM = 26 IPV6_V6ONLY = 27 IPV6_BINDV6ONLY = IPV6_V6ONLY IPV6_IPSEC_POLICY = 28 IPV6_FAITH = 29 IPV6_FW_ADD = 30 IPV6_FW_DEL = 31 IPV6_FW_FLUSH = 32 IPV6_FW_ZERO = 33 IPV6_FW_GET = 34 IPV6_RTHDR_LOOSE = 0 IPV6_RTHDR_STRICT = 1 IPV6_RTHDR_TYPE_0 = 0 IPV6_DEFAULT_MULTICAST_HOPS = 1 IPV6_DEFAULT_MULTICAST_LOOP = 1 IPV6_PORTRANGE_DEFAULT = 0 IPV6_PORTRANGE_HIGH = 1 IPV6_PORTRANGE_LOW = 2 IPV6PROTO_MAXID = (IPPROTO_PIM + 1) IPV6CTL_FORWARDING = 1 IPV6CTL_SENDREDIRECTS = 2 IPV6CTL_DEFHLIM = 3 IPV6CTL_DEFMTU = 4 IPV6CTL_FORWSRCRT = 5 IPV6CTL_STATS = 6 IPV6CTL_MRTSTATS = 7 IPV6CTL_MRTPROTO = 8 IPV6CTL_MAXFRAGPACKETS = 9 IPV6CTL_SOURCECHECK = 10 IPV6CTL_SOURCECHECK_LOGINT = 11 IPV6CTL_ACCEPT_RTADV = 12 IPV6CTL_KEEPFAITH = 13 IPV6CTL_LOG_INTERVAL = 14 IPV6CTL_HDRNESTLIMIT = 15 IPV6CTL_DAD_COUNT = 16 IPV6CTL_AUTO_FLOWLABEL = 17 IPV6CTL_DEFMCASTHLIM = 18 IPV6CTL_GIF_HLIM = 19 IPV6CTL_KAME_VERSION = 20 IPV6CTL_USE_DEPRECATED = 21 IPV6CTL_RR_PRUNE = 22 IPV6CTL_MAPPED_ADDR = 23 IPV6CTL_V6ONLY = 24 IPV6CTL_RTEXPIRE = 25 IPV6CTL_RTMINEXPIRE = 26 IPV6CTL_RTMAXCACHE = 27 IPV6CTL_USETEMPADDR = 32 IPV6CTL_TEMPPLTIME = 33 IPV6CTL_TEMPVLTIME = 34 IPV6CTL_AUTO_LINKLOCAL = 35 IPV6CTL_RIP6STATS = 36 IPV6CTL_MAXFRAGS = 41 IPV6CTL_MAXID = 42
lgpl-3.0
jmesteve/medical
openerp/addons/stock/wizard/stock_partial_picking.py
11
12706
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-TODAY OpenERP SA (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from lxml import etree from openerp.osv import fields, osv from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools.float_utils import float_compare import openerp.addons.decimal_precision as dp from openerp.tools.translate import _ class stock_partial_picking_line(osv.TransientModel): def _tracking(self, cursor, user, ids, name, arg, context=None): res = {} for tracklot in self.browse(cursor, user, ids, context=context): tracking = False if (tracklot.move_id.picking_id.type == 'in' and tracklot.product_id.track_incoming == True) or \ (tracklot.move_id.picking_id.type == 'out' and tracklot.product_id.track_outgoing == True): tracking = True res[tracklot.id] = tracking return res _name = "stock.partial.picking.line" _rec_name = 'product_id' _columns = { 'product_id' : fields.many2one('product.product', string="Product", required=True, ondelete='CASCADE'), 'quantity' : fields.float("Quantity", digits_compute=dp.get_precision('Product Unit of Measure'), required=True), 'product_uom': fields.many2one('product.uom', 'Unit of Measure', required=True, ondelete='CASCADE'), 'prodlot_id' : fields.many2one('stock.production.lot', 'Serial Number', ondelete='CASCADE'), 'location_id': fields.many2one('stock.location', 'Location', required=True, ondelete='CASCADE', domain = [('usage','<>','view')]), 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', required=True, ondelete='CASCADE',domain = [('usage','<>','view')]), 'move_id' : fields.many2one('stock.move', "Move", ondelete='CASCADE'), 'wizard_id' : fields.many2one('stock.partial.picking', string="Wizard", ondelete='CASCADE'), 'update_cost': fields.boolean('Need cost update'), 'cost' : fields.float("Cost", help="Unit Cost for this product line"), 'currency' : fields.many2one('res.currency', string="Currency", help="Currency in which Unit cost is expressed", ondelete='CASCADE'), 'tracking': fields.function(_tracking, string='Tracking', type='boolean'), } def onchange_product_id(self, cr, uid, ids, product_id, context=None): uom_id = False if product_id: product = self.pool.get('product.product').browse(cr, uid, product_id, context=context) uom_id = product.uom_id.id return {'value': {'product_uom': uom_id}} class stock_partial_picking(osv.osv_memory): _name = "stock.partial.picking" _rec_name = 'picking_id' _description = "Partial Picking Processing Wizard" def _hide_tracking(self, cursor, user, ids, name, arg, context=None): res = {} for wizard in self.browse(cursor, user, ids, context=context): res[wizard.id] = any([not(x.tracking) for x in wizard.move_ids]) return res _columns = { 'date': fields.datetime('Date', required=True), 'move_ids' : fields.one2many('stock.partial.picking.line', 'wizard_id', 'Product Moves'), 'picking_id': fields.many2one('stock.picking', 'Picking', required=True, ondelete='CASCADE'), 'hide_tracking': fields.function(_hide_tracking, string='Tracking', type='boolean', help='This field is for internal purpose. It is used to decide if the column production lot has to be shown on the moves or not.'), } def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): #override of fields_view_get in order to change the label of the process button and the separator accordingly to the shipping type if context is None: context={} res = super(stock_partial_picking, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) type = context.get('default_type', False) if type: doc = etree.XML(res['arch']) for node in doc.xpath("//button[@name='do_partial']"): if type == 'in': node.set('string', _('_Receive')) elif type == 'out': node.set('string', _('_Deliver')) for node in doc.xpath("//separator[@name='product_separator']"): if type == 'in': node.set('string', _('Receive Products')) elif type == 'out': node.set('string', _('Deliver Products')) res['arch'] = etree.tostring(doc) return res def default_get(self, cr, uid, fields, context=None): if context is None: context = {} res = super(stock_partial_picking, self).default_get(cr, uid, fields, context=context) picking_ids = context.get('active_ids', []) active_model = context.get('active_model') if not picking_ids or len(picking_ids) != 1: # Partial Picking Processing may only be done for one picking at a time return res assert active_model in ('stock.picking', 'stock.picking.in', 'stock.picking.out'), 'Bad context propagation' picking_id, = picking_ids if 'picking_id' in fields: res.update(picking_id=picking_id) if 'move_ids' in fields: picking = self.pool.get('stock.picking').browse(cr, uid, picking_id, context=context) moves = [self._partial_move_for(cr, uid, m) for m in picking.move_lines if m.state not in ('done','cancel')] res.update(move_ids=moves) if 'date' in fields: res.update(date=time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) return res def _product_cost_for_average_update(self, cr, uid, move): """Returns product cost and currency ID for the given move, suited for re-computing the average product cost. :return: map of the form:: {'cost': 123.34, 'currency': 42} """ # Currently, the cost on the product form is supposed to be expressed in the currency # of the company owning the product. If not set, we fall back to the picking's company, # which should work in simple cases. product_currency_id = move.product_id.company_id.currency_id and move.product_id.company_id.currency_id.id picking_currency_id = move.picking_id.company_id.currency_id and move.picking_id.company_id.currency_id.id return {'cost': move.product_id.standard_price, 'currency': product_currency_id or picking_currency_id or False} def _partial_move_for(self, cr, uid, move): partial_move = { 'product_id' : move.product_id.id, 'quantity' : move.product_qty if move.state == 'assigned' else 0, 'product_uom' : move.product_uom.id, 'prodlot_id' : move.prodlot_id.id, 'move_id' : move.id, 'location_id' : move.location_id.id, 'location_dest_id' : move.location_dest_id.id, } if move.picking_id.type == 'in' and move.product_id.cost_method == 'average': partial_move.update(update_cost=True, **self._product_cost_for_average_update(cr, uid, move)) return partial_move def do_partial(self, cr, uid, ids, context=None): assert len(ids) == 1, 'Partial picking processing may only be done one at a time.' stock_picking = self.pool.get('stock.picking') stock_move = self.pool.get('stock.move') uom_obj = self.pool.get('product.uom') partial = self.browse(cr, uid, ids[0], context=context) partial_data = { 'delivery_date' : partial.date } picking_type = partial.picking_id.type for wizard_line in partial.move_ids: line_uom = wizard_line.product_uom move_id = wizard_line.move_id.id #Quantiny must be Positive if wizard_line.quantity < 0: raise osv.except_osv(_('Warning!'), _('Please provide proper Quantity.')) #Compute the quantity for respective wizard_line in the line uom (this jsut do the rounding if necessary) qty_in_line_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, line_uom.id) if line_uom.factor and line_uom.factor <> 0: if float_compare(qty_in_line_uom, wizard_line.quantity, precision_rounding=line_uom.rounding) != 0: raise osv.except_osv(_('Warning!'), _('The unit of measure rounding does not allow you to ship "%s %s", only rounding of "%s %s" is accepted by the Unit of Measure.') % (wizard_line.quantity, line_uom.name, line_uom.rounding, line_uom.name)) if move_id: #Check rounding Quantity.ex. #picking: 1kg, uom kg rounding = 0.01 (rounding to 10g), #partial delivery: 253g #=> result= refused, as the qty left on picking would be 0.747kg and only 0.75 is accepted by the uom. initial_uom = wizard_line.move_id.product_uom #Compute the quantity for respective wizard_line in the initial uom qty_in_initial_uom = uom_obj._compute_qty(cr, uid, line_uom.id, wizard_line.quantity, initial_uom.id) without_rounding_qty = (wizard_line.quantity / line_uom.factor) * initial_uom.factor if float_compare(qty_in_initial_uom, without_rounding_qty, precision_rounding=initial_uom.rounding) != 0: raise osv.except_osv(_('Warning!'), _('The rounding of the initial uom does not allow you to ship "%s %s", as it would let a quantity of "%s %s" to ship and only rounding of "%s %s" is accepted by the uom.') % (wizard_line.quantity, line_uom.name, wizard_line.move_id.product_qty - without_rounding_qty, initial_uom.name, initial_uom.rounding, initial_uom.name)) else: seq_obj_name = 'stock.picking.' + picking_type move_id = stock_move.create(cr,uid,{'name' : self.pool.get('ir.sequence').get(cr, uid, seq_obj_name), 'product_id': wizard_line.product_id.id, 'product_qty': wizard_line.quantity, 'product_uom': wizard_line.product_uom.id, 'prodlot_id': wizard_line.prodlot_id.id, 'location_id' : wizard_line.location_id.id, 'location_dest_id' : wizard_line.location_dest_id.id, 'picking_id': partial.picking_id.id },context=context) stock_move.action_confirm(cr, uid, [move_id], context) partial_data['move%s' % (move_id)] = { 'product_id': wizard_line.product_id.id, 'product_qty': wizard_line.quantity, 'product_uom': wizard_line.product_uom.id, 'prodlot_id': wizard_line.prodlot_id.id, } if (picking_type == 'in') and (wizard_line.product_id.cost_method == 'average'): partial_data['move%s' % (wizard_line.move_id.id)].update(product_price=wizard_line.cost, product_currency=wizard_line.currency.id) stock_picking.do_partial(cr, uid, [partial.picking_id.id], partial_data, context=context) return {'type': 'ir.actions.act_window_close'} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
GustavWi/mbed
workspace_tools/dev/syms.py
120
2186
""" mbed SDK Copyright (c) 2011-2013 ARM Limited 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. Utility to find which libraries could define a given symbol """ from argparse import ArgumentParser from os.path import join, splitext from os import walk from subprocess import Popen, PIPE OBJ_EXT = ['.o', '.a', '.ar'] def find_sym_in_lib(sym, obj_path): contain_symbol = False out = Popen(["nm", "-C", obj_path], stdout=PIPE, stderr=PIPE).communicate()[0] for line in out.splitlines(): tokens = line.split() n = len(tokens) if n == 2: sym_type = tokens[0] sym_name = tokens[1] elif n == 3: sym_type = tokens[1] sym_name = tokens[2] else: continue if sym_type == "U": # This object is using this symbol, not defining it continue if sym_name == sym: contain_symbol = True return contain_symbol def find_sym_in_path(sym, dir_path): for root, _, files in walk(dir_path): for file in files: _, ext = splitext(file) if ext not in OBJ_EXT: continue path = join(root, file) if find_sym_in_lib(sym, path): print path if __name__ == '__main__': parser = ArgumentParser(description='Find Symbol') parser.add_argument('-s', '--sym', required=True, help='The symbol to be searched') parser.add_argument('-p', '--path', required=True, help='The path where to search') args = parser.parse_args() find_sym_in_path(args.sym, args.path)
apache-2.0
wzbozon/statsmodels
statsmodels/sandbox/distributions/gof_new.py
28
22302
'''More Goodness of fit tests contains GOF : 1 sample gof tests based on Stephens 1970, plus AD A^2 bootstrap : vectorized bootstrap p-values for gof test with fitted parameters Created : 2011-05-21 Author : Josef Perktold parts based on ks_2samp and kstest from scipy.stats (license: Scipy BSD, but were completely rewritten by Josef Perktold) References ---------- ''' from __future__ import print_function from statsmodels.compat.python import range, lmap, string_types, callable import numpy as np from scipy.stats import distributions from statsmodels.tools.decorators import cache_readonly from scipy.special import kolmogorov as ksprob #from scipy.stats unchanged def ks_2samp(data1, data2): """ Computes the Kolmogorov-Smirnof statistic on 2 samples. This is a two-sided test for the null hypothesis that 2 independent samples are drawn from the same continuous distribution. Parameters ---------- a, b : sequence of 1-D ndarrays two arrays of sample observations assumed to be drawn from a continuous distribution, sample sizes can be different Returns ------- D : float KS statistic p-value : float two-tailed p-value Notes ----- This tests whether 2 samples are drawn from the same distribution. Note that, like in the case of the one-sample K-S test, the distribution is assumed to be continuous. This is the two-sided test, one-sided tests are not implemented. The test uses the two-sided asymptotic Kolmogorov-Smirnov distribution. If the K-S statistic is small or the p-value is high, then we cannot reject the hypothesis that the distributions of the two samples are the same. Examples -------- >>> from scipy import stats >>> import numpy as np >>> from scipy.stats import ks_2samp >>> #fix random seed to get the same result >>> np.random.seed(12345678); >>> n1 = 200 # size of first sample >>> n2 = 300 # size of second sample different distribution we can reject the null hypothesis since the pvalue is below 1% >>> rvs1 = stats.norm.rvs(size=n1,loc=0.,scale=1); >>> rvs2 = stats.norm.rvs(size=n2,loc=0.5,scale=1.5) >>> ks_2samp(rvs1,rvs2) (0.20833333333333337, 4.6674975515806989e-005) slightly different distribution we cannot reject the null hypothesis at a 10% or lower alpha since the pvalue at 0.144 is higher than 10% >>> rvs3 = stats.norm.rvs(size=n2,loc=0.01,scale=1.0) >>> ks_2samp(rvs1,rvs3) (0.10333333333333333, 0.14498781825751686) identical distribution we cannot reject the null hypothesis since the pvalue is high, 41% >>> rvs4 = stats.norm.rvs(size=n2,loc=0.0,scale=1.0) >>> ks_2samp(rvs1,rvs4) (0.07999999999999996, 0.41126949729859719) """ data1, data2 = lmap(np.asarray, (data1, data2)) n1 = data1.shape[0] n2 = data2.shape[0] n1 = len(data1) n2 = len(data2) data1 = np.sort(data1) data2 = np.sort(data2) data_all = np.concatenate([data1,data2]) #reminder: searchsorted inserts 2nd into 1st array cdf1 = np.searchsorted(data1,data_all,side='right')/(1.0*n1) cdf2 = (np.searchsorted(data2,data_all,side='right'))/(1.0*n2) d = np.max(np.absolute(cdf1-cdf2)) #Note: d absolute not signed distance en = np.sqrt(n1*n2/float(n1+n2)) try: prob = ksprob((en+0.12+0.11/en)*d) except: prob = 1.0 return d, prob #from scipy.stats unchanged def kstest(rvs, cdf, args=(), N=20, alternative = 'two_sided', mode='approx',**kwds): """ Perform the Kolmogorov-Smirnov test for goodness of fit This performs a test of the distribution G(x) of an observed random variable against a given distribution F(x). Under the null hypothesis the two distributions are identical, G(x)=F(x). The alternative hypothesis can be either 'two_sided' (default), 'less' or 'greater'. The KS test is only valid for continuous distributions. Parameters ---------- rvs : string or array or callable string: name of a distribution in scipy.stats array: 1-D observations of random variables callable: function to generate random variables, requires keyword argument `size` cdf : string or callable string: name of a distribution in scipy.stats, if rvs is a string then cdf can evaluate to `False` or be the same as rvs callable: function to evaluate cdf args : tuple, sequence distribution parameters, used if rvs or cdf are strings N : int sample size if rvs is string or callable alternative : 'two_sided' (default), 'less' or 'greater' defines the alternative hypothesis (see explanation) mode : 'approx' (default) or 'asymp' defines the distribution used for calculating p-value 'approx' : use approximation to exact distribution of test statistic 'asymp' : use asymptotic distribution of test statistic Returns ------- D : float KS test statistic, either D, D+ or D- p-value : float one-tailed or two-tailed p-value Notes ----- In the one-sided test, the alternative is that the empirical cumulative distribution function of the random variable is "less" or "greater" than the cumulative distribution function F(x) of the hypothesis, G(x)<=F(x), resp. G(x)>=F(x). Examples -------- >>> from scipy import stats >>> import numpy as np >>> from scipy.stats import kstest >>> x = np.linspace(-15,15,9) >>> kstest(x,'norm') (0.44435602715924361, 0.038850142705171065) >>> np.random.seed(987654321) # set random seed to get the same result >>> kstest('norm','',N=100) (0.058352892479417884, 0.88531190944151261) is equivalent to this >>> np.random.seed(987654321) >>> kstest(stats.norm.rvs(size=100),'norm') (0.058352892479417884, 0.88531190944151261) Test against one-sided alternative hypothesis: >>> np.random.seed(987654321) Shift distribution to larger values, so that cdf_dgp(x)< norm.cdf(x): >>> x = stats.norm.rvs(loc=0.2, size=100) >>> kstest(x,'norm', alternative = 'less') (0.12464329735846891, 0.040989164077641749) Reject equal distribution against alternative hypothesis: less >>> kstest(x,'norm', alternative = 'greater') (0.0072115233216311081, 0.98531158590396395) Don't reject equal distribution against alternative hypothesis: greater >>> kstest(x,'norm', mode='asymp') (0.12464329735846891, 0.08944488871182088) Testing t distributed random variables against normal distribution: With 100 degrees of freedom the t distribution looks close to the normal distribution, and the kstest does not reject the hypothesis that the sample came from the normal distribution >>> np.random.seed(987654321) >>> stats.kstest(stats.t.rvs(100,size=100),'norm') (0.072018929165471257, 0.67630062862479168) With 3 degrees of freedom the t distribution looks sufficiently different from the normal distribution, that we can reject the hypothesis that the sample came from the normal distribution at a alpha=10% level >>> np.random.seed(987654321) >>> stats.kstest(stats.t.rvs(3,size=100),'norm') (0.131016895759829, 0.058826222555312224) """ if isinstance(rvs, string_types): #cdf = getattr(stats, rvs).cdf if (not cdf) or (cdf == rvs): cdf = getattr(distributions, rvs).cdf rvs = getattr(distributions, rvs).rvs else: raise AttributeError('if rvs is string, cdf has to be the same distribution') if isinstance(cdf, string_types): cdf = getattr(distributions, cdf).cdf if callable(rvs): kwds = {'size':N} vals = np.sort(rvs(*args,**kwds)) else: vals = np.sort(rvs) N = len(vals) cdfvals = cdf(vals, *args) if alternative in ['two_sided', 'greater']: Dplus = (np.arange(1.0, N+1)/N - cdfvals).max() if alternative == 'greater': return Dplus, distributions.ksone.sf(Dplus,N) if alternative in ['two_sided', 'less']: Dmin = (cdfvals - np.arange(0.0, N)/N).max() if alternative == 'less': return Dmin, distributions.ksone.sf(Dmin,N) if alternative == 'two_sided': D = np.max([Dplus,Dmin]) if mode == 'asymp': return D, distributions.kstwobign.sf(D*np.sqrt(N)) if mode == 'approx': pval_two = distributions.kstwobign.sf(D*np.sqrt(N)) if N > 2666 or pval_two > 0.80 - N*0.3/1000.0 : return D, distributions.kstwobign.sf(D*np.sqrt(N)) else: return D, distributions.ksone.sf(D,N)*2 #TODO: split into modification and pvalue functions separately ? # for separate testing and combining different pieces def dplus_st70_upp(stat, nobs): mod_factor = np.sqrt(nobs) + 0.12 + 0.11 / np.sqrt(nobs) stat_modified = stat * mod_factor pval = np.exp(-2 * stat_modified**2) digits = np.sum(stat > np.array([0.82, 0.82, 1.00])) #repeat low to get {0,2,3} return stat_modified, pval, digits dminus_st70_upp = dplus_st70_upp def d_st70_upp(stat, nobs): mod_factor = np.sqrt(nobs) + 0.12 + 0.11 / np.sqrt(nobs) stat_modified = stat * mod_factor pval = 2 * np.exp(-2 * stat_modified**2) digits = np.sum(stat > np.array([0.91, 0.91, 1.08])) #repeat low to get {0,2,3} return stat_modified, pval, digits def v_st70_upp(stat, nobs): mod_factor = np.sqrt(nobs) + 0.155 + 0.24 / np.sqrt(nobs) #repeat low to get {0,2,3} stat_modified = stat * mod_factor zsqu = stat_modified**2 pval = (8 * zsqu - 2) * np.exp(-2 * zsqu) digits = np.sum(stat > np.array([1.06, 1.06, 1.26])) return stat_modified, pval, digits def wsqu_st70_upp(stat, nobs): nobsinv = 1. / nobs stat_modified = (stat - 0.4 * nobsinv + 0.6 * nobsinv**2) * (1 + nobsinv) pval = 0.05 * np.exp(2.79 - 6 * stat_modified) digits = np.nan # some explanation in txt #repeat low to get {0,2,3} return stat_modified, pval, digits def usqu_st70_upp(stat, nobs): nobsinv = 1. / nobs stat_modified = (stat - 0.1 * nobsinv + 0.1 * nobsinv**2) stat_modified *= (1 + 0.8 * nobsinv) pval = 2 * np.exp(- 2 * stat_modified * np.pi**2) digits = np.sum(stat > np.array([0.29, 0.29, 0.34])) #repeat low to get {0,2,3} return stat_modified, pval, digits def a_st70_upp(stat, nobs): nobsinv = 1. / nobs stat_modified = (stat - 0.7 * nobsinv + 0.9 * nobsinv**2) stat_modified *= (1 + 1.23 * nobsinv) pval = 1.273 * np.exp(- 2 * stat_modified / 2. * np.pi**2) digits = np.sum(stat > np.array([0.11, 0.11, 0.452])) #repeat low to get {0,2,3} return stat_modified, pval, digits gof_pvals = {} gof_pvals['stephens70upp'] = { 'd_plus' : dplus_st70_upp, 'd_minus' : dplus_st70_upp, 'd' : d_st70_upp, 'v' : v_st70_upp, 'wsqu' : wsqu_st70_upp, 'usqu' : usqu_st70_upp, 'a' : a_st70_upp } def pval_kstest_approx(D, N): pval_two = distributions.kstwobign.sf(D*np.sqrt(N)) if N > 2666 or pval_two > 0.80 - N*0.3/1000.0 : return D, distributions.kstwobign.sf(D*np.sqrt(N)), np.nan else: return D, distributions.ksone.sf(D,N)*2, np.nan gof_pvals['scipy'] = { 'd_plus' : lambda Dplus, N: (Dplus, distributions.ksone.sf(Dplus, N), np.nan), 'd_minus' : lambda Dmin, N: (Dmin, distributions.ksone.sf(Dmin,N), np.nan), 'd' : lambda D, N: (D, distributions.kstwobign.sf(D*np.sqrt(N)), np.nan) } gof_pvals['scipy_approx'] = { 'd' : pval_kstest_approx } class GOF(object): '''One Sample Goodness of Fit tests includes Kolmogorov-Smirnov D, D+, D-, Kuiper V, Cramer-von Mises W^2, U^2 and Anderson-Darling A, A^2. The p-values for all tests except for A^2 are based on the approximatiom given in Stephens 1970. A^2 has currently no p-values. For the Kolmogorov-Smirnov test the tests as given in scipy.stats are also available as options. design: I might want to retest with different distributions, to calculate data summary statistics only once, or add separate class that holds summary statistics and data (sounds good). ''' def __init__(self, rvs, cdf, args=(), N=20): if isinstance(rvs, string_types): #cdf = getattr(stats, rvs).cdf if (not cdf) or (cdf == rvs): cdf = getattr(distributions, rvs).cdf rvs = getattr(distributions, rvs).rvs else: raise AttributeError('if rvs is string, cdf has to be the same distribution') if isinstance(cdf, string_types): cdf = getattr(distributions, cdf).cdf if callable(rvs): kwds = {'size':N} vals = np.sort(rvs(*args,**kwds)) else: vals = np.sort(rvs) N = len(vals) cdfvals = cdf(vals, *args) self.nobs = N self.vals_sorted = vals self.cdfvals = cdfvals @cache_readonly def d_plus(self): nobs = self.nobs cdfvals = self.cdfvals return (np.arange(1.0, nobs+1)/nobs - cdfvals).max() @cache_readonly def d_minus(self): nobs = self.nobs cdfvals = self.cdfvals return (cdfvals - np.arange(0.0, nobs)/nobs).max() @cache_readonly def d(self): return np.max([self.d_plus, self.d_minus]) @cache_readonly def v(self): '''Kuiper''' return self.d_plus + self.d_minus @cache_readonly def wsqu(self): '''Cramer von Mises''' nobs = self.nobs cdfvals = self.cdfvals #use literal formula, TODO: simplify with arange(,,2) wsqu = ((cdfvals - (2. * np.arange(1., nobs+1) - 1)/nobs/2.)**2).sum() \ + 1./nobs/12. return wsqu @cache_readonly def usqu(self): nobs = self.nobs cdfvals = self.cdfvals #use literal formula, TODO: simplify with arange(,,2) usqu = self.wsqu - nobs * (cdfvals.mean() - 0.5)**2 return usqu @cache_readonly def a(self): nobs = self.nobs cdfvals = self.cdfvals #one loop instead of large array msum = 0 for j in range(1,nobs): mj = cdfvals[j] - cdfvals[:j] mask = (mj > 0.5) mj[mask] = 1 - mj[mask] msum += mj.sum() a = nobs / 4. - 2. / nobs * msum return a @cache_readonly def asqu(self): '''Stephens 1974, doesn't have p-value formula for A^2''' nobs = self.nobs cdfvals = self.cdfvals asqu = -((2. * np.arange(1., nobs+1) - 1) * (np.log(cdfvals) + np.log(1-cdfvals[::-1]) )).sum()/nobs - nobs return asqu def get_test(self, testid='d', pvals='stephens70upp'): ''' ''' #print gof_pvals[pvals][testid] stat = getattr(self, testid) if pvals == 'stephens70upp': return gof_pvals[pvals][testid](stat, self.nobs), stat else: return gof_pvals[pvals][testid](stat, self.nobs) def gof_mc(randfn, distr, nobs=100): #print '\nIs it correctly sized?' from collections import defaultdict results = defaultdict(list) for i in range(1000): rvs = randfn(nobs) goft = GOF(rvs, distr) for ti in all_gofs: results[ti].append(goft.get_test(ti, 'stephens70upp')[0][1]) resarr = np.array([results[ti] for ti in all_gofs]) print(' ', ' '.join(all_gofs)) print('at 0.01:', (resarr < 0.01).mean(1)) print('at 0.05:', (resarr < 0.05).mean(1)) print('at 0.10:', (resarr < 0.1).mean(1)) def asquare(cdfvals, axis=0): '''vectorized Anderson Darling A^2, Stephens 1974''' ndim = len(cdfvals.shape) nobs = cdfvals.shape[axis] slice_reverse = [slice(None)] * ndim #might make copy if not specific axis??? islice = [None] * ndim islice[axis] = slice(None) slice_reverse[axis] = slice(None, None, -1) asqu = -((2. * np.arange(1., nobs+1)[islice] - 1) * (np.log(cdfvals) + np.log(1-cdfvals[slice_reverse]))/nobs).sum(axis) \ - nobs return asqu #class OneSGOFFittedVec(object): # '''for vectorized fitting''' # currently I use the bootstrap as function instead of full class #note: kwds loc and scale are a pain # I would need to overwrite rvs, fit and cdf depending on fixed parameters #def bootstrap(self, distr, args=(), kwds={}, nobs=200, nrep=1000, def bootstrap(distr, args=(), nobs=200, nrep=100, value=None, batch_size=None): '''Monte Carlo (or parametric bootstrap) p-values for gof currently hardcoded for A^2 only assumes vectorized fit_vec method, builds and analyses (nobs, nrep) sample in one step rename function to less generic this works also with nrep=1 ''' #signature similar to kstest ? #delegate to fn ? #rvs_kwds = {'size':(nobs, nrep)} #rvs_kwds.update(kwds) #it will be better to build a separate batch function that calls bootstrap #keep batch if value is true, but batch iterate from outside if stat is returned if (not batch_size is None): if value is None: raise ValueError('using batching requires a value') n_batch = int(np.ceil(nrep/float(batch_size))) count = 0 for irep in range(n_batch): rvs = distr.rvs(args, **{'size':(batch_size, nobs)}) params = distr.fit_vec(rvs, axis=1) params = lmap(lambda x: np.expand_dims(x, 1), params) cdfvals = np.sort(distr.cdf(rvs, params), axis=1) stat = asquare(cdfvals, axis=1) count += (stat >= value).sum() return count / float(n_batch * batch_size) else: #rvs = distr.rvs(args, **kwds) #extension to distribution kwds ? rvs = distr.rvs(args, **{'size':(nrep, nobs)}) params = distr.fit_vec(rvs, axis=1) params = lmap(lambda x: np.expand_dims(x, 1), params) cdfvals = np.sort(distr.cdf(rvs, params), axis=1) stat = asquare(cdfvals, axis=1) if value is None: #return all bootstrap results stat_sorted = np.sort(stat) return stat_sorted else: #calculate and return specific p-value return (stat >= value).mean() def bootstrap2(value, distr, args=(), nobs=200, nrep=100): '''Monte Carlo (or parametric bootstrap) p-values for gof currently hardcoded for A^2 only non vectorized, loops over all parametric bootstrap replications and calculates and returns specific p-value, rename function to less generic ''' #signature similar to kstest ? #delegate to fn ? #rvs_kwds = {'size':(nobs, nrep)} #rvs_kwds.update(kwds) count = 0 for irep in range(nrep): #rvs = distr.rvs(args, **kwds) #extension to distribution kwds ? rvs = distr.rvs(args, **{'size':nobs}) params = distr.fit_vec(rvs) cdfvals = np.sort(distr.cdf(rvs, params)) stat = asquare(cdfvals, axis=0) count += (stat >= value) return count * 1. / nrep class NewNorm(object): '''just a holder for modified distributions ''' def fit_vec(self, x, axis=0): return x.mean(axis), x.std(axis) def cdf(self, x, args): return distributions.norm.cdf(x, loc=args[0], scale=args[1]) def rvs(self, args, size): loc=args[0] scale=args[1] return loc + scale * distributions.norm.rvs(size=size) if __name__ == '__main__': from scipy import stats #rvs = np.random.randn(1000) rvs = stats.t.rvs(3, size=200) print('scipy kstest') print(kstest(rvs, 'norm')) goft = GOF(rvs, 'norm') print(goft.get_test()) all_gofs = ['d', 'd_plus', 'd_minus', 'v', 'wsqu', 'usqu', 'a'] for ti in all_gofs: print(ti, goft.get_test(ti, 'stephens70upp')) print('\nIs it correctly sized?') from collections import defaultdict results = defaultdict(list) nobs = 200 for i in range(100): rvs = np.random.randn(nobs) goft = GOF(rvs, 'norm') for ti in all_gofs: results[ti].append(goft.get_test(ti, 'stephens70upp')[0][1]) resarr = np.array([results[ti] for ti in all_gofs]) print(' ', ' '.join(all_gofs)) print('at 0.01:', (resarr < 0.01).mean(1)) print('at 0.05:', (resarr < 0.05).mean(1)) print('at 0.10:', (resarr < 0.1).mean(1)) gof_mc(lambda nobs: stats.t.rvs(3, size=nobs), 'norm', nobs=200) nobs = 200 nrep = 100 bt = bootstrap(NewNorm(), args=(0,1), nobs=nobs, nrep=nrep, value=None) quantindex = np.floor(nrep * np.array([0.99, 0.95, 0.9])).astype(int) print(bt[quantindex]) #the bootstrap results match Stephens pretty well for nobs=100, but not so well for #large (1000) or small (20) nobs ''' >>> np.array([15.0, 10.0, 5.0, 2.5, 1.0])/100. #Stephens array([ 0.15 , 0.1 , 0.05 , 0.025, 0.01 ]) >>> nobs = 100 >>> [bootstrap(NewNorm(), args=(0,1), nobs=nobs, nrep=10000, value=c/ (1 + 4./nobs - 25./nobs**2)) for c in [0.576, 0.656, 0.787, 0.918, 1.092]] [0.1545, 0.10009999999999999, 0.049000000000000002, 0.023, 0.0104] >>> ''' #test equality of loop, vectorized, batch-vectorized np.random.seed(8765679) resu1 = bootstrap(NewNorm(), args=(0,1), nobs=nobs, nrep=100, value=0.576/(1 + 4./nobs - 25./nobs**2)) np.random.seed(8765679) tmp = [bootstrap(NewNorm(), args=(0,1), nobs=nobs, nrep=1) for _ in range(100)] resu2 = (np.array(tmp) > 0.576/(1 + 4./nobs - 25./nobs**2)).mean() np.random.seed(8765679) tmp = [bootstrap(NewNorm(), args=(0,1), nobs=nobs, nrep=1, value=0.576/ (1 + 4./nobs - 25./nobs**2), batch_size=10) for _ in range(10)] resu3 = np.array(resu).mean() from numpy.testing import assert_almost_equal, assert_array_almost_equal assert_array_almost_equal(resu1, resu2, 15) assert_array_almost_equal(resu2, resu3, 15)
bsd-3-clause
ibushong/test-repo
flask_admin/form/rules.py
7
9864
from jinja2 import Markup from flask.ext.admin._compat import string_types from flask.ext.admin import helpers class BaseRule(object): """ Base form rule. All form formatting rules should derive from `BaseRule`. """ def __init__(self): self.parent = None self.rule_set = None def configure(self, rule_set, parent): """ Configure rule and assign to rule set. :param rule_set: Rule set :param parent: Parent rule (if any) """ self.parent = parent self.rule_set = rule_set return self def __call__(self, form, form_opts=None, field_args={}): """ Render rule. :param form: Form object :param form_opts: Form options :param field_args: Optional arguments that should be passed to template or the field """ raise NotImplementedError() class NestedRule(BaseRule): """ Nested rule. Can contain child rules and render them. """ def __init__(self, rules=[], separator=''): """ Constructor. :param rules: Child rule list :param separator: Default separator between rules when rendering them. """ super(NestedRule, self).__init__() self.rules = list(rules) self.separator = separator def configure(self, rule_set, parent): """ Configure rule. :param rule_set: Rule set :param parent: Parent rule (if any) """ self.rules = rule_set.configure_rules(self.rules, self) return super(NestedRule, self).configure(rule_set, parent) def __iter__(self): """ Return rules. """ return self.rules def __call__(self, form, form_opts=None, field_args={}): """ Render all children. :param form: Form object :param form_opts: Form options :param field_args: Optional arguments that should be passed to template or the field """ result = [] for r in self.rules: result.append(r(form, form_opts, field_args)) return Markup(self.separator.join(result)) class Text(BaseRule): """ Render text (or HTML snippet) from string. """ def __init__(self, text, escape=True): """ Constructor. :param text: Text to render :param escape: Should text be escaped or not. Default is `True`. """ super(Text, self).__init__() self.text = text self.escape = escape def __call__(self, form, form_opts=None, field_args={}): if self.escape: return self.text return Markup(self.text) class HTML(Text): """ Shortcut for `Text` rule with `escape` set to `False. """ def __init__(self, html): super(HTML, self).__init__(html, escape=False) class Macro(BaseRule): """ Render macro by its name from current Jinja2 context. """ def __init__(self, macro_name, **kwargs): """ Constructor. :param macro_name: Macro name :param kwargs: Default macro parameters """ super(Macro, self).__init__() self.macro_name = macro_name self.default_args = kwargs def _resolve(self, context, name): """ Resolve macro in a Jinja2 context :param context: Jinja2 context :param name: Macro name. May be full path (with dots) """ parts = name.split('.') field = context.resolve(parts[0]) if not field: return None for p in parts[1:]: field = getattr(field, p, None) if not field: return field return field def __call__(self, form, form_opts=None, field_args={}): """ Render macro rule. :param form: Form object :param form_opts: Form options :param field_args: Optional arguments that should be passed to the macro """ context = helpers.get_render_ctx() macro = self._resolve(context, self.macro_name) if not macro: raise ValueError('Cannot find macro %s in current context.' % self.macro_name) opts = dict(self.default_args) opts.update(field_args) return macro(**opts) class Container(Macro): """ Render container around child rule. """ def __init__(self, macro_name, child_rule, **kwargs): """ Constructor. :param macro_name: Macro name that will be used as a container :param child_rule: Child rule to be rendered inside of container :param kwargs: Container macro arguments """ super(Container, self).__init__(macro_name, **kwargs) self.child_rule = child_rule def configure(self, rule_set, parent): """ Configure rule. :param rule_set: Rule set :param parent: Parent rule (if any) """ self.child_rule.configure(rule_set, self) return super(Container, self).configure(rule_set, parent) def __call__(self, form, form_opts=None, field_args={}): """ Render container. :param form: Form object :param form_opts: Form options :param field_args: Optional arguments that should be passed to template or the field """ context = helpers.get_render_ctx() def caller(**kwargs): return context.call(self.child_rule, form, form_opts, kwargs) args = dict(field_args) args['caller'] = caller return super(Container, self).__call__(form, form_opts, args) class Field(Macro): """ Form field rule. """ def __init__(self, field_name, render_field='lib.render_field'): """ Constructor. :param field_name: Field name to render :param render_field: Macro that will be used to render the field. """ super(Field, self).__init__(render_field) self.field_name = field_name def __call__(self, form, form_opts=None, field_args={}): """ Render field. :param form: Form object :param form_opts: Form options :param field_args: Optional arguments that should be passed to template or the field """ field = getattr(form, self.field_name, None) if field is None: raise ValueError('Form %s does not have field %s' % (form, self.field_name)) opts = {} if form_opts: opts.update(form_opts.widget_args.get(self.field_name, {})) opts.update(field_args) params = { 'form': form, 'field': field, 'kwargs': opts } return super(Field, self).__call__(form, form_opts, params) class Header(Macro): """ Render header text. """ def __init__(self, text, header_macro='lib.render_header'): """ Constructor. :param text: Text to render :param header_macro: Header rendering macro """ super(Header, self).__init__(header_macro, text=text) class FieldSet(NestedRule): """ Field set with header. """ def __init__(self, rules, header=None, separator=''): """ Constructor. :param rules: Child rules :param header: Header text :param separator: Child rule separator """ if header: rule_set = [Header(header)] + list(rules) else: rule_set = list(rules) super(FieldSet, self).__init__(rule_set, separator=separator) class RuleSet(object): """ Rule set. """ def __init__(self, view, rules): """ Constructor. :param view: Administrative view :param rules: Rule list """ self.view = view self.rules = self.configure_rules(rules) def convert_string(self, value): """ Convert string to rule. Override this method to change default behavior. """ return Field(value) def configure_rules(self, rules, parent=None): """ Configure all rules recursively - bind them to current RuleSet and convert string references to `Field` rules. :param rules: Rule list :param parent: Parent rule (if any) """ result = [] for r in rules: if isinstance(r, BaseRule): result.append(r.configure(self, parent)) elif isinstance(r, string_types): result.append(self.convert_string(r).configure(self, parent)) else: raise ValueError('Dont know how to convert %s' % repr(r)) return result def __iter__(self): """ Iterate through registered rules. """ for r in self.rules: yield r
bsd-3-clause
vitaly4uk/django
tests/fixtures_regress/models.py
281
8611
from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.utils import six from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Animal(models.Model): name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) count = models.IntegerField() weight = models.FloatField() # use a non-default name for the default manager specimens = models.Manager() def __str__(self): return self.name class Plant(models.Model): name = models.CharField(max_length=150) class Meta: # For testing when upper case letter in app name; regression for #4057 db_table = "Fixtures_regress_plant" @python_2_unicode_compatible class Stuff(models.Model): name = models.CharField(max_length=20, null=True) owner = models.ForeignKey(User, models.SET_NULL, null=True) def __str__(self): return six.text_type(self.name) + ' is owned by ' + six.text_type(self.owner) class Absolute(models.Model): name = models.CharField(max_length=40) class Parent(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ('id',) class Child(Parent): data = models.CharField(max_length=10) # Models to regression test #7572, #20820 class Channel(models.Model): name = models.CharField(max_length=255) class Article(models.Model): title = models.CharField(max_length=255) channels = models.ManyToManyField(Channel) class Meta: ordering = ('id',) # Subclass of a model with a ManyToManyField for test_ticket_20820 class SpecialArticle(Article): pass # Models to regression test #22421 class CommonFeature(Article): class Meta: abstract = True class Feature(CommonFeature): pass # Models to regression test #11428 @python_2_unicode_compatible class Widget(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __str__(self): return self.name class WidgetProxy(Widget): class Meta: proxy = True # Check for forward references in FKs and M2Ms with natural keys class TestManager(models.Manager): def get_by_natural_key(self, key): return self.get(name=key) @python_2_unicode_compatible class Store(models.Model): objects = TestManager() name = models.CharField(max_length=255) main = models.ForeignKey('self', models.SET_NULL, null=True) class Meta: ordering = ('name',) def __str__(self): return self.name def natural_key(self): return (self.name,) @python_2_unicode_compatible class Person(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __str__(self): return self.name # Person doesn't actually have a dependency on store, but we need to define # one to test the behavior of the dependency resolution algorithm. def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.store'] @python_2_unicode_compatible class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(Person, models.CASCADE) stores = models.ManyToManyField(Store) class Meta: ordering = ('name',) def __str__(self): return '%s by %s (available at %s)' % ( self.name, self.author.name, ', '.join(s.name for s in self.stores.all()) ) class NKManager(models.Manager): def get_by_natural_key(self, data): return self.get(data=data) @python_2_unicode_compatible class NKChild(Parent): data = models.CharField(max_length=10, unique=True) objects = NKManager() def natural_key(self): return (self.data,) def __str__(self): return 'NKChild %s:%s' % (self.name, self.data) @python_2_unicode_compatible class RefToNKChild(models.Model): text = models.CharField(max_length=10) nk_fk = models.ForeignKey(NKChild, models.CASCADE, related_name='ref_fks') nk_m2m = models.ManyToManyField(NKChild, related_name='ref_m2ms') def __str__(self): return '%s: Reference to %s [%s]' % ( self.text, self.nk_fk, ', '.join(str(o) for o in self.nk_m2m.all()) ) # ome models with pathological circular dependencies class Circle1(models.Model): name = models.CharField(max_length=255) def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.circle2'] class Circle2(models.Model): name = models.CharField(max_length=255) def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.circle1'] class Circle3(models.Model): name = models.CharField(max_length=255) def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.circle3'] class Circle4(models.Model): name = models.CharField(max_length=255) def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.circle5'] class Circle5(models.Model): name = models.CharField(max_length=255) def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.circle6'] class Circle6(models.Model): name = models.CharField(max_length=255) def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.circle4'] class ExternalDependency(models.Model): name = models.CharField(max_length=255) def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.book'] # Model for regression test of #11101 class Thingy(models.Model): name = models.CharField(max_length=255) class M2MToSelf(models.Model): parent = models.ManyToManyField("self", blank=True) @python_2_unicode_compatible class BaseNKModel(models.Model): """ Base model with a natural_key and a manager with `get_by_natural_key` """ data = models.CharField(max_length=20, unique=True) objects = NKManager() class Meta: abstract = True def __str__(self): return self.data def natural_key(self): return (self.data,) class M2MSimpleA(BaseNKModel): b_set = models.ManyToManyField("M2MSimpleB") class M2MSimpleB(BaseNKModel): pass class M2MSimpleCircularA(BaseNKModel): b_set = models.ManyToManyField("M2MSimpleCircularB") class M2MSimpleCircularB(BaseNKModel): a_set = models.ManyToManyField("M2MSimpleCircularA") class M2MComplexA(BaseNKModel): b_set = models.ManyToManyField("M2MComplexB", through="M2MThroughAB") class M2MComplexB(BaseNKModel): pass class M2MThroughAB(BaseNKModel): a = models.ForeignKey(M2MComplexA, models.CASCADE) b = models.ForeignKey(M2MComplexB, models.CASCADE) class M2MComplexCircular1A(BaseNKModel): b_set = models.ManyToManyField("M2MComplexCircular1B", through="M2MCircular1ThroughAB") class M2MComplexCircular1B(BaseNKModel): c_set = models.ManyToManyField("M2MComplexCircular1C", through="M2MCircular1ThroughBC") class M2MComplexCircular1C(BaseNKModel): a_set = models.ManyToManyField("M2MComplexCircular1A", through="M2MCircular1ThroughCA") class M2MCircular1ThroughAB(BaseNKModel): a = models.ForeignKey(M2MComplexCircular1A, models.CASCADE) b = models.ForeignKey(M2MComplexCircular1B, models.CASCADE) class M2MCircular1ThroughBC(BaseNKModel): b = models.ForeignKey(M2MComplexCircular1B, models.CASCADE) c = models.ForeignKey(M2MComplexCircular1C, models.CASCADE) class M2MCircular1ThroughCA(BaseNKModel): c = models.ForeignKey(M2MComplexCircular1C, models.CASCADE) a = models.ForeignKey(M2MComplexCircular1A, models.CASCADE) class M2MComplexCircular2A(BaseNKModel): b_set = models.ManyToManyField("M2MComplexCircular2B", through="M2MCircular2ThroughAB") class M2MComplexCircular2B(BaseNKModel): def natural_key(self): return (self.data,) # Fake the dependency for a circularity natural_key.dependencies = ["fixtures_regress.M2MComplexCircular2A"] class M2MCircular2ThroughAB(BaseNKModel): a = models.ForeignKey(M2MComplexCircular2A, models.CASCADE) b = models.ForeignKey(M2MComplexCircular2B, models.CASCADE)
bsd-3-clause
tcoppex/gl-compute-c99
tools/glextgen/main.py
1
2567
# GL Extension Generator script # # This script generates an header and inline file from a list of OpenGL extensions # functions to automate the loading process. # # Usage : python main.py extension_file dst_dir # # ----------------------------------------------------------------------------- def HeadComment(): import time now = time.strftime("%Y/%m/%d %H:%M:%S") return "/* This file was generated by a script @ %s */\n\n" % now # ----------------------------------------------------------------------------- def GenerateInline(path, declarations, funcloads): filename = "%s/_extensions.inl" % path func = """ static void LoadExtensionFuncPtrs() { %s } """ func = func % '\n'.join(funcloads) with open(filename, "w") as fd: fd.write(HeadComment()) fd.write('\n'.join(declarations)) fd.write('\n') fd.write(func) # ----------------------------------------------------------------------------- def GenerateHeader(path, ext_declarations, defines): import os if not os.path.exists(path): print("Creating \"%s\"." % path) os.makedirs(path) filename = "%s/_extensions.h" % path with open(filename, "w") as fd: fd.write(HeadComment()) fd.write("#ifndef EXT_EXTENSIONS_H\n") fd.write("#define EXT_EXTENSIONS_H\n\n") fd.write("#include \"GL/glext.h\"\n\n") fd.write('\n'.join(ext_declarations)) fd.write("\n\n") fd.write('\n'.join(defines)) fd.write("\n\n") fd.write("#endif\n") # ----------------------------------------------------------------------------- if __name__ == '__main__': import sys if len(sys.argv) != 3: print("usage : %s extensions_file generate_path" % sys.argv[0]) exit(-1) exts = [] with open(sys.argv[1], "r") as fd: exts = fd.read().split('\n') # Sort and remove redundancies exts = sorted(list(set(exts))) declarations = [] e_declarations = [] defines = [] funcloads = [] for ext in exts: # functions declaration typename = "PFN%sPROC" % ext.upper() funcname = "pfn%s" % ext[2:] decl = "%s %s;" % (typename, funcname) declarations.append(decl) # 'extern' functions declaration e_declarations.append("extern %s" % decl) # defines to simplify use define = "#define %s %s" % (ext, funcname) defines.append(define) # loaders code funcload = " %s = (%s)\n getAddress(\"%s\");\n" % (funcname, typename, ext) funcloads.append(funcload) path = sys.argv[2] GenerateHeader(path, e_declarations, defines) GenerateInline(path, declarations, funcloads)
unlicense
markeTIC/OCB
addons/association/__openerp__.py
260
1700
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Associations Management', 'version': '0.1', 'category': 'Specific Industry Applications', 'description': """ This module is to configure modules related to an association. ============================================================== It installs the profile for associations to manage events, registrations, memberships, membership products (schemes). """, 'author': 'OpenERP SA', 'depends': ['base_setup', 'membership', 'event'], 'data': ['security/ir.model.access.csv', 'profile_association.xml'], 'demo': [], 'installable': True, 'auto_install': False, 'website': 'https://www.odoo.com' } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
rafael1193/spicegui
spicegui/running_dialog.py
1
3173
# -*- coding: utf-8 -*- # # SpiceGUI # Copyright (C) 2014-2015 Rafael Bailón-Ruiz <rafaelbailon@ieee.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function from gi.repository import Gtk, GObject class RunningDialog(Gtk.Dialog): def __init__(self, parent, event): if Gtk.check_version(3, 12, 0) is None: # Use header bar Gtk.Dialog.__init__(self, _("Simulation"), parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL), use_header_bar=True) self.get_header_bar().set_show_close_button(False) else: # Do not use header bar Gtk.Dialog.__init__(self, _("Simulation"), parent, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)) self.event = event self.set_default_size(150, 100) self.props.resizable = False self.set_default_response(Gtk.ResponseType.CANCEL) self.progress_bar = Gtk.ProgressBar() self.progress_bar.activity_mode = True self.progress_bar.pulse() self.progress_bar.set_text(_(u"Running ngspice…")) self.progress_bar.set_show_text(True) self.hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL) self.hbox.set_margin_left(18) self.hbox.set_margin_top(18) self.hbox.set_margin_bottom(18) self.hbox.set_margin_right(18) self.hbox.set_vexpand(True) self.hbox.set_spacing(12) self.hbox.pack_start(self.progress_bar, True, True, 18) box = self.get_content_area() box.add(self.hbox) self.timeout_id = GObject.timeout_add(50, self.on_timeout, None) self.show_all() def on_timeout(self, user_data): """ Update value in the progress bar. If simulation event is set, dialog emits response 1 """ self.progress_bar.pulse() if self.event.is_set(): # if thread finished self.response(1) # 1 is an application-defined response type return True if __name__ == "__main__": from multiprocessing import Event event_test = Event() win = Gtk.Window() dialog = RunningDialog(win, event_test) dialog.run() dialog.destroy() win.destroy()
gpl-3.0
cloudbase/neutron
neutron/api/rpc/handlers/resources_rpc.py
3
10920
# Copyright (c) 2015 Mellanox Technologies, Ltd # 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 collections from neutron_lib import exceptions from oslo_log import helpers as log_helpers import oslo_messaging from neutron._i18n import _ from neutron.api.rpc.callbacks.consumer import registry as cons_registry from neutron.api.rpc.callbacks import exceptions as rpc_exc from neutron.api.rpc.callbacks.producer import registry as prod_registry from neutron.api.rpc.callbacks import resources from neutron.api.rpc.callbacks import version_manager from neutron.common import constants from neutron.common import rpc as n_rpc from neutron.common import topics from neutron.objects import base as obj_base class ResourcesRpcError(exceptions.NeutronException): pass class InvalidResourceTypeClass(ResourcesRpcError): message = _("Invalid resource type %(resource_type)s") class ResourceNotFound(ResourcesRpcError): message = _("Resource %(resource_id)s of type %(resource_type)s " "not found") def _validate_resource_type(resource_type): if not resources.is_valid_resource_type(resource_type): raise InvalidResourceTypeClass(resource_type=resource_type) def resource_type_versioned_topic(resource_type, version=None): """Return the topic for a resource type. If no version is provided, the latest version of the object will be used. """ _validate_resource_type(resource_type) cls = resources.get_resource_cls(resource_type) return topics.RESOURCE_TOPIC_PATTERN % {'resource_type': resource_type, 'version': version or cls.VERSION} class ResourcesPullRpcApi(object): """Agent-side RPC (stub) for agent-to-plugin interaction. This class implements the client side of an rpc interface. The server side can be found below: ResourcesPullRpcCallback. For more information on this RPC interface, see doc/source/devref/rpc_callbacks.rst. """ def __new__(cls): # make it a singleton if not hasattr(cls, '_instance'): cls._instance = super(ResourcesPullRpcApi, cls).__new__(cls) target = oslo_messaging.Target( topic=topics.PLUGIN, version='1.0', namespace=constants.RPC_NAMESPACE_RESOURCES) cls._instance.client = n_rpc.get_client(target) return cls._instance @log_helpers.log_method_call def pull(self, context, resource_type, resource_id): _validate_resource_type(resource_type) # we've already validated the resource type, so we are pretty sure the # class is there => no need to validate it specifically resource_type_cls = resources.get_resource_cls(resource_type) cctxt = self.client.prepare() primitive = cctxt.call(context, 'pull', resource_type=resource_type, version=resource_type_cls.VERSION, resource_id=resource_id) if primitive is None: raise ResourceNotFound(resource_type=resource_type, resource_id=resource_id) return resource_type_cls.clean_obj_from_primitive(primitive) class ResourcesPullRpcCallback(object): """Plugin-side RPC (implementation) for agent-to-plugin interaction. This class implements the server side of an rpc interface. The client side can be found above: ResourcesPullRpcApi. For more information on this RPC interface, see doc/source/devref/rpc_callbacks.rst. """ # History # 1.0 Initial version target = oslo_messaging.Target( version='1.0', namespace=constants.RPC_NAMESPACE_RESOURCES) @oslo_messaging.expected_exceptions(rpc_exc.CallbackNotFound) def pull(self, context, resource_type, version, resource_id): obj = prod_registry.pull(resource_type, resource_id, context=context) if obj: return obj.obj_to_primitive(target_version=version) class ResourcesPushToServersRpcApi(object): """Publisher-side RPC (stub) for plugin-to-plugin fanout interaction. This class implements the client side of an rpc interface. The receiver side can be found below: ResourcesPushToServerRpcCallback. For more information on this RPC interface, see doc/source/devref/rpc_callbacks.rst. """ def __init__(self): target = oslo_messaging.Target( topic=topics.SERVER_RESOURCE_VERSIONS, version='1.0', namespace=constants.RPC_NAMESPACE_RESOURCES) self.client = n_rpc.get_client(target) @log_helpers.log_method_call def report_agent_resource_versions(self, context, agent_type, agent_host, version_map): """Fan out all the agent resource versions to other servers.""" cctxt = self.client.prepare(fanout=True) cctxt.cast(context, 'report_agent_resource_versions', agent_type=agent_type, agent_host=agent_host, version_map=version_map) class ResourcesPushToServerRpcCallback(object): """Receiver-side RPC (implementation) for plugin-to-plugin interaction. This class implements the receiver side of an rpc interface. The client side can be found above: ResourcePushToServerRpcApi. For more information on this RPC interface, see doc/source/devref/rpc_callbacks.rst. """ # History # 1.0 Initial version target = oslo_messaging.Target( version='1.0', namespace=constants.RPC_NAMESPACE_RESOURCES) @log_helpers.log_method_call def report_agent_resource_versions(self, context, agent_type, agent_host, version_map): consumer_id = version_manager.AgentConsumer(agent_type=agent_type, host=agent_host) version_manager.update_versions(consumer_id, version_map) class ResourcesPushRpcApi(object): """Plugin-side RPC for plugin-to-agents interaction. This interface is designed to push versioned object updates to interested agents using fanout topics. This class implements the caller side of an rpc interface. The receiver side can be found below: ResourcesPushRpcCallback. """ def __init__(self): target = oslo_messaging.Target( namespace=constants.RPC_NAMESPACE_RESOURCES) self.client = n_rpc.get_client(target) def _prepare_object_fanout_context(self, obj, resource_version, rpc_version): """Prepare fanout context, one topic per object type.""" obj_topic = resource_type_versioned_topic(obj.obj_name(), resource_version) return self.client.prepare(fanout=True, topic=obj_topic, version=rpc_version) @staticmethod def _classify_resources_by_type(resource_list): resources_by_type = collections.defaultdict(list) for resource in resource_list: resource_type = resources.get_resource_type(resource) resources_by_type[resource_type].append(resource) return resources_by_type @log_helpers.log_method_call def push(self, context, resource_list, event_type): """Push an event and list of resources to agents, batched per type. When a list of different resource types is passed to this method, the push will be sent as separate individual list pushes, one per resource type. """ resources_by_type = self._classify_resources_by_type(resource_list) for resource_type, type_resources in resources_by_type.items(): self._push(context, resource_type, type_resources, event_type) def _push(self, context, resource_type, resource_list, event_type): """Push an event and list of resources of the same type to agents.""" _validate_resource_type(resource_type) compat_call = len(resource_list) == 1 for version in version_manager.get_resource_versions(resource_type): cctxt = self._prepare_object_fanout_context( resource_list[0], version, rpc_version='1.0' if compat_call else '1.1') dehydrated_resources = [ resource.obj_to_primitive(target_version=version) for resource in resource_list] if compat_call: #TODO(mangelajo): remove in Ocata, backwards compatibility # for agents expecting a single element as # a single element instead of a list, this # is only relevant to the QoSPolicy topic queue cctxt.cast(context, 'push', resource=dehydrated_resources[0], event_type=event_type) else: cctxt.cast(context, 'push', resource_list=dehydrated_resources, event_type=event_type) class ResourcesPushRpcCallback(object): """Agent-side RPC for plugin-to-agents interaction. This class implements the receiver for notification about versioned objects resource updates used by neutron.api.rpc.callbacks. You can find the caller side in ResourcesPushRpcApi. """ # History # 1.0 Initial version # 1.1 push method introduces resource_list support target = oslo_messaging.Target(version='1.1', namespace=constants.RPC_NAMESPACE_RESOURCES) @oslo_messaging.expected_exceptions(rpc_exc.CallbackNotFound) def push(self, context, **kwargs): """Push receiver, will always receive resources of the same type.""" # TODO(mangelajo): accept single 'resource' parameter for backwards # compatibility during Newton, remove in Ocata resource_list = ([kwargs['resource']] if 'resource' in kwargs else kwargs['resource_list']) event_type = kwargs['event_type'] resource_objs = [ obj_base.NeutronObject.clean_obj_from_primitive(resource) for resource in resource_list] resource_type = resources.get_resource_type(resource_objs[0]) cons_registry.push(resource_type, resource_objs, event_type)
apache-2.0
liam2/larray
larray/tests/test_array.py
2
174871
# -*- coding: utf8 -*- from __future__ import absolute_import, division, print_function import os import re import sys import pytest import numpy as np import pandas as pd from collections import OrderedDict from larray.tests.common import (inputpath, tmp_path, meta, assert_array_equal, assert_array_nan_equal, assert_larray_equiv, assert_larray_equal, needs_xlwings, needs_pytables, needs_xlsxwriter, needs_xlrd, needs_python35, needs_python36, needs_python37) from larray import (Array, LArray, Axis, LGroup, union, zeros, zeros_like, ndtest, empty, ones, eye, diag, stack, clip, exp, where, X, mean, isnan, round, read_hdf, read_csv, read_eurostat, read_excel, from_lists, from_string, open_excel, from_frame, sequence, nan, IGroup) from larray.inout.pandas import from_series from larray.core.axis import _to_ticks, _to_key from larray.util.misc import LHDFStore from larray.util.compat import StringIO from larray.core.metadata import Metadata # ================== # # Test Value Strings # # ================== # def test_value_string_split(): assert_array_equal(_to_ticks('M,F'), np.asarray(['M', 'F'])) assert_array_equal(_to_ticks('M, F'), np.asarray(['M', 'F'])) def test_value_string_union(): assert union('A11,A22', 'A12,A22') == ['A11', 'A22', 'A12'] def test_value_string_range(): assert_array_equal(_to_ticks('0..115'), np.asarray(range(116))) assert_array_equal(_to_ticks('..115'), np.asarray(range(116))) with pytest.raises(ValueError): _to_ticks('10..') with pytest.raises(ValueError): _to_ticks('..') # ================ # # Test Key Strings # # ================ # def test_key_string_nonstring(): assert _to_key(('M', 'F')) == ['M', 'F'] assert _to_key(['M', 'F']) == ['M', 'F'] def test_key_string_split(): assert _to_key('M,F') == ['M', 'F'] assert _to_key('M, F') == ['M', 'F'] assert _to_key('M,') == ['M'] assert _to_key('M') == 'M' def test_key_string_slice_strings(): # these two examples have different results and this is fine because numeric axes do not necessarily start at 0 assert _to_key('0:115') == slice(0, 115) assert _to_key(':115') == slice(115) assert _to_key('10:') == slice(10, None) assert _to_key(':') == slice(None) # =================== # # Test Metadata # # =================== # def test_read_set_update_delete_metadata(meta, tmpdir): # __eq__ meta2 = meta.copy() assert meta2 == meta # set/get metadata to/from an array arr = ndtest((3, 3)) arr.meta = meta assert arr.meta == meta # access item assert arr.meta.date == meta.date # add new item arr.meta.city = 'London' assert arr.meta.city == 'London' # update item arr.meta.city = 'Berlin' assert arr.meta.city == 'Berlin' # __contains__ assert 'city' in arr.meta # delete item del arr.meta.city assert arr.meta == meta # __reduce__ and __reduce_ex__ import pickle fname = os.path.join(tmpdir.strpath, 'test_metadata.pkl') with open(fname, 'wb') as f: pickle.dump(meta, f) with open(fname, 'rb') as f: meta2 = Metadata(pickle.load(f)) assert meta2 == meta @needs_pytables def test_metadata_hdf(meta, tmpdir): key = 'meta' fname = os.path.join(tmpdir.strpath, 'test_metadata.hdf') with LHDFStore(fname) as store: ndtest(3).to_hdf(store, key) meta.to_hdf(store, key) meta2 = Metadata.from_hdf(store, key) assert meta2 == meta def test_meta_arg_array_creation(array): meta_list = [('title', 'test array'), ('description', 'Array used for testing'), ('author', 'John Cleese')] meta = Metadata(meta_list) # meta as list arr = Array(array.data, array.axes, meta=meta_list) assert arr.meta == meta # meta as OrderedDict arr = Array(array.data, array.axes, meta=OrderedDict(meta_list)) assert arr.meta == meta # ================ # # Test Array # # ================ # # AXES lipro = Axis(['P%02d' % i for i in range(1, 16)], 'lipro') age = Axis('age=0..115') sex = Axis('sex=M,F') vla = 'A11,A12,A13,A23,A24,A31,A32,A33,A34,A35,A36,A37,A38,A41,A42,A43,A44,A45,A46,A71,A72,A73' wal = 'A25,A51,A52,A53,A54,A55,A56,A57,A61,A62,A63,A64,A65,A81,A82,A83,A84,A85,A91,A92,A93' bru = 'A21' vla_str = vla wal_str = wal bru_str = bru belgium = union(vla, wal, bru) geo = Axis(belgium, 'geo') # ARRAYS @pytest.fixture() def array(): data = np.arange(116 * 44 * 2 * 15).reshape(116, 44, 2, 15).astype(float) return Array(data, axes=(age, geo, sex, lipro)) @pytest.fixture() def small_array(): small_data = np.arange(30).reshape(2, 15) return Array(small_data, axes=(sex, lipro)) io_1d = ndtest(3) io_2d = ndtest("a=1..3; b=b0,b1") io_3d = ndtest("a=1..3; b=b0,b1; c=c0..c2") io_int_labels = ndtest("a=0..2; b=0..2; c=0..2") io_unsorted = ndtest("a=3..1; b=b1,b0; c=c2..c0") io_missing_values = ndtest("a=1..3; b=b0,b1; c=c0..c2", dtype=float) io_missing_values[2, 'b0'] = nan io_missing_values[3, 'b1'] = nan io_narrow_missing_values = io_missing_values.copy() io_narrow_missing_values[2, 'b1', 'c1'] = nan def test_larray_renamed_as_array(): with pytest.warns(FutureWarning) as caught_warnings: arr = LArray([0, 1, 2, 3], 'a=a0..a3') assert len(caught_warnings) == 1 assert caught_warnings[0].message.args[0] == "LArray has been renamed as Array." assert caught_warnings[0].filename == __file__ def test_ndtest(): arr = ndtest('a=a0..a2') assert arr.shape == (3,) assert arr.axes.names == ['a'] assert_array_equal(arr.data, np.arange(3)) # using an explicit Axis object a = Axis('a=a0..a2') arr = ndtest(a) assert arr.shape == (3,) assert arr.axes.names == ['a'] assert_array_equal(arr.data, np.arange(3)) # using a group as an axis arr = ndtest(a[:'a1']) assert arr.shape == (2,) assert arr.axes.names == ['a'] assert_array_equal(arr.data, np.arange(2)) def test_getattr(array): assert type(array.geo) == Axis assert array.geo is geo with pytest.raises(AttributeError): array.geom def test_zeros(): la = zeros((geo, age)) assert la.shape == (44, 116) assert_array_equal(la, np.zeros((44, 116))) def test_zeros_like(array): la = zeros_like(array) assert la.shape == (116, 44, 2, 15) assert_array_equal(la, np.zeros((116, 44, 2, 15))) def test_bool(): a = ones([2]) # ValueError: The truth value of an array with more than one element # is ambiguous. Use a.any() or a.all() with pytest.raises(ValueError): bool(a) a = ones([1]) assert bool(a) a = zeros([1]) assert not bool(a) a = Array(np.array(2), []) assert bool(a) a = Array(np.array(0), []) assert not bool(a) def test_iter(small_array): l = list(small_array) assert_array_equal(l[0], small_array['M']) assert_array_equal(l[1], small_array['F']) def test_keys(): arr = ndtest((2, 2)) a, b = arr.axes keys = arr.keys() assert list(keys) == [(a.i[0], b.i[0]), (a.i[0], b.i[1]), (a.i[1], b.i[0]), (a.i[1], b.i[1])] assert keys[0] == (a.i[0], b.i[0]) assert keys[-1] == (a.i[1], b.i[1]) keys = arr.keys(ascending=False) assert list(keys) == [(a.i[1], b.i[1]), (a.i[1], b.i[0]), (a.i[0], b.i[1]), (a.i[0], b.i[0])] assert keys[0] == (a.i[1], b.i[1]) assert keys[-1] == (a.i[0], b.i[0]) keys = arr.keys(('b', 'a')) assert list(keys) == [(b.i[0], a.i[0]), (b.i[0], a.i[1]), (b.i[1], a.i[0]), (b.i[1], a.i[1])] assert keys[1] == (b.i[0], a.i[1]) assert keys[2] == (b.i[1], a.i[0]) keys = arr.keys(('b', 'a'), ascending=False) assert list(keys) == [(b.i[1], a.i[1]), (b.i[1], a.i[0]), (b.i[0], a.i[1]), (b.i[0], a.i[0])] assert keys[1] == (b.i[1], a.i[0]) assert keys[2] == (b.i[0], a.i[1]) keys = arr.keys('b') assert list(keys) == [(b.i[0],), (b.i[1],)] assert keys[0] == (b.i[0],) assert keys[-1] == (b.i[1],) keys = arr.keys('b', ascending=False) assert list(keys) == [(b.i[1],), (b.i[0],)] assert keys[0] == (b.i[1],) assert keys[-1] == (b.i[0],) def test_values(): arr = ndtest((2, 2)) a, b = arr.axes values = arr.values() assert list(values) == [0, 1, 2, 3] assert values[0] == 0 assert values[-1] == 3 values = arr.values(ascending=False) assert list(values) == [3, 2, 1, 0] assert values[0] == 3 assert values[-1] == 0 values = arr.values(('b', 'a')) assert list(values) == [0, 2, 1, 3] assert values[1] == 2 assert values[2] == 1 values = arr.values(('b', 'a'), ascending=False) assert list(values) == [3, 1, 2, 0] assert values[1] == 1 assert values[2] == 2 values = arr.values('b') res = list(values) assert_larray_equal(res[0], arr['b0']) assert_larray_equal(res[1], arr['b1']) assert_larray_equal(values[0], arr['b0']) assert_larray_equal(values[-1], arr['b1']) values = arr.values('b', ascending=False) res = list(values) assert_larray_equal(res[0], arr['b1']) assert_larray_equal(res[1], arr['b0']) assert_larray_equal(values[0], arr['b1']) assert_larray_equal(values[-1], arr['b0']) def test_items(): arr = ndtest((2, 2)) a, b = arr.axes items = arr.items() assert list(items) == [((a.i[0], b.i[0]), 0), ((a.i[0], b.i[1]), 1), ((a.i[1], b.i[0]), 2), ((a.i[1], b.i[1]), 3)] assert items[0] == ((a.i[0], b.i[0]), 0) assert items[-1] == ((a.i[1], b.i[1]), 3) items = arr.items(ascending=False) assert list(items) == [((a.i[1], b.i[1]), 3), ((a.i[1], b.i[0]), 2), ((a.i[0], b.i[1]), 1), ((a.i[0], b.i[0]), 0)] assert items[0] == ((a.i[1], b.i[1]), 3) assert items[-1] == ((a.i[0], b.i[0]), 0) items = arr.items(('b', 'a')) assert list(items) == [((b.i[0], a.i[0]), 0), ((b.i[0], a.i[1]), 2), ((b.i[1], a.i[0]), 1), ((b.i[1], a.i[1]), 3)] assert items[1] == ((b.i[0], a.i[1]), 2) assert items[2] == ((b.i[1], a.i[0]), 1) items = arr.items(('b', 'a'), ascending=False) assert list(items) == [((b.i[1], a.i[1]), 3), ((b.i[1], a.i[0]), 1), ((b.i[0], a.i[1]), 2), ((b.i[0], a.i[0]), 0)] assert items[1] == ((b.i[1], a.i[0]), 1) assert items[2] == ((b.i[0], a.i[1]), 2) items = arr.items('b') items_list = list(items) key, value = items[0] assert key == (b.i[0],) assert_larray_equal(value, arr['b0']) key, value = items_list[0] assert key == (b.i[0],) assert_larray_equal(value, arr['b0']) key, value = items[-1] assert key == (b.i[1],) assert_larray_equal(value, arr['b1']) key, value = items_list[-1] assert key == (b.i[1],) assert_larray_equal(value, arr['b1']) items = arr.items('b', ascending=False) items_list = list(items) key, value = items[0] assert key == (b.i[1],) assert_larray_equal(value, arr['b1']) key, value = items_list[0] assert key == (b.i[1],) assert_larray_equal(value, arr['b1']) key, value = items[-1] assert key == (b.i[0],) assert_larray_equal(value, arr['b0']) key, value = items_list[-1] assert key == (b.i[0],) assert_larray_equal(value, arr['b0']) def test_rename(array): new_array = array.rename('sex', 'gender') # old array axes names not modified assert array.axes.names == ['age', 'geo', 'sex', 'lipro'] assert new_array.axes.names == ['age', 'geo', 'gender', 'lipro'] new_array = array.rename(sex, 'gender') # old array axes names not modified assert array.axes.names == ['age', 'geo', 'sex', 'lipro'] assert new_array.axes.names == ['age', 'geo', 'gender', 'lipro'] def test_info(array, meta): array.meta = meta expected = """\ title: test array description: Array used for testing author: John Cleese location: Ministry of Silly Walks office_number: 42 score: 9.7 date: 1970-03-21 00:00:00 116 x 44 x 2 x 15 age [116]: 0 1 2 ... 113 114 115 geo [44]: 'A11' 'A12' 'A13' ... 'A92' 'A93' 'A21' sex [2]: 'M' 'F' lipro [15]: 'P01' 'P02' 'P03' ... 'P13' 'P14' 'P15' dtype: float64 memory used: 1.17 Mb""" assert array.info == expected def test_str(small_array, array): lipro3 = lipro['P01:P03'] # zero dimension / scalar assert str(small_array[lipro['P01'], sex['F']]) == "15" # empty / len 0 first dimension assert str(small_array[sex[[]]]) == "Array([])" # one dimension assert str(small_array[lipro3, sex['M']]) == """\ lipro P01 P02 P03 0 1 2""" # two dimensions assert str(small_array.filter(lipro=lipro3)) == """\ sex\\lipro P01 P02 P03 M 0 1 2 F 15 16 17""" # four dimensions (too many rows) assert str(array.filter(lipro=lipro3)) == """\ age geo sex\\lipro P01 P02 P03 0 A11 M 0.0 1.0 2.0 0 A11 F 15.0 16.0 17.0 0 A12 M 30.0 31.0 32.0 0 A12 F 45.0 46.0 47.0 0 A13 M 60.0 61.0 62.0 ... ... ... ... ... ... 115 A92 F 153045.0 153046.0 153047.0 115 A93 M 153060.0 153061.0 153062.0 115 A93 F 153075.0 153076.0 153077.0 115 A21 M 153090.0 153091.0 153092.0 115 A21 F 153105.0 153106.0 153107.0""" # too many columns assert str(array['P01', 'A11', 'M']) == """\ age 0 1 2 ... 112 113 114 115 0.0 1320.0 2640.0 ... 147840.0 149160.0 150480.0 151800.0""" arr = Array([0, ''], Axis(['a0', ''], 'a')) assert str(arr) == "a a0 \n 0 " def test_getitem(array): raw = array.data age, geo, sex, lipro = array.axes age159 = age[[1, 5, 9]] lipro159 = lipro['P01,P05,P09'] # LGroup at "correct" place subset = array[age159] assert subset.axes[1:] == (geo, sex, lipro) assert subset.axes[0].equals(Axis([1, 5, 9], 'age')) assert_array_equal(subset, raw[[1, 5, 9]]) # LGroup at "incorrect" place assert_array_equal(array[lipro159], raw[..., [0, 4, 8]]) # multiple LGroup key (in "incorrect" order) res = array[lipro159, age159] assert res.axes.names == ['age', 'geo', 'sex', 'lipro'] assert_array_equal(res, raw[[1, 5, 9]][..., [0, 4, 8]]) # LGroup key and scalar res = array[lipro159, 5] assert res.axes.names == ['geo', 'sex', 'lipro'] assert_array_equal(res, raw[..., [0, 4, 8]][5]) # mixed LGroup/positional key assert_array_equal(array[[1, 5, 9], lipro159], raw[[1, 5, 9]][..., [0, 4, 8]]) # single None slice assert_array_equal(array[:], raw) # only Ellipsis assert_array_equal(array[...], raw) # Ellipsis and LGroup assert_array_equal(array[..., lipro159], raw[..., [0, 4, 8]]) # string 'int..int' assert_array_equal(array['10..13'], array['10,11,12,13']) assert_array_equal(array['8, 10..13, 15'], array['8,10,11,12,13,15']) # ambiguous label arr = ndtest("a=l0,l1;b=l1,l2") res = arr[arr.b['l1']] assert_array_equal(res, arr.data[:, 0]) # scalar group on another axis arr = ndtest((3, 2)) alt_a = Axis("alt_a=a1..a2") lgroup = alt_a['a1'] assert_array_equal(arr[lgroup], arr['a1']) pgroup = alt_a.i[0] assert_array_equal(arr[pgroup], arr['a1']) # key with duplicate axes with pytest.raises(ValueError): array[age[1, 2], age[3, 4]] # key with lgroup from another axis leading to duplicate axis bad = Axis(3, 'bad') with pytest.raises(ValueError): array[bad[1, 2], age[3, 4]] def test_getitem_abstract_axes(array): raw = array.data age, geo, sex, lipro = array.axes age159 = X.age[1, 5, 9] lipro159 = X.lipro['P01,P05,P09'] # LGroup at "correct" place subset = array[age159] assert subset.axes[1:] == (geo, sex, lipro) assert subset.axes[0].equals(Axis([1, 5, 9], 'age')) assert_array_equal(subset, raw[[1, 5, 9]]) # LGroup at "incorrect" place assert_array_equal(array[lipro159], raw[..., [0, 4, 8]]) # multiple LGroup key (in "incorrect" order) assert_array_equal(array[lipro159, age159], raw[[1, 5, 9]][..., [0, 4, 8]]) # mixed LGroup/positional key assert_array_equal(array[[1, 5, 9], lipro159], raw[[1, 5, 9]][..., [0, 4, 8]]) # single None slice assert_array_equal(array[:], raw) # only Ellipsis assert_array_equal(array[...], raw) # Ellipsis and LGroup assert_array_equal(array[..., lipro159], raw[..., [0, 4, 8]]) # key with duplicate axes with pytest.raises(ValueError): array[X.age[1, 2], X.age[3]] # key with invalid axis with pytest.raises(ValueError): array[X.bad[1, 2], X.age[3, 4]] def test_getitem_anonymous_axes(): arr = ndtest([Axis(3), Axis(4)]) raw = arr.data assert_array_equal(arr[X[0][1:]], raw[1:]) assert_array_equal(arr[X[1][2:]], raw[:, 2:]) assert_array_equal(arr[X[0][2:], X[1][1:]], raw[2:, 1:]) assert_array_equal(arr.i[2:, 1:], raw[2:, 1:]) def test_getitem_guess_axis(array): raw = array.data age, geo, sex, lipro = array.axes # key at "correct" place assert_array_equal(array[[1, 5, 9]], raw[[1, 5, 9]]) subset = array[[1, 5, 9]] assert subset.axes[1:] == (geo, sex, lipro) assert subset.axes[0].equals(Axis([1, 5, 9], 'age')) assert_array_equal(subset, raw[[1, 5, 9]]) # key at "incorrect" place assert_array_equal(array['P01,P05,P09'], raw[..., [0, 4, 8]]) assert_array_equal(array[['P01', 'P05', 'P09']], raw[..., [0, 4, 8]]) # multiple keys (in "incorrect" order) assert_array_equal(array['P01,P05,P09', [1, 5, 9]], raw[[1, 5, 9]][..., [0, 4, 8]]) # mixed LGroup/key assert_array_equal(array[lipro['P01,P05,P09'], [1, 5, 9]], raw[[1, 5, 9]][..., [0, 4, 8]]) # single None slice assert_array_equal(array[:], raw) # only Ellipsis assert_array_equal(array[...], raw) # Ellipsis and LGroup assert_array_equal(array[..., 'P01,P05,P09'], raw[..., [0, 4, 8]]) assert_array_equal(array[..., ['P01', 'P05', 'P09']], raw[..., [0, 4, 8]]) # LGroup without axis (which also needs to be guessed) g = LGroup(['P01', 'P05', 'P09']) assert_array_equal(array[g], raw[..., [0, 4, 8]]) # key with duplicate axes with pytest.raises(ValueError, match="key has several values for axis: age"): array[[1, 2], [3, 4]] # key with invalid label (ie label not found on any axis) with pytest.raises(ValueError, match="999 is not a valid label for any axis"): array[[1, 2], 999] # key with invalid label list (ie list of labels not found on any axis) with pytest.raises(ValueError, match=r"\[998, 999\] is not a valid label for any axis"): array[[1, 2], [998, 999]] # key with partial invalid list (ie list containing a label not found # on any axis) # FIXME: the message should be the same as for 999, 4 (ie it should NOT mention age). with pytest.raises(ValueError, match=r"age\[3, 999\] is not a valid label for any axis"): array[[1, 2], [3, 999]] with pytest.raises(ValueError, match=r"\[999, 4\] is not a valid label for any axis"): array[[1, 2], [999, 4]] # ambiguous key arr = ndtest("a=l0,l1;b=l1,l2") with pytest.raises(ValueError, match=r"l1 is ambiguous \(valid in a, b\)"): arr['l1'] # ambiguous key disambiguated via string res = arr['b[l1]'] assert_array_equal(res, arr.data[:, 0]) def test_getitem_positional_group(array): raw = array.data age, geo, sex, lipro = array.axes age159 = age.i[1, 5, 9] lipro159 = lipro.i[0, 4, 8] # LGroup at "correct" place subset = array[age159] assert subset.axes[1:] == (geo, sex, lipro) assert subset.axes[0].equals(Axis([1, 5, 9], 'age')) assert_array_equal(subset, raw[[1, 5, 9]]) # LGroup at "incorrect" place assert_array_equal(array[lipro159], raw[..., [0, 4, 8]]) # multiple LGroup key (in "incorrect" order) assert_array_equal(array[lipro159, age159], raw[[1, 5, 9]][..., [0, 4, 8]]) # mixed LGroup/positional key assert_array_equal(array[[1, 5, 9], lipro159], raw[[1, 5, 9]][..., [0, 4, 8]]) # single None slice assert_array_equal(array[:], raw) # only Ellipsis assert_array_equal(array[...], raw) # Ellipsis and LGroup assert_array_equal(array[..., lipro159], raw[..., [0, 4, 8]]) # key with duplicate axes with pytest.raises(ValueError, match="key has several values for axis: age"): array[age.i[1, 2], age.i[3, 4]] def test_getitem_str_positional_group(): arr = ndtest('a=l0..l2;b=l0..l2') a, b = arr.axes res = arr['b.i[1]'] expected = Array([1, 4, 7], 'a=l0..l2') assert_array_equal(res, expected) def test_getitem_abstract_positional(array): raw = array.data age, geo, sex, lipro = array.axes age159 = X.age.i[1, 5, 9] lipro159 = X.lipro.i[0, 4, 8] # LGroup at "correct" place subset = array[age159] assert subset.axes[1:] == (geo, sex, lipro) assert subset.axes[0].equals(Axis([1, 5, 9], 'age')) assert_array_equal(subset, raw[[1, 5, 9]]) # LGroup at "incorrect" place assert_array_equal(array[lipro159], raw[..., [0, 4, 8]]) # multiple LGroup key (in "incorrect" order) assert_array_equal(array[lipro159, age159], raw[[1, 5, 9]][..., [0, 4, 8]]) # mixed LGroup/positional key assert_array_equal(array[[1, 5, 9], lipro159], raw[[1, 5, 9]][..., [0, 4, 8]]) # single None slice assert_array_equal(array[:], raw) # only Ellipsis assert_array_equal(array[...], raw) # Ellipsis and LGroup assert_array_equal(array[..., lipro159], raw[..., [0, 4, 8]]) # key with duplicate axes with pytest.raises(ValueError, match="key has several values for axis: age"): array[X.age.i[2, 3], X.age.i[1, 5]] def test_getitem_bool_larray_key_arr_whout_bool_axis(): arr = ndtest((3, 2, 4)) raw = arr.data # all dimensions res = arr[arr < 5] assert isinstance(res, Array) assert res.ndim == 1 assert_array_equal(res, raw[raw < 5]) # missing dimension filter_ = arr['b1'] % 5 == 0 res = arr[filter_] assert isinstance(res, Array) assert res.ndim == 2 assert res.shape == (3, 2) raw_key = raw[:, 1, :] % 5 == 0 raw_d1, raw_d3 = raw_key.nonzero() assert_array_equal(res, raw[raw_d1, :, raw_d3]) # using an Axis object arr = ndtest('a=a0,a1;b=0..3') raw = arr.data res = arr[arr.b < 2] assert_array_equal(res, raw[:, :2]) # using an AxisReference (ExprNode) res = arr[X.b < 2] assert_array_equal(res, raw[:, :2]) def test_getitem_bool_larray_key_arr_wh_bool_axis(): gender = Axis([False, True], 'gender') arr = Array([0.1, 0.2], gender) id_axis = Axis('id=0..3') key = Array([True, False, True, True], id_axis) expected = Array([0.2, 0.1, 0.2, 0.2], id_axis) # LGroup using the real axis assert_larray_equal(arr[gender[key]], expected) # LGroup using an AxisReference assert_larray_equal(arr[X.gender[key]], expected) # this test checks that the current behavior does not change unintentionally... # ... but I am unsure the current behavior is what we actually want msg = re.escape("boolean subset key contains more axes ({id}) than array ({gender})") with pytest.raises(ValueError, match=msg): arr[key] def test_getitem_bool_larray_and_group_key(): arr = ndtest((3, 6, 4)).set_labels('b', '0..5') # using axis res = arr['a0,a2', arr.b < 3, 'c0:c3'] assert isinstance(res, Array) assert res.ndim == 3 expected = arr['a0,a2', '0:2', 'c0:c3'] assert_array_equal(res, expected) # using axis reference res = arr['a0,a2', X.b < 3, 'c0:c3'] assert isinstance(res, Array) assert res.ndim == 3 assert_array_equal(res, expected) def test_getitem_bool_ndarray_key_arr_whout_bool_axis(array): raw = array.data res = array[raw < 5] assert isinstance(res, Array) assert res.ndim == 1 assert_array_equal(res, raw[raw < 5]) def test_getitem_bool_ndarray_key_arr_wh_bool_axis(): gender = Axis([False, True], 'gender') arr = Array([0.1, 0.2], gender) key = np.array([True, False, True, True]) expected = arr.i[[1, 0, 1, 1]] # LGroup using the real axis assert_larray_equal(arr[gender[key]], expected) # LGroup using an AxisReference assert_larray_equal(arr[X.gender[key]], expected) # raw key => ??? # this test checks that the current behavior does not change unintentionally... # ... but I am unsure the current behavior is what we actually want # L? is to account for Python2 where shape can be 'long' integers msg = r"boolean key with a different shape \(\(4L?,\)\) than array \(\(2,\)\)" with pytest.raises(ValueError, match=msg): arr[key] def test_getitem_bool_anonymous_axes(): a = ndtest([Axis(2), Axis(3), Axis(4), Axis(5)]) mask = ones(a.axes[1, 3], dtype=bool) res = a[mask] assert res.ndim == 3 assert res.shape == (15, 2, 4) # XXX: we might want to transpose the result to always move combined axes to the front a = ndtest([Axis(2), Axis(3), Axis(4), Axis(5)]) mask = ones(a.axes[1, 2], dtype=bool) res = a[mask] assert res.ndim == 3 assert res.shape == (2, 12, 5) def test_getitem_igroup_on_int_axis(): a = Axis('a=1..3') arr = ndtest(a) assert arr[a.i[1]] == 1 def test_getitem_integer_string_axes(): arr = ndtest((5, 5)) a, b = arr.axes assert_array_equal(arr['0[a0, a2]'], arr[a['a0', 'a2']]) assert_array_equal(arr['0[a0:a2]'], arr[a['a0:a2']]) with pytest.raises(ValueError): arr['1[a0, a2]'] assert_array_equal(arr['0.i[0, 2]'], arr[a.i[0, 2]]) assert_array_equal(arr['0.i[0:2]'], arr[a.i[0:2]]) with pytest.raises(ValueError): arr['3.i[0, 2]'] def test_getitem_int_larray_lgroup_key(): # e axis go from 0 to 3 arr = ndtest("c=0,1; d=0,1; e=0..3") # key values go from 0 to 3 key = ndtest("a=0,1; b=0,1") # this replaces 'e' axis by 'a' and 'b' axes res = arr[X.e[key]] assert res.shape == (2, 2, 2, 2) assert res.axes.names == ['c', 'd', 'a', 'b'] def test_getitem_structured_key_with_groups(): arr = ndtest((3, 2)) expected = arr['a1':] a, b = arr.axes alt_a = Axis('a=a1..a3') # a) slice with lgroup # a.1) LGroup.axis from array.axes assert_array_equal(arr[a['a1']:a['a2']], expected) # a.2) LGroup.axis not from array.axes assert_array_equal((arr[alt_a['a1']:alt_a['a2']]), expected) # b) slice with igroup # b.1) IGroup.axis from array.axes assert_array_equal((arr[a.i[1]:a.i[2]]), expected) # b.2) IGroup.axis not from array.axes assert_array_equal((arr[alt_a.i[0]:alt_a.i[1]]), expected) # c) list with LGroup # c.1) LGroup.axis from array.axes assert_array_equal((arr[[a['a1'], a['a2']]]), expected) # c.2) LGroup.axis not from array.axes assert_array_equal((arr[[alt_a['a1'], alt_a['a2']]]), expected) # d) list with IGroup # d.1) IGroup.axis from array.axes assert_array_equal((arr[[a.i[1], a.i[2]]]), expected) # d.2) IGroup.axis not from array.axes assert_array_equal((arr[[alt_a.i[0], alt_a.i[1]]]), expected) def test_getitem_single_larray_key_guess(): # TODO: we really need another way to get test axes, e.g. testaxes(2, 3, 4) or testaxes((2, 3, 4)) a, b, c = ndtest((2, 3, 4)).axes arr = ndtest((a, b)) # >>> arr # a\b b0 b1 b2 # a0 0 1 2 # a1 3 4 5 # 1) key with extra axis key = Array(['a0', 'a1', 'a1', 'a0'], c) # replace the target axis by the extra axis expected = from_string(r""" c\b b0 b1 b2 c0 0 1 2 c1 3 4 5 c2 3 4 5 c3 0 1 2""") assert_array_equal(arr[key], expected) # 2) key with the target axis (the one being replaced) key = Array(['b1', 'b0', 'b2'], b) # axis stays the same but data should be flipped/shuffled expected = from_string(r""" a\b b0 b1 b2 a0 1 0 2 a1 4 3 5""") assert_array_equal(arr[key], expected) # 2bis) key with part of the target axis (the one being replaced) key = Array(['b2', 'b1'], 'b=b0,b1') expected = from_string(r""" a\b b0 b1 a0 2 1 a1 5 4""") assert_array_equal(arr[key], expected) # 3) key with another existing axis (not the target axis) key = Array(['a0', 'a1', 'a0'], b) expected = from_string(""" b b0 b1 b2 \t 0 4 2""") assert_array_equal(arr[key], expected) # TODO: this does not work yet but should be much easier to implement with "align" in make_np_broadcastable # 3bis) key with *part* of another existing axis (not the target axis) # key = Array(['a1', 'a0'], 'b=b0,b1') # expected = from_string(""" # b b0 b1 # \t 3 1""") # assert_array_equal(arr[key], expected) # 4) key has both the target axis and another existing axis # TODO: maybe we should make this work without requiring astype! key = from_string(r""" a\b b0 b1 b2 a0 a0 a1 a0 a1 a1 a0 a1""").astype(str) expected = from_string(r""" a\b b0 b1 b2 a0 0 4 2 a1 3 1 5""") assert_array_equal(arr[key], expected) # 5) key has both the target axis and an extra axis key = from_string(r""" a\c c0 c1 c2 c3 a0 a0 a1 a1 a0 a1 a1 a0 a0 a1""").astype(str) expected = from_string(r""" a c\b b0 b1 b2 a0 c0 0 1 2 a0 c1 3 4 5 a0 c2 3 4 5 a0 c3 0 1 2 a1 c0 3 4 5 a1 c1 0 1 2 a1 c2 0 1 2 a1 c3 3 4 5""") assert_array_equal(arr[key], expected) # 6) key has both another existing axis (not target) and an extra axis key = from_string(r""" a\c c0 c1 c2 c3 a0 b0 b1 b0 b1 a1 b2 b1 b2 b1""").astype(str) expected = from_string(r""" a\c c0 c1 c2 c3 a0 0 1 0 1 a1 5 4 5 4""") assert_array_equal(arr[key], expected) # 7) key has the target axis, another existing axis and an extra axis key = from_string(r""" a b\c c0 c1 c2 c3 a0 b0 a0 a1 a0 a1 a0 b1 a1 a0 a1 a0 a0 b2 a0 a1 a0 a1 a1 b0 a0 a1 a1 a0 a1 b1 a1 a1 a1 a1 a1 b2 a0 a1 a1 a0""").astype(str) expected = from_string(r""" a b\c c0 c1 c2 c3 a0 b0 0 3 0 3 a0 b1 4 1 4 1 a0 b2 2 5 2 5 a1 b0 0 3 3 0 a1 b1 4 4 4 4 a1 b2 2 5 5 2""") assert_array_equal(arr[key], expected) def test_getitem_multiple_larray_key_guess(): a, b, c, d, e = ndtest((2, 3, 2, 3, 2)).axes arr = ndtest((a, b)) # >>> arr # a\b b0 b1 b2 # a0 0 1 2 # a1 3 4 5 # 1) keys with each a different existing axis k1 = from_string(""" a a1 a0 \t b2 b0""") k2 = from_string(""" b b1 b2 b3 \t a0 a1 a0""") expected = from_string(r"""b\a a1 a0 b1 2 0 b2 5 3 b3 2 0""") assert_array_equal(arr[k1, k2], expected) # 2) keys with a common existing axis k1 = from_string(""" b b0 b1 b2 \t a1 a0 a1""") k2 = from_string(""" b b0 b1 b2 \t b1 b2 b0""") expected = from_string(""" b b0 b1 b2 \t 4 2 3""") assert_array_equal(arr[k1, k2], expected) # 3) keys with each a different extra axis k1 = from_string(""" c c0 c1 \t a1 a0""") k2 = from_string(""" d d0 d1 d2 \t b1 b2 b0""") expected = from_string(r"""c\d d0 d1 d2 c0 4 5 3 c1 1 2 0""") assert_array_equal(arr[k1, k2], expected) # 4) keys with a common extra axis k1 = from_string(r"""c\d d0 d1 d2 c0 a1 a0 a1 c1 a0 a1 a0""").astype(str) k2 = from_string(r"""c\e e0 e1 c0 b1 b2 c1 b0 b1""").astype(str) expected = from_string(r""" c d\e e0 e1 c0 d0 4 5 c0 d1 1 2 c0 d2 4 5 c1 d0 0 1 c1 d1 3 4 c1 d2 0 1""") assert_array_equal(arr[k1, k2], expected) def test_getitem_ndarray_key_guess(array): raw = array.data keys = ['P04', 'P01', 'P03', 'P02'] key = np.array(keys) res = array[key] assert isinstance(res, Array) assert res.axes == array.axes.replace(X.lipro, Axis(keys, 'lipro')) assert_array_equal(res, raw[:, :, :, [3, 0, 2, 1]]) def test_getitem_int_larray_key_guess(): a = Axis([0, 1], 'a') b = Axis([2, 3], 'b') c = Axis([4, 5], 'c') d = Axis([6, 7], 'd') e = Axis([8, 9, 10, 11], 'e') arr = ndtest([c, d, e]) key = Array([[8, 9], [10, 11]], [a, b]) assert arr[key].axes == [c, d, a, b] def test_getitem_int_ndarray_key_guess(): c = Axis([4, 5], 'c') d = Axis([6, 7], 'd') e = Axis([8, 9, 10, 11], 'e') arr = ndtest([c, d, e]) # ND keys do not work yet # key = nparray([[8, 11], [10, 9]]) key = np.array([8, 11, 10]) res = arr[key] assert res.axes == [c, d, Axis([8, 11, 10], 'e')] def test_getitem_axis_object(): arr = ndtest((2, 3)) a, b = arr.axes assert_array_equal(arr[a], arr) assert_array_equal(arr[b], arr) b2 = Axis('b=b0,b2') assert_array_equal(arr[b2], from_string("""a\\b b0 b2 a0 0 2 a1 3 5""")) def test_getitem_empty_tuple(): # an empty tuple should return a view on the original array arr = ndtest((2, 3)) res = arr[()] assert_array_equal(res, arr) assert res is not arr z = Array(0) res = z[()] assert res == z assert res is not z def test_positional_indexer_getitem(array): raw = array.data for key in [0, (0, 5, 1, 2), (slice(None), 5, 1), (0, 5), [1, 0], ([1, 0], 5)]: assert_array_equal(array.i[key], raw[key]) assert_array_equal(array.i[[1, 0], [5, 4]], raw[np.ix_([1, 0], [5, 4])]) with pytest.raises(IndexError): array.i[0, 0, 0, 0, 0] def test_positional_indexer_setitem(array): for key in [0, (0, 2, 1, 2), (slice(None), 2, 1), (0, 2), [1, 0], ([1, 0], 2)]: arr = array.copy() raw = array.data.copy() arr.i[key] = 42 raw[key] = 42 assert_array_equal(arr, raw) raw = array.data array.i[[1, 0], [5, 4]] = 42 raw[np.ix_([1, 0], [5, 4])] = 42 assert_array_equal(array, raw) def test_points_indexer_getitem(): arr = ndtest((2, 3, 3)) raw = arr.data keys = [ ('a0', 0), (('a0', 'c2'), (0, slice(None), 2)), (('a0', 'b1', 'c2'), (0, 1, 2)), # key in the "correct" order ((['a1', 'a0', 'a1', 'a0'], 'b1', ['c1', 'c0', 'c1', 'c0']), ([1, 0, 1, 0], 1, [1, 0, 1, 0])), # key in the "wrong" order ((['a1', 'a0', 'a1', 'a0'], ['c1', 'c0', 'c1', 'c0'], 'b1'), ([1, 0, 1, 0], 1, [1, 0, 1, 0])), # advanced key with a missing dimension ((['a1', 'a0', 'a1', 'a0'], ['c1', 'c0', 'c1', 'c0']), ([1, 0, 1, 0], slice(None), [1, 0, 1, 0])), ] for label_key, index_key in keys: assert_array_equal(arr.points[label_key], raw[index_key]) # XXX: we might want to raise KeyError or IndexError instead? with pytest.raises(ValueError): arr.points['a0', 'b1', 'c2', 'd0'] def test_points_indexer_setitem(): keys = [ ('a0', 0), (('a0', 'c2'), (0, slice(None), 2)), (('a0', 'b1', 'c2'), (0, 1, 2)), # key in the "correct" order ((['a1', 'a0', 'a1', 'a0'], 'b1', ['c1', 'c0', 'c1', 'c0']), ([1, 0, 1, 0], 1, [1, 0, 1, 0])), # key in the "wrong" order ((['a1', 'a0', 'a1', 'a0'], ['c1', 'c0', 'c1', 'c0'], 'b1'), ([1, 0, 1, 0], 1, [1, 0, 1, 0])), # advanced key with a missing dimension ((['a1', 'a0', 'a1', 'a0'], ['c1', 'c0', 'c1', 'c0']), ([1, 0, 1, 0], slice(None), [1, 0, 1, 0])), ] for label_key, index_key in keys: arr = ndtest((2, 3, 3)) raw = arr.data.copy() arr.points[label_key] = 42 raw[index_key] = 42 assert_array_equal(arr, raw) arr = ndtest(2) # XXX: we might want to raise KeyError or IndexError instead? with pytest.raises(ValueError): arr.points['a0', 'b1'] = 42 # test when broadcasting is involved arr = ndtest((2, 3, 4)) raw = arr.data.copy() raw_value = raw[:, 0, 0].reshape(2, 1) raw[:, [0, 1, 2], [0, 1, 2]] = raw_value arr.points['b0,b1,b2', 'c0,c1,c2'] = arr['b0', 'c0'] assert_array_equal(arr, raw) def test_setitem_larray(array, small_array): """ tests Array.__setitem__(key, value) where value is an Array """ age, geo, sex, lipro = array.axes # 1) using a LGroup key ages1_5_9 = age[[1, 5, 9]] # a) value has exactly the same shape as the target slice arr = array.copy() raw = array.data.copy() arr[ages1_5_9] = arr[ages1_5_9] + 25.0 raw[[1, 5, 9]] = raw[[1, 5, 9]] + 25.0 assert_array_equal(arr, raw) # b) value has exactly the same shape but LGroup at a "wrong" positions arr = array.copy() arr[geo[:], ages1_5_9] = arr[ages1_5_9] + 25.0 # same raw as previous test assert_array_equal(arr, raw) # c) value has an extra length-1 axis arr = array.copy() raw = array.data.copy() raw_value = raw[[1, 5, 9], np.newaxis] + 26.0 fake_axis = Axis(['label'], 'fake') age_axis = arr[ages1_5_9].axes.age value = Array(raw_value, axes=(age_axis, fake_axis, geo, sex, lipro)) arr[ages1_5_9] = value raw[[1, 5, 9]] = raw[[1, 5, 9]] + 26.0 assert_array_equal(arr, raw) # d) value has the same axes than target but one has length 1 # arr = array.copy() # raw = array.data.copy() # raw[[1, 5, 9]] = np.sum(raw[[1, 5, 9]], axis=1, keepdims=True) # arr[ages1_5_9] = arr[ages1_5_9].sum(geo=(geo.all(),)) # assert_array_equal(arr, raw) # e) value has a missing dimension arr = array.copy() raw = array.data.copy() arr[ages1_5_9] = arr[ages1_5_9].sum(geo) raw[[1, 5, 9]] = np.sum(raw[[1, 5, 9]], axis=1, keepdims=True) assert_array_equal(arr, raw) # 2) using a LGroup and scalar key (triggers advanced indexing/cross) # a) value has exactly the same shape as the target slice arr = array.copy() raw = array.data.copy() # using 1, 5, 8 and not 9 so that the list is not collapsed to slice value = arr[age[1, 5, 8], sex['M']] + 25.0 arr[age[1, 5, 8], sex['M']] = value raw[[1, 5, 8], :, 0] = raw[[1, 5, 8], :, 0] + 25.0 assert_array_equal(arr, raw) # 3) using a string key arr = array.copy() raw = array.data.copy() arr['1, 5, 9'] = arr['1, 5, 9'] + 27.0 raw[[1, 5, 9]] = raw[[1, 5, 9]] + 27.0 assert_array_equal(arr, raw) # 4) using ellipsis keys # only Ellipsis arr = array.copy() arr[...] = 0 assert_array_equal(arr, np.zeros_like(raw)) # Ellipsis and LGroup arr = array.copy() raw = array.data.copy() arr[..., lipro['P01,P05,P09']] = 0 raw[..., [0, 4, 8]] = 0 assert_array_equal(arr, raw) # 5) using a single slice(None) key arr = array.copy() arr[:] = 0 assert_array_equal(arr, np.zeros_like(raw)) # 6) incompatible axes arr = small_array.copy() la2 = small_array.copy() with pytest.raises(ValueError, match="Value {!s} axis is not present in target subset {!s}. " "A value can only have the same axes or fewer axes than the subset " "being targeted".format(la2.axes - arr['P01'].axes, arr['P01'].axes)): arr['P01'] = la2 la2 = arr.rename('sex', 'gender') with pytest.raises(ValueError, match="Value {!s} axis is not present in target subset {!s}. " "A value can only have the same axes or fewer axes than the subset " "being targeted".format(la2['P01'].axes - arr['P01'].axes, arr['P01'].axes)): arr['P01'] = la2['P01'] # 7) incompatible labels sex2 = Axis('sex=F,M') la2 = Array(small_array.data, axes=(sex2, lipro)) with pytest.raises(ValueError, match="incompatible axes:"): arr[:] = la2 # key has multiple Arrays (this is used within .points indexing) # ============================================================== # first some setup a = Axis(['a0', 'a1'], None) b = Axis(['b0', 'b1', 'b2'], None) expected = ndtest((a, b)) value = expected.combine_axes() # a) with anonymous axes combined_axis = value.axes[0] a_key = Array([0, 0, 0, 1, 1, 1], combined_axis) b_key = Array([0, 1, 2, 0, 1, 2], combined_axis) key = (a.i[a_key], b.i[b_key]) array = empty((a, b)) array[key] = value assert_array_equal(array, expected) # b) with wildcard combined_axis wild_combined_axis = combined_axis.ignore_labels() wild_a_key = Array([0, 0, 0, 1, 1, 1], wild_combined_axis) wild_b_key = Array([0, 1, 2, 0, 1, 2], wild_combined_axis) wild_key = (a.i[wild_a_key], b.i[wild_b_key]) array = empty((a, b)) array[wild_key] = value assert_array_equal(array, expected) # c) with a wildcard value wild_value = value.ignore_labels() array = empty((a, b)) array[key] = wild_value assert_array_equal(array, expected) # d) with a wildcard combined axis and wildcard value array = empty((a, b)) array[wild_key] = wild_value assert_array_equal(array, expected) def test_setitem_ndarray(array): """ tests Array.__setitem__(key, value) where value is a raw ndarray. In that case, value.shape is more restricted as we rely on numpy broadcasting. """ # a) value has exactly the same shape as the target slice arr = array.copy() raw = array.data.copy() value = raw[[1, 5, 9]] + 25.0 arr[[1, 5, 9]] = value raw[[1, 5, 9]] = value assert_array_equal(arr, raw) # b) value has the same axes than target but one has length 1 arr = array.copy() raw = array.data.copy() value = np.sum(raw[[1, 5, 9]], axis=1, keepdims=True) arr[[1, 5, 9]] = value raw[[1, 5, 9]] = value assert_array_equal(arr, raw) def test_setitem_scalar(array): """ tests Array.__setitem__(key, value) where value is a scalar """ # a) list key (one dimension) arr = array.copy() raw = array.data.copy() arr[[1, 5, 9]] = 42 raw[[1, 5, 9]] = 42 assert_array_equal(arr, raw) # b) full scalar key (ie set one cell) arr = array.copy() raw = array.data.copy() arr[0, 'P02', 'A12', 'M'] = 42 raw[0, 1, 0, 1] = 42 assert_array_equal(arr, raw) def test_setitem_bool_array_key(array): # XXX: this test is awfully slow (more than 1s) age, geo, sex, lipro = array.axes # Array key # a1) same shape, same order arr = array.copy() raw = array.data.copy() arr[arr < 5] = 0 raw[raw < 5] = 0 assert_array_equal(arr, raw) # a2) same shape, different order arr = array.copy() raw = array.data.copy() key = (arr < 5).T arr[key] = 0 raw[raw < 5] = 0 assert_array_equal(arr, raw) # b) numpy-broadcastable shape # arr = array.copy() # raw = array.data.copy() # key = arr[sex['F,']] < 5 # self.assertEqual(key.ndim, 4) # arr[key] = 0 # raw[raw[:, :, [1]] < 5] = 0 # assert_array_equal(arr, raw) # c) Array-broadcastable shape (missing axis) arr = array.copy() raw = array.data.copy() key = arr[sex['M']] < 5 assert key.ndim == 3 arr[key] = 0 raw_key = raw[:, :, 0, :] < 5 raw_d1, raw_d2, raw_d4 = raw_key.nonzero() raw[raw_d1, raw_d2, :, raw_d4] = 0 assert_array_equal(arr, raw) # ndarray key arr = array.copy() raw = array.data.copy() arr[raw < 5] = 0 raw[raw < 5] = 0 assert_array_equal(arr, raw) # d) Array with extra axes arr = array.copy() key = (arr < 5).expand([Axis(2, 'extra')]) assert key.ndim == 5 # TODO: make this work with pytest.raises(ValueError): arr[key] = 0 def test_set(array): age, geo, sex, lipro = array.axes # 1) using a LGroup key ages1_5_9 = age[[1, 5, 9]] # a) value has exactly the same shape as the target slice arr = array.copy() raw = array.data.copy() arr.set(arr[ages1_5_9] + 25.0, age=ages1_5_9) raw[[1, 5, 9]] = raw[[1, 5, 9]] + 25.0 assert_array_equal(arr, raw) # b) same size but a different shape (extra length-1 axis) arr = array.copy() raw = array.data.copy() raw_value = raw[[1, 5, 9], np.newaxis] + 26.0 fake_axis = Axis(['label'], 'fake') age_axis = arr[ages1_5_9].axes.age value = Array(raw_value, axes=(age_axis, fake_axis, geo, sex, lipro)) arr.set(value, age=ages1_5_9) raw[[1, 5, 9]] = raw[[1, 5, 9]] + 26.0 assert_array_equal(arr, raw) # dimension of length 1 # arr = array.copy() # raw = array.data.copy() # raw[[1, 5, 9]] = np.sum(raw[[1, 5, 9]], axis=1, keepdims=True) # arr.set(arr[ages1_5_9].sum(geo=(geo.all(),)), age=ages1_5_9) # assert_array_equal(arr, raw) # c) missing dimension arr = array.copy() raw = array.data.copy() arr.set(arr[ages1_5_9].sum(geo), age=ages1_5_9) raw[[1, 5, 9]] = np.sum(raw[[1, 5, 9]], axis=1, keepdims=True) assert_array_equal(arr, raw) # 2) using a raw key arr = array.copy() raw = array.data.copy() arr.set(arr[[1, 5, 9]] + 27.0, age=[1, 5, 9]) raw[[1, 5, 9]] = raw[[1, 5, 9]] + 27.0 assert_array_equal(arr, raw) def test_filter(array): age, geo, sex, lipro = array.axes ages1_5_9 = age[(1, 5, 9)] ages11 = age[11] # with LGroup assert array.filter(age=ages1_5_9).shape == (3, 44, 2, 15) # FIXME: this should raise a comprehensible error! # self.assertEqual(array.filter(age=[ages1_5_9]).shape, (3, 44, 2, 15)) # LGroup with 1 value => collapse assert array.filter(age=ages11).shape == (44, 2, 15) # LGroup with a list of 1 value => do not collapse assert array.filter(age=age[[11]]).shape == (1, 44, 2, 15) # LGroup with a list of 1 value defined as a string => do not collapse assert array.filter(lipro=lipro['P01,']).shape == (116, 44, 2, 1) # LGroup with 1 value # XXX: this does not work. Do we want to make this work? # filtered = array.filter(age=(ages11,)) # self.assertEqual(filtered.shape, (1, 44, 2, 15)) # list assert array.filter(age=[1, 5, 9]).shape == (3, 44, 2, 15) # string assert array.filter(lipro='P01,P02').shape == (116, 44, 2, 2) # multiple axes at once assert array.filter(age=[1, 5, 9], lipro='P01,P02').shape == (3, 44, 2, 2) # multiple axes one after the other assert array.filter(age=[1, 5, 9]).filter(lipro='P01,P02').shape == (3, 44, 2, 2) # a single value for one dimension => collapse the dimension assert array.filter(sex='M').shape == (116, 44, 15) # but a list with a single value for one dimension => do not collapse assert array.filter(sex=['M']).shape == (116, 44, 1, 15) assert array.filter(sex='M,').shape == (116, 44, 1, 15) # with duplicate keys # XXX: do we want to support this? I don't see any value in that but I might be short-sighted. # filtered = array.filter(lipro='P01,P02,P01') # XXX: we could abuse python to allow naming groups via Axis.__getitem__ # (but I doubt it is a good idea). # child = age[':17', 'child'] # slices # ------ # LGroup slice assert array.filter(age=age[:17]).shape == (18, 44, 2, 15) # string slice assert array.filter(lipro=':P03').shape == (116, 44, 2, 3) # raw slice assert array.filter(age=slice(17)).shape == (18, 44, 2, 15) # filter chain with a slice assert array.filter(age=slice(17)).filter(geo='A12,A13').shape == (18, 2, 2, 15) def test_filter_multiple_axes(array): # multiple values in each group assert array.filter(age=[1, 5, 9], lipro='P01,P02').shape == (3, 44, 2, 2) # with a group of one value assert array.filter(age=[1, 5, 9], sex='M,').shape == (3, 44, 1, 15) # with a discarded axis (there is a scalar in the key) assert array.filter(age=[1, 5, 9], sex='M').shape == (3, 44, 15) # with a discarded axis that is not adjacent to the ix_array axis ie with a sliced axis between the scalar axis # and the ix_array axis since our array has a axes: age, geo, sex, lipro, any of the following should be tested: # age+sex / age+lipro / geo+lipro # additionally, if the ix_array axis was first (ie ix_array on age), it worked even before the issue was fixed, # since the "indexing" subspace is tacked-on to the beginning (as the first dimension) assert array.filter(age=57, sex='M,F').shape == (44, 2, 15) assert array.filter(age=57, lipro='P01,P05').shape == (44, 2, 2) assert array.filter(geo='A57', lipro='P01,P05').shape == (116, 2, 2) def test_nonzero(): arr = ndtest((2, 3)) a, b = arr.axes cond = arr > 1 assert_array_equal(cond, from_string(r"""a\b b0 b1 b2 a0 False False True a1 True True True""")) a_group, b_group = cond.nonzero() assert isinstance(a_group, IGroup) assert a_group.axis is a assert a_group.key.equals(from_string("""a_b a0_b2 a1_b0 a1_b1 a1_b2 \t 0 1 1 1""")) assert isinstance(b_group, IGroup) assert b_group.axis is b assert b_group.key.equals(from_string("""a_b a0_b2 a1_b0 a1_b1 a1_b2 \t 2 0 1 2""")) expected = from_string("""a_b a0_b2 a1_b0 a1_b1 a1_b2 \t 2 3 4 5""") assert_array_equal(arr[a_group, b_group], expected) assert_array_equal(arr.points[a_group, b_group], expected) assert_array_equal(arr[cond], expected) def test_contains(): arr = ndtest('a=0..2;b=b0..b2;c=2..4') # string label assert 'b1' in arr assert 'b4' not in arr # int label assert 1 in arr assert 5 not in arr # duplicate label assert 2 in arr # slice assert not slice('b0', 'b2') in arr def test_sum_full_axes(array): age, geo, sex, lipro = array.axes # everything assert array.sum() == np.asarray(array).sum() # using axes numbers assert array.sum(axis=2).shape == (116, 44, 15) assert array.sum(axis=(0, 2)).shape == (44, 15) # using Axis objects assert array.sum(age).shape == (44, 2, 15) assert array.sum(age, sex).shape == (44, 15) # using axes names assert array.sum('age', 'sex').shape == (44, 15) # chained sum assert array.sum(age, sex).sum(geo).shape == (15,) assert array.sum(age, sex).sum(lipro, geo) == array.sum() # getitem on aggregated aggregated = array.sum(age, sex) assert aggregated[vla_str].shape == (22, 15) # filter on aggregated assert aggregated.filter(geo=vla_str).shape == (22, 15) def test_sum_full_axes_with_nan(array): array['M', 'P02', 'A12', 0] = nan raw = array.data # everything assert array.sum() == np.nansum(raw) assert isnan(array.sum(skipna=False)) # using Axis objects assert_array_nan_equal(array.sum(X.age), np.nansum(raw, 0)) assert_array_nan_equal(array.sum(X.age, skipna=False), raw.sum(0)) assert_array_nan_equal(array.sum(X.age, X.sex), np.nansum(raw, (0, 2))) assert_array_nan_equal(array.sum(X.age, X.sex, skipna=False), raw.sum((0, 2))) def test_sum_full_axes_keep_axes(array): agg = array.sum(keepaxes=True) assert agg.shape == (1, 1, 1, 1) for axis in agg.axes: assert axis.labels == ['sum'] agg = array.sum(keepaxes='total') assert agg.shape == (1, 1, 1, 1) for axis in agg.axes: assert axis.labels == ['total'] def test_mean_full_axes(array): raw = array.data assert array.mean() == np.mean(raw) assert_array_nan_equal(array.mean(X.age), np.mean(raw, 0)) assert_array_nan_equal(array.mean(X.age, X.sex), np.mean(raw, (0, 2))) def test_mean_groups(array): # using int type to test that we get a float in return arr = array.astype(int) raw = array.data res = arr.mean(X.geo['A11', 'A13', 'A24', 'A31']) assert_array_nan_equal(res, np.mean(raw[:, [0, 2, 4, 5]], 1)) def test_median_full_axes(array): raw = array.data assert array.median() == np.median(raw) assert_array_nan_equal(array.median(X.age), np.median(raw, 0)) assert_array_nan_equal(array.median(X.age, X.sex), np.median(raw, (0, 2))) def test_median_groups(array): raw = array.data res = array.median(X.geo['A11', 'A13', 'A24']) assert res.shape == (116, 2, 15) assert_array_nan_equal(res, np.median(raw[:, [0, 2, 4]], 1)) def test_percentile_full_axes(): arr = ndtest((2, 3, 4)) raw = arr.data assert arr.percentile(10) == np.percentile(raw, 10) assert_array_nan_equal(arr.percentile(10, X.a), np.percentile(raw, 10, 0)) assert_array_nan_equal(arr.percentile(10, X.c, X.a), np.percentile(raw, 10, (2, 0))) def test_percentile_groups(): arr = ndtest((2, 5, 3)) raw = arr.data res = arr.percentile(10, X.b['b0', 'b2', 'b4']) assert_array_nan_equal(res, np.percentile(raw[:, [0, 2, 4]], 10, 1)) def test_cumsum(array): raw = array.data # using Axis objects assert_array_equal(array.cumsum(X.age), raw.cumsum(0)) assert_array_equal(array.cumsum(X.lipro), raw.cumsum(3)) # using axes numbers assert_array_equal(array.cumsum(1), raw.cumsum(1)) # using axes names assert_array_equal(array.cumsum('sex'), raw.cumsum(2)) def test_group_agg_kwargs(array): age, geo, sex, lipro = array.axes vla, wal, bru = vla_str, wal_str, bru_str # a) group aggregate on a fresh array # a.1) one group => collapse dimension assert array.sum(sex='M').shape == (116, 44, 15) assert array.sum(sex='M,F').shape == (116, 44, 15) assert array.sum(sex=sex['M']).shape == (116, 44, 15) assert array.sum(geo='A11,A21,A25').shape == (116, 2, 15) assert array.sum(geo=['A11', 'A21', 'A25']).shape == (116, 2, 15) assert array.sum(geo=geo['A11,A21,A25']).shape == (116, 2, 15) assert array.sum(geo=':').shape == (116, 2, 15) assert array.sum(geo=geo[:]).shape == (116, 2, 15) assert array.sum(geo=geo[':']).shape == (116, 2, 15) # Include everything between two labels. Since A11 is the first label # and A21 is the last one, this should be equivalent to the previous # tests. assert array.sum(geo='A11:A21').shape == (116, 2, 15) assert_array_equal(array.sum(geo='A11:A21'), array.sum(geo=':')) assert_array_equal(array.sum(geo=geo['A11:A21']), array.sum(geo=':')) # a.2) a tuple of one group => do not collapse dimension assert array.sum(geo=(geo[:],)).shape == (116, 1, 2, 15) # a.3) several groups # string groups assert array.sum(geo=(vla, wal, bru)).shape == (116, 3, 2, 15) # with one label in several groups assert array.sum(sex=(['M'], ['M', 'F'])).shape == (116, 44, 2, 15) assert array.sum(sex=('M', 'M,F')).shape == (116, 44, 2, 15) assert array.sum(sex='M;M,F').shape == (116, 44, 2, 15) res = array.sum(geo=(vla, wal, bru, belgium)) assert res.shape == (116, 4, 2, 15) # a.4) several dimensions at the same time res = array.sum(lipro='P01,P03;P02,P05;:', geo=(vla, wal, bru, belgium)) assert res.shape == (116, 4, 2, 3) # b) both axis aggregate and group aggregate at the same time # Note that you must list "full axes" aggregates first (Python does not allow non-kwargs after kwargs. res = array.sum(age, sex, geo=(vla, wal, bru, belgium)) assert res.shape == (4, 15) # c) chain group aggregate after axis aggregate res = array.sum(age, sex).sum(geo=(vla, wal, bru, belgium)) assert res.shape == (4, 15) def test_group_agg_guess_axis(array): raw = array.data.copy() age, geo, sex, lipro = array.axes vla, wal, bru = vla_str, wal_str, bru_str # a) group aggregate on a fresh array # a.1) one group => collapse dimension # not sure I should support groups with a single item in an aggregate assert array.sum('M').shape == (116, 44, 15) assert array.sum('M,').shape == (116, 44, 15) assert array.sum('M,F').shape == (116, 44, 15) assert array.sum('A11,A21,A25').shape == (116, 2, 15) # with a name assert array.sum('A11,A21,A25 >> g1').shape == (116, 2, 15) assert array.sum(['A11', 'A21', 'A25']).shape == (116, 2, 15) # Include everything between two labels. Since A11 is the first label # and A21 is the last one, this should be equivalent to taking the # full axis. assert array.sum('A11:A21').shape == (116, 2, 15) assert_array_equal(array.sum('A11:A21'), array.sum(geo=':')) assert_array_equal(array.sum('A11:A21'), array.sum(geo)) # a.2) a tuple of one group => do not collapse dimension assert array.sum((geo[:],)).shape == (116, 1, 2, 15) # a.3) several groups # string groups assert array.sum((vla, wal, bru)).shape == (116, 3, 2, 15) # XXX: do we also want to support this? I do not really like it because it gets tricky when we have some other # axes into play. For now the error message is unclear because it first aggregates on "vla", then tries to # aggregate on "wal", but there is no "geo" dimension anymore. # self.assertEqual(array.sum(vla, wal, bru).shape, (116, 3, 2, 15)) # with one label in several groups assert array.sum((['M'], ['M', 'F'])).shape == (116, 44, 2, 15) assert array.sum(('M', 'M,F')).shape == (116, 44, 2, 15) assert array.sum('M;M,F').shape == (116, 44, 2, 15) # with group names res = array.sum('M >> men;M,F >> all') assert res.shape == (116, 44, 2, 15) assert 'sex' in res.axes men = sex['M'].named('men') all_ = sex['M,F'].named('all') assert_array_equal(res.axes.sex.labels, ['men', 'all']) assert_array_equal(res['men'], raw[:, :, 0, :]) assert_array_equal(res['all'], raw.sum(2)) res = array.sum(('M >> men', 'M,F >> all')) assert res.shape == (116, 44, 2, 15) assert 'sex' in res.axes assert_array_equal(res.axes.sex.labels, ['men', 'all']) assert_array_equal(res['men'], raw[:, :, 0, :]) assert_array_equal(res['all'], raw.sum(2)) res = array.sum((vla, wal, bru, belgium)) assert res.shape == (116, 4, 2, 15) # a.4) several dimensions at the same time res = array.sum('P01,P03;P02,P05;P01:', (vla, wal, bru, belgium)) assert res.shape == (116, 4, 2, 3) # b) both axis aggregate and group aggregate at the same time res = array.sum(age, sex, (vla, wal, bru, belgium)) assert res.shape == (4, 15) # c) chain group aggregate after axis aggregate res = array.sum(age, sex).sum((vla, wal, bru, belgium)) assert res.shape == (4, 15) def test_group_agg_label_group(array): age, geo, sex, lipro = array.axes vla, wal, bru = geo[vla_str], geo[wal_str], geo[bru_str] lg_belgium = geo[belgium] # a) group aggregate on a fresh array # a.1) one group => collapse dimension # not sure I should support groups with a single item in an aggregate men = sex.i[[0]] assert array.sum(men).shape == (116, 44, 15) assert array.sum(sex['M']).shape == (116, 44, 15) assert array.sum(sex['M,']).shape == (116, 44, 15) assert array.sum(sex['M,F']).shape == (116, 44, 15) assert array.sum(geo['A11,A21,A25']).shape == (116, 2, 15) assert array.sum(geo[['A11', 'A21', 'A25']]).shape == (116, 2, 15) assert array.sum(geo['A11', 'A21', 'A25']).shape == (116, 2, 15) assert array.sum(geo['A11,A21,A25']).shape == (116, 2, 15) assert array.sum(geo[:]).shape == (116, 2, 15) assert array.sum(geo[':']).shape == (116, 2, 15) assert array.sum(geo[:]).shape == (116, 2, 15) # Include everything between two labels. Since A11 is the first label and A21 is the last one, this should be # equivalent to the previous tests. assert array.sum(geo['A11:A21']).shape == (116, 2, 15) assert_array_equal(array.sum(geo['A11:A21']), array.sum(geo)) assert_array_equal(array.sum(geo['A11':'A21']), array.sum(geo)) # a.2) a tuple of one group => do not collapse dimension assert array.sum((geo[:],)).shape == (116, 1, 2, 15) # a.3) several groups # string groups assert array.sum((vla, wal, bru)).shape == (116, 3, 2, 15) # XXX: do we also want to support this? I do not really like it because it gets tricky when we have some other # axes into play. For now the error message is unclear because it first aggregates on "vla", then tries to # aggregate on "wal", but there is no "geo" dimension anymore. # self.assertEqual(array.sum(vla, wal, bru).shape, (116, 3, 2, 15)) # with one label in several groups assert array.sum((sex['M'], sex[['M', 'F']])).shape == (116, 44, 2, 15) assert array.sum((sex['M'], sex['M', 'F'])).shape == (116, 44, 2, 15) assert array.sum((sex['M'], sex['M,F'])).shape == (116, 44, 2, 15) # XXX: do we want to support this? # self.assertEqual(array.sum(sex['M;H,F']).shape, (116, 44, 2, 15)) res = array.sum((vla, wal, bru, lg_belgium)) assert res.shape == (116, 4, 2, 15) # a.4) several dimensions at the same time # self.assertEqual(array.sum(lipro['P01,P03;P02,P05;P01:'], (vla, wal, bru, lg_belgium)).shape, # (116, 4, 2, 3)) res = array.sum((lipro['P01,P03'], lipro['P02,P05'], lipro[:]), (vla, wal, bru, lg_belgium)) assert res.shape == (116, 4, 2, 3) # b) both axis aggregate and group aggregate at the same time res = array.sum(age, sex, (vla, wal, bru, lg_belgium)) assert res.shape == (4, 15) # c) chain group aggregate after axis aggregate res = array.sum(age, sex).sum((vla, wal, bru, lg_belgium)) assert res.shape == (4, 15) def test_group_agg_label_group_no_axis(array): age, geo, sex, lipro = array.axes vla, wal, bru = LGroup(vla_str), LGroup(wal_str), LGroup(bru_str) lg_belgium = LGroup(belgium) # a) group aggregate on a fresh array # a.1) one group => collapse dimension # not sure I should support groups with a single item in an aggregate assert array.sum(LGroup('M')).shape == (116, 44, 15) assert array.sum(LGroup('M,')).shape == (116, 44, 15) assert array.sum(LGroup('M,F')).shape == (116, 44, 15) assert array.sum(LGroup('A11,A21,A25')).shape == (116, 2, 15) assert array.sum(LGroup(['A11', 'A21', 'A25'])).shape == (116, 2, 15) # Include everything between two labels. Since A11 is the first label # and A21 is the last one, this should be equivalent to the full axis. assert array.sum(LGroup('A11:A21')).shape == (116, 2, 15) assert_array_equal(array.sum(LGroup('A11:A21')), array.sum(geo)) assert_array_equal(array.sum(LGroup(slice('A11', 'A21'))), array.sum(geo)) # a.3) several groups # string groups assert array.sum((vla, wal, bru)).shape == (116, 3, 2, 15) # XXX: do we also want to support this? I do not really like it because it gets tricky when we have some other # axes into play. For now the error message is unclear because it first aggregates on "vla", then tries to # aggregate on "wal", but there is no "geo" dimension anymore. # self.assertEqual(array.sum(vla, wal, bru).shape, (116, 3, 2, 15)) # with one label in several groups assert array.sum((LGroup('M'), LGroup(['M', 'F']))).shape == (116, 44, 2, 15) assert array.sum((LGroup('M'), LGroup('M,F'))).shape == (116, 44, 2, 15) # XXX: do we want to support this? # self.assertEqual(array.sum(sex['M;M,F']).shape, (116, 44, 2, 15)) res = array.sum((vla, wal, bru, lg_belgium)) assert res.shape == (116, 4, 2, 15) # a.4) several dimensions at the same time # self.assertEqual(array.sum(lipro['P01,P03;P02,P05;P01:'], (vla, wal, bru, lg_belgium)).shape, # (116, 4, 2, 3)) res = array.sum((LGroup('P01,P03'), LGroup('P02,P05')), (vla, wal, bru, lg_belgium)) assert res.shape == (116, 4, 2, 2) # b) both axis aggregate and group aggregate at the same time res = array.sum(age, sex, (vla, wal, bru, lg_belgium)) assert res.shape == (4, 15) # c) chain group aggregate after axis aggregate res = array.sum(age, sex).sum((vla, wal, bru, lg_belgium)) assert res.shape == (4, 15) def test_group_agg_axis_ref_label_group(array): age, geo, sex, lipro = X.age, X.geo, X.sex, X.lipro vla, wal, bru = geo[vla_str], geo[wal_str], geo[bru_str] lg_belgium = geo[belgium] # a) group aggregate on a fresh array # a.1) one group => collapse dimension # not sure I should support groups with a single item in an aggregate men = sex.i[[0]] assert array.sum(men).shape == (116, 44, 15) assert array.sum(sex['M']).shape == (116, 44, 15) assert array.sum(sex['M,']).shape == (116, 44, 15) assert array.sum(sex['M,F']).shape == (116, 44, 15) assert array.sum(geo['A11,A21,A25']).shape == (116, 2, 15) assert array.sum(geo[['A11', 'A21', 'A25']]).shape == (116, 2, 15) assert array.sum(geo['A11', 'A21', 'A25']).shape == (116, 2, 15) assert array.sum(geo['A11,A21,A25']).shape == (116, 2, 15) assert array.sum(geo[:]).shape == (116, 2, 15) assert array.sum(geo[':']).shape == (116, 2, 15) assert array.sum(geo[:]).shape == (116, 2, 15) # Include everything between two labels. Since A11 is the first label # and A21 is the last one, this should be equivalent to the previous # tests. assert array.sum(geo['A11:A21']).shape == (116, 2, 15) assert_array_equal(array.sum(geo['A11:A21']), array.sum(geo)) assert_array_equal(array.sum(geo['A11':'A21']), array.sum(geo)) # a.2) a tuple of one group => do not collapse dimension assert array.sum((geo[:],)).shape == (116, 1, 2, 15) # a.3) several groups # string groups assert array.sum((vla, wal, bru)).shape == (116, 3, 2, 15) # XXX: do we also want to support this? I do not really like it because # it gets tricky when we have some other axes into play. For now the # error message is unclear because it first aggregates on "vla", then # tries to aggregate on "wal", but there is no "geo" dimension anymore. # self.assertEqual(array.sum(vla, wal, bru).shape, (116, 3, 2, 15)) # with one label in several groups assert array.sum((sex['M'], sex[['M', 'F']])).shape == (116, 44, 2, 15) assert array.sum((sex['M'], sex['M', 'F'])).shape == (116, 44, 2, 15) assert array.sum((sex['M'], sex['M,F'])).shape == (116, 44, 2, 15) # XXX: do we want to support this? # self.assertEqual(array.sum(sex['M;M,F']).shape, (116, 44, 2, 15)) res = array.sum((vla, wal, bru, lg_belgium)) assert res.shape == (116, 4, 2, 15) # a.4) several dimensions at the same time # self.assertEqual(array.sum(lipro['P01,P03;P02,P05;P01:'], # (vla, wal, bru, belgium)).shape, # (116, 4, 2, 3)) res = array.sum((lipro['P01,P03'], lipro['P02,P05'], lipro[:]), (vla, wal, bru, lg_belgium)) assert res.shape == (116, 4, 2, 3) # b) both axis aggregate and group aggregate at the same time res = array.sum(age, sex, (vla, wal, bru, lg_belgium)) assert res.shape == (4, 15) # c) chain group aggregate after axis aggregate res = array.sum(age, sex).sum((vla, wal, bru, lg_belgium)) assert res.shape == (4, 15) def test_group_agg_one_axis(): a = Axis(range(3), 'a') la = ndtest(a) raw = np.asarray(la) assert_array_equal(la.sum(a[0, 2]), raw[[0, 2]].sum()) def test_group_agg_anonymous_axis(): la = ndtest([Axis(2), Axis(3)]) a1, a2 = la.axes raw = np.asarray(la) assert_array_equal(la.sum(a2[0, 2]), raw[:, [0, 2]].sum(1)) def test_group_agg_zero_padded_label(): arr = ndtest("a=01,02,03,10,11; b=b0..b2") expected = Array([36, 30, 39], "a=01_03,10,11") assert_array_equal(arr.sum("01,02,03 >> 01_03; 10; 11", "b"), expected) def test_group_agg_on_int_array(): # issue 193 arr = ndtest('year=2014..2018') group = arr.year[:2016] assert arr.mean(group) == 1.0 assert arr.median(group) == 1.0 assert arr.percentile(90, group) == 1.8 assert arr.std(group) == 1.0 assert arr.var(group) == 1.0 def test_group_agg_on_bool_array(): # issue 194 a = ndtest((2, 3)) b = a > 1 expected = from_string("""a,a0,a1 , 1, 2""", sep=',') assert_array_equal(b.sum('b1:'), expected) # TODO: fix this (and add other tests for references (X.) to anonymous axes # def test_group_agg_anonymous_axis_ref(): # la = ndtest([Axis(2), Axis(3)]) # raw = np.asarray(la) # # this does not work because x[1] refers to an axis with name 1, # # which does not exist. We might want to change this. # assert_array_equal(la.sum(x[1][0, 2]), raw[:, [0, 2]].sum(1)) # group aggregates on a group-aggregated array def test_group_agg_on_group_agg(array): age, geo, sex, lipro = array.axes vla, wal, bru = vla_str, wal_str, bru_str reg = array.sum(age, sex).sum(geo=(vla, wal, bru, belgium)) # 1) one group => collapse dimension assert reg.sum(lipro='P01,P02').shape == (4,) # 2) a tuple of one group => do not collapse dimension assert reg.sum(lipro=('P01,P02',)).shape == (4, 1) # 3) several groups assert reg.sum(lipro='P01;P02;:').shape == (4, 3) # this is INVALID # TODO: raise a nice exception # regsum = reg.sum(lipro='P01,P02,:') # this is currently allowed even though it can be confusing: # P01 and P02 are both groups with one element each. assert reg.sum(lipro=('P01', 'P02', ':')).shape == (4, 3) assert reg.sum(lipro=('P01', 'P02', lipro[:])).shape == (4, 3) # explicit groups are better assert reg.sum(lipro=('P01,', 'P02,', ':')).shape == (4, 3) assert reg.sum(lipro=(['P01'], ['P02'], ':')).shape == (4, 3) # 4) groups on the aggregated dimension # self.assertEqual(reg.sum(geo=([vla, bru], [wal, bru])).shape, (2, 3)) # vla, wal, bru # group aggregates on a group-aggregated array def test_group_agg_on_group_agg_nokw(array): age, geo, sex, lipro = array.axes vla, wal, bru = vla_str, wal_str, bru_str reg = array.sum(age, sex).sum((vla, wal, bru, belgium)) # XXX: should this be supported too? (it currently fails) # reg = array.sum(age, sex).sum(vla, wal, bru, belgium) # 1) one group => collapse dimension assert reg.sum('P01,P02').shape == (4,) # 2) a tuple of one group => do not collapse dimension assert reg.sum(('P01,P02',)).shape == (4, 1) # 3) several groups # : is ambiguous # self.assertEqual(reg.sum('P01;P02;:').shape, (4, 3)) assert reg.sum('P01;P02;P01:').shape == (4, 3) # this is INVALID # TODO: raise a nice exception # regsum = reg.sum(lipro='P01,P02,:') # this is currently allowed even though it can be confusing: # P01 and P02 are both groups with one element each. assert reg.sum(('P01', 'P02', 'P01:')).shape == (4, 3) assert reg.sum(('P01', 'P02', lipro[:])).shape == (4, 3) # explicit groups are better assert reg.sum(('P01,', 'P02,', 'P01:')).shape == (4, 3) assert reg.sum((['P01'], ['P02'], 'P01:')).shape == (4, 3) # 4) groups on the aggregated dimension # self.assertEqual(reg.sum(geo=([vla, bru], [wal, bru])).shape, (2, 3)) # vla, wal, bru def test_getitem_on_group_agg(array): age, geo, sex, lipro = array.axes vla, wal, bru = vla_str, wal_str, bru_str # using a string vla = vla_str reg = array.sum(age, sex).sum(geo=(vla, wal, bru, belgium)) # the following are all equivalent assert reg[vla].shape == (15,) assert reg[(vla,)].shape == (15,) assert reg[(vla, slice(None))].shape == (15,) assert reg[vla, slice(None)].shape == (15,) assert reg[vla, :].shape == (15,) # one more level... assert reg[vla]['P03'] == 389049848.0 # using an anonymous LGroup vla = geo[vla_str] reg = array.sum(age, sex).sum(geo=(vla, wal, bru, belgium)) # the following are all equivalent assert reg[vla].shape == (15,) assert reg[(vla,)].shape == (15,) assert reg[(vla, slice(None))].shape == (15,) assert reg[vla, slice(None)].shape == (15,) assert reg[vla, :].shape == (15,) # using a named LGroup vla = geo[vla_str] >> 'Vlaanderen' reg = array.sum(age, sex).sum(geo=(vla, wal, bru, belgium)) # the following are all equivalent assert reg[vla].shape == (15,) assert reg[(vla,)].shape == (15,) assert reg[(vla, slice(None))].shape == (15,) assert reg[vla, slice(None)].shape == (15,) assert reg[vla, :].shape == (15,) def test_getitem_on_group_agg_nokw(array): age, geo, sex, lipro = array.axes vla, wal, bru = vla_str, wal_str, bru_str # using a string vla = vla_str reg = array.sum(age, sex).sum((vla, wal, bru, belgium)) # the following are all equivalent assert reg[vla].shape == (15,) assert reg[(vla,)].shape == (15,) assert reg[(vla, slice(None))].shape == (15,) assert reg[vla, slice(None)].shape == (15,) assert reg[vla, :].shape == (15,) # one more level... assert reg[vla]['P03'] == 389049848.0 # using an anonymous LGroup vla = geo[vla_str] reg = array.sum(age, sex).sum((vla, wal, bru, belgium)) # the following are all equivalent assert reg[vla].shape == (15,) assert reg[(vla,)].shape == (15,) assert reg[(vla, slice(None))].shape == (15,) assert reg[vla, slice(None)].shape == (15,) assert reg[vla, :].shape == (15,) # using a named LGroup vla = geo[vla_str] >> 'Vlaanderen' reg = array.sum(age, sex).sum((vla, wal, bru, belgium)) # the following are all equivalent assert reg[vla].shape == (15,) assert reg[(vla,)].shape == (15,) assert reg[(vla, slice(None))].shape == (15,) assert reg[vla, slice(None)].shape == (15,) assert reg[vla, :].shape == (15,) def test_filter_on_group_agg(array): age, geo, sex, lipro = array.axes vla, wal, bru = vla_str, wal_str, bru_str # using a string # vla = vla_str # reg = array.sum(age, sex).sum(geo=(vla, wal, bru, belgium)) # assert reg.filter(geo=vla).shape == (15,) # using a named LGroup vla = geo[vla_str] >> 'Vlaanderen' reg = array.sum(age, sex).sum(geo=(vla, wal, bru, belgium)) assert reg.filter(geo=vla).shape == (15,) # Note that reg.filter(geo=(vla,)) does NOT work. It might be a # little confusing for users, because reg[(vla,)] works but it is # normal because reg.filter(geo=(vla,)) is equivalent to: # reg[((vla,),)] or reg[(vla,), :] # mixed LGroup/string slices child = age[:17] child_named = age[:17] >> 'child' working = age[18:64] retired = age[65:] byage = array.sum(age=(child, 5, working, retired)) assert byage.shape == (4, 44, 2, 15) byage = array.sum(age=(child, slice(5, 10), working, retired)) assert byage.shape == (4, 44, 2, 15) # filter on an aggregated larray created with mixed groups # assert byage.filter(age=':17').shape == (44, 2, 15) byage = array.sum(age=(child_named, 5, working, retired)) assert byage.filter(age=child_named).shape == (44, 2, 15) def test_sum_several_lg_groups(array): # 1) aggregated array created using LGroups # ----------------------------------------- fla = geo[vla_str] >> 'Flanders' wal = geo[wal_str] >> 'Wallonia' bru = geo[bru_str] >> 'Brussels' reg = array.sum(geo=(fla, wal, bru)) assert reg.shape == (116, 3, 2, 15) # the result is indexable # 1.a) by LGroup assert reg.filter(geo=fla).shape == (116, 2, 15) assert reg.filter(geo=(fla, wal)).shape == (116, 2, 2, 15) # 1.b) by string (name of groups) assert reg.filter(geo='Flanders').shape == (116, 2, 15) assert reg.filter(geo='Flanders,Wallonia').shape == (116, 2, 2, 15) # 2) aggregated array created using string groups # ----------------------------------------------- reg = array.sum(geo=(vla_str, wal_str, bru_str)) assert reg.shape == (116, 3, 2, 15) # the result is indexable # 2.a) by string (def) # assert reg.filter(geo=vla_str).shape == (116, 2, 15) assert reg.filter(geo=(vla_str, wal_str)).shape == (116, 2, 2, 15) # 2.b) by LGroup # assert reg.filter(geo=fla).shape == (116, 2, 15) # assert reg.filter(geo=(fla, wal)).shape == (116, 2, 2, 15) def test_sum_with_groups_from_other_axis(small_array): # use a group from another *compatible* axis lipro2 = Axis('lipro=P01..P15') assert small_array.sum(lipro=lipro2['P01,P03']).shape == (2,) # use (compatible) group from another *incompatible* axis # XXX: I am unsure whether or not this should be allowed. Maybe we # should simply check that the group is valid in axis, but that # will trigger a pretty meaningful error anyway lipro3 = Axis('lipro=P01,P03,P05') assert small_array.sum(lipro3['P01,P03']).shape == (2,) # use a group (from another axis) which is incompatible with the axis of # the same name in the array lipro4 = Axis('lipro=P01,P03,P16') with pytest.raises(ValueError, match=r"lipro\['P01', 'P16'\] is not a valid label for any axis"): small_array.sum(lipro4['P01,P16']) def test_agg_kwargs(array): raw = array.data # dtype assert array.sum(dtype=int) == raw.sum(dtype=int) # ddof assert array.std(ddof=0) == raw.std(ddof=0) # out res = array.std(X.sex) out = zeros_like(res) array.std(X.sex, out=out) assert_array_equal(res, out) def test_agg_by(array): age, geo, sex, lipro = array.axes vla, wal, bru = vla_str, wal_str, bru_str # no group or axis assert array.sum_by().shape == () assert array.sum_by() == array.sum() # a) group aggregate on a fresh array # a.1) one group res = array.sum_by(geo='A11,A21,A25') assert res.shape == () assert res == array.sum(geo='A11,A21,A25').sum() # a.2) a tuple of one group res = array.sum_by(geo=(geo[:],)) assert res.shape == (1,) assert_array_equal(res, array.sum(age, sex, lipro, geo=(geo[:],))) # a.3) several groups # string groups res = array.sum_by(geo=(vla, wal, bru)) assert res.shape == (3,) assert_array_equal(res, array.sum(age, sex, lipro, geo=(vla, wal, bru))) # with one label in several groups assert array.sum_by(sex=(['M'], ['M', 'F'])).shape == (2,) assert array.sum_by(sex=('M', 'M,F')).shape == (2,) res = array.sum_by(sex='M;M,F') assert res.shape == (2,) assert_array_equal(res, array.sum(age, geo, lipro, sex='M;M,F')) # a.4) several dimensions at the same time res = array.sum_by(geo=(vla, wal, bru, belgium), lipro='P01,P03;P02,P05;:') assert res.shape == (4, 3) assert_array_equal(res, array.sum(age, sex, geo=(vla, wal, bru, belgium), lipro='P01,P03;P02,P05;:')) # b) both axis aggregate and group aggregate at the same time # Note that you must list "full axes" aggregates first (Python does not allow non-kwargs after kwargs. res = array.sum_by(sex, geo=(vla, wal, bru, belgium)) assert res.shape == (4, 2) assert_array_equal(res, array.sum(age, lipro, geo=(vla, wal, bru, belgium))) # c) chain group aggregate after axis aggregate res = array.sum_by(geo, sex) assert res.shape == (44, 2) assert_array_equal(res, array.sum(age, lipro)) res2 = res.sum_by(geo=(vla, wal, bru, belgium)) assert res2.shape == (4,) assert_array_equal(res2, res.sum(sex, geo=(vla, wal, bru, belgium))) def test_agg_igroup(): arr = ndtest(3) res = arr.sum((X.a.i[:2], X.a.i[1:])) assert_array_equal(res.a.labels, [':a1', 'a1:']) def test_ratio(array): age, geo, sex, lipro = array.axes regions = (vla_str, wal_str, bru_str, belgium) reg = array.sum(age, sex, regions) assert reg.shape == (4, 15) fla = geo[vla_str] >> 'Flanders' wal = geo[wal_str] >> 'Wallonia' bru = geo[bru_str] >> 'Brussels' regions = (fla, wal, bru) reg = array.sum(age, sex, regions) ratio = reg.ratio() assert_array_equal(ratio, reg / reg.sum(geo, lipro)) assert ratio.shape == (3, 15) ratio = reg.ratio(geo) assert_array_equal(ratio, reg / reg.sum(geo)) assert ratio.shape == (3, 15) ratio = reg.ratio(geo, lipro) assert_array_equal(ratio, reg / reg.sum(geo, lipro)) assert ratio.shape == (3, 15) assert ratio.sum() == 1.0 def test_percent(array): age, geo, sex, lipro = array.axes regions = (vla_str, wal_str, bru_str, belgium) reg = array.sum(age, sex, regions) assert reg.shape == (4, 15) fla = geo[vla_str] >> 'Flanders' wal = geo[wal_str] >> 'Wallonia' bru = geo[bru_str] >> 'Brussels' regions = (fla, wal, bru) reg = array.sum(age, sex, regions) percent = reg.percent() assert_array_equal(percent, (reg * 100.0 / reg.sum(geo, lipro))) assert percent.shape == (3, 15) percent = reg.percent(geo) assert_array_equal(percent, (reg * 100.0 / reg.sum(geo))) assert percent.shape == (3, 15) percent = reg.percent(geo, lipro) assert_array_equal(percent, (reg * 100.0 / reg.sum(geo, lipro))) assert percent.shape == (3, 15) assert round(abs(percent.sum() - 100.0), 7) == 0 def test_total(array): age, geo, sex, lipro = array.axes # array = small_array # sex, lipro = array.axes assert array.with_total().shape == (117, 45, 3, 16) assert array.with_total(sex).shape == (116, 44, 3, 15) assert array.with_total(lipro).shape == (116, 44, 2, 16) assert array.with_total(sex, lipro).shape == (116, 44, 3, 16) fla = geo[vla_str] >> 'Flanders' wal = geo[wal_str] >> 'Wallonia' bru = geo[bru_str] >> 'Brussels' bel = geo[:] >> 'Belgium' assert array.with_total(geo=(fla, wal, bru), op=mean).shape == (116, 47, 2, 15) assert array.with_total((fla, wal, bru), op=mean).shape == (116, 47, 2, 15) # works but "wrong" for X.geo (double what is expected because it includes fla wal & bru) # TODO: we probably want to display a warning (or even an error?) in that case. # If we really want that behavior, we can still split the operation: # .with_total((fla, wal, bru)).with_total(X.geo) # OR we might want to only sum the axis as it was before the op (but that does not play well when working with # multiple axes). a1 = array.with_total(X.sex, (fla, wal, bru), X.geo, X.lipro) assert a1.shape == (116, 48, 3, 16) # correct total but the order is not very nice a2 = array.with_total(X.sex, X.geo, (fla, wal, bru), X.lipro) assert a2.shape == (116, 48, 3, 16) # the correct way to do it a3 = array.with_total(X.sex, (fla, wal, bru, bel), X.lipro) assert a3.shape == (116, 48, 3, 16) # a4 = array.with_total((lipro[':P05'], lipro['P05:']), op=mean) a4 = array.with_total((':P05', 'P05:'), op=mean) assert a4.shape == (116, 44, 2, 17) def test_transpose(): arr = ndtest((2, 3, 4)) a, b, c = arr.axes res = arr.transpose() assert res.axes == [c, b, a] res = arr.transpose('b', 'c', 'a') assert res.axes == [b, c, a] res = arr.transpose('b') assert res.axes == [b, a, c] # using Ellipsis instead of ... to avoid a syntax error on Python 2 (where ... is only available within []) res = arr.transpose(Ellipsis, 'a') assert res.axes == [b, c, a] res = arr.transpose('c', Ellipsis, 'a') assert res.axes == [c, b, a] def test_transpose_anonymous(): a = ndtest([Axis(2), Axis(3), Axis(4)]) # reordered = a.transpose(0, 2, 1) # self.assertEqual(reordered.shape, (2, 4, 3)) # axes = [1, 2] # => union(axes, ) # => axes.extend([[0]]) # => breaks because [0] not compatible with axes[0] # => breaks because [0] not compatible with [1] # a real union should not care and should return # [1, 2, 0] but will this break other stuff? My gut feeling is yes # when doing a binop between anonymous axes, we use union too (that might be the problem) and we need *that* # union to match axes by position reordered = a.transpose(1, 2) assert reordered.shape == (3, 4, 2) reordered = a.transpose(2, 0) assert reordered.shape == (4, 2, 3) reordered = a.transpose() assert reordered.shape == (4, 3, 2) def test_binary_ops(small_array): raw = small_array.data assert_array_equal(small_array + small_array, raw + raw) assert_array_equal(small_array + 1, raw + 1) assert_array_equal(1 + small_array, 1 + raw) assert_array_equal(small_array - small_array, raw - raw) assert_array_equal(small_array - 1, raw - 1) assert_array_equal(1 - small_array, 1 - raw) assert_array_equal(small_array * small_array, raw * raw) assert_array_equal(small_array * 2, raw * 2) assert_array_equal(2 * small_array, 2 * raw) with np.errstate(invalid='ignore'): raw_res = raw / raw with pytest.warns(RuntimeWarning) as caught_warnings: res = small_array / small_array assert_array_nan_equal(res, raw_res) assert len(caught_warnings) == 1 warn_msg = "invalid value (NaN) encountered during operation (this is typically caused by a 0 / 0)" assert caught_warnings[0].message.args[0] == warn_msg assert caught_warnings[0].filename == __file__ assert_array_equal(small_array / 2, raw / 2) with np.errstate(divide='ignore'): raw_res = 30 / raw with pytest.warns(RuntimeWarning) as caught_warnings: res = 30 / small_array assert_array_equal(res, raw_res) assert len(caught_warnings) == 1 assert caught_warnings[0].message.args[0] == "divide by zero encountered during operation" assert caught_warnings[0].filename == __file__ assert_array_equal(30 / (small_array + 1), 30 / (raw + 1)) raw_int = raw.astype(int) la_int = Array(raw_int, axes=(sex, lipro)) assert_array_equal(la_int / 2, raw_int / 2) assert_array_equal(la_int // 2, raw_int // 2) # test adding two larrays with different axes order assert_array_equal(small_array + small_array.transpose(), raw * 2) # mixed operations raw2 = raw / 2 la_raw2 = small_array - raw2 assert la_raw2.axes == small_array.axes assert_array_equal(la_raw2, raw - raw2) raw2_la = raw2 - small_array assert raw2_la.axes == small_array.axes assert_array_equal(raw2_la, raw2 - raw) la_ge_raw2 = small_array >= raw2 assert la_ge_raw2.axes == small_array.axes assert_array_equal(la_ge_raw2, raw >= raw2) raw2_ge_la = raw2 >= small_array assert raw2_ge_la.axes == small_array.axes assert_array_equal(raw2_ge_la, raw2 >= raw) def test_binary_ops_no_name_axes(small_array): raw = small_array.data raw2 = small_array.data + 1 la = ndtest([Axis(l) for l in small_array.shape]) la2 = ndtest([Axis(l) for l in small_array.shape]) + 1 assert_array_equal(la + la2, raw + raw2) assert_array_equal(la + 1, raw + 1) assert_array_equal(1 + la, 1 + raw) assert_array_equal(la - la2, raw - raw2) assert_array_equal(la - 1, raw - 1) assert_array_equal(1 - la, 1 - raw) assert_array_equal(la * la2, raw * raw2) assert_array_equal(la * 2, raw * 2) assert_array_equal(2 * la, 2 * raw) assert_array_nan_equal(la / la2, raw / raw2) assert_array_equal(la / 2, raw / 2) with np.errstate(divide='ignore'): raw_res = 30 / raw with pytest.warns(RuntimeWarning) as caught_warnings: res = 30 / la assert_array_equal(res, raw_res) assert len(caught_warnings) == 1 assert caught_warnings[0].message.args[0] == "divide by zero encountered during operation" assert caught_warnings[0].filename == __file__ assert_array_equal(30 / (la + 1), 30 / (raw + 1)) raw_int = raw.astype(int) la_int = Array(raw_int) assert_array_equal(la_int / 2, raw_int / 2) assert_array_equal(la_int // 2, raw_int // 2) # adding two larrays with different axes order cannot work with unnamed axes # assert_array_equal(la + la.transpose(), raw * 2) # mixed operations raw2 = raw / 2 la_raw2 = la - raw2 assert la_raw2.axes == la.axes assert_array_equal(la_raw2, raw - raw2) raw2_la = raw2 - la assert raw2_la.axes == la.axes assert_array_equal(raw2_la, raw2 - raw) la_ge_raw2 = la >= raw2 assert la_ge_raw2.axes == la.axes assert_array_equal(la_ge_raw2, raw >= raw2) raw2_ge_la = raw2 >= la assert raw2_ge_la.axes == la.axes assert_array_equal(raw2_ge_la, raw2 >= raw) def test_broadcasting_no_name(): a = ndtest([Axis(2), Axis(3)]) b = ndtest(Axis(3)) c = ndtest(Axis(2)) with pytest.raises(ValueError): # ValueError: incompatible axes: # Axis(None, [0, 1, 2]) # vs # Axis(None, [0, 1]) a * b d = a * c assert d.shape == (2, 3) # {0}*\{1}* 0 1 2 # 0 0 0 0 # 1 3 4 5 assert np.array_equal(d, [[0, 0, 0], [3, 4, 5]]) # it is unfortunate that the behavior is different from numpy (even though I find our behavior more intuitive) d = np.asarray(a) * np.asarray(b) assert d.shape == (2, 3) assert np.array_equal(d, [[0, 1, 4], [0, 4, 10]]) with pytest.raises(ValueError): # ValueError: operands could not be broadcast together with shapes (2,3) (2,) np.asarray(a) * np.asarray(c) def test_binary_ops_with_scalar_group(): time = Axis('time=2015..2019') arr = ndtest(3) expected = arr + 2015 assert_larray_equal(time.i[0] + arr, expected) assert_larray_equal(arr + time.i[0], expected) def test_unary_ops(small_array): raw = small_array.data # using numpy functions assert_array_equal(np.abs(small_array - 10), np.abs(raw - 10)) assert_array_equal(np.negative(small_array), np.negative(raw)) assert_array_equal(np.invert(small_array), np.invert(raw)) # using python builtin ops assert_array_equal(abs(small_array - 10), abs(raw - 10)) assert_array_equal(-small_array, -raw) assert_array_equal(+small_array, +raw) assert_array_equal(~small_array, ~raw) def test_mean(small_array): raw = small_array.data sex, lipro = small_array.axes assert_array_equal(small_array.mean(lipro), raw.mean(1)) def test_sequence(): res = sequence('b=b0..b2', ndtest(3) * 3, 1.0) assert_array_equal(ndtest((3, 3), dtype=float), res) def test_sort_values(): # 1D arrays arr = Array([0, 1, 6, 3, -1], "a=a0..a4") res = arr.sort_values() expected = Array([-1, 0, 1, 3, 6], "a=a4,a0,a1,a3,a2") assert_array_equal(res, expected) # ascending arg res = arr.sort_values(ascending=False) expected = Array([6, 3, 1, 0, -1], "a=a2,a3,a1,a0,a4") assert_array_equal(res, expected) # 3D arrays arr = Array([[[10, 2, 4], [3, 7, 1]], [[5, 1, 6], [2, 8, 9]]], 'a=a0,a1; b=b0,b1; c=c0..c2') res = arr.sort_values(axis='c') expected = Array([[[2, 4, 10], [1, 3, 7]], [[1, 5, 6], [2, 8, 9]]], [Axis('a=a0,a1'), Axis('b=b0,b1'), Axis(3, 'c')]) assert_array_equal(res, expected) def test_set_labels(small_array): small_array.set_labels(X.sex, ['Man', 'Woman'], inplace=True) expected = small_array.set_labels(X.sex, ['Man', 'Woman']) assert_array_equal(small_array, expected) def test_set_axes(small_array): lipro2 = Axis([l.replace('P', 'Q') for l in lipro.labels], 'lipro2') sex2 = Axis(['Man', 'Woman'], 'sex2') la = Array(small_array.data, axes=(sex, lipro2)) # replace one axis la2 = small_array.set_axes(X.lipro, lipro2) assert_array_equal(la, la2) la = Array(small_array.data, axes=(sex2, lipro2)) # all at once la2 = small_array.set_axes([sex2, lipro2]) assert_array_equal(la, la2) # using keywrods args la2 = small_array.set_axes(sex=sex2, lipro=lipro2) assert_array_equal(la, la2) # using dict la2 = small_array.set_axes({X.sex: sex2, X.lipro: lipro2}) assert_array_equal(la, la2) # using list of pairs (axis_to_replace, new_axis) la2 = small_array.set_axes([(X.sex, sex2), (X.lipro, lipro2)]) assert_array_equal(la, la2) def test_reindex(): arr = ndtest((2, 2)) res = arr.reindex(X.b, ['b1', 'b2', 'b0'], fill_value=-1) assert_array_equal(res, from_string("""a\\b b1 b2 b0 a0 1 -1 0 a1 3 -1 2""")) arr2 = ndtest((2, 2)) arr2.reindex(X.b, ['b1', 'b2', 'b0'], fill_value=-1, inplace=True) assert_array_equal(arr2, from_string("""a\\b b1 b2 b0 a0 1 -1 0 a1 3 -1 2""")) # Array fill value filler = ndtest(arr.a) res = arr.reindex(X.b, ['b1', 'b2', 'b0'], fill_value=filler) assert_array_equal(res, from_string("""a\\b b1 b2 b0 a0 1 0 0 a1 3 1 2""")) # using labels from another array arr = ndtest('a=v0..v2;b=v0,v2,v1,v3') res = arr.reindex('a', arr.b.labels, fill_value=-1) assert_array_equal(res, from_string("""a\\b v0 v2 v1 v3 v0 0 1 2 3 v2 8 9 10 11 v1 4 5 6 7 v3 -1 -1 -1 -1""")) res = arr.reindex('a', arr.b, fill_value=-1) assert_array_equal(res, from_string("""a\\b v0 v2 v1 v3 v0 0 1 2 3 v2 8 9 10 11 v1 4 5 6 7 v3 -1 -1 -1 -1""")) # passing a list of Axis arr = ndtest((2, 2)) res = arr.reindex([Axis("a=a0,a1"), Axis("c=c0"), Axis("b=b1,b2")], fill_value=-1) assert_array_equal(res, from_string(""" a b\\c c0 a0 b1 1 a0 b2 -1 a1 b1 3 a1 b2 -1""")) def test_expand(): country = Axis("country=BE,FR,DE") arr = ndtest(country) out1 = empty((sex, country)) arr.expand(out=out1) out2 = empty((sex, country)) out2[:] = arr assert_array_equal(out1, out2) def test_append(small_array): sex, lipro = small_array.axes small_array = small_array.append(lipro, small_array.sum(lipro), label='sum') assert small_array.shape == (2, 16) small_array = small_array.append(sex, small_array.sum(sex), label='sum') assert small_array.shape == (3, 16) # crap the sex axis is different !!!! we don't have this problem with # the kwargs syntax below # small_array = small_array.append(small_array.mean(sex), axis=sex, label='mean') # self.assertEqual(small_array.shape, (4, 16)) # another syntax (which implies we could not have an axis named "label") # small_array = small_array.append(lipro=small_array.sum(lipro), label='sum') # self.assertEqual(small_array.shape, (117, 44, 2, 15)) def test_insert(): # simple tests are in the docstring arr1 = ndtest((2, 3)) # insert at multiple places at once # we cannot use from_string in these tests because it deduplicates ambiguous (column) labels automatically res = arr1.insert([42, 43], before='b1', label='new') assert_array_equal(res, from_lists([ ['a\\b', 'b0', 'new', 'new', 'b1', 'b2'], ['a0', 0, 42, 43, 1, 2], ['a1', 3, 42, 43, 4, 5]])) res = arr1.insert(42, before=['b1', 'b2'], label='new') assert_array_equal(res, from_lists([ ['a\\b', 'b0', 'new', 'b1', 'new', 'b2'], ['a0', 0, 42, 1, 42, 2], ['a1', 3, 42, 4, 42, 5]])) res = arr1.insert(42, before='b1', label=['b0.1', 'b0.2']) assert_array_equal(res, from_string(r""" a\b b0 b0.1 b0.2 b1 b2 a0 0 42 42 1 2 a1 3 42 42 4 5""")) res = arr1.insert(42, before=['b1', 'b2'], label=['b0.5', 'b1.5']) assert_array_equal(res, from_string(r""" a\b b0 b0.5 b1 b1.5 b2 a0 0 42 1 42 2 a1 3 42 4 42 5""")) res = arr1.insert([42, 43], before='b1', label=['b0.1', 'b0.2']) assert_array_equal(res, from_string(r""" a\b b0 b0.1 b0.2 b1 b2 a0 0 42 43 1 2 a1 3 42 43 4 5""")) res = arr1.insert([42, 43], before=['b1', 'b2'], label='new') assert_array_equal(res, from_lists([ ['a\\b', 'b0', 'new', 'b1', 'new', 'b2'], [ 'a0', 0, 42, 1, 43, 2], [ 'a1', 3, 42, 4, 43, 5]])) res = arr1.insert([42, 43], before=['b1', 'b2'], label=['b0.5', 'b1.5']) assert_array_equal(res, from_string(r""" a\b b0 b0.5 b1 b1.5 b2 a0 0 42 1 43 2 a1 3 42 4 43 5""")) res = arr1.insert([42, 43], before='b1,b2', label=['b0.5', 'b1.5']) assert_array_equal(res, from_string(r""" a\b b0 b0.5 b1 b1.5 b2 a0 0 42 1 43 2 a1 3 42 4 43 5""")) arr2 = ndtest(2) res = arr1.insert([arr2 + 42, arr2 + 43], before=['b1', 'b2'], label=['b0.5', 'b1.5']) assert_array_equal(res, from_string(r""" a\b b0 b0.5 b1 b1.5 b2 a0 0 42 1 43 2 a1 3 43 4 44 5""")) arr3 = ndtest('a=a0,a1;b=b0.1,b0.2') + 42 res = arr1.insert(arr3, before='b1,b2') assert_array_equal(res, from_string(r""" a\b b0 b0.1 b1 b0.2 b2 a0 0 42 1 43 2 a1 3 44 4 45 5""")) # with ambiguous labels arr4 = ndtest('a=v0,v1;b=v0,v1') expected = from_string(r""" a\b v0 v0.5 v1 v0 0 42 1 v1 2 42 3""") res = arr4.insert(42, before='b[v1]', label='v0.5') assert_array_equal(res, expected) res = arr4.insert(42, before=X.b['v1'], label='v0.5') assert_array_equal(res, expected) res = arr4.insert(42, before=arr4.b['v1'], label='v0.5') assert_array_equal(res, expected) def test_drop(): arr1 = ndtest(3) expected = Array([0, 2], 'a=a0,a2') # indices res = arr1.drop('a.i[1]') assert_array_equal(res, expected) res = arr1.drop(X.a.i[1]) assert_array_equal(res, expected) # labels res = arr1.drop(X.a['a1']) assert_array_equal(res, expected) res = arr1.drop('a[a1]') assert_array_equal(res, expected) # 2D array arr2 = ndtest((2, 4)) expected = from_string(r""" a\b b0 b2 a0 0 2 a1 4 6""") res = arr2.drop(['b1', 'b3']) assert_array_equal(res, expected) res = arr2.drop(X.b['b1', 'b3']) assert_array_equal(res, expected) res = arr2.drop('b.i[1, 3]') assert_array_equal(res, expected) res = arr2.drop(X.b.i[1, 3]) assert_array_equal(res, expected) a = Axis('a=label0..label2') b = Axis('b=label0..label2') arr3 = ndtest((a, b)) res = arr3.drop('a[label1]') assert_array_equal(res, from_string(r""" a\b label0 label1 label2 label0 0 1 2 label2 6 7 8""")) # XXX: implement the following (#671)? # res = arr3.drop('0[label1]') res = arr3.drop(X[0]['label1']) assert_array_equal(res, from_string(r""" a\b label0 label1 label2 label0 0 1 2 label2 6 7 8""")) res = arr3.drop(a['label1']) assert_array_equal(res, from_string(r""" a\b label0 label1 label2 label0 0 1 2 label2 6 7 8""")) # the aim of this test is to drop the last value of an axis, but instead # of dropping the last axis tick/label, drop the first one. def test_shift_axis(small_array): sex, lipro = small_array.axes # TODO: check how awful the syntax is with an axis that is not last # or first l2 = Array(small_array[:, :'P14'], axes=[sex, Axis(lipro.labels[1:], 'lipro')]) l2 = Array(small_array[:, :'P14'], axes=[sex, lipro.subaxis(slice(1, None))]) # We can also modify the axis in-place (dangerous!) # lipro.labels = np.append(lipro.labels[1:], lipro.labels[0]) l2 = small_array[:, 'P02':] l2.axes.lipro.labels = lipro.labels[1:] def test_unique(): arr = Array([[[0, 2, 0, 0], [1, 1, 1, 0]], [[0, 2, 0, 0], [2, 1, 2, 0]]], 'a=a0,a1;b=b0,b1;c=c0..c3') assert_array_equal(arr.unique('a'), arr) assert_array_equal(arr.unique('b'), arr) assert_array_equal(arr.unique('c'), arr['c0,c1,c3']) expected = from_string("""\ a_b\\c c0 c1 c2 c3 a0_b0 0 2 0 0 a0_b1 1 1 1 0 a1_b1 2 1 2 0""") assert_array_equal(arr.unique(('a', 'b')), expected) def test_extend(small_array): sex, lipro = small_array.axes all_lipro = lipro[:] tail = small_array.sum(lipro=(all_lipro,)) small_array = small_array.extend(lipro, tail) assert small_array.shape == (2, 16) # test with a string axis small_array = small_array.extend('sex', small_array.sum(sex=(sex[:],))) assert small_array.shape == (3, 16) @needs_pytables def test_hdf_roundtrip(tmpdir, meta): a = ndtest((2, 3), meta=meta) fpath = tmp_path(tmpdir, 'test.h5') a.to_hdf(fpath, 'a') res = read_hdf(fpath, 'a') assert a.ndim == 2 assert a.shape == (2, 3) assert a.axes.names == ['a', 'b'] assert_array_equal(res, a) assert res.meta == a.meta # issue 72: int-like strings should not be parsed (should round-trip correctly) fpath = tmp_path(tmpdir, 'issue72.h5') a = from_lists([['axis', '10', '20'], ['', 0, 1]]) a.to_hdf(fpath, 'a') res = read_hdf(fpath, 'a') assert res.ndim == 1 axis = res.axes[0] assert axis.name == 'axis' assert_array_equal(axis.labels, ['10', '20']) # passing group as key to to_hdf a3 = ndtest((4, 3, 4)) fpath = tmp_path(tmpdir, 'test.h5') os.remove(fpath) # single element group for label in a3.a: a3[label].to_hdf(fpath, label) # unnamed group group = a3.c['c0,c2'] a3[group].to_hdf(fpath, group) # unnamed group + slice group = a3.c['c0::2'] a3[group].to_hdf(fpath, group) # named group group = a3.c['c0,c2'] >> 'even' a3[group].to_hdf(fpath, group) # group with name containing special characters (replaced by _) group = a3.c['c0,c2'] >> r':name?with*special/\[characters]' a3[group].to_hdf(fpath, group) # passing group as key to read_hdf for label in a3.a: subset = read_hdf(fpath, label) assert_array_equal(subset, a3[label]) # load Session from larray.core.session import Session s = Session(fpath) assert s.names == sorted(['a0', 'a1', 'a2', 'a3', 'c0,c2', 'c0::2', 'even', ':name?with*special__[characters]']) def test_from_string(): expected = ndtest("sex=M,F") res = from_string('''sex M F \t 0 1''') assert_array_equal(res, expected) res = from_string('''sex M F nan 0 1''') assert_array_equal(res, expected) res = from_string('''sex M F NaN 0 1''') assert_array_equal(res, expected) def test_read_csv(): res = read_csv(inputpath('test1d.csv')) assert_array_equal(res, io_1d) res = read_csv(inputpath('test2d.csv')) assert_array_equal(res, io_2d) res = read_csv(inputpath('test3d.csv')) assert_array_equal(res, io_3d) res = read_csv(inputpath('testint_labels.csv')) assert_array_equal(res, io_int_labels) res = read_csv(inputpath('test2d_classic.csv')) assert_array_equal(res, ndtest("a=a0..a2; b0..b2")) la = read_csv(inputpath('test1d_liam2.csv'), dialect='liam2') assert la.ndim == 1 assert la.shape == (3,) assert la.axes.names == ['time'] assert_array_equal(la, [3722, 3395, 3347]) la = read_csv(inputpath('test5d_liam2.csv'), dialect='liam2') assert la.ndim == 5 assert la.shape == (2, 5, 2, 2, 3) assert la.axes.names == ['arr', 'age', 'sex', 'nat', 'time'] assert_array_equal(la[X.arr[1], 0, 'F', X.nat[1], :], [3722, 3395, 3347]) # missing values res = read_csv(inputpath('testmissing_values.csv')) assert_array_nan_equal(res, io_missing_values) # test StringIO res = read_csv(StringIO('a,1,2\n,0,1\n')) assert_array_equal(res, ndtest('a=1,2')) # sort_columns=True res = read_csv(StringIO('a,a2,a0,a1\n,2,0,1\n'), sort_columns=True) assert_array_equal(res, ndtest(3)) ################# # narrow format # ################# res = read_csv(inputpath('test1d_narrow.csv'), wide=False) assert_array_equal(res, io_1d) res = read_csv(inputpath('test2d_narrow.csv'), wide=False) assert_array_equal(res, io_2d) res = read_csv(inputpath('test3d_narrow.csv'), wide=False) assert_array_equal(res, io_3d) # missing values res = read_csv(inputpath('testmissing_values_narrow.csv'), wide=False) assert_array_nan_equal(res, io_narrow_missing_values) # unsorted values res = read_csv(inputpath('testunsorted_narrow.csv'), wide=False) assert_array_equal(res, io_unsorted) def test_read_eurostat(): la = read_eurostat(inputpath('test5d_eurostat.csv')) assert la.ndim == 5 assert la.shape == (2, 5, 2, 2, 3) assert la.axes.names == ['arr', 'age', 'sex', 'nat', 'time'] # FIXME: integer labels should be parsed as such assert_array_equal(la[X.arr['1'], '0', 'F', X.nat['1'], :], [3722, 3395, 3347]) @needs_xlwings def test_read_excel_xlwings(): arr = read_excel(inputpath('test.xlsx'), '1d') assert_array_equal(arr, io_1d) arr = read_excel(inputpath('test.xlsx'), '2d') assert_array_equal(arr, io_2d) arr = read_excel(inputpath('test.xlsx'), '2d_classic') assert_array_equal(arr, ndtest("a=a0..a2; b0..b2")) arr = read_excel(inputpath('test.xlsx'), '2d_classic', nb_axes=2) assert_array_equal(arr, ndtest("a=a0..a2; b0..b2")) arr = read_excel(inputpath('test.xlsx'), '3d') assert_array_equal(arr, io_3d) # for > 2d, specifying nb_axes is required if there is no name for the horizontal axis arr = read_excel(inputpath('test.xlsx'), '3d_classic', nb_axes=3) assert_array_equal(arr, ndtest("a=1..3; b=b0,b1; c0..c2")) arr = read_excel(inputpath('test.xlsx'), 'int_labels') assert_array_equal(arr, io_int_labels) # passing a Group as sheet arg axis = Axis('dim=1d,2d,3d,5d') arr = read_excel(inputpath('test.xlsx'), axis['1d']) assert_array_equal(arr, io_1d) # missing rows, default fill_value arr = read_excel(inputpath('test.xlsx'), 'missing_values') expected = ndtest("a=1..3; b=b0,b1; c=c0..c2", dtype=float) expected[2, 'b0'] = nan expected[3, 'b1'] = nan assert_array_nan_equal(arr, expected) # missing rows + fill_value argument arr = read_excel(inputpath('test.xlsx'), 'missing_values', fill_value=42) expected = ndtest("a=1..3; b=b0,b1; c=c0..c2", dtype=float) expected[2, 'b0'] = 42 expected[3, 'b1'] = 42 assert_array_equal(arr, expected) # range arr = read_excel(inputpath('test.xlsx'), 'position', range='D3:H9') assert_array_equal(arr, io_3d) ################# # narrow format # ################# arr = read_excel(inputpath('test_narrow.xlsx'), '1d', wide=False) assert_array_equal(arr, io_1d) arr = read_excel(inputpath('test_narrow.xlsx'), '2d', wide=False) assert_array_equal(arr, io_2d) arr = read_excel(inputpath('test_narrow.xlsx'), '3d', wide=False) assert_array_equal(arr, io_3d) # missing rows + fill_value argument arr = read_excel(inputpath('test_narrow.xlsx'), 'missing_values', fill_value=42, wide=False) expected = io_narrow_missing_values.copy() expected[isnan(expected)] = 42 assert_array_equal(arr, expected) # unsorted values arr = read_excel(inputpath('test_narrow.xlsx'), 'unsorted', wide=False) assert_array_equal(arr, io_unsorted) # range arr = read_excel(inputpath('test_narrow.xlsx'), 'position', range='D3:G21', wide=False) assert_array_equal(arr, io_3d) ############################## # invalid keyword argument # ############################## with pytest.raises(TypeError, match="'dtype' is an invalid keyword argument for this function " "when using the xlwings backend"): read_excel(inputpath('test.xlsx'), engine='xlwings', dtype=float) ################# # blank cells # ################# # Excel sheet with blank cells on right/bottom border of the array to read fpath = inputpath('test_blank_cells.xlsx') good = read_excel(fpath, 'good') bad1 = read_excel(fpath, 'blanksafter_morerowsthancols') bad2 = read_excel(fpath, 'blanksafter_morecolsthanrows') assert_array_equal(bad1, good) assert_array_equal(bad2, good) # with additional empty column in the middle of the array to read good2 = ndtest('a=a0,a1;b=2003..2006').astype(object) good2[2005] = None good2 = good2.set_axes('b', Axis([2003, 2004, None, 2006], 'b')) bad3 = read_excel(fpath, 'middleblankcol') bad4 = read_excel(fpath, '16384col') assert_array_equal(bad3, good2) assert_array_equal(bad4, good2) @needs_xlrd def test_read_excel_pandas(): arr = read_excel(inputpath('test.xlsx'), '1d', engine='xlrd') assert_array_equal(arr, io_1d) arr = read_excel(inputpath('test.xlsx'), '2d', engine='xlrd') assert_array_equal(arr, io_2d) arr = read_excel(inputpath('test.xlsx'), '2d', nb_axes=2, engine='xlrd') assert_array_equal(arr, io_2d) arr = read_excel(inputpath('test.xlsx'), '2d_classic', engine='xlrd') assert_array_equal(arr, ndtest("a=a0..a2; b0..b2")) arr = read_excel(inputpath('test.xlsx'), '2d_classic', nb_axes=2, engine='xlrd') assert_array_equal(arr, ndtest("a=a0..a2; b0..b2")) arr = read_excel(inputpath('test.xlsx'), '3d', index_col=[0, 1], engine='xlrd') assert_array_equal(arr, io_3d) arr = read_excel(inputpath('test.xlsx'), '3d', engine='xlrd') assert_array_equal(arr, io_3d) # for > 2d, specifying nb_axes is required if there is no name for the horizontal axis arr = read_excel(inputpath('test.xlsx'), '3d_classic', nb_axes=3, engine='xlrd') assert_array_equal(arr, ndtest("a=1..3; b=b0,b1; c0..c2")) arr = read_excel(inputpath('test.xlsx'), 'int_labels', engine='xlrd') assert_array_equal(arr, io_int_labels) # passing a Group as sheet arg axis = Axis('dim=1d,2d,3d,5d') arr = read_excel(inputpath('test.xlsx'), axis['1d'], engine='xlrd') assert_array_equal(arr, io_1d) # missing rows + fill_value argument arr = read_excel(inputpath('test.xlsx'), 'missing_values', fill_value=42, engine='xlrd') expected = io_missing_values.copy() expected[isnan(expected)] = 42 assert_array_equal(arr, expected) ################# # narrow format # ################# arr = read_excel(inputpath('test_narrow.xlsx'), '1d', wide=False, engine='xlrd') assert_array_equal(arr, io_1d) arr = read_excel(inputpath('test_narrow.xlsx'), '2d', wide=False, engine='xlrd') assert_array_equal(arr, io_2d) arr = read_excel(inputpath('test_narrow.xlsx'), '3d', wide=False, engine='xlrd') assert_array_equal(arr, io_3d) # missing rows + fill_value argument arr = read_excel(inputpath('test_narrow.xlsx'), 'missing_values', fill_value=42, wide=False, engine='xlrd') expected = io_narrow_missing_values.copy() expected[isnan(expected)] = 42 assert_array_equal(arr, expected) # unsorted values arr = read_excel(inputpath('test_narrow.xlsx'), 'unsorted', wide=False, engine='xlrd') assert_array_equal(arr, io_unsorted) ################# # blank cells # ################# # Excel sheet with blank cells on right/bottom border of the array to read fpath = inputpath('test_blank_cells.xlsx') good1 = read_excel(fpath, 'good', engine='xlrd') bad1 = read_excel(fpath, 'blanksafter_morerowsthancols', engine='xlrd') bad2 = read_excel(fpath, 'blanksafter_morecolsthanrows', engine='xlrd') assert_array_equal(bad1, good1) assert_array_equal(bad2, good1) # with additional empty column in the middle of the array to read good2 = ndtest('a=a0,a1;b=2003..2006').astype(float) good2[2005] = nan good2 = good2.set_axes('b', Axis([2003, 2004, 'Unnamed: 3', 2006], 'b')) bad3 = read_excel(fpath, 'middleblankcol', engine='xlrd') bad4 = read_excel(fpath, '16384col', engine='xlrd') assert_array_nan_equal(bad3, good2) assert_array_nan_equal(bad4, good2) def test_from_lists(): simple_arr = ndtest((2, 2, 3)) # simple arr_list = [['a', 'b\\c', 'c0', 'c1', 'c2'], ['a0', 'b0', 0, 1, 2], ['a0', 'b1', 3, 4, 5], ['a1', 'b0', 6, 7, 8], ['a1', 'b1', 9, 10, 11]] res = from_lists(arr_list) assert_array_equal(res, simple_arr) # simple (using dump). This should be the same test than above. # We just make sure dump() and from_lists() round-trip correctly. arr_list = simple_arr.dump() res = from_lists(arr_list) assert_array_equal(res, simple_arr) # with anonymous axes arr_anon = simple_arr.rename({0: None, 1: None, 2: None}) arr_list = arr_anon.dump() assert arr_list == [[None, None, 'c0', 'c1', 'c2'], ['a0', 'b0', 0, 1, 2], ['a0', 'b1', 3, 4, 5], ['a1', 'b0', 6, 7, 8], ['a1', 'b1', 9, 10, 11]] res = from_lists(arr_list, nb_axes=3) assert_array_equal(res, arr_anon) # with empty ('') axes names arr_empty_names = simple_arr.rename({0: '', 1: '', 2: ''}) arr_list = arr_empty_names.dump() assert arr_list == [[ '', '', 'c0', 'c1', 'c2'], ['a0', 'b0', 0, 1, 2], ['a0', 'b1', 3, 4, 5], ['a1', 'b0', 6, 7, 8], ['a1', 'b1', 9, 10, 11]] res = from_lists(arr_list, nb_axes=3) # this is purposefully NOT arr_empty_names because from_lists (via df_asarray) transforms '' axes to None assert_array_equal(res, arr_anon) # sort_rows arr = from_lists([['sex', 'nat\\year', 1991, 1992, 1993], ['F', 'BE', 0, 0, 1], ['F', 'FO', 0, 0, 2], ['M', 'BE', 1, 0, 0], ['M', 'FO', 2, 0, 0]]) sorted_arr = from_lists([['sex', 'nat\\year', 1991, 1992, 1993], ['M', 'BE', 1, 0, 0], ['M', 'FO', 2, 0, 0], ['F', 'BE', 0, 0, 1], ['F', 'FO', 0, 0, 2]], sort_rows=True) assert_array_equal(sorted_arr, arr) # sort_columns arr = from_lists([['sex', 'nat\\year', 1991, 1992, 1993], ['M', 'BE', 1, 0, 0], ['M', 'FO', 2, 0, 0], ['F', 'BE', 0, 0, 1], ['F', 'FO', 0, 0, 2]]) sorted_arr = from_lists([['sex', 'nat\\year', 1992, 1991, 1993], ['M', 'BE', 0, 1, 0], ['M', 'FO', 0, 2, 0], ['F', 'BE', 0, 0, 1], ['F', 'FO', 0, 0, 2]], sort_columns=True) assert_array_equal(sorted_arr, arr) def test_from_series(): # Series with Index as index expected = ndtest(3) s = pd.Series([0, 1, 2], index=pd.Index(['a0', 'a1', 'a2'], name='a')) assert_array_equal(from_series(s), expected) s = pd.Series([2, 0, 1], index=pd.Index(['a2', 'a0', 'a1'], name='a')) assert_array_equal(from_series(s, sort_rows=True), expected) expected = ndtest(3)[['a2', 'a0', 'a1']] assert_array_equal(from_series(s), expected) # Series with MultiIndex as index age = Axis('age=0..3') gender = Axis('gender=M,F') time = Axis('time=2015..2017') expected = ndtest((age, gender, time)) index = pd.MultiIndex.from_product(expected.axes.labels, names=expected.axes.names) data = expected.data.flatten() s = pd.Series(data, index) res = from_series(s) assert_array_equal(res, expected) res = from_series(s, sort_rows=True) assert_array_equal(res, expected.sort_axes()) expected[0, 'F'] = -1 s = s.reset_index().drop([3, 4, 5]).set_index(['age', 'gender', 'time'])[0] res = from_series(s, fill_value=-1) assert_array_equal(res, expected) def test_from_frame(): # 1) data = scalar # ================ # Dataframe becomes 1D Array data = np.array([10]) index = ['i0'] columns = ['c0'] axis_index, axis_columns = Axis(index), Axis(columns) df = pd.DataFrame(data, index=index, columns=columns) assert df.index.name is None assert df.columns.name is None assert list(df.index.values) == index assert list(df.columns.values) == columns # anonymous indexes/columns # input dataframe: # ---------------- # c0 # i0 10 # output Array: # ------------- # {0}\{1} c0 # i0 10 la = from_frame(df) assert la.ndim == 2 assert la.shape == (1, 1) assert la.axes.names == [None, None] assert list(la.axes.labels[0]) == index assert list(la.axes.labels[1]) == columns expected_la = Array(data.reshape((1, 1)), [axis_index, axis_columns]) assert_array_equal(la, expected_la) # anonymous columns # input dataframe: # ---------------- # c0 # index # i0 10 # output Array: # ------------- # index\{1} c0 # i0 10 df.index.name, df.columns.name = 'index', None la = from_frame(df) assert la.ndim == 2 assert la.shape == (1, 1) assert la.axes.names == ['index', None] assert list(la.axes.labels[0]) == index assert list(la.axes.labels[1]) == columns expected_la = Array(data.reshape((1, 1)), [axis_index.rename('index'), axis_columns]) assert_array_equal(la, expected_la) # anonymous columns/non string row axis name # input dataframe: # ---------------- # c0 # 0 # i0 10 # output Array: # ------------- # 0\{1} c0 # i0 10 df = pd.DataFrame([10], index=pd.Index(['i0'], name=0), columns=['c0']) res = from_frame(df) expected = Array([[10]], [Axis(['i0'], name=0), Axis(['c0'])]) assert res.ndim == 2 assert res.shape == (1, 1) assert res.axes.names == [0, None] assert_array_equal(res, expected) # anonymous index # input dataframe: # ---------------- # columns c0 # i0 10 # output Array: # ------------- # {0}\columns c0 # i0 10 df.index.name, df.columns.name = None, 'columns' la = from_frame(df) assert la.ndim == 2 assert la.shape == (1, 1) assert la.axes.names == [None, 'columns'] assert list(la.axes.labels[0]) == index assert list(la.axes.labels[1]) == columns expected_la = Array(data.reshape((1, 1)), [axis_index, axis_columns.rename('columns')]) assert_array_equal(la, expected_la) # index and columns with name # input dataframe: # ---------------- # columns c0 # index # i0 10 # output Array: # ------------- # index\columns c0 # i0 10 df.index.name, df.columns.name = 'index', 'columns' la = from_frame(df) assert la.ndim == 2 assert la.shape == (1, 1) assert la.axes.names == ['index', 'columns'] assert list(la.axes.labels[0]) == index assert list(la.axes.labels[1]) == columns expected_la = Array(data.reshape((1, 1)), [axis_index.rename('index'), axis_columns.rename('columns')]) assert_array_equal(la, expected_la) # 2) data = vector # ================ size = 3 # 2A) data = horizontal vector (1 x N) # ==================================== # Dataframe becomes 1D Array data = np.arange(size) indexes = ['i0'] columns = ['c{}'.format(i) for i in range(size)] axis_index, axis_columns = Axis(indexes), Axis(columns) df = pd.DataFrame(data.reshape(1, size), index=indexes, columns=columns) assert df.index.name is None assert df.columns.name is None assert list(df.index.values) == indexes assert list(df.columns.values) == columns # anonymous indexes/columns # input dataframe: # ---------------- # c0 c1 c2 # i0 0 1 2 # output Array: # ------------- # {0}\{1} c0 c1 c2 # i0 0 1 2 la = from_frame(df) assert la.ndim == 2 assert la.shape == (1, size) assert la.axes.names == [None, None] assert list(la.axes.labels[0]) == index assert list(la.axes.labels[1]) == columns expected_la = Array(data.reshape((1, size)), [axis_index, axis_columns]) assert_array_equal(la, expected_la) # anonymous columns # input dataframe: # ---------------- # c0 c1 c2 # index # i0 0 1 2 # output Array: # ------------- # index\{1} c0 c1 c2 # i0 0 1 2 df.index.name, df.columns.name = 'index', None la = from_frame(df) assert la.ndim == 2 assert la.shape == (1, size) assert la.axes.names == ['index', None] assert list(la.axes.labels[0]) == index assert list(la.axes.labels[1]) == columns expected_la = Array(data.reshape((1, size)), [axis_index.rename('index'), axis_columns]) assert_array_equal(la, expected_la) # anonymous index # input dataframe: # ---------------- # columns c0 c1 c2 # i0 0 1 2 # output Array: # ------------- # {0}\columns c0 c1 c2 # i0 0 1 2 df.index.name, df.columns.name = None, 'columns' la = from_frame(df) assert la.ndim == 2 assert la.shape == (1, size) assert la.axes.names == [None, 'columns'] assert list(la.axes.labels[0]) == index assert list(la.axes.labels[1]) == columns expected_la = Array(data.reshape((1, size)), [axis_index, axis_columns.rename('columns')]) assert_array_equal(la, expected_la) # index and columns with name # input dataframe: # ---------------- # columns c0 c1 c2 # index # i0 0 1 2 # output Array: # ------------- # index\columns c0 c1 c2 # i0 0 1 2 df.index.name, df.columns.name = 'index', 'columns' la = from_frame(df) assert la.ndim == 2 assert la.shape == (1, size) assert la.axes.names == ['index', 'columns'] assert list(la.axes.labels[0]) == index assert list(la.axes.labels[1]) == columns expected_la = Array(data.reshape((1, size)), [axis_index.rename('index'), axis_columns.rename('columns')]) assert_array_equal(la, expected_la) # 2B) data = vertical vector (N x 1) # ================================== # Dataframe becomes 2D Array data = data.reshape(size, 1) indexes = ['i{}'.format(i) for i in range(size)] columns = ['c0'] axis_index, axis_columns = Axis(indexes), Axis(columns) df = pd.DataFrame(data, index=indexes, columns=columns) assert df.index.name is None assert df.columns.name is None assert list(df.index.values) == indexes assert list(df.columns.values) == columns # anonymous indexes/columns # input dataframe: # ---------------- # c0 # i0 0 # i1 1 # i2 2 # output Array: # ------------- # {0}\{1} c0 # i0 0 # i1 1 # i2 2 la = from_frame(df) assert la.ndim == 2 assert la.shape == (size, 1) assert la.axes.names == [None, None] assert list(la.axes.labels[0]) == indexes assert list(la.axes.labels[1]) == columns expected_la = Array(data, [axis_index, axis_columns]) assert_array_equal(la, expected_la) # anonymous columns # input dataframe: # ---------------- # c0 # index # i0 0 # i1 1 # i2 2 # output Array: # ------------- # index\{1} c0 # i0 0 # i1 1 # i2 2 df.index.name, df.columns.name = 'index', None la = from_frame(df) assert la.ndim == 2 assert la.shape == (size, 1) assert la.axes.names == ['index', None] assert list(la.axes.labels[0]) == indexes assert list(la.axes.labels[1]) == columns expected_la = Array(data, [axis_index.rename('index'), axis_columns]) assert_array_equal(la, expected_la) # anonymous index # input dataframe: # ---------------- # columns c0 # i0 0 # i1 1 # i2 2 # output Array: # ------------- # {0}\columns c0 # i0 0 # i1 1 # i2 2 df.index.name, df.columns.name = None, 'columns' la = from_frame(df) assert la.ndim == 2 assert la.shape == (size, 1) assert la.axes.names == [None, 'columns'] assert list(la.axes.labels[0]) == indexes assert list(la.axes.labels[1]) == columns expected_la = Array(data, [axis_index, axis_columns.rename('columns')]) assert_array_equal(la, expected_la) # index and columns with name # input dataframe: # ---------------- # columns c0 # index # i0 0 # i1 1 # i2 2 # output Array: # ------------- # {0}\columns c0 # i0 0 # i1 1 # i2 2 df.index.name, df.columns.name = 'index', 'columns' assert la.ndim == 2 assert la.shape == (size, 1) assert la.axes.names == [None, 'columns'] assert list(la.axes.labels[0]) == indexes assert list(la.axes.labels[1]) == columns expected_la = Array(data, [axis_index, axis_columns.rename('columns')]) assert_array_equal(la, expected_la) # 3) 3D array # =========== # 3A) Dataframe with 2 index columns # ================================== dt = [('age', int), ('sex', 'U1'), ('2007', int), ('2010', int), ('2013', int)] data = np.array([ (0, 'F', 3722, 3395, 3347), (0, 'M', 338, 316, 323), (1, 'F', 2878, 2791, 2822), (1, 'M', 1121, 1037, 976), (2, 'F', 4073, 4161, 4429), (2, 'M', 1561, 1463, 1467), (3, 'F', 3507, 3741, 3366), (3, 'M', 2052, 2052, 2118), ], dtype=dt) df = pd.DataFrame(data) df.set_index(['age', 'sex'], inplace=True) df.columns.name = 'time' la = from_frame(df) assert la.ndim == 3 assert la.shape == (4, 2, 3) assert la.axes.names == ['age', 'sex', 'time'] assert_array_equal(la[0, 'F', :], [3722, 3395, 3347]) # 3B) Dataframe with columns.name containing \\ # ============================================= dt = [('age', int), ('sex\\time', 'U1'), ('2007', int), ('2010', int), ('2013', int)] data = np.array([ (0, 'F', 3722, 3395, 3347), (0, 'M', 338, 316, 323), (1, 'F', 2878, 2791, 2822), (1, 'M', 1121, 1037, 976), (2, 'F', 4073, 4161, 4429), (2, 'M', 1561, 1463, 1467), (3, 'F', 3507, 3741, 3366), (3, 'M', 2052, 2052, 2118), ], dtype=dt) df = pd.DataFrame(data) df.set_index(['age', 'sex\\time'], inplace=True) la = from_frame(df, unfold_last_axis_name=True) assert la.ndim == 3 assert la.shape == (4, 2, 3) assert la.axes.names == ['age', 'sex', 'time'] assert_array_equal(la[0, 'F', :], [3722, 3395, 3347]) # 3C) Dataframe with no axe names (names are None) # =============================== arr_no_names = ndtest("a0,a1;b0..b2;c0..c3") df_no_names = arr_no_names.df res = from_frame(df_no_names) assert_array_equal(res, arr_no_names) # 3D) Dataframe with empty axe names (names are '') # ================================== arr_empty_names = ndtest("=a0,a1;=b0..b2;=c0..c3") assert arr_empty_names.axes.names == ['', '', ''] df_no_names = arr_empty_names.df res = from_frame(df_no_names) assert_array_equal(res, arr_empty_names) # 4) test sort_rows and sort_columns arguments # ============================================ age = Axis('age=2,0,1,3') gender = Axis('gender=M,F') time = Axis('time=2016,2015,2017') columns = pd.Index(time.labels, name=time.name) # df.index is an Index instance expected = ndtest((gender, time)) index = pd.Index(gender.labels, name=gender.name) data = expected.data df = pd.DataFrame(data, index=index, columns=columns) expected = expected.sort_axes() res = from_frame(df, sort_rows=True, sort_columns=True) assert_array_equal(res, expected) # df.index is a MultiIndex instance expected = ndtest((age, gender, time)) index = pd.MultiIndex.from_product(expected.axes[:-1].labels, names=expected.axes[:-1].names) data = expected.data.reshape(len(age) * len(gender), len(time)) df = pd.DataFrame(data, index=index, columns=columns) res = from_frame(df, sort_rows=True, sort_columns=True) assert_array_equal(res, expected.sort_axes()) # 5) test fill_value # ================== expected[0, 'F'] = -1 df = df.reset_index().drop([3]).set_index(['age', 'gender']) res = from_frame(df, fill_value=-1) assert_array_equal(res, expected) def test_to_csv(tmpdir): arr = io_3d.copy() arr.to_csv(tmp_path(tmpdir, 'out.csv')) result = ['a,b\\c,c0,c1,c2\n', '1,b0,0,1,2\n', '1,b1,3,4,5\n'] with open(tmp_path(tmpdir, 'out.csv')) as f: assert f.readlines()[:3] == result # stacked data (one column containing all the values and another column listing the context of the value) arr.to_csv(tmp_path(tmpdir, 'out.csv'), wide=False) result = ['a,b,c,value\n', '1,b0,c0,0\n', '1,b0,c1,1\n'] with open(tmp_path(tmpdir, 'out.csv')) as f: assert f.readlines()[:3] == result arr = io_1d.copy() arr.to_csv(tmp_path(tmpdir, 'test_out1d.csv')) result = ['a,a0,a1,a2\n', ',0,1,2\n'] with open(tmp_path(tmpdir, 'test_out1d.csv')) as f: assert f.readlines() == result @needs_xlsxwriter def test_to_excel_xlsxwriter(tmpdir): fpath = tmp_path(tmpdir, 'test_to_excel_xlsxwriter.xlsx') # 1D a1 = ndtest(3) # fpath/Sheet1/A1 a1.to_excel(fpath, overwrite_file=True, engine='xlsxwriter') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a1) # fpath/Sheet1/A1(transposed) a1.to_excel(fpath, transpose=True, engine='xlsxwriter') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a1) # fpath/Sheet1/A1 # stacked data (one column containing all the values and another column listing the context of the value) a1.to_excel(fpath, wide=False, engine='xlsxwriter') res = read_excel(fpath, engine='xlrd') stacked_a1 = a1.reshape([a1.a, Axis(['value'])]) assert_array_equal(res, stacked_a1) # 2D a2 = ndtest((2, 3)) # fpath/Sheet1/A1 a2.to_excel(fpath, overwrite_file=True, engine='xlsxwriter') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a2) # fpath/Sheet1/A10 # TODO: this is currently not supported (though we would only need to translate A10 to startrow=0 and startcol=0 # a2.to_excel('fpath', 'Sheet1', 'A10', engine='xlsxwriter') # res = read_excel('fpath', 'Sheet1', engine='xlrd', skiprows=9) # assert_array_equal(res, a2) # fpath/other/A1 a2.to_excel(fpath, 'other', engine='xlsxwriter') res = read_excel(fpath, 'other', engine='xlrd') assert_array_equal(res, a2) # 3D a3 = ndtest((2, 3, 4)) # fpath/Sheet1/A1 # FIXME: merge_cells=False should be the default (until Pandas is fixed to read its format) a3.to_excel(fpath, overwrite_file=True, engine='xlsxwriter', merge_cells=False) # a3.to_excel('fpath', overwrite_file=True, engine='openpyxl') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a3) # fpath/Sheet1/A20 # TODO: implement position (see above) # a3.to_excel('fpath', 'Sheet1', 'A20', engine='xlsxwriter', merge_cells=False) # res = read_excel('fpath', 'Sheet1', engine='xlrd', skiprows=19) # assert_array_equal(res, a3) # fpath/other/A1 a3.to_excel(fpath, 'other', engine='xlsxwriter', merge_cells=False) res = read_excel(fpath, 'other', engine='xlrd') assert_array_equal(res, a3) # 1D a1 = ndtest(3) # fpath/Sheet1/A1 a1.to_excel(fpath, overwrite_file=True, engine='xlsxwriter') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a1) # fpath/Sheet1/A1(transposed) a1.to_excel(fpath, transpose=True, engine='xlsxwriter') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a1) # fpath/Sheet1/A1 # stacked data (one column containing all the values and another column listing the context of the value) a1.to_excel(fpath, wide=False, engine='xlsxwriter') res = read_excel(fpath, engine='xlrd') stacked_a1 = a1.reshape([a1.a, Axis(['value'])]) assert_array_equal(res, stacked_a1) # 2D a2 = ndtest((2, 3)) # fpath/Sheet1/A1 a2.to_excel(fpath, overwrite_file=True, engine='xlsxwriter') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a2) # fpath/Sheet1/A10 # TODO: this is currently not supported (though we would only need to translate A10 to startrow=0 and startcol=0 # a2.to_excel(fpath, 'Sheet1', 'A10', engine='xlsxwriter') # res = read_excel('fpath', 'Sheet1', engine='xlrd', skiprows=9) # assert_array_equal(res, a2) # fpath/other/A1 a2.to_excel(fpath, 'other', engine='xlsxwriter') res = read_excel(fpath, 'other', engine='xlrd') assert_array_equal(res, a2) # 3D a3 = ndtest((2, 3, 4)) # fpath/Sheet1/A1 # FIXME: merge_cells=False should be the default (until Pandas is fixed to read its format) a3.to_excel(fpath, overwrite_file=True, engine='xlsxwriter', merge_cells=False) # a3.to_excel('fpath', overwrite_file=True, engine='openpyxl') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a3) # fpath/Sheet1/A20 # TODO: implement position (see above) # a3.to_excel('fpath', 'Sheet1', 'A20', engine='xlsxwriter', merge_cells=False) # res = read_excel('fpath', 'Sheet1', engine='xlrd', skiprows=19) # assert_array_equal(res, a3) # fpath/other/A1 a3.to_excel(fpath, 'other', engine='xlsxwriter', merge_cells=False) res = read_excel(fpath, 'other', engine='xlrd') assert_array_equal(res, a3) # passing group as sheet_name a3 = ndtest((4, 3, 4)) os.remove(fpath) # single element group for label in a3.a: a3[label].to_excel(fpath, label, engine='xlsxwriter') # unnamed group group = a3.c['c0,c2'] a3[group].to_excel(fpath, group, engine='xlsxwriter') # unnamed group + slice group = a3.c['c0::2'] a3[group].to_excel(fpath, group, engine='xlsxwriter') # named group group = a3.c['c0,c2'] >> 'even' a3[group].to_excel(fpath, group, engine='xlsxwriter') # group with name containing special characters (replaced by _) group = a3.c['c0,c2'] >> r':name?with*special/\[char]' a3[group].to_excel(fpath, group, engine='xlsxwriter') @needs_xlwings def test_to_excel_xlwings(tmpdir): fpath = tmp_path(tmpdir, 'test_to_excel_xlwings.xlsx') # 1D a1 = ndtest(3) # live book/Sheet1/A1 # a1.to_excel() # fpath/Sheet1/A1 (create a new file if does not exist) if os.path.isfile(fpath): os.remove(fpath) a1.to_excel(fpath, engine='xlwings') # we use xlrd to read back instead of xlwings even if that should work, to make the test faster res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a1) # fpath/Sheet1/A1(transposed) a1.to_excel(fpath, transpose=True, engine='xlwings') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a1) # fpath/Sheet1/A1 # stacked data (one column containing all the values and another column listing the context of the value) a1.to_excel(fpath, wide=False, engine='xlwings') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a1) # 2D a2 = ndtest((2, 3)) # fpath/Sheet1/A1 a2.to_excel(fpath, overwrite_file=True, engine='xlwings') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a2) # fpath/Sheet1/A10 a2.to_excel(fpath, 'Sheet1', 'A10', engine='xlwings') res = read_excel(fpath, 'Sheet1', engine='xlrd', skiprows=9) assert_array_equal(res, a2) # fpath/other/A1 a2.to_excel(fpath, 'other', engine='xlwings') res = read_excel(fpath, 'other', engine='xlrd') assert_array_equal(res, a2) # transpose a2.to_excel(fpath, 'transpose', transpose=True, engine='xlwings') res = read_excel(fpath, 'transpose', engine='xlrd') assert_array_equal(res, a2.T) # 3D a3 = ndtest((2, 3, 4)) # fpath/Sheet1/A1 a3.to_excel(fpath, overwrite_file=True, engine='xlwings') res = read_excel(fpath, engine='xlrd') assert_array_equal(res, a3) # fpath/Sheet1/A20 a3.to_excel(fpath, 'Sheet1', 'A20', engine='xlwings') res = read_excel(fpath, 'Sheet1', engine='xlrd', skiprows=19) assert_array_equal(res, a3) # fpath/other/A1 a3.to_excel(fpath, 'other', engine='xlwings') res = read_excel(fpath, 'other', engine='xlrd') assert_array_equal(res, a3) # passing group as sheet_name a3 = ndtest((4, 3, 4)) os.remove(fpath) # single element group for label in a3.a: a3[label].to_excel(fpath, label, engine='xlwings') # unnamed group group = a3.c['c0,c2'] a3[group].to_excel(fpath, group, engine='xlwings') # unnamed group + slice group = a3.c['c0::2'] a3[group].to_excel(fpath, group, engine='xlwings') # named group group = a3.c['c0,c2'] >> 'even' a3[group].to_excel(fpath, group, engine='xlwings') # group with name containing special characters (replaced by _) group = a3.c['c0,c2'] >> r':name?with*special/\[char]' a3[group].to_excel(fpath, group, engine='xlwings') # checks sheet names sheet_names = sorted(open_excel(fpath).sheet_names()) assert sheet_names == sorted(['a0', 'a1', 'a2', 'a3', 'c0,c2', 'c0__2', 'even', '_name_with_special___char_']) # sheet name of 31 characters (= maximum authorized length) a3.to_excel(fpath, "sheetname_of_exactly_31_chars__", engine='xlwings') # sheet name longer than 31 characters with pytest.raises(ValueError, match="Sheet names cannot exceed 31 characters"): a3.to_excel(fpath, "sheetname_longer_than_31_characters", engine='xlwings') def test_dump(): # narrow format res = list(ndtest(3).dump(wide=False, value_name='data')) assert res == [['a', 'data'], ['a0', 0], ['a1', 1], ['a2', 2]] # array with an anonymous axis and a wildcard axis arr = ndtest((Axis('a0,a1'), Axis(2, 'b'))) res = arr.dump() assert res == [['\\b', 0, 1], ['a0', 0, 1], ['a1', 2, 3]] res = arr.dump(_axes_display_names=True) assert res == [['{0}\\b*', 0, 1], ['a0', 0, 1], ['a1', 2, 3]] @needs_xlwings def test_open_excel(tmpdir): # 1) Create new file # ================== fpath = inputpath('should_not_exist.xlsx') # overwrite_file must be set to True to create a new file with pytest.raises(ValueError): open_excel(fpath) # 2) with headers # =============== with open_excel(visible=False) as wb: # 1D a1 = ndtest(3) # Sheet1/A1 wb['Sheet1'] = a1.dump() res = wb['Sheet1'].load() assert_array_equal(res, a1) wb[0] = a1.dump() res = wb[0].load() assert_array_equal(res, a1) # Sheet1/A1(transposed) # TODO: implement .options on Sheet so that one can write: # wb[0].options(transpose=True).value = a1.dump() wb[0]['A1'].options(transpose=True).value = a1.dump() # TODO: implement .options on Range so that you can write: # res = wb[0]['A1:B4'].options(transpose=True).load() # res = from_lists(wb[0]['A1:B4'].options(transpose=True).value) # assert_array_equal(res, a1) # 2D a2 = ndtest((2, 3)) # Sheet1/A1 wb[0] = a2.dump() res = wb[0].load() assert_array_equal(res, a2) # Sheet1/A10 wb[0]['A10'] = a2.dump() res = wb[0]['A10:D12'].load() assert_array_equal(res, a2) # other/A1 wb['other'] = a2.dump() res = wb['other'].load() assert_array_equal(res, a2) # new/A10 # we need to create the sheet first wb['new'] = '' wb['new']['A10'] = a2.dump() res = wb['new']['A10:D12'].load() assert_array_equal(res, a2) # new2/A10 # cannot store the return value of "add" because that's a raw xlwings Sheet wb.sheets.add('new2') wb['new2']['A10'] = a2.dump() res = wb['new2']['A10:D12'].load() assert_array_equal(res, a2) # 3D a3 = ndtest((2, 3, 4)) # 3D/A1 wb['3D'] = a3.dump() res = wb['3D'].load() assert_array_equal(res, a3) # 3D/A20 wb['3D']['A20'] = a3.dump() res = wb['3D']['A20:F26'].load() assert_array_equal(res, a3) # 3D/A20 without name for columns wb['3D']['A20'] = a3.dump() # assume we have no name for the columns axis (ie change b\c to b) wb['3D']['B20'] = 'b' res = wb['3D']['A20:F26'].load(nb_axes=3) assert_array_equal(res, a3.data) # the two first axes should be the same assert res.axes[:2] == a3.axes[:2] # the third axis should have the same labels (but not the same name obviously) assert_array_equal(res.axes[2].labels, a3.axes[2].labels) with open_excel(inputpath('test.xlsx')) as wb: expected = ndtest("a=a0..a2; b0..b2") res = wb['2d_classic'].load() assert_array_equal(res, expected) # 3) without headers # ================== with open_excel(visible=False) as wb: # 1D a1 = ndtest(3) # Sheet1/A1 wb['Sheet1'] = a1 res = wb['Sheet1'].load(header=False) assert_array_equal(res, a1.data) wb[0] = a1 res = wb[0].load(header=False) assert_array_equal(res, a1.data) # Sheet1/A1(transposed) # FIXME: we need to .dump(header=False) explicitly because otherwise we go via ArrayConverter which # includes labels. for consistency's sake we should either change ArrayConverter to not include # labels, or change wb[0] = a1 to include them (and use wb[0] = a1.data to avoid them?) but that # would be heavily backward incompatible and how would I load them back? # wb[0]['A1'].options(transpose=True).value = a1 wb[0]['A1'].options(transpose=True).value = a1.dump(header=False) res = wb[0]['A1:A3'].load(header=False) assert_array_equal(res, a1.data) # 2D a2 = ndtest((2, 3)) # Sheet1/A1 wb[0] = a2 res = wb[0].load(header=False) assert_array_equal(res, a2.data) # Sheet1/A10 wb[0]['A10'] = a2 res = wb[0]['A10:C11'].load(header=False) assert_array_equal(res, a2.data) # other/A1 wb['other'] = a2 res = wb['other'].load(header=False) assert_array_equal(res, a2.data) # new/A10 # we need to create the sheet first wb['new'] = '' wb['new']['A10'] = a2 res = wb['new']['A10:C11'].load(header=False) assert_array_equal(res, a2.data) # 3D a3 = ndtest((2, 3, 4)) # 3D/A1 wb['3D'] = a3 res = wb['3D'].load(header=False) assert_array_equal(res, a3.data.reshape((6, 4))) # 3D/A20 wb['3D']['A20'] = a3 res = wb['3D']['A20:D25'].load(header=False) assert_array_equal(res, a3.data.reshape((6, 4))) # 4) Blank cells # ============== # Excel sheet with blank cells on right/bottom border of the array to read fpath = inputpath('test_blank_cells.xlsx') with open_excel(fpath) as wb: good = wb['good'].load() bad1 = wb['blanksafter_morerowsthancols'].load() bad2 = wb['blanksafter_morecolsthanrows'].load() # with additional empty column in the middle of the array to read good2 = wb['middleblankcol']['A1:E3'].load() bad3 = wb['middleblankcol'].load() bad4 = wb['16384col'].load() assert_array_equal(bad1, good) assert_array_equal(bad2, good) assert_array_equal(bad3, good2) assert_array_equal(bad4, good2) # 5) anonymous and wilcard axes # ============================= arr = ndtest((Axis('a0,a1'), Axis(2, 'b'))) fpath = tmp_path(tmpdir, 'anonymous_and_wildcard_axes.xlsx') with open_excel(fpath, overwrite_file=True) as wb: wb[0] = arr.dump() res = wb[0].load() # the result should be identical to the original array except we lost the information about # the wildcard axis being a wildcard axis expected = arr.set_axes('b', Axis([0, 1], 'b')) assert_array_equal(res, expected) # 6) crash test # ============= arr = ndtest((2, 2)) fpath = tmp_path(tmpdir, 'temporary_test_file.xlsx') # create and save a test file with open_excel(fpath, overwrite_file=True) as wb: wb['arr'] = arr.dump() wb.save() # raise exception when the file is open try: with open_excel(fpath, overwrite_file=True) as wb: raise ValueError("") except ValueError: pass # check if file is still available with open_excel(fpath) as wb: assert wb.sheet_names() == ['arr'] assert_array_equal(wb['arr'].load(), arr) # remove file if os.path.exists(fpath): os.remove(fpath) def test_ufuncs(small_array): raw = small_array.data # simple one-argument ufunc assert_array_equal(exp(small_array), np.exp(raw)) # with out= la_out = zeros(small_array.axes) raw_out = np.zeros(raw.shape) la_out2 = exp(small_array, la_out) raw_out2 = np.exp(raw, raw_out) # FIXME: this is not the case currently # self.assertIs(la_out2, la_out) assert_array_equal(la_out2, la_out) assert raw_out2 is raw_out assert_array_equal(la_out, raw_out) # with out= and broadcasting # we need to put the 'a' axis first because array numpy only supports that la_out = zeros([Axis([0, 1, 2], 'a')] + list(small_array.axes)) raw_out = np.zeros((3,) + raw.shape) la_out2 = exp(small_array, la_out) raw_out2 = np.exp(raw, raw_out) # self.assertIs(la_out2, la_out) # XXX: why is la_out2 transposed? assert_array_equal(la_out2.transpose(X.a), la_out) assert raw_out2 is raw_out assert_array_equal(la_out, raw_out) sex, lipro = small_array.axes low = small_array.sum(sex) // 4 + 3 raw_low = raw.sum(0) // 4 + 3 high = small_array.sum(sex) // 4 + 13 raw_high = raw.sum(0) // 4 + 13 # LA + scalars assert_array_equal(small_array.clip(0, 10), raw.clip(0, 10)) assert_array_equal(clip(small_array, 0, 10), np.clip(raw, 0, 10)) # LA + LA (no broadcasting) assert_array_equal(clip(small_array, 21 - small_array, 9 + small_array // 2), np.clip(raw, 21 - raw, 9 + raw // 2)) # LA + LA (with broadcasting) assert_array_equal(clip(small_array, low, high), np.clip(raw, raw_low, raw_high)) # where (no broadcasting) assert_array_equal(where(small_array < 5, -5, small_array), np.where(raw < 5, -5, raw)) # where (transposed no broadcasting) assert_array_equal(where(small_array < 5, -5, small_array.T), np.where(raw < 5, -5, raw)) # where (with broadcasting) result = where(small_array['P01'] < 5, -5, small_array) assert result.axes.names == ['sex', 'lipro'] assert_array_equal(result, np.where(raw[:, [0]] < 5, -5, raw)) # round small_float = small_array + 0.6 rounded = round(small_float) assert_array_equal(rounded, np.round(raw + 0.6)) def test_diag(): # 2D -> 1D a = ndtest((3, 3)) d = diag(a) assert d.ndim == 1 assert d.i[0] == a.i[0, 0] assert d.i[1] == a.i[1, 1] assert d.i[2] == a.i[2, 2] # 1D -> 2D a2 = diag(d) assert a2.ndim == 2 assert a2.i[0, 0] == a.i[0, 0] assert a2.i[1, 1] == a.i[1, 1] assert a2.i[2, 2] == a.i[2, 2] # 3D -> 2D a = ndtest((3, 3, 3)) d = diag(a) assert d.ndim == 2 assert d.i[0, 0] == a.i[0, 0, 0] assert d.i[1, 1] == a.i[1, 1, 1] assert d.i[2, 2] == a.i[2, 2, 2] # 3D -> 1D d = diag(a, axes=(0, 1, 2)) assert d.ndim == 1 assert d.i[0] == a.i[0, 0, 0] assert d.i[1] == a.i[1, 1, 1] assert d.i[2] == a.i[2, 2, 2] # 1D (anon) -> 2D d_anon = d.rename(0, None).ignore_labels() a2 = diag(d_anon) assert a2.ndim == 2 # 1D (anon) -> 3D a3 = diag(d_anon, ndim=3) assert a2.ndim == 2 assert a3.i[0, 0, 0] == a.i[0, 0, 0] assert a3.i[1, 1, 1] == a.i[1, 1, 1] assert a3.i[2, 2, 2] == a.i[2, 2, 2] # using Axis object sex = Axis('sex=M,F') a = eye(sex) d = diag(a) assert d.ndim == 1 assert d.axes.names == ['sex_sex'] assert_array_equal(d.axes.labels, [['M_M', 'F_F']]) assert d.i[0] == 1.0 assert d.i[1] == 1.0 @needs_python35 def test_matmul(): # 2D / anonymous axes a1 = ndtest([Axis(3), Axis(3)]) a2 = eye(3, 3) * 2 # Note that we cannot use @ because that is an invalid syntax in Python 2 # Array value assert_array_equal(a1.__matmul__(a2), ndtest([Axis(3), Axis(3)]) * 2) # ndarray value assert_array_equal(a1.__matmul__(a2.data), ndtest([Axis(3), Axis(3)]) * 2) # non anonymous axes (N <= 2) arr1d = ndtest(3) arr2d = ndtest((3, 3)) # 1D @ 1D res = arr1d.__matmul__(arr1d) assert isinstance(res, np.integer) assert res == 5 # 1D @ 2D assert_array_equal(arr1d.__matmul__(arr2d), Array([15, 18, 21], 'b=b0..b2')) # 2D @ 1D assert_array_equal(arr2d.__matmul__(arr1d), Array([5, 14, 23], 'a=a0..a2')) # 2D(a,b) @ 2D(a,b) -> 2D(a,b) res = from_lists([['a\\b', 'b0', 'b1', 'b2'], ['a0', 15, 18, 21], ['a1', 42, 54, 66], ['a2', 69, 90, 111]]) assert_array_equal(arr2d.__matmul__(arr2d), res) # 2D(a,b) @ 2D(b,a) -> 2D(a,a) res = from_lists([['a\\a', 'a0', 'a1', 'a2'], ['a0', 5, 14, 23], ['a1', 14, 50, 86], ['a2', 23, 86, 149]]) assert_array_equal(arr2d.__matmul__(arr2d.T), res) # ndarray value assert_array_equal(arr1d.__matmul__(arr2d.data), Array([15, 18, 21])) assert_array_equal(arr2d.data.__matmul__(arr2d.T.data), res.data) # different axes a1 = ndtest('a=a0..a1;b=b0..b2') a2 = ndtest('b=b0..b2;c=c0..c3') res = from_lists([[r'a\c', 'c0', 'c1', 'c2', 'c3'], ['a0', 20, 23, 26, 29], ['a1', 56, 68, 80, 92]]) assert_array_equal(a1.__matmul__(a2), res) # non anonymous axes (N >= 2) arr2d = ndtest((2, 2)) arr3d = ndtest((2, 2, 2)) arr4d = ndtest((2, 2, 2, 2)) a, b, c, d = arr4d.axes e = Axis('e=e0,e1') f = Axis('f=f0,f1') # 4D(a, b, c, d) @ 3D(e, d, f) -> 5D(a, b, e, c, f) arr3d = arr3d.set_axes([e, d, f]) res = from_lists([['a', 'b', 'e', 'c\\f', 'f0', 'f1'], ['a0', 'b0', 'e0', 'c0', 2, 3], ['a0', 'b0', 'e0', 'c1', 6, 11], ['a0', 'b0', 'e1', 'c0', 6, 7], ['a0', 'b0', 'e1', 'c1', 26, 31], ['a0', 'b1', 'e0', 'c0', 10, 19], ['a0', 'b1', 'e0', 'c1', 14, 27], ['a0', 'b1', 'e1', 'c0', 46, 55], ['a0', 'b1', 'e1', 'c1', 66, 79], ['a1', 'b0', 'e0', 'c0', 18, 35], ['a1', 'b0', 'e0', 'c1', 22, 43], ['a1', 'b0', 'e1', 'c0', 86, 103], ['a1', 'b0', 'e1', 'c1', 106, 127], ['a1', 'b1', 'e0', 'c0', 26, 51], ['a1', 'b1', 'e0', 'c1', 30, 59], ['a1', 'b1', 'e1', 'c0', 126, 151], ['a1', 'b1', 'e1', 'c1', 146, 175]]) assert_array_equal(arr4d.__matmul__(arr3d), res) # 3D(e, d, f) @ 4D(a, b, c, d) -> 5D(e, a, b, d, d) res = from_lists([['e', 'a', 'b', 'd\\d', 'd0', 'd1'], ['e0', 'a0', 'b0', 'd0', 2, 3], ['e0', 'a0', 'b0', 'd1', 6, 11], ['e0', 'a0', 'b1', 'd0', 6, 7], ['e0', 'a0', 'b1', 'd1', 26, 31], ['e0', 'a1', 'b0', 'd0', 10, 11], ['e0', 'a1', 'b0', 'd1', 46, 51], ['e0', 'a1', 'b1', 'd0', 14, 15], ['e0', 'a1', 'b1', 'd1', 66, 71], ['e1', 'a0', 'b0', 'd0', 10, 19], ['e1', 'a0', 'b0', 'd1', 14, 27], ['e1', 'a0', 'b1', 'd0', 46, 55], ['e1', 'a0', 'b1', 'd1', 66, 79], ['e1', 'a1', 'b0', 'd0', 82, 91], ['e1', 'a1', 'b0', 'd1', 118, 131], ['e1', 'a1', 'b1', 'd0', 118, 127], ['e1', 'a1', 'b1', 'd1', 170, 183]]) assert_array_equal(arr3d.__matmul__(arr4d), res) # 4D(a, b, c, d) @ 3D(b, d, f) -> 4D(a, b, c, f) arr3d = arr3d.set_axes([b, d, f]) res = from_lists([['a', 'b', 'c\\f', 'f0', 'f1'], ['a0', 'b0', 'c0', 2, 3], ['a0', 'b0', 'c1', 6, 11], ['a0', 'b1', 'c0', 46, 55], ['a0', 'b1', 'c1', 66, 79], ['a1', 'b0', 'c0', 18, 35], ['a1', 'b0', 'c1', 22, 43], ['a1', 'b1', 'c0', 126, 151], ['a1', 'b1', 'c1', 146, 175]]) assert_array_equal(arr4d.__matmul__(arr3d), res) # 3D(b, d, f) @ 4D(a, b, c, d) -> 4D(b, a, d, d) res = from_lists([['b', 'a', 'd\\d', 'd0', 'd1'], ['b0', 'a0', 'd0', 2, 3], ['b0', 'a0', 'd1', 6, 11], ['b0', 'a1', 'd0', 10, 11], ['b0', 'a1', 'd1', 46, 51], ['b1', 'a0', 'd0', 46, 55], ['b1', 'a0', 'd1', 66, 79], ['b1', 'a1', 'd0', 118, 127], ['b1', 'a1', 'd1', 170, 183]]) assert_array_equal(arr3d.__matmul__(arr4d), res) # 4D(a, b, c, d) @ 2D(d, f) -> 5D(a, b, c, f) arr2d = arr2d.set_axes([d, f]) res = from_lists([['a', 'b', 'c\\f', 'f0', 'f1'], ['a0', 'b0', 'c0', 2, 3], ['a0', 'b0', 'c1', 6, 11], ['a0', 'b1', 'c0', 10, 19], ['a0', 'b1', 'c1', 14, 27], ['a1', 'b0', 'c0', 18, 35], ['a1', 'b0', 'c1', 22, 43], ['a1', 'b1', 'c0', 26, 51], ['a1', 'b1', 'c1', 30, 59]]) assert_array_equal(arr4d.__matmul__(arr2d), res) # 2D(d, f) @ 4D(a, b, c, d) -> 5D(a, b, d, d) res = from_lists([['a', 'b', 'd\\d', 'd0', 'd1'], ['a0', 'b0', 'd0', 2, 3], ['a0', 'b0', 'd1', 6, 11], ['a0', 'b1', 'd0', 6, 7], ['a0', 'b1', 'd1', 26, 31], ['a1', 'b0', 'd0', 10, 11], ['a1', 'b0', 'd1', 46, 51], ['a1', 'b1', 'd0', 14, 15], ['a1', 'b1', 'd1', 66, 71]]) assert_array_equal(arr2d.__matmul__(arr4d), res) @needs_python35 def test_rmatmul(): a1 = eye(3) * 2 a2 = ndtest([Axis(3), Axis(3)]) # equivalent to a1.data @ a2 res = a2.__rmatmul__(a1.data) assert isinstance(res, Array) assert_array_equal(res, ndtest([Axis(3), Axis(3)]) * 2) def test_broadcast_with(): a1 = ndtest((3, 2)) a2 = ndtest(3) b = a2.broadcast_with(a1) assert b.ndim == a1.ndim assert b.shape == (3, 1) assert_array_equal(b.i[:, 0], a2) # anonymous axes a1 = ndtest([Axis(3), Axis(2)]) a2 = ndtest(Axis(3)) b = a2.broadcast_with(a1) assert b.ndim == a1.ndim assert b.shape == (3, 1) assert_array_equal(b.i[:, 0], a2) a1 = ndtest([Axis(1), Axis(3)]) a2 = ndtest([Axis(3), Axis(1)]) b = a2.broadcast_with(a1) assert b.ndim == 2 # common axes are reordered according to target (a1 in this case) assert b.shape == (1, 3) assert_larray_equiv(b, a2) a1 = ndtest([Axis(2), Axis(3)]) a2 = ndtest([Axis(3), Axis(2)]) b = a2.broadcast_with(a1) assert b.ndim == 2 assert b.shape == (2, 3) assert_larray_equiv(b, a2) def test_plot(): pass # small_h = small['M'] # small_h.plot(kind='bar') # small_h.plot() # small_h.hist() # large_data = np.random.randn(1000) # tick_v = np.random.randint(ord('a'), ord('z'), size=1000) # ticks = [chr(c) for c in tick_v] # large_axis = Axis('large', ticks) # large = Array(large_data, axes=[large_axis]) # large.plot() # large.hist() def test_combine_axes(): # combine N axes into 1 # ===================== arr = ndtest((2, 3, 4, 5)) res = arr.combine_axes((X.a, X.b)) assert res.axes.names == ['a_b', 'c', 'd'] assert res.size == arr.size assert res.shape == (2 * 3, 4, 5) assert_array_equal(res.axes.a_b.labels[:2], ['a0_b0', 'a0_b1']) assert_array_equal(res['a1_b0'], arr['a1', 'b0']) res = arr.combine_axes((X.a, X.c)) assert res.axes.names == ['a_c', 'b', 'd'] assert res.size == arr.size assert res.shape == (2 * 4, 3, 5) assert_array_equal(res.axes.a_c.labels[:2], ['a0_c0', 'a0_c1']) assert_array_equal(res['a1_c0'], arr['a1', 'c0']) res = arr.combine_axes((X.b, X.d)) assert res.axes.names == ['a', 'b_d', 'c'] assert res.size == arr.size assert res.shape == (2, 3 * 5, 4) assert_array_equal(res.axes.b_d.labels[:2], ['b0_d0', 'b0_d1']) assert_array_equal(res['b1_d0'], arr['b1', 'd0']) # combine M axes into N # ===================== arr = ndtest((2, 3, 4, 4, 3, 2)) # using a list of tuples res = arr.combine_axes([('a', 'c'), ('b', 'f'), ('d', 'e')]) assert res.axes.names == ['a_c', 'b_f', 'd_e'] assert res.size == arr.size assert res.shape == (2 * 4, 3 * 2, 4 * 3) assert list(res.axes.a_c.labels[:2]) == ['a0_c0', 'a0_c1'] assert list(res.axes.b_f.labels[:2]) == ['b0_f0', 'b0_f1'] assert list(res.axes.d_e.labels[:2]) == ['d0_e0', 'd0_e1'] assert res['a0_c2', 'b1_f1', 'd3_e2'] == arr['a0', 'b1', 'c2', 'd3', 'e2', 'f1'] res = arr.combine_axes([('a', 'c'), ('b', 'e', 'f')]) assert res.axes.names == ['a_c', 'b_e_f', 'd'] assert res.size == arr.size assert res.shape == (2 * 4, 3 * 3 * 2, 4) assert list(res.axes.b_e_f.labels[:4]) == ['b0_e0_f0', 'b0_e0_f1', 'b0_e1_f0', 'b0_e1_f1'] assert_array_equal(res['a0_c2', 'b1_e2_f1'], arr['a0', 'b1', 'c2', 'e2', 'f1']) # using a dict (-> user defined axes names) res = arr.combine_axes({('a', 'c'): 'AC', ('b', 'f'): 'BF', ('d', 'e'): 'DE'}) assert res.axes.names == ['AC', 'BF', 'DE'] assert res.size == arr.size assert res.shape == (2 * 4, 3 * 2, 4 * 3) res = arr.combine_axes({('a', 'c'): 'AC', ('b', 'e', 'f'): 'BEF'}) assert res.axes.names == ['AC', 'BEF', 'd'] assert res.size == arr.size assert res.shape == (2 * 4, 3 * 3 * 2, 4) # combine with wildcard=True arr = ndtest((2, 3)) res = arr.combine_axes(wildcard=True) assert res.axes.names == ['a_b'] assert res.size == arr.size assert res.shape == (6,) assert_array_equal(res.axes[0].labels, np.arange(6)) def test_split_axes(): # split one axis # ============== # default sep arr = ndtest((2, 3, 4, 5)) combined = arr.combine_axes(('b', 'd')) assert combined.axes.names == ['a', 'b_d', 'c'] res = combined.split_axes('b_d') assert res.axes.names == ['a', 'b', 'd', 'c'] assert res.shape == (2, 3, 5, 4) assert_array_equal(res.transpose('a', 'b', 'c', 'd'), arr) # with specified names res = combined.rename(b_d='bd').split_axes('bd', names=('b', 'd')) assert res.axes.names == ['a', 'b', 'd', 'c'] assert res.shape == (2, 3, 5, 4) assert_array_equal(res.transpose('a', 'b', 'c', 'd'), arr) # regex res = combined.split_axes('b_d', names=['b', 'd'], regex=r'(\w+)_(\w+)') assert res.axes.names == ['a', 'b', 'd', 'c'] assert res.shape == (2, 3, 5, 4) assert_array_equal(res.transpose('a', 'b', 'c', 'd'), arr) # custom sep combined = ndtest('a|b=a0|b0,a0|b1') res = combined.split_axes(sep='|') assert_array_equal(res, ndtest('a=a0;b=b0,b1')) # split several axes at once # ========================== arr = ndtest('a_b=a0_b0..a1_b2; c=c0..c3; d=d0..d3; e_f=e0_f0..e2_f1') # using a list of tuples res = arr.split_axes(['a_b', 'e_f']) assert res.axes.names == ['a', 'b', 'c', 'd', 'e', 'f'] assert res.size == arr.size assert res.shape == (2, 3, 4, 4, 3, 2) assert list(res.axes.a.labels) == ['a0', 'a1'] assert list(res.axes.b.labels) == ['b0', 'b1', 'b2'] assert list(res.axes.e.labels) == ['e0', 'e1', 'e2'] assert list(res.axes.f.labels) == ['f0', 'f1'] assert res['a0', 'b1', 'c2', 'd3', 'e2', 'f1'] == arr['a0_b1', 'c2', 'd3', 'e2_f1'] # default to all axes with name containing the delimiter _ assert_array_equal(arr.split_axes(), res) # using a dict (-> user defined axes names) res = arr.split_axes({'a_b': ('A', 'B'), 'e_f': ('E', 'F')}) assert res.axes.names == ['A', 'B', 'c', 'd', 'E', 'F'] assert res.size == arr.size assert res.shape == (2, 3, 4, 4, 3, 2) # split an axis in more than 2 axes arr = ndtest('a_b_c=a0_b0_c0..a1_b2_c3; d=d0..d3; e_f=e0_f0..e2_f1') res = arr.split_axes(['a_b_c', 'e_f']) assert res.axes.names == ['a', 'b', 'c', 'd', 'e', 'f'] assert res.size == arr.size assert res.shape == (2, 3, 4, 4, 3, 2) assert list(res.axes.a.labels) == ['a0', 'a1'] assert list(res.axes.b.labels) == ['b0', 'b1', 'b2'] assert list(res.axes.e.labels) == ['e0', 'e1', 'e2'] assert list(res.axes.f.labels) == ['f0', 'f1'] assert res['a0', 'b1', 'c2', 'd3', 'e2', 'f1'] == arr['a0_b1_c2', 'd3', 'e2_f1'] # split an axis in more than 2 axes + passing a dict res = arr.split_axes({'a_b_c': ('A', 'B', 'C'), 'e_f': ('E', 'F')}) assert res.axes.names == ['A', 'B', 'C', 'd', 'E', 'F'] assert res.size == arr.size assert res.shape == (2, 3, 4, 4, 3, 2) # using regex arr = ndtest('ab=a0b0..a1b2; c=c0..c3; d=d0..d3; ef=e0f0..e2f1') res = arr.split_axes({'ab': ('a', 'b'), 'ef': ('e', 'f')}, regex=r'(\w{2})(\w{2})') assert res.axes.names == ['a', 'b', 'c', 'd', 'e', 'f'] assert res.size == arr.size assert res.shape == (2, 3, 4, 4, 3, 2) assert list(res.axes.a.labels) == ['a0', 'a1'] assert list(res.axes.b.labels) == ['b0', 'b1', 'b2'] assert list(res.axes.e.labels) == ['e0', 'e1', 'e2'] assert list(res.axes.f.labels) == ['f0', 'f1'] assert res['a0', 'b1', 'c2', 'd3', 'e2', 'f1'] == arr['a0b1', 'c2', 'd3', 'e2f1'] # labels with object dtype arr = ndtest((2, 2, 2)).combine_axes(('a', 'b')) arr = arr.set_axes([Axis(a.labels.astype(object), a.name) for a in arr.axes]) res = arr.split_axes() expected_kind = 'U' if sys.version_info[0] >= 3 else 'S' assert res.a.labels.dtype.kind == expected_kind assert res.b.labels.dtype.kind == expected_kind assert res.c.labels.dtype.kind == 'O' assert_array_equal(res, ndtest((2, 2, 2))) # not sorted by first part then second part (issue #364) arr = ndtest((2, 3)) combined = arr.combine_axes()['a0_b0, a1_b0, a0_b1, a1_b1, a0_b2, a1_b2'] assert_array_equal(combined.split_axes('a_b'), arr) # another weirdly sorted test combined = arr.combine_axes()['a0_b1, a0_b0, a0_b2, a1_b1, a1_b0, a1_b2'] assert_array_equal(combined.split_axes('a_b'), arr['b1,b0,b2']) # combined does not contain all combinations of labels (issue #369) combined_partial = combined[['a0_b0', 'a0_b1', 'a1_b1', 'a0_b2', 'a1_b2']] expected = arr.astype(float) expected['a1', 'b0'] = nan assert_array_nan_equal(combined_partial.split_axes('a_b'), expected) # split labels are ambiguous (issue #485) combined = ndtest('a_b=a0_b0..a1_b1;c_d=a0_b0..a1_b1') expected = ndtest('a=a0,a1;b=b0,b1;c=a0,a1;d=b0,b1') assert_array_equal(combined.split_axes(('a_b', 'c_d')), expected) # anonymous axes combined = ndtest('a0_b0,a0_b1,a0_b2,a1_b0,a1_b1,a1_b2') expected = ndtest('a0,a1;b0,b1,b2') assert_array_equal(combined.split_axes(0), expected) # when no axis is specified and no axis contains the sep, split_axes is a no-op. assert_array_equal(combined.split_axes(), combined) def test_stack(): # stack along a single axis # ========================= # simple a = Axis('a=a0,a1,a2') b = Axis('b=b0,b1') arr0 = ndtest(a) arr1 = ndtest(a, start=-1) res = stack((arr0, arr1), b) expected = Array([[0, -1], [1, 0], [2, 1]], [a, b]) assert_array_equal(res, expected) # same but using a group as the stacking axis larger_b = Axis('b=b0..b3') res = stack((arr0, arr1), larger_b[:'b1']) assert_array_equal(res, expected) # simple with anonymous axis axis0 = Axis(3) arr0 = ndtest(axis0) arr1 = ndtest(axis0, start=-1) res = stack((arr0, arr1), b) expected = Array([[0, -1], [1, 0], [2, 1]], [axis0, b]) assert_array_equal(res, expected) # using res_axes res = stack({'b0': 0, 'b1': 1}, axes=b, res_axes=(a, b)) expected = Array([[0, 1], [0, 1], [0, 1]], [a, b]) assert_array_equal(res, expected) # giving elements as on Array containing Arrays sex = Axis('sex=M,F') # not using the same length for nat and type, otherwise numpy gets confused :( arr1 = ones('nat=BE, FO') arr2 = zeros('type=1..3') array_of_arrays = Array([arr1, arr2], sex) res = stack(array_of_arrays, sex) expected = from_string(r"""nat type\sex M F BE 1 1.0 0.0 BE 2 1.0 0.0 BE 3 1.0 0.0 FO 1 1.0 0.0 FO 2 1.0 0.0 FO 3 1.0 0.0""") assert_array_equal(res, expected) # non scalar/non Array res = stack(([1, 2, 3], [4, 5, 6])) expected = Array([[1, 4], [2, 5], [3, 6]]) assert_array_equal(res, expected) # stack along multiple axes # ========================= # a) simple res = stack({('a0', 'b0'): 0, ('a0', 'b1'): 1, ('a1', 'b0'): 2, ('a1', 'b1'): 3, ('a2', 'b0'): 4, ('a2', 'b1'): 5}, (a, b)) expected = ndtest((a, b)) assert_array_equal(res, expected) # b) keys not given in axes iteration order res = stack({('a0', 'b0'): 0, ('a1', 'b0'): 2, ('a2', 'b0'): 4, ('a0', 'b1'): 1, ('a1', 'b1'): 3, ('a2', 'b1'): 5}, (a, b)) expected = ndtest((a, b)) assert_array_equal(res, expected) # c) key parts not given in the order of axes (ie key part for b before key part for a) res = stack({('a0', 'b0'): 0, ('a1', 'b0'): 1, ('a2', 'b0'): 2, ('a0', 'b1'): 3, ('a1', 'b1'): 4, ('a2', 'b1'): 5}, (b, a)) expected = ndtest((b, a)) assert_array_equal(res, expected) # d) same as c) but with a key-value sequence res = stack([(('a0', 'b0'), 0), (('a1', 'b0'), 1), (('a2', 'b0'), 2), (('a0', 'b1'), 3), (('a1', 'b1'), 4), (('a2', 'b1'), 5)], (b, a)) expected = ndtest((b, a)) assert_array_equal(res, expected) @needs_python36 def test_stack_kwargs_no_axis_labels(): # these tests rely on kwargs ordering, hence python 3.6 # 1) using scalars # ---------------- # a) with an axis name res = stack(a0=0, a1=1, axes='a') expected = Array([0, 1], 'a=a0,a1') assert_array_equal(res, expected) # b) without an axis name res = stack(a0=0, a1=1) expected = Array([0, 1], 'a0,a1') assert_array_equal(res, expected) # 2) dict of arrays # ----------------- a = Axis('a=a0,a1,a2') arr0 = ndtest(a) arr1 = ndtest(a, start=-1) # a) with an axis name res = stack(b0=arr0, b1=arr1, axes='b') expected = Array([[0, -1], [1, 0], [2, 1]], [a, 'b=b0,b1']) assert_array_equal(res, expected) # b) without an axis name res = stack(b0=arr0, b1=arr1) expected = Array([[0, -1], [1, 0], [2, 1]], [a, 'b0,b1']) assert_array_equal(res, expected) @needs_python37 def test_stack_dict_no_axis_labels(): # these tests rely on dict ordering, hence python 3.7 # 1) dict of scalars # ------------------ # a) with an axis name res = stack({'a0': 0, 'a1': 1}, 'a') expected = Array([0, 1], 'a=a0,a1') assert_array_equal(res, expected) # b) without an axis name res = stack({'a0': 0, 'a1': 1}) expected = Array([0, 1], 'a0,a1') assert_array_equal(res, expected) # 2) dict of arrays # ----------------- a = Axis('a=a0,a1,a2') arr0 = ndtest(a) arr1 = ndtest(a, start=-1) # a) with an axis name res = stack({'b0': arr0, 'b1': arr1}, 'b') expected = Array([[0, -1], [1, 0], [2, 1]], [a, 'b=b0,b1']) assert_array_equal(res, expected) # b) without an axis name res = stack({'b0': arr0, 'b1': arr1}) expected = Array([[0, -1], [1, 0], [2, 1]], [a, 'b0,b1']) assert_array_equal(res, expected) def test_0darray_convert(): int_arr = Array(1) assert int(int_arr) == 1 assert float(int_arr) == 1.0 assert int_arr.__index__() == 1 float_arr = Array(1.0) assert int(float_arr) == 1 assert float(float_arr) == 1.0 with pytest.raises(TypeError) as e_info: float_arr.__index__() msg = e_info.value.args[0] expected_np11 = "only integer arrays with one element can be converted to an index" expected_np12 = "only integer scalar arrays can be converted to a scalar index" assert msg in {expected_np11, expected_np12} def test_deprecated_methods(): with pytest.warns(FutureWarning) as caught_warnings: ndtest((2, 2)).with_axes('a', 'd=d0,d1') assert len(caught_warnings) == 1 assert caught_warnings[0].message.args[0] == "with_axes() is deprecated. Use set_axes() instead." assert caught_warnings[0].filename == __file__ with pytest.warns(FutureWarning) as caught_warnings: ndtest((2, 2)).combine_axes().split_axis() assert len(caught_warnings) == 1 assert caught_warnings[0].message.args[0] == "split_axis() is deprecated. Use split_axes() instead." assert caught_warnings[0].filename == __file__ def test_eq(): a = ndtest((2, 3, 4)) ao = a.astype(object) assert_array_equal(ao.eq(ao['c0'], nans_equal=True), a == a['c0']) if __name__ == "__main__": # import doctest # import unittest # from larray import core # doctest.testmod(core) # unittest.main() pytest.main()
gpl-3.0