repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
jnerin/ansible
refs/heads/devel
lib/ansible/modules/cloud/vultr/vr_server.py
14
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2017, René Moser <mail@renemoser.net> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: vr_server short_description: Manages virtual servers on Vultr. description: - Deploy, start, stop, update, restart, reinstall servers. version_added: "2.5" author: "René Moser (@resmo)" options: name: description: - Name of the server. required: true aliases: [ label ] hostname: description: - Hostname to assign to this server. os: description: - The operating system. - Required if the server does not yet exist. firewall_group: description: - The firewall group to assign this server to. plan: description: - Plan to use for the server. - Required if the server does not yet exist. force: description: - Force stop/start the server if required to apply changes - Otherwise a running server will not be changed. notify_activate: description: - Whether to send an activation email when the server is ready or not. - Only considered on creation. type: bool private_network_enabled: description: - Whether to enable private networking or not. type: bool auto_backup_enabled: description: - Whether to enable automatic backups or not. type: bool ipv6_enabled: description: - Whether to enable IPv6 or not. type: bool tag: description: - Tag for the server. user_data: description: - User data to be passed to the server. startup_script: description: - Name of the startup script to execute on boot. - Only considered while creating the server. ssh_keys: description: - List of SSH keys passed to the server on creation. aliases: [ ssh_key ] reserved_ip_v4: description: - IP address of the floating IP to use as the main IP of this server. - Only considered on creation. region: description: - Region the server is deployed into. - Required if the server does not yet exist. state: description: - State of the server. default: present choices: [ present, absent, restarted, reinstalled, started, stopped ] extends_documentation_fragment: vultr ''' EXAMPLES = ''' - name: create server local_action: module: vr_server name: "{{ vr_server_name }}" os: CentOS 7 x64 plan: 1024 MB RAM,25 GB SSD,1.00 TB BW region: Amsterdam state: present - name: ensure a server is present and started local_action: module: vr_server name: "{{ vr_server_name }}" os: CentOS 7 x64 plan: 1024 MB RAM,25 GB SSD,1.00 TB BW region: Amsterdam state: started - name: ensure a server is present and stopped local_action: module: vr_server name: "{{ vr_server_name }}" os: CentOS 7 x64 plan: 1024 MB RAM,25 GB SSD,1.00 TB BW region: Amsterdam state: stopped - name: ensure an existing server is stopped local_action: module: vr_server name: "{{ vr_server_name }}" state: stopped - name: ensure an existing server is started local_action: module: vr_server name: "{{ vr_server_name }}" state: started - name: ensure a server is absent local_action: module: vr_server name: "{{ vr_server_name }}" state: absent ''' RETURN = ''' --- vultr_api: description: Response from Vultr API with a few additions/modification returned: success type: complex contains: api_account: description: Account used in the ini file to select the key returned: success type: string sample: default api_timeout: description: Timeout used for the API requests returned: success type: int sample: 60 api_retries: description: Amount of max retries for the API requests returned: success type: int sample: 5 api_endpoint: description: Endpoint used for the API requests returned: success type: string sample: "https://api.vultr.com" vultr_server: description: Response from Vultr API with a few additions/modification returned: success type: complex contains: id: description: ID of the server returned: success type: string sample: 10194376 name: description: Name (label) of the server returned: success type: string sample: "ansible-test-vm" plan: description: Plan used for the server returned: success type: string sample: "1024 MB RAM,25 GB SSD,1.00 TB BW" allowed_bandwidth_gb: description: Allowed bandwidth to use in GB returned: success type: int sample: 1000 auto_backup_enabled: description: Whether automatic backups are enabled returned: success type: bool sample: false cost_per_month: description: Cost per month for the server returned: success type: float sample: 5.00 current_bandwidth_gb: description: Current bandwidth used for the server returned: success type: int sample: 0 date_created: description: Date when the server was created returned: success type: string sample: "2017-08-26 12:47:48" default_password: description: Password to login as root into the server returned: success type: string sample: "!p3EWYJm$qDWYaFr" disk: description: Information about the disk returned: success type: string sample: "Virtual 25 GB" v4_gateway: description: IPv4 gateway returned: success type: string sample: "45.32.232.1" internal_ip: description: Internal IP returned: success type: string sample: "" kvm_url: description: URL to the VNC returned: success type: string sample: "https://my.vultr.com/subs/vps/novnc/api.php?data=xyz" region: description: Region the server was deployed into returned: success type: string sample: "Amsterdam" v4_main_ip: description: Main IPv4 returned: success type: string sample: "45.32.233.154" v4_netmask: description: Netmask IPv4 returned: success type: string sample: "255.255.254.0" os: description: Operating system used for the server returned: success type: string sample: "CentOS 6 x64" firewall_group: description: Firewall group the server is assinged to returned: success and available type: string sample: "CentOS 6 x64" pending_charges: description: Pending charges returned: success type: float sample: 0.01 power_status: description: Power status of the server returned: success type: string sample: "running" ram: description: Information about the RAM size returned: success type: string sample: "1024 MB" server_state: description: State about the server returned: success type: string sample: "ok" status: description: Status about the deployment of the server returned: success type: string sample: "active" tag: description: TBD returned: success type: string sample: "" v6_main_ip: description: Main IPv6 returned: success type: string sample: "" v6_network: description: Network IPv6 returned: success type: string sample: "" v6_network_size: description: Network size IPv6 returned: success type: string sample: "" v6_networks: description: Networks IPv6 returned: success type: list sample: [] vcpu_count: description: Virtual CPU count returned: success type: int sample: 1 ''' import time import base64 from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.vultr import ( Vultr, vultr_argument_spec, ) class AnsibleVultrServer(Vultr): def __init__(self, module): super(AnsibleVultrServer, self).__init__(module, "vultr_server") self.server = None self.returns = { 'SUBID': dict(key='id'), 'label': dict(key='name'), 'date_created': dict(), 'allowed_bandwidth_gb': dict(convert_to='int'), 'auto_backups': dict(key='auto_backup_enabled', convert_to='bool'), 'current_bandwidth_gb': dict(), 'kvm_url': dict(), 'default_password': dict(), 'internal_ip': dict(), 'disk': dict(), 'cost_per_month': dict(convert_to='float'), 'location': dict(key='region'), 'main_ip': dict(key='v4_main_ip'), 'network_v4': dict(key='v4_network'), 'gateway_v4': dict(key='v4_gateway'), 'os': dict(), 'pending_charges': dict(convert_to='float'), 'power_status': dict(), 'ram': dict(), 'plan': dict(), 'server_state': dict(), 'status': dict(), 'firewall_group': dict(), 'tag': dict(), 'v6_main_ip': dict(), 'v6_network': dict(), 'v6_network_size': dict(), 'v6_networks': dict(), 'vcpu_count': dict(convert_to='int'), } self.server_power_state = None def get_startup_script(self): return self.query_resource_by_key( key='name', value=self.module.params.get('startup_script'), resource='startupscript', ) def get_os(self): return self.query_resource_by_key( key='name', value=self.module.params.get('os'), resource='os', use_cache=True ) def get_ssh_key(self): return self.query_resource_by_key( key='name', value=self.module.params.get('ssh_key'), resource='sshkey', use_cache=True ) def get_region(self): return self.query_resource_by_key( key='name', value=self.module.params.get('region'), resource='regions', use_cache=True ) def get_plan(self): return self.query_resource_by_key( key='name', value=self.module.params.get('plan'), resource='plans', use_cache=True ) def get_firewall_group(self): return self.query_resource_by_key( key='description', value=self.module.params.get('firewall_group'), resource='firewall', query_by='group_list' ) def get_user_data(self): user_data = self.module.params.get('user_data') if user_data is not None: user_data = base64.b64encode(str(user_data)) return user_data def get_server_user_data(self, server): if not server or not server.get('SUBID'): return None user_data = self.api_query(path="/v1/server/get_user_data?SUBID=%s" % server.get('SUBID')) return user_data.get('userdata') def get_server(self, refresh=False): if self.server is None or refresh: self.server = None server_list = self.api_query(path="/v1/server/list") if server_list: for server_id, server_data in server_list.items(): if server_data.get('label') == self.module.params.get('name'): self.server = server_data plan = self.query_resource_by_key( key='VPSPLANID', value=server_data['VPSPLANID'], resource='plans', use_cache=True ) self.server['plan'] = plan.get('name') os = self.query_resource_by_key( key='OSID', value=int(server_data['OSID']), resource='os', use_cache=True ) self.server['os'] = os.get('name') fwg_id = server_data.get('FIREWALLGROUPID') fw = self.query_resource_by_key( key='FIREWALLGROUPID', value=server_data.get('FIREWALLGROUPID') if fwg_id and fwg_id != "0" else None, resource='firewall', query_by='group_list', use_cache=True ) self.server['firewall_group'] = fw.get('description') return self.server def present_server(self, start_server=True): server = self.get_server() if not server: server = self._create_server(server=server) else: server = self._update_server(server=server, start_server=start_server) return server def _create_server(self, server=None): required_params = [ 'os', 'plan', 'region', ] self.module.fail_on_missing_params(required_params=required_params) self.result['changed'] = True if not self.module.check_mode: data = { 'DCID': self.get_region().get('DCID'), 'VPSPLANID': self.get_plan().get('VPSPLANID'), 'FIREWALLGROUPID': self.get_firewall_group().get('FIREWALLGROUPID'), 'OSID': self.get_os().get('OSID'), 'label': self.module.params.get('name'), 'hostname': self.module.params.get('hostname'), 'SSHKEYID': self.get_ssh_key().get('SSHKEYID'), 'enable_ipv6': self.get_yes_or_no('ipv6_enabled'), 'enable_private_network': self.get_yes_or_no('private_network_enabled'), 'auto_backups': self.get_yes_or_no('auto_backup_enabled'), 'notify_activate': self.get_yes_or_no('notify_activate'), 'tag': self.module.params.get('tag'), 'reserved_ip_v4': self.module.params.get('reserved_ip_v4'), 'user_data': self.get_user_data(), 'SCRIPTID': self.get_startup_script().get('SCRIPTID'), } self.api_query( path="/v1/server/create", method="POST", data=data ) server = self._wait_for_state(key='status', state='active') server = self._wait_for_state(state='running') return server def _update_auto_backups_setting(self, server, start_server): auto_backup_enabled_changed = self.switch_enable_disable(server, 'auto_backup_enabled', 'auto_backups') if auto_backup_enabled_changed: if auto_backup_enabled_changed == "enable" and server['auto_backups'] == 'disable': self.module.warn("Backups are disabled. Once disabled, backups can only be enabled again by customer support") else: server, warned = self._handle_power_status_for_update(server, start_server) if not warned: self.result['changed'] = True self.result['diff']['before']['auto_backup_enabled'] = server.get('auto_backups') self.result['diff']['after']['auto_backup_enabled'] = self.get_yes_or_no('auto_backup_enabled') if not self.module.check_mode: data = { 'SUBID': server['SUBID'] } self.api_query( path="/v1/server/backup_%s" % auto_backup_enabled_changed, method="POST", data=data ) server = self._wait_for_state(key='server_state', state='ok') return server def _update_ipv6_setting(self, server, start_server): ipv6_enabled_changed = self.switch_enable_disable(server, 'ipv6_enabled', 'v6_main_ip') if ipv6_enabled_changed: if ipv6_enabled_changed == "disable": self.module.warn("The Vultr API does not allow to disable IPv6") else: server, warned = self._handle_power_status_for_update(server, start_server) if not warned: self.result['changed'] = True self.result['diff']['before']['ipv6_enabled'] = False self.result['diff']['after']['ipv6_enabled'] = True if not self.module.check_mode: data = { 'SUBID': server['SUBID'] } self.api_query( path="/v1/server/ipv6_%s" % ipv6_enabled_changed, method="POST", data=data ) server = self._wait_for_state(key='server_state', state='ok') server = self._wait_for_state(key='v6_main_ip') return server def _update_private_network_setting(self, server, start_server): private_network_enabled_changed = self.switch_enable_disable(server, 'private_network_enabled', 'internal_ip') if private_network_enabled_changed: if private_network_enabled_changed == "disable": self.module.warn("The Vultr API does not allow to disable private network") else: server, warned = self._handle_power_status_for_update(server, start_server) if not warned: self.result['changed'] = True self.result['diff']['before']['private_network_enabled'] = False self.result['diff']['after']['private_network_enabled'] = True if not self.module.check_mode: data = { 'SUBID': server['SUBID'] } self.api_query( path="/v1/server/private_network_%s" % private_network_enabled_changed, method="POST", data=data ) server = self._wait_for_state(key='server_state', state='ok') return server def _update_plan_setting(self, server, start_server): plan = self.get_plan() plan_changed = True if plan and plan['VPSPLANID'] != server.get('VPSPLANID') else False if plan_changed: server, warned = self._handle_power_status_for_update(server, start_server) if not warned: self.result['changed'] = True self.result['diff']['before']['plan'] = server.get('plan') self.result['diff']['after']['plan'] = plan['name'] if not self.module.check_mode: data = { 'SUBID': server['SUBID'], 'VPSPLANID': plan['VPSPLANID'], } self.api_query( path="/v1/server/upgrade_plan", method="POST", data=data ) server = self._wait_for_state(key='server_state', state='ok') return server def _handle_power_status_for_update(self, server, start_server): # Remember the power state before we handle any action if self.server_power_state is None: self.server_power_state = server['power_status'] # A stopped server can be updated if self.server_power_state == "stopped": return server, False # A running server must be forced to update unless the wanted state is stopped elif self.module.params.get('force') or not start_server: warned = False if not self.module.check_mode: # Some update APIs would restart the VM, we handle the restart manually # by stopping the server and start it at the end of the changes server = self.stop_server(skip_results=True) # Warn the user that a running server won't get changed else: warned = True self.module.warn("Some changes won't be applied to running instances. " + "Use force=true to allow the instance %s to be stopped/started." % server['label']) return server, warned def _update_server(self, server=None, start_server=True): # Update auto backups settings, stops server server = self._update_auto_backups_setting(server=server, start_server=start_server) # Update IPv6 settings, stops server server = self._update_ipv6_setting(server=server, start_server=start_server) # Update private network settings, stops server server = self._update_private_network_setting(server=server, start_server=start_server) # Update plan settings, stops server server = self._update_plan_setting(server=server, start_server=start_server) # User data user_data = self.get_user_data() server_user_data = self.get_server_user_data(server=server) if user_data is not None and user_data != server_user_data: self.result['changed'] = True self.result['diff']['before']['tag'] = server_user_data self.result['diff']['after']['tag'] = user_data if not self.module.check_mode: data = { 'SUBID': server['SUBID'], 'userdata': user_data, } self.api_query( path="/v1/server/set_user_data", method="POST", data=data ) # Tags tag = self.module.params.get('tag') if tag is not None and tag != server.get('tag'): self.result['changed'] = True self.result['diff']['before']['tag'] = server.get('tag') self.result['diff']['after']['tag'] = tag if not self.module.check_mode: data = { 'SUBID': server['SUBID'], 'tag': tag, } self.api_query( path="/v1/server/tag_set", method="POST", data=data ) # Firewall group firewall_group = self.get_firewall_group() if firewall_group and firewall_group.get('description') != server.get('firewall_group'): self.result['changed'] = True self.result['diff']['before']['firewall_group'] = server.get('firewall_group') self.result['diff']['after']['firewall_group'] = firewall_group.get('description') if not self.module.check_mode: data = { 'SUBID': server['SUBID'], 'FIREWALLGROUPID': firewall_group.get('FIREWALLGROUPID'), } self.api_query( path="/v1/server/firewall_group_set", method="POST", data=data ) # Start server again if it was running before the changes if not self.module.check_mode: if self.server_power_state in ['starting', 'running'] and start_server: server = self.start_server(skip_results=True) server = self._wait_for_state(key='server_state', state='ok') return server def absent_server(self): server = self.get_server() if server: self.result['changed'] = True self.result['diff']['before']['id'] = server['SUBID'] self.result['diff']['after']['id'] = "" if not self.module.check_mode: data = { 'SUBID': server['SUBID'] } self.api_query( path="/v1/server/destroy", method="POST", data=data ) for s in range(0, 30): if server is not None: break time.sleep(2) server = self.get_server(refresh=True) else: self.fail_json(msg="Wait for server '%s' to get deleted timed out" % server['label']) return server def restart_server(self): self.result['changed'] = True server = self.get_server() if server: if not self.module.check_mode: data = { 'SUBID': server['SUBID'] } self.api_query( path="/v1/server/reboot", method="POST", data=data ) server = self._wait_for_state(state='running') return server def reinstall_server(self): self.result['changed'] = True server = self.get_server() if server: if not self.module.check_mode: data = { 'SUBID': server['SUBID'] } self.api_query( path="/v1/server/reinstall", method="POST", data=data ) server = self._wait_for_state(state='running') return server def _wait_for_state(self, key='power_status', state=None): time.sleep(1) server = self.get_server(refresh=True) for s in range(0, 30): # Check for Truely if wanted state is None if state is None and server.get(key): break elif server.get(key) == state: break time.sleep(2) server = self.get_server(refresh=True) # Timed out else: if state is None: msg = "Wait for '%s' timed out" % key else: msg = "Wait for '%s' to get into state '%s' timed out" % (key, state) self.fail_json(msg=msg) return server def start_server(self, skip_results=False): server = self.get_server() if server: if server['power_status'] == 'starting': server = self._wait_for_state(state='running') elif server['power_status'] != 'running': if not skip_results: self.result['changed'] = True self.result['diff']['before']['power_status'] = server['power_status'] self.result['diff']['after']['power_status'] = "running" if not self.module.check_mode: data = { 'SUBID': server['SUBID'] } self.api_query( path="/v1/server/start", method="POST", data=data ) server = self._wait_for_state(state='running') return server def stop_server(self, skip_results=False): server = self.get_server() if server and server['power_status'] != "stopped": if not skip_results: self.result['changed'] = True self.result['diff']['before']['power_status'] = server['power_status'] self.result['diff']['after']['power_status'] = "stopped" if not self.module.check_mode: data = { 'SUBID': server['SUBID'], } self.api_query( path="/v1/server/halt", method="POST", data=data ) server = self._wait_for_state(state='stopped') return server def main(): argument_spec = vultr_argument_spec() argument_spec.update(dict( name=dict(required=True, aliases=['label']), hostname=dict(), os=dict(), plan=dict(), force=dict(type='bool', default=False), notify_activate=dict(type='bool', default=False), private_network_enabled=dict(type='bool'), auto_backup_enabled=dict(type='bool'), ipv6_enabled=dict(type='bool'), tag=dict(), reserved_ip_v4=dict(), firewall_group=dict(), startup_script=dict(), user_data=dict(), ssh_keys=dict(type='list', aliases=['ssh_key']), region=dict(), state=dict(choices=['present', 'absent', 'restarted', 'reinstalled', 'started', 'stopped'], default='present'), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) vr_server = AnsibleVultrServer(module) if module.params.get('state') == "absent": server = vr_server.absent_server() else: if module.params.get('state') == "started": server = vr_server.present_server() server = vr_server.start_server() elif module.params.get('state') == "stopped": server = vr_server.present_server(start_server=False) server = vr_server.stop_server() elif module.params.get('state') == "restarted": server = vr_server.present_server() server = vr_server.restart_server() elif module.params.get('state') == "reinstalled": server = vr_server.reinstall_server() else: server = vr_server.present_server() result = vr_server.get_result(server) module.exit_json(**result) if __name__ == '__main__': main()
JorgeCoock/django
refs/heads/master
tests/version/tests.py
352
from unittest import TestCase from django import get_version from django.utils import six class VersionTests(TestCase): def test_development(self): ver_tuple = (1, 4, 0, 'alpha', 0) # This will return a different result when it's run within or outside # of a git clone: 1.4.devYYYYMMDDHHMMSS or 1.4. ver_string = get_version(ver_tuple) six.assertRegex(self, ver_string, r'1\.4(\.dev[0-9]+)?') def test_releases(self): tuples_to_strings = ( ((1, 4, 0, 'alpha', 1), '1.4a1'), ((1, 4, 0, 'beta', 1), '1.4b1'), ((1, 4, 0, 'rc', 1), '1.4c1'), ((1, 4, 0, 'final', 0), '1.4'), ((1, 4, 1, 'rc', 2), '1.4.1c2'), ((1, 4, 1, 'final', 0), '1.4.1'), ) for ver_tuple, ver_string in tuples_to_strings: self.assertEqual(get_version(ver_tuple), ver_string)
focode/buddy2
refs/heads/master
src/buddy/forms.py
1
from __future__ import unicode_literals from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions from django.contrib.auth import get_user_model from . import models from datetimewidget.widgets import DateTimeWidget class UserProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Submit('update', 'Update', css_class="btn-success"), ) class Meta: model = models.usersProfiles fields = "__all__" class boozProfilesForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(boozProfilesForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Submit('update', 'Update', css_class="btn-success"), ) class Meta: model = models.boozProfiles widgets = { #Use localization and bootstrap 3 'datetime': DateTimeWidget(attrs={'id':"yourdatetimeid"}, usel10n = True, bootstrap_version=3) } fields = ['Booz_shop_location', 'mobile', 'boozshopname', 'boozshopaddress','zipcod','datetime','GendersAllowed','message'] class LocateDrinkersForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(LocateDrinkersForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Submit('update', 'Update', css_class="btn-success"), ) class Meta: model = models.locateDrinkers fields = "__all__" ''' class GuestEntryForm(forms.ModelForm): def __init__(self,*args,**kwargs): super(GuestEntryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Submit('update', 'Update', css_class="btn-success"), ) class Meta: model = models.GuestEntry fields = "__all__" '''
pynag/pynag
refs/heads/master
pynag/Utils/checkresult.py
1
# !/usr/bin/python # # NagiosCheckResult- Class that creates Nagios checkresult file and # writes Passive Host and Service checks to it # # 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 absolute_import import os import tempfile import time service_state = ['OK', 'WARNING', 'CRITICAL', 'UNKNOWN'] host_state = ['UP', 'DOWN', 'DOWN', 'DOWN'] class CheckResult(object): """ Methods for creating host and service checkresults for nagios processing """ def __init__(self, nagios_result_dir, file_time=None): if file_time is not None: self.file_time = file_time else: self.file_time = time.time() # Nagios is quite fussy about the filename, it must be # a 7 character name starting with 'c' self.fh, self.cmd_file = tempfile.mkstemp(prefix='c', dir=nagios_result_dir) os.write(self.fh, "### Active Check Result File ###\n".encode()) os.write(self.fh, "file_time={0}\n".format(str(self.file_time)).encode()) def service_result(self, host_name, service_description, **kwargs): """ Create a service checkresult Any kwarg will be added to the checkresult Args: host_name (str) service_descritpion (str) Kwargs: check_type (int): active(0) or passive(1) check_options (int) scheduled_check (int) reschedule_check (int) latency (float) start_time (float) finish_time (float) early_timeout (int) exited_ok (int) return_code (int) output (str): plugin output """ kwargs.update({ 'host_name': host_name, 'service_description': service_description }) return self.__output_result(**kwargs) def host_result(self, host_name, **kwargs): """ Create a service checkresult Any kwarg will be added to the checkresult Args: host_name (str) service_descritpion (str) Kwargs: check_type (int): active(0) or passive(1) check_options (int) scheduled_check (int) reschedule_check (int) latency (float) start_time (float) finish_time (float) early_timeout (int) exited_ok (int) return_code (int) output (str): plugin output """ kwargs.update({ 'host_name': host_name, }) return self.__output_result(**kwargs) def __output_result(self, **kwargs): """ Create a checkresult Kwargs: host_name (str) service_descritpion (str) check_type (int): active(0) or passive(1) check_options (int) scheduled_check (int) reschedule_check (int) latency (float) start_time (float) finish_time (float) early_timeout (int) exited_ok (int) return_code (int) output (str): plugin output """ parms = { 'check_type': 0, # Active 'check_options': 0, 'scheduled_check': 0, 'reschedule_check': 0, 'latency': 0.0, 'start_time': time.time(), 'finish_time': time.time(), 'early_timeout': 0, 'exited_ok': 0, 'return_code': 0 } parms.update(**kwargs) object_type = 'host' if 'service_description' in parms: object_type = 'service' if 'output' not in parms: if object_type == 'host': parms['output'] = host_state[int(parms['return_code'])] else: parms['output'] = service_state[int(parms['return_code'])] parms['output'].replace('\n', '\\n') os.write(self.fh, """ ### Nagios {1} Check Result ### # Time: {0}\n""".format(self.file_time, object_type.capitalize()).encode()) for key, value in parms.items(): os.write(self.fh, "{0}={1}\n".format(key, str(value)).encode()) def submit(self): """Submits the results to nagios""" os.close(self.fh) ok_filename = self.cmd_file + ".ok" ok_fh = open(ok_filename, 'a') ok_fh.close() return self.cmd_file
Incrediblewheat/PterodactylAttack
refs/heads/master
project/bg/extractSvgLayers.py
2
#!/usr/bin/env python import sys usage = """ extractSvgLayers.py <svg file> Given an SVG file, extract the top level groups into individual two-digit numbered layers (e.g. 00.svg, 01.svg, 02.svg) """ if __name__ == "__main__": args = sys.argv[1:] if len(args) != 1: print usage sys.exit(1) filename = args[0] header = "" gatheringHeader = True num = 0 fileText = None with open(filename) as f: for line in f: # Reached the end of a new top-level group. if line.startswith('</g'): fileText += line # write group text to file filename2 = '%02d.svg' % num with open(filename2, 'w') as f2: f2.write(fileText+"</svg>") print filename2 # increment to next numbered file num += 1 # Reached the start of a new top-level group. if line.startswith('<g'): # Stop gathering the header gatheringHeader = False # Initialize this group to the header and this current line fileText = header + line elif gatheringHeader: # keep building the header header += line else: # add current line to current group text fileText += line
patathor/django-paypal
refs/heads/master
paypal/standard/ipn/south_migrations/0003_auto__add_field_paypalipn_mp_id.py
12
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'PayPalIPN.mp_id' db.add_column(u'paypal_ipn', 'mp_id', self.gf('django.db.models.fields.CharField')(max_length=128, null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'PayPalIPN.mp_id' db.delete_column(u'paypal_ipn', 'mp_id') models = { u'ipn.paypalipn': { 'Meta': {'object_name': 'PayPalIPN', 'db_table': "u'paypal_ipn'"}, 'address_city': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}), 'address_country': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'address_country_code': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'address_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'address_state': ('django.db.models.fields.CharField', [], {'max_length': '40', 'blank': 'True'}), 'address_status': ('django.db.models.fields.CharField', [], {'max_length': '11', 'blank': 'True'}), 'address_street': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}), 'address_zip': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}), 'amount': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'amount1': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'amount2': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'amount3': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'amount_per_cycle': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'auction_buyer_id': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'auction_closing_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'auction_multi_item': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'auth_amount': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'auth_exp': ('django.db.models.fields.CharField', [], {'max_length': '28', 'blank': 'True'}), 'auth_id': ('django.db.models.fields.CharField', [], {'max_length': '19', 'blank': 'True'}), 'auth_status': ('django.db.models.fields.CharField', [], {'max_length': '9', 'blank': 'True'}), 'business': ('django.db.models.fields.CharField', [], {'max_length': '127', 'blank': 'True'}), 'case_creation_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'case_id': ('django.db.models.fields.CharField', [], {'max_length': '14', 'blank': 'True'}), 'case_type': ('django.db.models.fields.CharField', [], {'max_length': '24', 'blank': 'True'}), 'charset': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'contact_phone': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'currency_code': ('django.db.models.fields.CharField', [], {'default': "'USD'", 'max_length': '32', 'blank': 'True'}), 'custom': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'exchange_rate': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '16', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'flag': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'flag_code': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'}), 'flag_info': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'for_auction': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'from_view': ('django.db.models.fields.CharField', [], {'max_length': '6', 'null': 'True', 'blank': 'True'}), 'handling_amount': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'initial_payment_amount': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'invoice': ('django.db.models.fields.CharField', [], {'max_length': '127', 'blank': 'True'}), 'ipaddress': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'blank': 'True'}), 'item_name': ('django.db.models.fields.CharField', [], {'max_length': '127', 'blank': 'True'}), 'item_number': ('django.db.models.fields.CharField', [], {'max_length': '127', 'blank': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'mc_amount1': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'mc_amount2': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'mc_amount3': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'mc_currency': ('django.db.models.fields.CharField', [], {'default': "'USD'", 'max_length': '32', 'blank': 'True'}), 'mc_fee': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'mc_gross': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'mc_handling': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'mc_shipping': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'memo': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'mp_id': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'next_payment_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'notify_version': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'num_cart_items': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'option_name1': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'option_name2': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'outstanding_balance': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'parent_txn_id': ('django.db.models.fields.CharField', [], {'max_length': '19', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '24', 'blank': 'True'}), 'payer_business_name': ('django.db.models.fields.CharField', [], {'max_length': '127', 'blank': 'True'}), 'payer_email': ('django.db.models.fields.CharField', [], {'max_length': '127', 'blank': 'True'}), 'payer_id': ('django.db.models.fields.CharField', [], {'max_length': '13', 'blank': 'True'}), 'payer_status': ('django.db.models.fields.CharField', [], {'max_length': '10', 'blank': 'True'}), 'payment_cycle': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'payment_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'payment_gross': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'payment_status': ('django.db.models.fields.CharField', [], {'max_length': '17', 'blank': 'True'}), 'payment_type': ('django.db.models.fields.CharField', [], {'max_length': '7', 'blank': 'True'}), 'pending_reason': ('django.db.models.fields.CharField', [], {'max_length': '14', 'blank': 'True'}), 'period1': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'period2': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'period3': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'period_type': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'product_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'product_type': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'profile_status': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'protection_eligibility': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'quantity': ('django.db.models.fields.IntegerField', [], {'default': '1', 'null': 'True', 'blank': 'True'}), 'query': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'reason_code': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'reattempt': ('django.db.models.fields.CharField', [], {'max_length': '1', 'blank': 'True'}), 'receipt_id': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'receiver_email': ('django.db.models.fields.EmailField', [], {'max_length': '127', 'blank': 'True'}), 'receiver_id': ('django.db.models.fields.CharField', [], {'max_length': '127', 'blank': 'True'}), 'recur_times': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'recurring': ('django.db.models.fields.CharField', [], {'max_length': '1', 'blank': 'True'}), 'recurring_payment_id': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'remaining_settle': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'residence_country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'blank': 'True'}), 'response': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'retry_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'rp_invoice_id': ('django.db.models.fields.CharField', [], {'max_length': '127', 'blank': 'True'}), 'settle_amount': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'settle_currency': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'shipping': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'shipping_method': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'subscr_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'subscr_effective': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'subscr_id': ('django.db.models.fields.CharField', [], {'max_length': '19', 'blank': 'True'}), 'tax': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '64', 'decimal_places': '2', 'blank': 'True'}), 'test_ipn': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'time_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'transaction_entity': ('django.db.models.fields.CharField', [], {'max_length': '7', 'blank': 'True'}), 'transaction_subject': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'txn_id': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '19', 'blank': 'True'}), 'txn_type': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'verify_sign': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['ipn']
mnahm5/django-estore
refs/heads/master
Lib/site-packages/braintree/merchant_account/individual_details.py
5
from braintree.attribute_getter import AttributeGetter from braintree.merchant_account.address_details import AddressDetails class IndividualDetails(AttributeGetter): detail_list = [ "first_name", "last_name", "email", "phone", "date_of_birth", "ssn_last_4", "address_details", ] def __init__(self, attributes): AttributeGetter.__init__(self, attributes) self.address_details = AddressDetails(attributes.get("address", {})) def __repr__(self): return super(IndividualDetails, self).__repr__(self.detail_list)
veikman/cbg
refs/heads/master
cbg/svg/tag.py
1
# -*- coding: utf-8 -*- '''Tag presentation support.''' # This file is part of CBG. # # CBG 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. # # CBG 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 CBG. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2014-2016 Viktor Eikman from cbg.svg import presenter from cbg.svg import shapes from cbg.svg import wardrobe def default_to_specified_text(method): def replacement(instance, text=None): if text is None: text = str(instance.field) return method(instance, text) return replacement class TagBanner(presenter.SVGPresenter): '''Text atop a rectangular background line built to suit the text. Abstract base class. Intended primarily for use with tag fields, like those in the tag module. By default, the text is taken directly from the field specification. ''' def present(self): self._insert_banner_line() self._insert_banner_text() self.cursor.slide(self.wardrobe.mode.thickness) def _choose_line_mode(self, text): '''Choose a wardrobe mode etc. for the line. No assumptions are made here in this superclass because the only truly standard modal key is used in _choose_text_mode(). ''' raise NotImplementedError def _choose_text_mode(self, text): '''Choose a wardrobe mode etc. for the text.''' self.wardrobe.set_mode(wardrobe.MAIN) @default_to_specified_text def _insert_banner_line(self, text): '''Draw the graphics. If there is text to be drawn, draw a thick line under it. Otherwise, make the line thin, just the wardrobe's thickness. ''' self._choose_text_mode(text) if self.wardrobe.literate: n_lines = len(self._wrap(text, '', '')) else: # We assume that a non-text wardrobe was chosen because there is # no text to display. n_lines = 0 self._choose_line_mode(text) textheight = n_lines * self.wardrobe.line_height boxheight = textheight + self.wardrobe.mode.thickness # Determine the vertical level of the line. self.cursor.slide(boxheight / 2) y_offset = self.cursor.offset self.cursor.slide(-boxheight / 2) # Determine the two anchor points of the line. a = self.origin + (0, y_offset) b = self.origin + (self.size[0], y_offset) # Encode the line. line = shapes.Line.new(a, b, stroke_width=boxheight, **self.wardrobe.to_svg_attributes()) self.append(line) @default_to_specified_text def _insert_banner_text(self, text): self._choose_line_mode(text) if self.field: # Add text to the box. self.cursor.slide(self.wardrobe.mode.thickness / 2) self._choose_text_mode(text) self.insert_paragraph(text) self._choose_line_mode(text) self.cursor.slide(self.wardrobe.mode.thickness / 2) else: self.cursor.slide(self.wardrobe.mode.thickness)
overtherain/scriptfile
refs/heads/master
software/googleAppEngine/google/appengine/api/channel/channel_service_stub.py
3
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Stub version of the Channel API, queues messages and writes them to a log.""" import logging import random import StringIO import time from google.appengine.api import apiproxy_stub from google.appengine.api.channel import channel_service_pb from google.appengine.runtime import apiproxy_errors class ChannelServiceStub(apiproxy_stub.APIProxyStub): """Python only channel service stub. This stub does not use a browser channel to push messages to a client. Instead it queues messages internally. """ CHANNEL_TIMEOUT_SECONDS = 2 XMPP_PUBLIC_IP = '0.1.0.10' CHANNEL_TOKEN_DEFAULT_DURATION = 120 CHANNEL_TOKEN_IDENTIFIER = 'channel' XMPP_PUBLIC_PORT = 80 def __init__(self, log=logging.debug, service_name='channel', time_func=time.time): """Initializer. Args: log: A logger, used for dependency injection. service_name: Service name expected for all calls. time_func: function to get the current time in seconds. """ apiproxy_stub.APIProxyStub.__init__(self, service_name) self._log = log self._time_func = time_func self._connected_channel_messages = {} self._add_event = None self._update_event = None def _Dynamic_CreateChannel(self, request, response): """Implementation of channel.create_channel. Args: request: A ChannelServiceRequest. response: A ChannelServiceResponse """ client_id = request.application_key() if not client_id: raise apiproxy_errors.ApplicationError( channel_service_pb.ChannelServiceError.INVALID_CHANNEL_KEY) if request.has_duration_minutes(): duration = request.duration_minutes() else: duration = ChannelServiceStub.CHANNEL_TOKEN_DEFAULT_DURATION expiration_sec = long(self._time_func() + duration * 60) + 1 token = '-'.join([ChannelServiceStub.CHANNEL_TOKEN_IDENTIFIER, str(random.randint(0, 2 ** 32)), str(expiration_sec), client_id]) self._log('Creating channel token %s with client id %s and duration %s', token, request.application_key(), duration) response.set_token(token) @apiproxy_stub.Synchronized def _Dynamic_SendChannelMessage(self, request, response): """Implementation of channel.send_message. Queues a message to be retrieved by the client when it polls. Args: request: A SendMessageRequest. response: A VoidProto. """ client_id = request.application_key() if not request.message(): raise apiproxy_errors.ApplicationError( channel_service_pb.ChannelServiceError.BAD_MESSAGE) if client_id in self._connected_channel_messages: self._log('Sending a message (%s) to channel with key (%s)', request.message(), client_id) self._connected_channel_messages[client_id].append(request.message()) else: self._log('SKIPPING message (%s) to channel with key (%s): ' 'no clients connected', request.message(), client_id) def client_id_from_token(self, token): """Returns the client id from a given token. Args: token: String representing an instance of a client connection to a client id, returned by CreateChannel. Returns: String representing the client id used to create this token, or None if this token is incorrectly formed and doesn't map to a client id. """ pieces = token.split('-', 3) if len(pieces) == 4: return pieces[3] else: return None def check_token_validity(self, token): """Checks if a token is well-formed and its expiration status. Args: token: a token returned by CreateChannel. Returns: A tuple (syntax_valid, time_valid) where syntax_valid is true if the token is well-formed and time_valid is true if the token is not expired. In other words, a usable token will return (true, true). """ pieces = token.split('-', 3) if len(pieces) != 4: return False, False (constant_identifier, token_id, expiration_sec, clientid) = pieces syntax_valid = ( constant_identifier == ChannelServiceStub.CHANNEL_TOKEN_IDENTIFIER and expiration_sec.isdigit()) time_valid = syntax_valid and long(expiration_sec) > self._time_func() return (syntax_valid, time_valid) @apiproxy_stub.Synchronized def get_channel_messages(self, token): """Returns the pending messages for a given channel. Args: token: String representing the channel. Note that this is the token returned by CreateChannel, not the client id. Returns: List of messages, or None if the channel doesn't exist. The messages are strings. """ self._log('Received request for messages for channel: ' + token) client_id = self.client_id_from_token(token) if client_id in self._connected_channel_messages: return self._connected_channel_messages[client_id] return None @apiproxy_stub.Synchronized def has_channel_messages(self, token): """Checks to see if the given channel has any pending messages. Args: token: String representing the channel. Note that this is the token returned by CreateChannel, not the client id. Returns: True if the channel exists and has pending messages. """ client_id = self.client_id_from_token(token) has_messages = (client_id in self._connected_channel_messages and bool(self._connected_channel_messages[client_id])) self._log('Checking for messages on channel (%s) (%s)', token, has_messages) return has_messages @apiproxy_stub.Synchronized def pop_first_message(self, token): """Returns and clears the first message from the message queue. Args: token: String representing the channel. Note that this is the token returned by CreateChannel, not the client id. Returns: The first message in the queue, or None if no messages. """ if self.has_channel_messages(token): client_id = self.client_id_from_token(token) self._log('Popping first message of queue for channel (%s)', token) return self._connected_channel_messages[client_id].pop(0) return None @apiproxy_stub.Synchronized def clear_channel_messages(self, token): """Clears all messages from the channel. Args: token: String representing the channel. Note that this is the token returned by CreateChannel, not the client id. """ client_id = self.client_id_from_token(token) if client_id: self._log('Clearing messages on channel (' + client_id + ')') if client_id in self._connected_channel_messages: self._connected_channel_messages[client_id] = [] else: self._log('Ignoring clear messages for nonexistent token (' + token + ')') class ChannelPresenceSocket(object): """A socket object to update channel client presence.""" def __init__(self, path, client_id): payload = StringIO.StringIO() body = 'from=%s' % client_id payload.write('%s %s HTTP/1.1\r\n' % ('POST', '/_ah/channel/' + path)) payload.write('Content-Length: %d\r\n' % len(body)) payload.write('Content-Type: application/x-www-form-urlencoded\r\n') payload.write('\r\n') payload.write(body) self.rfile = StringIO.StringIO(payload.getvalue()) self.wfile = StringIO.StringIO() self.wfile_close = self.wfile.close self.wfile.close = self.connection_done def connection_done(self): self.wfile_close() def makefile(self, mode, buffsize): if mode.startswith('w'): return self.wfile else: return self.rfile def close(self): pass def shutdown(self, how): pass def connect_channel_event(self, client_id): """Tell the application that the client has connected.""" return (self.ChannelPresenceSocket('connected/', client_id), (ChannelServiceStub.XMPP_PUBLIC_IP, ChannelServiceStub.XMPP_PUBLIC_PORT)) def add_connect_event(self, client_id): """Add an event to make a POST to the /_ah/channel/connect path. Args: client_id: A client ID used for a particular channel. In production, the BuzzBot will make an HttpOverRpc call to the above path when it receives a presence stanza. We simulate the same thing here by using the dev_appserver's eventing architecture to make a request. Note that this request will be blocked in the dev_appserver if the app.yaml file doesn't contain a channel_presence entry in inbound_services (in production, this is blocked by the reserved_path_prefix_map flag used in ReservedUrls::ShouldBlock, called by AppServerImpl::HandleHttpRequest). """ def DefineSendConnectPresenceCallback(client_id): return lambda: self.connect_channel_event(client_id) self._add_event(0, DefineSendConnectPresenceCallback(client_id), 'channel-connect', client_id) @apiproxy_stub.Synchronized def disconnect_channel_event(self, client_id): """Removes the channel from the list of connected channels.""" self._log('Removing channel %s', client_id) if client_id in self._connected_channel_messages: del self._connected_channel_messages[client_id] return (self.ChannelPresenceSocket('disconnected/', client_id), (ChannelServiceStub.XMPP_PUBLIC_IP, ChannelServiceStub.XMPP_PUBLIC_PORT)) def add_disconnect_event(self, client_id): """Add an event to notify the app if a client has disconnected. Args: client_id: A client ID used for a particular channel. See the comments in add_connect_event above. """ timeout = self._time_func() + ChannelServiceStub.CHANNEL_TIMEOUT_SECONDS def DefineDisconnectCallback(client_id): return lambda: self.disconnect_channel_event(client_id) self._add_event(timeout, DefineDisconnectCallback(client_id), 'channel-disconnect', client_id) @apiproxy_stub.Synchronized def connect_channel(self, token): """Marks the channel identified by the token (token) as connected.""" client_id = self.client_id_from_token(token) if client_id in self._connected_channel_messages: if self._update_event: timeout = self._time_func() + ChannelServiceStub.CHANNEL_TIMEOUT_SECONDS self._update_event('channel-disconnect', client_id, timeout) return self._connected_channel_messages[client_id] = [] if self._add_event: self.add_connect_event(client_id) self.add_disconnect_event(client_id)
chengduoZH/Paddle
refs/heads/develop
python/paddle/fluid/transpiler/details/vars_distributed.py
5
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function from paddle.fluid.framework import Variable class VarStruct(object): """ record part properties of a Variable in python. """ def __init__(self, name, shape, dtype, type, lod_level, persistable): self.name = name self.shape = shape self.dtype = dtype self.type = type self.lod_level = lod_level self.persistable = persistable class VarDistributed(object): """ a class to record the var distributed on parameter servers. the class will record the relationship between origin var and slice var. the slice var's properties, such as type/shape/offset/endpoint. """ def __init__(self, origin_var, slice_var, is_slice=None, block_id=None, offset=None, vtype=None, endpoint=None): """ Args: origin_var(Variable|VarStruct): origin var properties slice_var(Variable|VarStruct): slice var properties is_slice(bool|None): slice or not, slice_var=True/False and its block size > 8192 are the judgement standard. block_id(int|None): the number about the slice var. offset(int|None): if the slice var is sliced, offset is the numel before the var. vtype(str|None): a tag, such as Optimizer/Param/RemoteProfetch. endpoint(str|None): which parameter the slice var on, such as "127.0.0.1:1001" """ if isinstance(origin_var, Variable): self.origin = self.__create_var_struct(origin_var) else: self.origin = origin_var if isinstance(slice_var, Variable): self.slice = self.__create_var_struct(slice_var) else: self.slice = slice_var if self.equal(self.origin, self.slice): self.is_slice = False self.block_id = 0 self.offset = 0 else: self.is_slice = True self.block_id = 0 self.offset = 0 if is_slice is not None: self.is_slice = is_slice if block_id is not None: self.block_id = block_id if offset is not None: self.offset = offset self.vtype = vtype self.endpoint = endpoint @staticmethod def __create_var_struct(var): return VarStruct(var.name, var.shape, var.dtype, var.type, var.lod_level, var.persistable) @staticmethod def equal(var1, var2): """ the two var is equal or not. Returns: bool: equal will return True else False """ assert isinstance(var1, VarStruct) and isinstance(var2, VarStruct) return var1.name == var2.name and \ var1.type == var2.type and \ var1.shape == var2.shape and \ var1.dtype == var2.dtype and \ var1.lod_level == var2.lod_level and \ var1.persistable == var2.persistable def __str__(self): origin_var_str = "{name} : fluid.{type}.shape{shape}.astype({dtype})". \ format(i="{", e="}", name=self.origin.name, type=self.origin.type, shape=self.origin.shape, dtype=self.origin.dtype) slice_var_str = "{name} : fluid.{type}.shape{shape}.astype({dtype})" \ ".slice({is_slice}).block({block_id}).offset({offset})". \ format(i="{", e="}", name=self.slice.name, type=self.slice.type, shape=self.slice.shape, dtype=self.slice.dtype, is_slice=self.is_slice, block_id=self.block_id, offset=self.offset) return "var owned: {}, origin var: ( {} ), slice var: ( {} ), endpoint: {} ".format( self.vtype, origin_var_str, slice_var_str, self.endpoint) class VarsDistributed(object): """ a gather about VarDistributed with many methods to find distributed vars. through the class, we can get overview about the distributed parameters on parameter servers. this class may centralized and convenient for developer to manage and get variable's distribute. other module can also use this to find variables such io.py. """ def __init__(self): self.distributed_vars = [] def add_distributed_var(self, origin_var, slice_var, is_slice=None, block_id=None, offset=None, vtype=None, endpoint=None): """ add distributed var in this. Args: origin_var(Variable|VarStruct): origin var properties slice_var(Variable|VarStruct): slice var properties is_slice(bool|None): slice or not, slice_var=True/False and its block size > 8192 are the judgement standard. block_id(int|None): the number about the slice var. offset(int|None): if the slice var is sliced, offset is the numel before the var. vtype(str|None): a tag, such as Optimizer/Param/RemoteProfetch. endpoint(str|None): which parameter the slice var on, such as "127.0.0.1:1001" Returns: None """ self.distributed_vars.append( VarDistributed(origin_var, slice_var, is_slice, block_id, offset, vtype, endpoint)) def get_distributed_var_by_slice(self, var_name): """ get distributed var by conditions. Args: var_name(str): slice var name, such as "w.traier0.block1" Returns: VarDistributed: distributed var. """ for dist_var in self.distributed_vars: if dist_var.slice.name == var_name: return dist_var return None @staticmethod def equal(var1, var2): """ the two var is equal or not. Returns: bool: equal will return True else False """ return var1.name == var2.name and \ var1.type == var2.type and \ var1.shape == var2.shape and \ var1.dtype == var2.dtype and \ var1.lod_level == var2.lod_level and \ var1.persistable == var2.persistable def get_distributed_var_by_origin_and_ep(self, origin_var_name, endpoint): """ get distributed var by conditions. Args: origin_var_name(str): endpoint(str): the parameter endpoint, such as "127.0.0.1:1001" Returns: VarDistributed: distributed var. """ for dist_var in self.distributed_vars: if dist_var.origin.name == origin_var_name and dist_var.endpoint == endpoint: return dist_var return None def get_distributed_vars_by_vtypes(self, vtypes, groupby=False): """ get distributed vars by conditions. Args: vtype(str|None): distributed var's vtype, such as "Optimizer", "RemotePrefetch" groupby(bool|False): group by origin var or not. Returns: list: distributed var list. dict: distributed var map when groupby=True """ vtype_vars = [] for var in self.distributed_vars: if var.vtype in vtypes: vtype_vars.append(var) if not groupby: return vtype_vars params_map = {} for var in vtype_vars: origin_var_name = var.origin.name if origin_var_name in params_map.keys(): optimizers = params_map.get(origin_var_name) else: optimizers = [] optimizers.append(var) params_map[origin_var_name] = optimizers return params_map def get_distributed_vars_by_ep(self, endpoint, vtype=None): """ get distributed vars by conditions. Args: endpoint(str): the parameter server endpoint, such as "127.0.0.1:2001" vtype(str|None): distributed var's vtype, such as "Optimizer", "RemotePrefetch" Returns: list: distributed var list. """ endpoint_vars = [] for var in self.distributed_vars: if var.endpoint == endpoint: endpoint_vars.append(var) if not vtype: return endpoint_vars vtype_vars = [] for var in endpoint_vars: if var.vtype == vtype: vtype_vars.append(var) return vtype_vars def overview(self): """ get the overview string about all params on all parameter servers. Returns: Str: overview string. """ vars_str = [] for var in self.distributed_vars: vars_str.append(str(var)) return "\n".join(vars_str)
40223249-1/-w16b_test
refs/heads/master
static/Brython3.1.3-20150514-095342/Lib/heapq.py
628
"""Heap queue algorithm (a.k.a. priority queue). Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that a[0] is always its smallest element. Usage: heap = [] # creates an empty heap heappush(heap, item) # pushes a new item on the heap item = heappop(heap) # pops the smallest item from the heap item = heap[0] # smallest item on the heap without popping it heapify(x) # transforms list into a heap, in-place, in linear time item = heapreplace(heap, item) # pops and returns smallest item, and adds # new item; the heap size is unchanged Our API differs from textbook heap algorithms as follows: - We use 0-based indexing. This makes the relationship between the index for a node and the indexes for its children slightly less obvious, but is more suitable since Python uses 0-based indexing. - Our heappop() method returns the smallest item, not the largest. These two make it possible to view the heap as a regular Python list without surprises: heap[0] is the smallest item, and heap.sort() maintains the heap invariant! """ # Original code by Kevin O'Connor, augmented by Tim Peters and Raymond Hettinger __about__ = """Heap queues [explanation by François Pinard] Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that a[0] is always its smallest element. The strange invariant above is meant to be an efficient memory representation for a tournament. The numbers below are `k', not a[k]: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In an usual binary tournament we see in sports, each cell is the winner over the two cells it tops, and we can trace the winner down the tree to see all opponents s/he had. However, in many computer applications of such tournaments, we do not need to trace the history of a winner. To be more memory efficient, when a winner is promoted, we try to replace it by something else at a lower level, and the rule becomes that a cell and the two cells it tops contain three different items, but the top cell "wins" over the two topped cells. If this heap invariant is protected at all time, index 0 is clearly the overall winner. The simplest algorithmic way to remove it and find the "next" winner is to move some loser (let's say cell 30 in the diagram above) into the 0 position, and then percolate this new 0 down the tree, exchanging values, until the invariant is re-established. This is clearly logarithmic on the total number of items in the tree. By iterating over all items, you get an O(n ln n) sort. A nice feature of this sort is that you can efficiently insert new items while the sort is going on, provided that the inserted items are not "better" than the last 0'th element you extracted. This is especially useful in simulation contexts, where the tree holds all incoming events, and the "win" condition means the smallest scheduled time. When an event schedule other events for execution, they are scheduled into the future, so they can easily go into the heap. So, a heap is a good structure for implementing schedulers (this is what I used for my MIDI sequencer :-). Various structures for implementing schedulers have been extensively studied, and heaps are good for this, as they are reasonably speedy, the speed is almost constant, and the worst case is not much different than the average case. However, there are other representations which are more efficient overall, yet the worst cases might be terrible. Heaps are also very useful in big disk sorts. You most probably all know that a big sort implies producing "runs" (which are pre-sorted sequences, which size is usually related to the amount of CPU memory), followed by a merging passes for these runs, which merging is often very cleverly organised[1]. It is very important that the initial sort produces the longest runs possible. Tournaments are a good way to that. If, using all the memory available to hold a tournament, you replace and percolate items that happen to fit the current run, you'll produce runs which are twice the size of the memory for random input, and much better for input fuzzily ordered. Moreover, if you output the 0'th item on disk and get an input which may not fit in the current tournament (because the value "wins" over the last output value), it cannot fit in the heap, so the size of the heap decreases. The freed memory could be cleverly reused immediately for progressively building a second heap, which grows at exactly the same rate the first heap is melting. When the first heap completely vanishes, you switch heaps and start a new run. Clever and quite effective! In a word, heaps are useful memory structures to know. I use them in a few applications, and I think it is good to keep a `heap' module around. :-) -------------------- [1] The disk balancing algorithms which are current, nowadays, are more annoying than clever, and this is a consequence of the seeking capabilities of the disks. On devices which cannot seek, like big tape drives, the story was quite different, and one had to be very clever to ensure (far in advance) that each tape movement will be the most effective possible (that is, will best participate at "progressing" the merge). Some tapes were even able to read backwards, and this was also used to avoid the rewinding time. Believe me, real good tape sorts were quite spectacular to watch! From all times, sorting has always been a Great Art! :-) """ __all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', 'nlargest', 'nsmallest', 'heappushpop'] from itertools import islice, count, tee, chain def heappush(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown(heap, 0, len(heap)-1) def heappop(heap): """Pop the smallest item off the heap, maintaining the heap invariant.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt _siftup(heap, 0) else: returnitem = lastelt return returnitem def heapreplace(heap, item): """Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item! That constrains reasonable uses of this routine unless written as part of a conditional replacement: if item > heap[0]: item = heapreplace(heap, item) """ returnitem = heap[0] # raises appropriate IndexError if heap is empty heap[0] = item _siftup(heap, 0) return returnitem def heappushpop(heap, item): """Fast version of a heappush followed by a heappop.""" if heap and heap[0] < item: item, heap[0] = heap[0], item _siftup(heap, 0) return item def heapify(x): """Transform list into a heap, in-place, in O(len(x)) time.""" n = len(x) # Transform bottom-up. The largest index there's any point to looking at # is the largest with a child index in-range, so must have 2*i + 1 < n, # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1. for i in reversed(range(n//2)): _siftup(x, i) def _heappushpop_max(heap, item): """Maxheap version of a heappush followed by a heappop.""" if heap and item < heap[0]: item, heap[0] = heap[0], item _siftup_max(heap, 0) return item def _heapify_max(x): """Transform list into a maxheap, in-place, in O(len(x)) time.""" n = len(x) for i in reversed(range(n//2)): _siftup_max(x, i) def nlargest(n, iterable): """Find the n largest elements in a dataset. Equivalent to: sorted(iterable, reverse=True)[:n] """ if n < 0: return [] it = iter(iterable) result = list(islice(it, n)) if not result: return result heapify(result) _heappushpop = heappushpop for elem in it: _heappushpop(result, elem) result.sort(reverse=True) return result def nsmallest(n, iterable): """Find the n smallest elements in a dataset. Equivalent to: sorted(iterable)[:n] """ if n < 0: return [] it = iter(iterable) result = list(islice(it, n)) if not result: return result _heapify_max(result) _heappushpop = _heappushpop_max for elem in it: _heappushpop(result, elem) result.sort() return result # 'heap' is a heap at all indices >= startpos, except possibly for pos. pos # is the index of a leaf with a possibly out-of-order value. Restore the # heap invariant. def _siftdown(heap, startpos, pos): newitem = heap[pos] # Follow the path to the root, moving parents down until finding a place # newitem fits. while pos > startpos: parentpos = (pos - 1) >> 1 parent = heap[parentpos] if newitem < parent: heap[pos] = parent pos = parentpos continue break heap[pos] = newitem # The child indices of heap index pos are already heaps, and we want to make # a heap at index pos too. We do this by bubbling the smaller child of # pos up (and so on with that child's children, etc) until hitting a leaf, # then using _siftdown to move the oddball originally at index pos into place. # # We *could* break out of the loop as soon as we find a pos where newitem <= # both its children, but turns out that's not a good idea, and despite that # many books write the algorithm that way. During a heap pop, the last array # element is sifted in, and that tends to be large, so that comparing it # against values starting from the root usually doesn't pay (= usually doesn't # get us out of the loop early). See Knuth, Volume 3, where this is # explained and quantified in an exercise. # # Cutting the # of comparisons is important, since these routines have no # way to extract "the priority" from an array element, so that intelligence # is likely to be hiding in custom comparison methods, or in array elements # storing (priority, record) tuples. Comparisons are thus potentially # expensive. # # On random arrays of length 1000, making this change cut the number of # comparisons made by heapify() a little, and those made by exhaustive # heappop() a lot, in accord with theory. Here are typical results from 3 # runs (3 just to demonstrate how small the variance is): # # Compares needed by heapify Compares needed by 1000 heappops # -------------------------- -------------------------------- # 1837 cut to 1663 14996 cut to 8680 # 1855 cut to 1659 14966 cut to 8678 # 1847 cut to 1660 15024 cut to 8703 # # Building the heap by using heappush() 1000 times instead required # 2198, 2148, and 2219 compares: heapify() is more efficient, when # you can use it. # # The total compares needed by list.sort() on the same lists were 8627, # 8627, and 8632 (this should be compared to the sum of heapify() and # heappop() compares): list.sort() is (unsurprisingly!) more efficient # for sorting. def _siftup(heap, pos): endpos = len(heap) startpos = pos newitem = heap[pos] # Bubble up the smaller child until hitting a leaf. childpos = 2*pos + 1 # leftmost child position while childpos < endpos: # Set childpos to index of smaller child. rightpos = childpos + 1 if rightpos < endpos and not heap[childpos] < heap[rightpos]: childpos = rightpos # Move the smaller child up. heap[pos] = heap[childpos] pos = childpos childpos = 2*pos + 1 # The leaf at pos is empty now. Put newitem there, and bubble it up # to its final resting place (by sifting its parents down). heap[pos] = newitem _siftdown(heap, startpos, pos) def _siftdown_max(heap, startpos, pos): 'Maxheap variant of _siftdown' newitem = heap[pos] # Follow the path to the root, moving parents down until finding a place # newitem fits. while pos > startpos: parentpos = (pos - 1) >> 1 parent = heap[parentpos] if parent < newitem: heap[pos] = parent pos = parentpos continue break heap[pos] = newitem def _siftup_max(heap, pos): 'Maxheap variant of _siftup' endpos = len(heap) startpos = pos newitem = heap[pos] # Bubble up the larger child until hitting a leaf. childpos = 2*pos + 1 # leftmost child position while childpos < endpos: # Set childpos to index of larger child. rightpos = childpos + 1 if rightpos < endpos and not heap[rightpos] < heap[childpos]: childpos = rightpos # Move the larger child up. heap[pos] = heap[childpos] pos = childpos childpos = 2*pos + 1 # The leaf at pos is empty now. Put newitem there, and bubble it up # to its final resting place (by sifting its parents down). heap[pos] = newitem _siftdown_max(heap, startpos, pos) # If available, use C implementation #_heapq does not exist in brython, so lets just comment it out. #try: # from _heapq import * #except ImportError: # pass def merge(*iterables): '''Merge multiple sorted inputs into a single sorted output. Similar to sorted(itertools.chain(*iterables)) but returns a generator, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] ''' _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration _len = len h = [] h_append = h.append for itnum, it in enumerate(map(iter, iterables)): try: next = it.__next__ h_append([next(), itnum, next]) except _StopIteration: pass heapify(h) while _len(h) > 1: try: while True: v, itnum, next = s = h[0] yield v s[0] = next() # raises StopIteration when exhausted _heapreplace(h, s) # restore heap condition except _StopIteration: _heappop(h) # remove empty iterator if h: # fast case when only a single iterator remains v, itnum, next = h[0] yield v yield from next.__self__ # Extend the implementations of nsmallest and nlargest to use a key= argument _nsmallest = nsmallest def nsmallest(n, iterable, key=None): """Find the n smallest elements in a dataset. Equivalent to: sorted(iterable, key=key)[:n] """ # Short-cut for n==1 is to use min() when len(iterable)>0 if n == 1: it = iter(iterable) head = list(islice(it, 1)) if not head: return [] if key is None: return [min(chain(head, it))] return [min(chain(head, it), key=key)] # When n>=size, it's faster to use sorted() try: size = len(iterable) except (TypeError, AttributeError): pass else: if n >= size: return sorted(iterable, key=key)[:n] # When key is none, use simpler decoration if key is None: it = zip(iterable, count()) # decorate result = _nsmallest(n, it) return [r[0] for r in result] # undecorate # General case, slowest method in1, in2 = tee(iterable) it = zip(map(key, in1), count(), in2) # decorate result = _nsmallest(n, it) return [r[2] for r in result] # undecorate _nlargest = nlargest def nlargest(n, iterable, key=None): """Find the n largest elements in a dataset. Equivalent to: sorted(iterable, key=key, reverse=True)[:n] """ # Short-cut for n==1 is to use max() when len(iterable)>0 if n == 1: it = iter(iterable) head = list(islice(it, 1)) if not head: return [] if key is None: return [max(chain(head, it))] return [max(chain(head, it), key=key)] # When n>=size, it's faster to use sorted() try: size = len(iterable) except (TypeError, AttributeError): pass else: if n >= size: return sorted(iterable, key=key, reverse=True)[:n] # When key is none, use simpler decoration if key is None: it = zip(iterable, count(0,-1)) # decorate result = _nlargest(n, it) return [r[0] for r in result] # undecorate # General case, slowest method in1, in2 = tee(iterable) it = zip(map(key, in1), count(0,-1), in2) # decorate result = _nlargest(n, it) return [r[2] for r in result] # undecorate if __name__ == "__main__": # Simple sanity test heap = [] data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] for item in data: heappush(heap, item) sort = [] while heap: sort.append(heappop(heap)) print(sort) import doctest doctest.testmod()
KaranToor/MA450
refs/heads/master
google-cloud-sdk/.install/.backup/lib/surface/compute/instance_groups/managed/delete_instances.py
3
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command for deleting instances managed by managed instance group.""" from googlecloudsdk.api_lib.compute import base_classes from googlecloudsdk.api_lib.compute import instance_groups_utils from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.command_lib.compute import flags from googlecloudsdk.command_lib.compute import scope as compute_scope from googlecloudsdk.command_lib.compute.instance_groups import flags as instance_groups_flags class DeleteInstances(base_classes.BaseAsyncMutator): """Delete instances managed by managed instance group.""" @staticmethod def Args(parser): parser.add_argument('--instances', type=arg_parsers.ArgList(min_length=1), metavar='INSTANCE', required=True, help='Names of instances to delete.') instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG.AddArgument( parser) @property def method(self): return 'DeleteInstances' @property def service(self): return self.compute.instanceGroupManagers @property def resource_type(self): return 'instanceGroupManagers' def CreateRequests(self, args): resource_arg = instance_groups_flags.MULTISCOPE_INSTANCE_GROUP_MANAGER_ARG default_scope = compute_scope.ScopeEnum.ZONE scope_lister = flags.GetDefaultScopeLister( self.compute_client, self.project) igm_ref = resource_arg.ResolveAsResource( args, self.resources, default_scope=default_scope, scope_lister=scope_lister) instances = instance_groups_utils.CreateInstanceReferences( self.resources, self.compute_client, igm_ref, args.instances) if igm_ref.Collection() == 'compute.instanceGroupManagers': service = self.compute.instanceGroupManagers request = ( self.messages. ComputeInstanceGroupManagersDeleteInstancesRequest( instanceGroupManager=igm_ref.Name(), instanceGroupManagersDeleteInstancesRequest=( self.messages.InstanceGroupManagersDeleteInstancesRequest( instances=instances, ) ), project=self.project, zone=igm_ref.zone, )) else: service = self.compute.regionInstanceGroupManagers request = ( self.messages. ComputeRegionInstanceGroupManagersDeleteInstancesRequest( instanceGroupManager=igm_ref.Name(), regionInstanceGroupManagersDeleteInstancesRequest=( self.messages. RegionInstanceGroupManagersDeleteInstancesRequest( instances=instances, ) ), project=self.project, region=igm_ref.region, )) return [(service, self.method, request)] DeleteInstances.detailed_help = { 'brief': 'Delete instances managed by managed instance group.', 'DESCRIPTION': """ *{command}* is used to deletes one or more instances from a managed instance group. Once the instances are deleted, the size of the group is automatically reduced to reflect the changes. If you would like to keep the underlying virtual machines but still remove them from the managed instance group, use the abandon-instances command instead. """, }
kai5263499/networkx
refs/heads/master
networkx/algorithms/graphical.py
32
# -*- coding: utf-8 -*- """Test sequences for graphiness. """ # Copyright (C) 2004-2013 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. from collections import defaultdict import heapq import networkx as nx __author__ = "\n".join(['Aric Hagberg (hagberg@lanl.gov)', 'Pieter Swart (swart@lanl.gov)', 'Dan Schult (dschult@colgate.edu)' 'Joel Miller (joel.c.miller.research@gmail.com)' 'Ben Edwards' 'Brian Cloteaux <brian.cloteaux@nist.gov>']) __all__ = ['is_graphical', 'is_multigraphical', 'is_pseudographical', 'is_digraphical', 'is_valid_degree_sequence_erdos_gallai', 'is_valid_degree_sequence_havel_hakimi', 'is_valid_degree_sequence', # deprecated ] def is_graphical(sequence, method='eg'): """Returns True if sequence is a valid degree sequence. A degree sequence is valid if some graph can realize it. Parameters ---------- sequence : list or iterable container A sequence of integer node degrees method : "eg" | "hh" The method used to validate the degree sequence. "eg" corresponds to the Erdős-Gallai algorithm, and "hh" to the Havel-Hakimi algorithm. Returns ------- valid : bool True if the sequence is a valid degree sequence and False if not. Examples -------- >>> G = nx.path_graph(4) >>> sequence = G.degree().values() >>> nx.is_valid_degree_sequence(sequence) True References ---------- Erdős-Gallai [EG1960]_, [choudum1986]_ Havel-Hakimi [havel1955]_, [hakimi1962]_, [CL1996]_ """ if method == 'eg': valid = is_valid_degree_sequence_erdos_gallai(list(sequence)) elif method == 'hh': valid = is_valid_degree_sequence_havel_hakimi(list(sequence)) else: msg = "`method` must be 'eg' or 'hh'" raise nx.NetworkXException(msg) return valid is_valid_degree_sequence = is_graphical def _basic_graphical_tests(deg_sequence): # Sort and perform some simple tests on the sequence if not nx.utils.is_list_of_ints(deg_sequence): raise nx.NetworkXUnfeasible p = len(deg_sequence) num_degs = [0]*p dmax, dmin, dsum, n = 0, p, 0, 0 for d in deg_sequence: # Reject if degree is negative or larger than the sequence length if d<0 or d>=p: raise nx.NetworkXUnfeasible # Process only the non-zero integers elif d>0: dmax, dmin, dsum, n = max(dmax,d), min(dmin,d), dsum+d, n+1 num_degs[d] += 1 # Reject sequence if it has odd sum or is oversaturated if dsum%2 or dsum>n*(n-1): raise nx.NetworkXUnfeasible return dmax,dmin,dsum,n,num_degs def is_valid_degree_sequence_havel_hakimi(deg_sequence): r"""Returns True if deg_sequence can be realized by a simple graph. The validation proceeds using the Havel-Hakimi theorem. Worst-case run time is: O(s) where s is the sum of the sequence. Parameters ---------- deg_sequence : list A list of integers where each element specifies the degree of a node in a graph. Returns ------- valid : bool True if deg_sequence is graphical and False if not. Notes ----- The ZZ condition says that for the sequence d if .. math:: |d| >= \frac{(\max(d) + \min(d) + 1)^2}{4*\min(d)} then d is graphical. This was shown in Theorem 6 in [1]_. References ---------- .. [1] I.E. Zverovich and V.E. Zverovich. "Contributions to the theory of graphic sequences", Discrete Mathematics, 105, pp. 292-303 (1992). [havel1955]_, [hakimi1962]_, [CL1996]_ """ try: dmax,dmin,dsum,n,num_degs = _basic_graphical_tests(deg_sequence) except nx.NetworkXUnfeasible: return False # Accept if sequence has no non-zero degrees or passes the ZZ condition if n==0 or 4*dmin*n >= (dmax+dmin+1) * (dmax+dmin+1): return True modstubs = [0]*(dmax+1) # Successively reduce degree sequence by removing the maximum degree while n > 0: # Retrieve the maximum degree in the sequence while num_degs[dmax] == 0: dmax -= 1; # If there are not enough stubs to connect to, then the sequence is # not graphical if dmax > n-1: return False # Remove largest stub in list num_degs[dmax], n = num_degs[dmax]-1, n-1 # Reduce the next dmax largest stubs mslen = 0 k = dmax for i in range(dmax): while num_degs[k] == 0: k -= 1 num_degs[k], n = num_degs[k]-1, n-1 if k > 1: modstubs[mslen] = k-1 mslen += 1 # Add back to the list any non-zero stubs that were removed for i in range(mslen): stub = modstubs[i] num_degs[stub], n = num_degs[stub]+1, n+1 return True def is_valid_degree_sequence_erdos_gallai(deg_sequence): r"""Returns True if deg_sequence can be realized by a simple graph. The validation is done using the Erdős-Gallai theorem [EG1960]_. Parameters ---------- deg_sequence : list A list of integers Returns ------- valid : bool True if deg_sequence is graphical and False if not. Notes ----- This implementation uses an equivalent form of the Erdős-Gallai criterion. Worst-case run time is: O(n) where n is the length of the sequence. Specifically, a sequence d is graphical if and only if the sum of the sequence is even and for all strong indices k in the sequence, .. math:: \sum_{i=1}^{k} d_i \leq k(k-1) + \sum_{j=k+1}^{n} \min(d_i,k) = k(n-1) - ( k \sum_{j=0}^{k-1} n_j - \sum_{j=0}^{k-1} j n_j ) A strong index k is any index where `d_k \geq k` and the value `n_j` is the number of occurrences of j in d. The maximal strong index is called the Durfee index. This particular rearrangement comes from the proof of Theorem 3 in [2]_. The ZZ condition says that for the sequence d if .. math:: |d| >= \frac{(\max(d) + \min(d) + 1)^2}{4*\min(d)} then d is graphical. This was shown in Theorem 6 in [2]_. References ---------- .. [1] A. Tripathi and S. Vijay. "A note on a theorem of Erdős & Gallai", Discrete Mathematics, 265, pp. 417-420 (2003). .. [2] I.E. Zverovich and V.E. Zverovich. "Contributions to the theory of graphic sequences", Discrete Mathematics, 105, pp. 292-303 (1992). [EG1960]_, [choudum1986]_ """ try: dmax,dmin,dsum,n,num_degs = _basic_graphical_tests(deg_sequence) except nx.NetworkXUnfeasible: return False # Accept if sequence has no non-zero degrees or passes the ZZ condition if n==0 or 4*dmin*n >= (dmax+dmin+1) * (dmax+dmin+1): return True # Perform the EG checks using the reformulation of Zverovich and Zverovich k, sum_deg, sum_nj, sum_jnj = 0, 0, 0, 0 for dk in range(dmax, dmin-1, -1): if dk < k+1: # Check if already past Durfee index return True if num_degs[dk] > 0: run_size = num_degs[dk] # Process a run of identical-valued degrees if dk < k+run_size: # Check if end of run is past Durfee index run_size = dk-k # Adjust back to Durfee index sum_deg += run_size * dk for v in range(run_size): sum_nj += num_degs[k+v] sum_jnj += (k+v) * num_degs[k+v] k += run_size if sum_deg > k*(n-1) - k*sum_nj + sum_jnj: return False return True def is_multigraphical(sequence): """Returns True if some multigraph can realize the sequence. Parameters ---------- deg_sequence : list A list of integers Returns ------- valid : bool True if deg_sequence is a multigraphic degree sequence and False if not. Notes ----- The worst-case run time is O(n) where n is the length of the sequence. References ---------- .. [1] S. L. Hakimi. "On the realizability of a set of integers as degrees of the vertices of a linear graph", J. SIAM, 10, pp. 496-506 (1962). """ deg_sequence = list(sequence) if not nx.utils.is_list_of_ints(deg_sequence): return False dsum, dmax = 0, 0 for d in deg_sequence: if d<0: return False dsum, dmax = dsum+d, max(dmax,d) if dsum%2 or dsum<2*dmax: return False return True def is_pseudographical(sequence): """Returns True if some pseudograph can realize the sequence. Every nonnegative integer sequence with an even sum is pseudographical (see [1]_). Parameters ---------- sequence : list or iterable container A sequence of integer node degrees Returns ------- valid : bool True if the sequence is a pseudographic degree sequence and False if not. Notes ----- The worst-case run time is O(n) where n is the length of the sequence. References ---------- .. [1] F. Boesch and F. Harary. "Line removal algorithms for graphs and their degree lists", IEEE Trans. Circuits and Systems, CAS-23(12), pp. 778-782 (1976). """ s = list(sequence) if not nx.utils.is_list_of_ints(s): return False return sum(s)%2 == 0 and min(s) >= 0 def is_digraphical(in_sequence, out_sequence): r"""Returns True if some directed graph can realize the in- and out-degree sequences. Parameters ---------- in_sequence : list or iterable container A sequence of integer node in-degrees out_sequence : list or iterable container A sequence of integer node out-degrees Returns ------- valid : bool True if in and out-sequences are digraphic False if not. Notes ----- This algorithm is from Kleitman and Wang [1]_. The worst case runtime is O(s * log n) where s and n are the sum and length of the sequences respectively. References ---------- .. [1] D.J. Kleitman and D.L. Wang Algorithms for Constructing Graphs and Digraphs with Given Valences and Factors, Discrete Mathematics, 6(1), pp. 79-88 (1973) """ in_deg_sequence = list(in_sequence) out_deg_sequence = list(out_sequence) if not nx.utils.is_list_of_ints(in_deg_sequence): return False if not nx.utils.is_list_of_ints(out_deg_sequence): return False # Process the sequences and form two heaps to store degree pairs with # either zero or non-zero out degrees sumin, sumout, nin, nout = 0, 0, len(in_deg_sequence), len(out_deg_sequence) maxn = max(nin, nout) maxin = 0 if maxn==0: return True stubheap, zeroheap = [ ], [ ] for n in range(maxn): in_deg, out_deg = 0, 0 if n<nout: out_deg = out_deg_sequence[n] if n<nin: in_deg = in_deg_sequence[n] if in_deg<0 or out_deg<0: return False sumin, sumout, maxin = sumin+in_deg, sumout+out_deg, max(maxin, in_deg) if in_deg > 0: stubheap.append((-1*out_deg, -1*in_deg)) elif out_deg > 0: zeroheap.append(-1*out_deg) if sumin != sumout: return False heapq.heapify(stubheap) heapq.heapify(zeroheap) modstubs = [(0,0)]*(maxin+1) # Successively reduce degree sequence by removing the maximum out degree while stubheap: # Take the first value in the sequence with non-zero in degree (freeout, freein) = heapq.heappop( stubheap ) freein *= -1 if freein > len(stubheap)+len(zeroheap): return False # Attach out stubs to the nodes with the most in stubs mslen = 0 for i in range(freein): if zeroheap and (not stubheap or stubheap[0][0] > zeroheap[0]): stubout = heapq.heappop(zeroheap) stubin = 0 else: (stubout, stubin) = heapq.heappop(stubheap) if stubout == 0: return False # Check if target is now totally connected if stubout+1<0 or stubin<0: modstubs[mslen] = (stubout+1, stubin) mslen += 1 # Add back the nodes to the heap that still have available stubs for i in range(mslen): stub = modstubs[i] if stub[1] < 0: heapq.heappush(stubheap, stub) else: heapq.heappush(zeroheap, stub[0]) if freeout<0: heapq.heappush(zeroheap, freeout) return True
gi11es/thumbor
refs/heads/master
thumbor/filters/convolution.py
4
# -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com thumbor@googlegroups.com from thumbor.ext.filters import _convolution from thumbor.filters import BaseFilter, filter_method # pylint: disable=line-too-long class Filter(BaseFilter): """ Usage: /filters:convolution(<semicolon separated matrix items>, <number of columns in matrix>, <should normalize boolean>) Example of blur filter: /filters:convolution(1;2;1;2;4;2;1;2;1,3,true)/ """ @filter_method( r"(?:[-]?[\d]+\.?[\d]*[;])*(?:[-]?[\d]+\.?[\d]*)", BaseFilter.PositiveNumber, BaseFilter.Boolean, ) def convolution(self, matrix, columns, should_normalize=True): matrix = tuple(matrix.split(";")) mode, data = self.engine.image_data_as_rgb() imgdata = _convolution.apply( mode, data, self.engine.size[0], self.engine.size[1], matrix, columns, should_normalize, ) self.engine.set_image_data(imgdata)
sstone/bitcoin
refs/heads/master
test/functional/feature_uacomment.py
46
#!/usr/bin/env python3 # Copyright (c) 2017-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the -uacomment option.""" import re from test_framework.test_framework import BitcoinTestFramework from test_framework.test_node import ErrorMatch from test_framework.util import assert_equal class UacommentTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.setup_clean_chain = True def run_test(self): self.log.info("test multiple -uacomment") test_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-12:-1] assert_equal(test_uacomment, "(testnode0)") self.restart_node(0, ["-uacomment=foo"]) foo_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-17:-1] assert_equal(foo_uacomment, "(testnode0; foo)") self.log.info("test -uacomment max length") self.stop_node(0) expected = r"Error: Total length of network version string \([0-9]+\) exceeds maximum length \(256\). Reduce the number or size of uacomments." self.nodes[0].assert_start_raises_init_error(["-uacomment=" + 'a' * 256], expected, match=ErrorMatch.FULL_REGEX) self.log.info("test -uacomment unsafe characters") for unsafe_char in ['/', ':', '(', ')', '₿', '🏃']: expected = r"Error: User Agent comment \(" + re.escape(unsafe_char) + r"\) contains unsafe characters." self.nodes[0].assert_start_raises_init_error(["-uacomment=" + unsafe_char], expected, match=ErrorMatch.FULL_REGEX) if __name__ == '__main__': UacommentTest().main()
savoirfairelinux/django
refs/heads/master
tests/shortcuts/urls.py
113
from django.conf.urls import url from . import views urlpatterns = [ url(r'^render_to_response/$', views.render_to_response_view), url(r'^render_to_response/multiple_templates/$', views.render_to_response_view_with_multiple_templates), url(r'^render_to_response/content_type/$', views.render_to_response_view_with_content_type), url(r'^render_to_response/status/$', views.render_to_response_view_with_status), url(r'^render_to_response/using/$', views.render_to_response_view_with_using), url(r'^render/$', views.render_view), url(r'^render/multiple_templates/$', views.render_view_with_multiple_templates), url(r'^render/content_type/$', views.render_view_with_content_type), url(r'^render/status/$', views.render_view_with_status), url(r'^render/using/$', views.render_view_with_using), ]
aykol/pymatgen
refs/heads/master
pymatgen/entries/tests/test_exp_entries.py
2
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals ''' Created on Jun 27, 2012 ''' __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Jun 27, 2012" import unittest2 as unittest import os import json from pymatgen.entries.exp_entries import ExpEntry from monty.json import MontyDecoder test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files') class ExpEntryTest(unittest.TestCase): def setUp(self): with open(os.path.join(test_dir, "Fe2O3_exp.json"), "r") as f: thermodata = json.load(f, cls=MontyDecoder) self.entry = ExpEntry("Fe2O3", thermodata) def test_energy(self): self.assertAlmostEqual(self.entry.energy, -825.5) def test_to_from_dict(self): d = self.entry.as_dict() e = ExpEntry.from_dict(d) self.assertAlmostEqual(e.energy, -825.5) def test_str(self): self.assertIsNotNone(str(self.entry)) if __name__ == "__main__": unittest.main()
sivel/ansible-modules-extras
refs/heads/devel
infrastructure/foreman/katello.py
23
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Eric D Helms <ericdhelms@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: katello short_description: Manage Katello Resources description: - Allows the management of Katello resources inside your Foreman server version_added: "2.3" author: "Eric D Helms (@ehelms)" requirements: - "nailgun >= 0.28.0" - "python >= 2.6" - datetime options: server_url: description: - URL of Foreman server required: true username: description: - Username on Foreman server required: true password: description: - Password for user accessing Foreman server required: true entity: description: - The Foreman resource that the action will be performed on (e.g. organization, host) required: true params: description: - Parameters associated to the entity resource to set or edit in dictionary format (e.g. name, description) required: true ''' EXAMPLES = ''' Simple Example: - name: "Create Product" local_action: module: katello username: "admin" password: "admin" server_url: "https://fakeserver.com" entity: "product" params: name: "Centos 7" Abstraction Example: katello.yml --- - name: "{{ name }}" local_action: module: katello username: "admin" password: "admin" server_url: "https://fakeserver.com" entity: "{{ entity }}" params: "{{ params }}" tasks.yml --- - include: katello.yml vars: name: "Create Dev Environment" entity: "lifecycle_environment" params: name: "Dev" prior: "Library" organization: "Default Organization" - include: katello.yml vars: name: "Create Centos Product" entity: "product" params: name: "Centos 7" organization: "Default Organization" - include: katello.yml vars: name: "Create 7.2 Repository" entity: "repository" params: name: "Centos 7.2" product: "Centos 7" organization: "Default Organization" content_type: "yum" url: "http://mirror.centos.org/centos/7/os/x86_64/" - include: katello.yml vars: name: "Create Centos 7 View" entity: "content_view" params: name: "Centos 7 View" organization: "Default Organization" repositories: - name: "Centos 7.2" product: "Centos 7" - include: katello.yml vars: name: "Enable RHEL Product" entity: "repository_set" params: name: "Red Hat Enterprise Linux 7 Server (RPMs)" product: "Red Hat Enterprise Linux Server" organization: "Default Organization" basearch: "x86_64" releasever: "7" ''' RETURN = '''# ''' import datetime try: from nailgun import entities, entity_fields, entity_mixins from nailgun.config import ServerConfig HAS_NAILGUN_PACKAGE = True except: HAS_NAILGUN_PACKAGE = False class NailGun(object): def __init__(self, server, entities, module): self._server = server self._entities = entities self._module = module entity_mixins.TASK_TIMEOUT = 1000 def find_organization(self, name, **params): org = self._entities.Organization(self._server, name=name, **params) response = org.search(set(), {'search': 'name={}'.format(name)}) if len(response) == 1: return response[0] else: self._module.fail_json(msg="No organization found for %s" % name) def find_lifecycle_environment(self, name, organization): org = self.find_organization(organization) lifecycle_env = self._entities.LifecycleEnvironment(self._server, name=name, organization=org) response = lifecycle_env.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Lifecycle Found found for %s" % name) def find_product(self, name, organization): org = self.find_organization(organization) product = self._entities.Product(self._server, name=name, organization=org) response = product.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Product found for %s" % name) def find_repository(self, name, product, organization): product = self.find_product(product, organization) repository = self._entities.Repository(self._server, name=name, product=product) repository._fields['organization'] = entity_fields.OneToOneField(entities.Organization) repository.organization = product.organization response = repository.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Repository found for %s" % name) def find_content_view(self, name, organization): org = self.find_organization(organization) content_view = self._entities.ContentView(self._server, name=name, organization=org) response = content_view.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Content View found for %s" % name) def organization(self, params): name = params['name'] del params['name'] org = self.find_organization(name, **params) if org: org = self._entities.Organization(self._server, name=name, id=org.id, **params) org.update() else: org = self._entities.Organization(self._server, name=name, **params) org.create() return True def manifest(self, params): org = self.find_organization(params['organization']) params['organization'] = org.id try: file = open(os.getcwd() + params['content'], 'r') content = file.read() finally: file.close() manifest = self._entities.Subscription(self._server) try: manifest.upload( data={'organization_id': org.id}, files={'content': content} ) return True except Exception: e = get_exception() if "Import is the same as existing data" in e.message: return True else: self._module.fail_json(msg="Manifest import failed with %s" % e) def product(self, params): org = self.find_organization(params['organization']) params['organization'] = org.id product = self._entities.Product(self._server, **params) response = product.search() if len(response) == 1: product.id = response[0].id product.update() else: product.create() return True def sync_product(self, params): org = self.find_organization(params['organization']) product = self.find_product(params['name'], org.name) return product.sync() def repository(self, params): product = self.find_product(params['product'], params['organization']) params['product'] = product.id del params['organization'] repository = self._entities.Repository(self._server, **params) repository._fields['organization'] = entity_fields.OneToOneField(entities.Organization) repository.organization = product.organization response = repository.search() if len(response) == 1: repository.id = response[0].id repository.update() else: repository.create() return True def sync_repository(self, params): org = self.find_organization(params['organization']) repository = self.find_repository(params['name'], params['product'], org.name) return repository.sync() def repository_set(self, params): product = self.find_product(params['product'], params['organization']) del params['product'] del params['organization'] if not product: return False else: reposet = self._entities.RepositorySet(self._server, product=product, name=params['name']) reposet = reposet.search()[0] formatted_name = [params['name'].replace('(', '').replace(')', '')] formatted_name.append(params['basearch']) if params['releasever']: formatted_name.append(params['releasever']) formatted_name = ' '.join(formatted_name) repository = self._entities.Repository(self._server, product=product, name=formatted_name) repository._fields['organization'] = entity_fields.OneToOneField(entities.Organization) repository.organization = product.organization repository = repository.search() if len(repository) == 0: reposet.enable(data={'basearch': params['basearch'], 'releasever': params['releasever']}) return True def sync_plan(self, params): org = self.find_organization(params['organization']) params['organization'] = org.id params['sync_date'] = datetime.datetime.strptime(params['sync_date'], "%H:%M") products = params['products'] del params['products'] sync_plan = self._entities.SyncPlan( self._server, name=params['name'], organization=org ) response = sync_plan.search() sync_plan.sync_date = params['sync_date'] sync_plan.interval = params['interval'] if len(response) == 1: sync_plan.id = response[0].id sync_plan.update() else: response = sync_plan.create() sync_plan.id = response[0].id if products: ids = [] for name in products: product = self.find_product(name, org.name) ids.append(product.id) sync_plan.add_products(data={'product_ids': ids}) return True def content_view(self, params): org = self.find_organization(params['organization']) content_view = self._entities.ContentView(self._server, name=params['name'], organization=org) response = content_view.search() if len(response) == 1: content_view.id = response[0].id content_view.update() else: content_view = content_view.create() if params['repositories']: repos = [] for repository in params['repositories']: repository = self.find_repository(repository['name'], repository['product'], org.name) repos.append(repository) content_view.repository = repos content_view.update(['repository']) def find_content_view(self, name, organization): org = self.find_organization(organization) content_view = self._entities.ContentView(self._server, name=name, organization=org) response = content_view.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Content View found for %s" % name) def find_content_view_version(self, name, organization, environment): env = self.find_lifecycle_environment(environment, organization) content_view = self.find_content_view(name, organization) content_view_version = self._entities.ContentViewVersion(self._server, content_view=content_view) response = content_view_version.search(['content_view'], {'environment_id': env.id}) if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Content View version found for %s" % response) def publish(self, params): content_view = self.find_content_view(params['name'], params['organization']) return content_view.publish() def promote(self, params): to_environment = self.find_lifecycle_environment(params['to_environment'], params['organization']) version = self.find_content_view_version(params['name'], params['organization'], params['from_environment']) data = {'environment_id': to_environment.id} return version.promote(data=data) def lifecycle_environment(self, params): org = self.find_organization(params['organization']) prior_env = self.find_lifecycle_environment(params['prior'], params['organization']) lifecycle_env = self._entities.LifecycleEnvironment(self._server, name=params['name'], organization=org, prior=prior_env) response = lifecycle_env.search() if len(response) == 1: lifecycle_env.id = response[0].id lifecycle_env.update() else: lifecycle_env.create() return True def activation_key(self, params): org = self.find_organization(params['organization']) activation_key = self._entities.ActivationKey(self._server, name=params['name'], organization=org) response = activation_key.search() if len(response) == 1: activation_key.id = response[0].id activation_key.update() else: activation_key.create() if params['content_view']: content_view = self.find_content_view(params['content_view'], params['organization']) lifecycle_environment = self.find_lifecycle_environment(params['lifecycle_environment'], params['organization']) activation_key.content_view = content_view activation_key.environment = lifecycle_environment activation_key.update() return True def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(required=True), username=dict(required=True, no_log=True), password=dict(required=True, no_log=True), entity=dict(required=True, no_log=False), action=dict(required=False, no_log=False), verify_ssl=dict(required=False, type='bool', default=False), params=dict(required=True, no_log=True, type='dict'), ), supports_check_mode=True ) if not HAS_NAILGUN_PACKAGE: module.fail_json(msg="Missing required nailgun module (check docs or install with: pip install nailgun") server_url = module.params['server_url'] username = module.params['username'] password = module.params['password'] entity = module.params['entity'] action = module.params['action'] params = module.params['params'] verify_ssl = module.params['verify_ssl'] server = ServerConfig( url=server_url, auth=(username, password), verify=verify_ssl ) ng = NailGun(server, entities, module) # Lets make an connection to the server with username and password try: org = entities.Organization(server) org.search() except Exception as e: module.fail_json(msg="Failed to connect to Foreman server: %s " % e) result = False if entity == 'product': if action == 'sync': result = ng.sync_product(params) else: result = ng.product(params) elif entity == 'repository': if action == 'sync': result = ng.sync_repository(params) else: result = ng.repository(params) elif entity == 'manifest': result = ng.manifest(params) elif entity == 'repository_set': result = ng.repository_set(params) elif entity == 'sync_plan': result = ng.sync_plan(params) elif entity == 'content_view': if action == 'publish': result = ng.publish(params) elif action == 'promote': result = ng.promote(params) else: result = ng.content_view(params) elif entity == 'lifecycle_environment': result = ng.lifecycle_environment(params) elif entity == 'activation_key': result = ng.activation_key(params) else: module.fail_json(changed=False, result="Unsupported entity supplied") module.exit_json(changed=result, result="%s updated" % entity) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
heijingjie/fs_linux_3.10.58
refs/heads/master
tools/perf/python/twatch.py
7370
#! /usr/bin/python # -*- python -*- # -*- coding: utf-8 -*- # twatch - Experimental use of the perf python interface # Copyright (C) 2011 Arnaldo Carvalho de Melo <acme@redhat.com> # # This application is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; version 2. # # This application is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. import perf def main(): cpus = perf.cpu_map() threads = perf.thread_map() evsel = perf.evsel(task = 1, comm = 1, mmap = 0, wakeup_events = 1, watermark = 1, sample_id_all = 1, sample_type = perf.SAMPLE_PERIOD | perf.SAMPLE_TID | perf.SAMPLE_CPU | perf.SAMPLE_TID) evsel.open(cpus = cpus, threads = threads); evlist = perf.evlist(cpus, threads) evlist.add(evsel) evlist.mmap() while True: evlist.poll(timeout = -1) for cpu in cpus: event = evlist.read_on_cpu(cpu) if not event: continue print "cpu: %2d, pid: %4d, tid: %4d" % (event.sample_cpu, event.sample_pid, event.sample_tid), print event if __name__ == '__main__': main()
SMALLplayer/smallplayer-image-creator
refs/heads/master
storage/.xbmc/addons/script.xbmc.subtitles/resources/lib/services/PTSubs/service.py
1
# -*- coding: utf-8 -*- # Service PT-SUBS.NET version 0.1.5 # Code based on Undertext service # Coded by HiGhLaNdR@OLDSCHOOL # Help by VaRaTRoN # Bugs & Features to highlander@teknorage.com # http://www.teknorage.com # License: GPL v2 # # NEW on Service PT-SUBS.NET v0.1.6: # Added uuid for better file handling, no more hangups. # # Initial Release of Service PT-SUBS.NET - v0.1.5: # TODO: re-arrange code :) # # PT-SUBS.NET subtitles, based on a mod of Undertext subtitles import os, sys, re, xbmc, xbmcgui, string, time, urllib, urllib2, cookielib, shutil, fnmatch from utilities import log _ = sys.modules[ "__main__" ].__language__ __scriptname__ = sys.modules[ "__main__" ].__scriptname__ __addon__ = sys.modules[ "__main__" ].__addon__ main_url = "http://www.pt-subs.net/site/" debug_pretext = "PT-SUBS" subext = ['srt', 'aas', 'ssa', 'sub', 'smi'] packext = ['rar', 'zip'] #==================================================================================================================== # Regular expression patterns #==================================================================================================================== """ """ desc_pattern = "<td><b>Descri.+?</b><br\s/>(.+?)<br\s/><a\shref=" subtitle_pattern = "<tr><td><a\shref=\"(.+?)\">(.+?)</a></td><td>(.+?)</td><td>(.+?)</td><td>(.+?)</td><td>(.+?)</td></tr>" # group(1) = Download link, group(2) = Name, group(3) = Visualizações, group(4) = N Legendas, group(5) = Tamanho, group(6) = Data #==================================================================================================================== # Functions #==================================================================================================================== def getallsubs(searchstring, languageshort, languagelong, file_original_path, subtitles_list, searchstring_notclean): #Grabbing login and pass from xbmc settings username = __addon__.getSetting( "PTSuser" ) password = __addon__.getSetting( "PTSpass" ) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) opener.addheaders.append(('User-agent', 'Mozilla/4.0')) login_data = urllib.urlencode({'user' : username, 'passwrd' : password, 'action' : 'login2'}) opener.open(main_url+'index.php', login_data) page = 0 if languageshort == "pt": url = main_url + "index.php?action=downloads;sa=search2;start=" + str(page) + ";searchfor=" + urllib.quote_plus(searchstring) content = opener.open(url) content = content.read() #For DEBUG only uncomment next line #log( __name__ ,"%s Getting '%s' list ..." % (debug_pretext, content)) #log( __name__ ,"%s Getting '%s' subs ..." % (debug_pretext, languageshort)) while re.search(subtitle_pattern, content, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE | re.VERBOSE): for matches in re.finditer(subtitle_pattern, content, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE | re.VERBOSE): hits = matches.group(4) id = matches.group(1) no_files = matches.group(3) downloads = int(matches.group(4)) / 10 if (downloads > 10): downloads=10 filename = string.strip(matches.group(2)) content_desc = opener.open(id) content_desc = content_desc.read() #For DEBUG only uncomment next line #log( __name__ ,"%s Getting '%s' desc" % (debug_pretext, content_desc)) for descmatch in re.finditer(desc_pattern, content_desc, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE | re.VERBOSE): desc = string.strip(descmatch.group(1)) #Remove new lines on the commentaries filename = re.sub('\n',' ',filename) desc = re.sub('\n',' ',desc) desc = re.sub('&quot;','"',desc) #Remove HTML tags on the commentaries filename = re.sub(r'<[^<]+?>','', filename) desc = re.sub(r'<[^<]+?>|[~]',' ', desc) #Find filename on the comentaries to show sync label using filename or dirname (making it global for further usage) global filesearch filesearch = os.path.abspath(file_original_path) #For DEBUG only uncomment next line #log( __name__ ,"%s abspath: '%s'" % (debug_pretext, filesearch)) filesearch = os.path.split(filesearch) #For DEBUG only uncomment next line #log( __name__ ,"%s path.split: '%s'" % (debug_pretext, filesearch)) dirsearch = filesearch[0].split(os.sep) #For DEBUG only uncomment next line #log( __name__ ,"%s dirsearch: '%s'" % (debug_pretext, dirsearch)) dirsearch_check = string.split(dirsearch[-1], '.') #For DEBUG only uncomment next line #log( __name__ ,"%s dirsearch_check: '%s'" % (debug_pretext, dirsearch_check)) if (searchstring_notclean != ""): sync = False if re.search(searchstring_notclean, desc): sync = True else: if (string.lower(dirsearch_check[-1]) == "rar") or (string.lower(dirsearch_check[-1]) == "cd1") or (string.lower(dirsearch_check[-1]) == "cd2"): sync = False if len(dirsearch) > 1 and dirsearch[1] != '': if re.search(filesearch[1][:len(filesearch[1])-4], desc) or re.search(dirsearch[-2], desc): sync = True else: if re.search(filesearch[1][:len(filesearch[1])-4], desc): sync = True else: sync = False if len(dirsearch) > 1 and dirsearch[1] != '': if re.search(filesearch[1][:len(filesearch[1])-4], desc) or re.search(dirsearch[-1], desc): sync = True else: if re.search(filesearch[1][:len(filesearch[1])-4], desc): sync = True filename = filename + " " + hits + "Hits" + " - " + desc subtitles_list.append({'rating': str(downloads), 'no_files': no_files, 'filename': filename, 'desc': desc, 'sync': sync, 'hits' : hits, 'id': id, 'language_flag': 'flags/' + languageshort + '.gif', 'language_name': languagelong}) page = page + 10 url = main_url + "index.php?action=downloads;sa=search2;start=" + str(page) + ";searchfor=" + urllib.quote_plus(searchstring) content = opener.open(url) content = content.read() #For DEBUG only uncomment next line #log( __name__ ,"%s Getting '%s' list part xxx..." % (debug_pretext, content)) # Bubble sort, to put syncs on top for n in range(0,len(subtitles_list)): for i in range(1, len(subtitles_list)): temp = subtitles_list[i] if subtitles_list[i]["sync"] > subtitles_list[i-1]["sync"]: subtitles_list[i] = subtitles_list[i-1] subtitles_list[i-1] = temp def geturl(url): class MyOpener(urllib.FancyURLopener): version = '' my_urlopener = MyOpener() log( __name__ ,"%s Getting url: %s" % (debug_pretext, url)) try: response = my_urlopener.open(url) content = response.read() except: log( __name__ ,"%s Failed to get url:%s" % (debug_pretext, url)) content = None return content def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input subtitles_list = [] msg = "" searchstring_notclean = "" searchstring = "" global israr israr = os.path.abspath(file_original_path) israr = os.path.split(israr) israr = israr[0].split(os.sep) israr = string.split(israr[-1], '.') israr = string.lower(israr[-1]) if len(tvshow) == 0: if 'rar' in israr and searchstring is not None: if 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title): dirsearch = os.path.abspath(file_original_path) dirsearch = os.path.split(dirsearch) dirsearch = dirsearch[0].split(os.sep) if len(dirsearch) > 1: searchstring_notclean = dirsearch[-3] searchstring = xbmc.getCleanMovieTitle(dirsearch[-3]) searchstring = searchstring[0] else: searchstring = title else: searchstring = title elif 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title): dirsearch = os.path.abspath(file_original_path) dirsearch = os.path.split(dirsearch) dirsearch = dirsearch[0].split(os.sep) if len(dirsearch) > 1: searchstring_notclean = dirsearch[-2] searchstring = xbmc.getCleanMovieTitle(dirsearch[-2]) searchstring = searchstring[0] else: #We are at the root of the drive!!! so there's no dir to lookup only file# title = os.path.split(file_original_path) searchstring = title[-1] else: if title == "": title = os.path.split(file_original_path) searchstring = title[-1] else: searchstring = title if len(tvshow) > 0: searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode)) log( __name__ ,"%s Search string = %s" % (debug_pretext, searchstring)) portuguese = 0 if string.lower(lang1) == "portuguese": portuguese = 1 elif string.lower(lang2) == "portuguese": portuguese = 2 elif string.lower(lang3) == "portuguese": portuguese = 3 getallsubs(searchstring, "pt", "Portuguese", file_original_path, subtitles_list, searchstring_notclean) if portuguese == 0: msg = "Won't work, LegendasDivx is only for Portuguese subtitles!" return subtitles_list, "", msg #standard output def recursive_glob(treeroot, pattern): results = [] for base, dirs, files in os.walk(treeroot): for extension in pattern: for filename in fnmatch.filter(files, '*.' + extension): results.append(os.path.join(base, filename)) return results def download_subtitles (subtitles_list, pos, zip_subs, tmp_sub_dir, sub_folder, session_id): #standard input id = subtitles_list[pos][ "id" ] id = string.split(id,"=") id = id[-1] sync = subtitles_list[pos][ "sync" ] log( __name__ ,"%s Fetching id using url %s" % (debug_pretext, id)) #Grabbing login and pass from xbmc settings username = __addon__.getSetting( "PTSuser" ) password = __addon__.getSetting( "PTSpass" ) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) opener.addheaders.append(('User-agent', 'Mozilla/4.0')) login_data = urllib.urlencode({'user' : username, 'passwrd' : password, 'action' : 'login2'}) #This is where you are logged in resp = opener.open('http://www.pt-subs.net/site/index.php', login_data) #For DEBUG only uncomment next line #log( __name__ ,"%s resposta '%s' subs ..." % (debug_pretext, resp)) #Now you download the subtitles language = subtitles_list[pos][ "language_name" ] if string.lower(language) == "portuguese": content = opener.open('http://www.pt-subs.net/site/index.php?action=downloads;sa=downfile;id=' + id) if content is not None: header = content.info()['Content-Disposition'].split('filename')[1].split('.')[-1].strip("\"") if header == 'rar': log( __name__ ,"%s file: content is RAR" % (debug_pretext)) #EGO local_tmp_file = os.path.join(tmp_sub_dir, str(uuid.uuid1()) + ".rar") log( __name__ ,"%s file: local_tmp_file %s" % (debug_pretext, local_tmp_file)) #EGO packed = True elif header == 'zip': local_tmp_file = os.path.join(tmp_sub_dir, str(uuid.uuid1()) + ".zip") packed = True else: # never found/downloaded an unpacked subtitles file, but just to be sure ... local_tmp_file = os.path.join(tmp_sub_dir, str(uuid.uuid1()) + ".srt") # assume unpacked sub file is an '.srt' subs_file = local_tmp_file packed = False log( __name__ ,"%s Saving subtitles to '%s'" % (debug_pretext, local_tmp_file)) try: log( __name__ ,"%s file: write in %s" % (debug_pretext, local_tmp_file)) #EGO local_file_handle = open(local_tmp_file, "wb") shutil.copyfileobj(content.fp, local_file_handle) local_file_handle.close() except: log( __name__ ,"%s Failed to save subtitles to '%s'" % (debug_pretext, local_tmp_file)) if packed: files = os.listdir(tmp_sub_dir) init_filecount = len(files) log( __name__ ,"%s file: number init_filecount %s" % (debug_pretext, init_filecount)) #EGO filecount = init_filecount max_mtime = 0 # determine the newest file from tmp_sub_dir for file in files: if (string.split(file,'.')[-1] in ['srt','sub','txt']): mtime = os.stat(os.path.join(tmp_sub_dir, file)).st_mtime if mtime > max_mtime: max_mtime = mtime init_max_mtime = max_mtime time.sleep(2) # wait 2 seconds so that the unpacked files are at least 1 second newer xbmc.executebuiltin("XBMC.Extract(" + local_tmp_file + "," + tmp_sub_dir +")") waittime = 0 while (filecount == init_filecount) and (waittime < 20) and (init_max_mtime == max_mtime): # nothing yet extracted time.sleep(1) # wait 1 second to let the builtin function 'XBMC.extract' unpack files = os.listdir(tmp_sub_dir) log( __name__ ,"%s DIRLIST '%s'" % (debug_pretext, files)) filecount = len(files) # determine if there is a newer file created in tmp_sub_dir (marks that the extraction had completed) for file in files: if (string.split(file,'.')[-1] in ['srt','sub','txt']): mtime = os.stat(os.path.join(tmp_sub_dir, file)).st_mtime if (mtime > max_mtime): max_mtime = mtime waittime = waittime + 1 if waittime == 20: log( __name__ ,"%s Failed to unpack subtitles in '%s'" % (debug_pretext, tmp_sub_dir)) else: log( __name__ ,"%s Unpacked files in '%s'" % (debug_pretext, tmp_sub_dir)) searchrars = recursive_glob(tmp_sub_dir, packext) searchrarcount = len(searchrars) if searchrarcount > 1: for filerar in searchrars: if filerar != os.path.join(tmp_sub_dir,'ldivx.rar') and filerar != os.path.join(tmp_sub_dir,'ldivx.zip'): xbmc.executebuiltin("XBMC.Extract(" + filerar + "," + tmp_sub_dir +")") time.sleep(1) searchsubs = recursive_glob(tmp_sub_dir, subext) searchsubscount = len(searchsubs) for filesub in searchsubs: nopath = string.split(filesub, tmp_sub_dir)[-1] justfile = nopath.split(os.sep)[-1] #For DEBUG only uncomment next line #log( __name__ ,"%s DEBUG-nopath: '%s'" % (debug_pretext, nopath)) #log( __name__ ,"%s DEBUG-justfile: '%s'" % (debug_pretext, justfile)) releasefilename = filesearch[1][:len(filesearch[1])-4] releasedirname = filesearch[0].split(os.sep) if 'rar' in israr: releasedirname = releasedirname[-2] else: releasedirname = releasedirname[-1] #For DEBUG only uncomment next line #log( __name__ ,"%s DEBUG-releasefilename: '%s'" % (debug_pretext, releasefilename)) #log( __name__ ,"%s DEBUG-releasedirname: '%s'" % (debug_pretext, releasedirname)) subsfilename = justfile[:len(justfile)-4] #For DEBUG only uncomment next line #log( __name__ ,"%s DEBUG-subsfilename: '%s'" % (debug_pretext, subsfilename)) #log( __name__ ,"%s DEBUG-subscount: '%s'" % (debug_pretext, searchsubscount)) #Check for multi CD Releases multicds_pattern = "\+?(cd\d)\+?" multicdsubs = re.search(multicds_pattern, subsfilename, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE | re.VERBOSE) multicdsrls = re.search(multicds_pattern, releasefilename, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE | re.VERBOSE) #Start choosing the right subtitle(s) if searchsubscount == 1 and sync == True: subs_file = filesub #For DEBUG only uncomment next line #log( __name__ ,"%s DEBUG-inside subscount: '%s'" % (debug_pretext, searchsubscount)) break elif string.lower(subsfilename) == string.lower(releasefilename) and sync == True: subs_file = filesub #For DEBUG only uncomment next line #log( __name__ ,"%s DEBUG-subsfile-morethen1: '%s'" % (debug_pretext, subs_file)) break elif string.lower(subsfilename) == string.lower(releasedirname) and sync == True: subs_file = filesub #For DEBUG only uncomment next line #log( __name__ ,"%s DEBUG-subsfile-morethen1-dirname: '%s'" % (debug_pretext, subs_file)) break elif (multicdsubs != None) and (multicdsrls != None) and sync == True: multicdsubs = string.lower(multicdsubs.group(1)) multicdsrls = string.lower(multicdsrls.group(1)) #For DEBUG only uncomment next line #log( __name__ ,"%s DEBUG-multicdsubs: '%s'" % (debug_pretext, multicdsubs)) #log( __name__ ,"%s DEBUG-multicdsrls: '%s'" % (debug_pretext, multicdsrls)) if multicdsrls == multicdsubs: subs_file = filesub break else: #If none is found just open a dialog box for browsing the temporary subtitle folder sub_ext = "srt,aas,ssa,sub,smi" sub_tmp = [] for root, dirs, files in os.walk(tmp_sub_dir, topdown=False): for file in files: dirfile = os.path.join(root, file) ext = os.path.splitext(dirfile)[1][1:].lower() if ext in sub_ext: sub_tmp.append(dirfile) elif os.path.isfile(dirfile): os.remove(dirfile) # If there are more than one subtitle in the temp dir, launch a browse dialog # so user can choose. If only one subtitle is found, parse it to the addon. if len(sub_tmp) > 1: dialog = xbmcgui.Dialog() subs_file = dialog.browse(1, 'XBMC', 'files', '', False, False, tmp_sub_dir+"/") if subs_file == tmp_sub_dir+"/": subs_file = "" elif sub_tmp: subs_file = sub_tmp[0] return False, language, subs_file #standard output
lanhel/viperaccept
refs/heads/master
viperaccept/__init__.py
1
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- #------------------------------------------------------------------------------- """Expanded unit and acceptance test system for setuptools.""" __author__ = ('Lance Finn Helsten',) __version__ = '0.0' __copyright__ = """Copyright (C) 2014 Lance Helsten""" __docformat__ = "reStructuredText en" __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. """ from .headers import * from .generators import * from .negotiate import *
GuillaumeDerval/INGInious-containers
refs/heads/master
default/inginious/feedback.py
1
#!/usr/bin/python import os import sys import json def load_feedback(): """ Open existing feedback file """ result = {} if os.path.exists('/.__output/__feedback.json'): f = open('/.__output/__feedback.json', 'r') cont = f.read() f.close() else: cont = '{}' try: result = json.loads(cont) except ValueError, e: result = {"result":"crash", "text":"Feedback file has been modified by user !"} return result def save_feedback(rdict): """ Save feedback file """ # Check for output folder if not os.path.exists('/.__output'): os.makedirs('/.__output/') jcont = json.dumps(rdict) f = open('/.__output/__feedback.json', 'w') f.write(jcont) f.close() # Doing the real stuff def set_result(result): """ Set global result value """ rdict = load_feedback() rdict['result'] = result save_feedback(rdict) def set_global_feedback(feedback): """ Set global feedback in case of error """ rdict = load_feedback() rdict['text'] = feedback save_feedback(rdict) def set_problem_feedback(feedback, problem_id): """ Set problem specific feedback """ rdict = load_feedback() if not 'problems' in rdict: rdict['problems'] = {} rdict['problems'][problem_id] = feedback save_feedback(rdict) def get_feedback(): """ Returns the dictionary containing the feedback """ rdict = load_feedback() return rdict
prutseltje/ansible
refs/heads/devel
lib/ansible/modules/network/avi/avi_customipamdnsprofile.py
41
#!/usr/bin/python # # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # # Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_customipamdnsprofile author: Gaurav Rastogi (grastogi@avinetworks.com) short_description: Module for setup of CustomIpamDnsProfile Avi RESTful Object description: - This module is used to configure CustomIpamDnsProfile object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.5" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent", "present"] avi_api_update_method: description: - Default method for object update is HTTP PUT. - Setting to patch will override that behavior to use HTTP PATCH. version_added: "2.5" default: put choices: ["put", "patch"] avi_api_patch_op: description: - Patch operation to use when using avi_api_update_method as patch. version_added: "2.5" choices: ["add", "replace", "delete"] name: description: - Name of the custom ipam dns profile. - Field introduced in 17.1.1. required: true script_params: description: - Parameters that are always passed to the ipam/dns script. - Field introduced in 17.1.1. script_uri: description: - Script uri of form controller //ipamdnsscripts/<file-name>. - Field introduced in 17.1.1. required: true tenant_ref: description: - It is a reference to an object of type tenant. - Field introduced in 17.1.1. url: description: - Avi controller URL of the object. uuid: description: - Field introduced in 17.1.1. extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Example to create CustomIpamDnsProfile object avi_customipamdnsprofile: controller: 10.10.25.42 username: admin password: something state: present name: sample_customipamdnsprofile """ RETURN = ''' obj: description: CustomIpamDnsProfile (api/customipamdnsprofile) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.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']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), name=dict(type='str', required=True), script_params=dict(type='list',), script_uri=dict(type='str', required=True), 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, 'customipamdnsprofile', set([])) if __name__ == '__main__': main()
nickleefly/youtube-dl
refs/heads/master
youtube_dl/extractor/miomio.py
15
# coding: utf-8 from __future__ import unicode_literals import random from .common import InfoExtractor from ..compat import compat_urlparse from ..utils import ( xpath_text, int_or_none, ExtractorError, sanitized_Request, ) class MioMioIE(InfoExtractor): IE_NAME = 'miomio.tv' _VALID_URL = r'https?://(?:www\.)?miomio\.tv/watch/cc(?P<id>[0-9]+)' _TESTS = [{ # "type=video" in flashvars 'url': 'http://www.miomio.tv/watch/cc88912/', 'info_dict': { 'id': '88912', 'ext': 'flv', 'title': '【SKY】字幕 铠武昭和VS平成 假面骑士大战FEAT战队 魔星字幕组 字幕', 'duration': 5923, }, 'skip': 'Unable to load videos', }, { 'url': 'http://www.miomio.tv/watch/cc184024/', 'info_dict': { 'id': '43729', 'title': '《动漫同人插画绘制》', }, 'playlist_mincount': 86, 'skip': 'Unable to load videos', }, { 'url': 'http://www.miomio.tv/watch/cc173113/', 'info_dict': { 'id': '173113', 'title': 'The New Macbook 2015 上手试玩与简评' }, 'playlist_mincount': 2, 'skip': 'Unable to load videos', }, { # new 'h5' player 'url': 'http://www.miomio.tv/watch/cc273997/', 'md5': '0b27a4b4495055d826813f8c3a6b2070', 'info_dict': { 'id': '273997', 'ext': 'mp4', 'title': 'マツコの知らない世界【劇的進化SP!ビニール傘&冷凍食品2016】 1_2 - 16 05 31', }, }] def _extract_mioplayer(self, webpage, video_id, title, http_headers): xml_config = self._search_regex( r'flashvars="type=(?:sina|video)&amp;(.+?)&amp;', webpage, 'xml config') # skipping the following page causes lags and eventually connection drop-outs self._request_webpage( 'http://www.miomio.tv/mioplayer/mioplayerconfigfiles/xml.php?id=%s&r=%s' % (id, random.randint(100, 999)), video_id) vid_config_request = sanitized_Request( 'http://www.miomio.tv/mioplayer/mioplayerconfigfiles/sina.php?{0}'.format(xml_config), headers=http_headers) # the following xml contains the actual configuration information on the video file(s) vid_config = self._download_xml(vid_config_request, video_id) if not int_or_none(xpath_text(vid_config, 'timelength')): raise ExtractorError('Unable to load videos!', expected=True) entries = [] for f in vid_config.findall('./durl'): segment_url = xpath_text(f, 'url', 'video url') if not segment_url: continue order = xpath_text(f, 'order', 'order') segment_id = video_id segment_title = title if order: segment_id += '-%s' % order segment_title += ' part %s' % order entries.append({ 'id': segment_id, 'url': segment_url, 'title': segment_title, 'duration': int_or_none(xpath_text(f, 'length', 'duration'), 1000), 'http_headers': http_headers, }) return entries def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) title = self._html_search_meta( 'description', webpage, 'title', fatal=True) mioplayer_path = self._search_regex( r'src="(/mioplayer(?:_h5)?/[^"]+)"', webpage, 'ref_path') if '_h5' in mioplayer_path: player_url = compat_urlparse.urljoin(url, mioplayer_path) player_webpage = self._download_webpage( player_url, video_id, note='Downloading player webpage', headers={'Referer': url}) entries = self._parse_html5_media_entries(player_url, player_webpage, video_id) http_headers = {'Referer': player_url} else: http_headers = {'Referer': 'http://www.miomio.tv%s' % mioplayer_path} entries = self._extract_mioplayer(webpage, video_id, title, http_headers) if len(entries) == 1: segment = entries[0] segment['id'] = video_id segment['title'] = title segment['http_headers'] = http_headers return segment return { '_type': 'multi_video', 'id': video_id, 'entries': entries, 'title': title, 'http_headers': http_headers, }
mollstam/UnrealPy
refs/heads/master
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/django-1.8.2/tests/migrations/migrations_test_apps/unspecified_app_with_conflict/migrations/0002_second.py
425
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("unspecified_app_with_conflict", "0001_initial")] operations = [ migrations.DeleteModel("Tribble"), migrations.RemoveField("Author", "silly_field"), migrations.AddField("Author", "rating", models.IntegerField(default=0)), migrations.CreateModel( "Book", [ ("id", models.AutoField(primary_key=True)), ], ) ]
Ictp/indico
refs/heads/master
bin/utils/fileArchiveStats.py
2
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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. ## ## Indico 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 Indico;if not, see <http://www.gnu.org/licenses/>. """ Calculates total size of archive and number of files """ from indico.core.db import DBMgr from MaKaC.conference import LocalFile, ConferenceHolder from indico.util.console import conferenceHolderIterator def main(): dbi = DBMgr.getInstance() dbi.startRequest() ch = ConferenceHolder() totalSize = 0 fNumber = 0 for __, obj in conferenceHolderIterator(ch, verbose=True): for material in obj.getAllMaterialList(): for res in material.getResourceList(): if isinstance(res, LocalFile): try: totalSize += res.getSize() fNumber += 1 except OSError: print "Problems stating size of '%s'" % res.getFilePath() dbi.endRequest(False) print "%d files, %d bytes total" % (fNumber, totalSize) print "avg %s bytes/file" % (float(totalSize) / fNumber) if __name__ == '__main__': main()
odyaka341/pyglet
refs/heads/master
tools/genmpkg/bdist_mpkg_pyglet/util.py
26
import os, sys try: set except NameError: from sets import Set as set def fsencoding(s, encoding=sys.getfilesystemencoding()): if isinstance(s, unicode): s = s.encode(encoding) return s SCMDIRS = ['CVS', '.svn'] def skipscm(ofn): ofn = fsencoding(ofn) fn = os.path.basename(ofn) if fn in SCMDIRS: return False return True def skipfunc(junk=(), junk_exts=(), chain=()): junk = set(junk) junk_exts = set(junk_exts) chain = tuple(chain) def _skipfunc(fn): if os.path.basename(fn) in junk: return False elif os.path.splitext(fn)[1] in junk_exts: return False for func in chain: if not func(fn): return False else: return True return _skipfunc JUNK = ['.DS_Store', '.gdb_history', 'build', 'dist'] + SCMDIRS JUNK_EXTS = ['.pbxuser', '.pyc', '.pyo', '.swp'] skipjunk = skipfunc(JUNK, JUNK_EXTS) def copy_tree(src, dst, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0, condition=None): """ Copy an entire directory tree 'src' to a new location 'dst'. Both 'src' and 'dst' must be directory names. If 'src' is not a directory, raise DistutilsFileError. If 'dst' does not exist, it is created with 'mkpath()'. The end result of the copy is that every file in 'src' is copied to 'dst', and directories under 'src' are recursively copied to 'dst'. Return the list of files that were copied or might have been copied, using their output name. The return value is unaffected by 'update' or 'dry_run': it is simply the list of all files under 'src', with the names changed to be under 'dst'. 'preserve_mode' and 'preserve_times' are the same as for 'copy_file'; note that they only apply to regular files, not to directories. If 'preserve_symlinks' is true, symlinks will be copied as symlinks (on platforms that support them!); otherwise (the default), the destination of the symlink will be copied. 'update' and 'verbose' are the same as for 'copy_file'. """ from distutils.dir_util import mkpath from distutils.file_util import copy_file from distutils.dep_util import newer from distutils.errors import DistutilsFileError from distutils import log src = fsencoding(src) dst = fsencoding(dst) if condition is None: condition = skipjunk if not dry_run and not os.path.isdir(src): raise DistutilsFileError( "cannot copy tree '%s': not a directory" % src) try: names = os.listdir(src) except os.error, (errno, errstr): if dry_run: names = [] else: raise DistutilsFileError("error listing files in '%s': %s" % ( src, errstr)) if not dry_run: mkpath(dst) outputs = [] for n in names: src_name = os.path.join(src, n) dst_name = os.path.join(dst, n) if (condition is not None) and (not condition(src_name)): continue if preserve_symlinks and os.path.islink(src_name): link_dest = os.readlink(src_name) log.info("linking %s -> %s", dst_name, link_dest) if not dry_run: if update and not newer(src, dst_name): pass else: if os.path.islink(dst_name): os.remove(dst_name) os.symlink(link_dest, dst_name) outputs.append(dst_name) elif os.path.isdir(src_name): outputs.extend( copy_tree(src_name, dst_name, preserve_mode, preserve_times, preserve_symlinks, update, dry_run=dry_run, condition=condition)) else: copy_file(src_name, dst_name, preserve_mode, preserve_times, update, dry_run=dry_run) outputs.append(dst_name) return outputs
SeleniumHQ/buck
refs/heads/master
test/com/facebook/buck/testrunner/check-allowed-entries-in-archive.py
2
#!/usr/bin/env python # Copyright 2017-present Facebook, 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. """ Verifies that an archive contains only allowed entries. """ import unittest from zipfile import ZipFile import pkg_resources ALLOWED_ENTRIES = """ com/facebook/buck/core/util/log/appendablelogrecord/AppendableLogRecord.class com/facebook/buck/jvm/java/runner/FileClassPathRunner.class com/facebook/buck/test/result/type/ResultType.class com/facebook/buck/test/selectors/Nullable.class com/facebook/buck/test/selectors/PatternTestSelector.class com/facebook/buck/test/selectors/SimpleTestSelector.class com/facebook/buck/test/selectors/TestDescription.class com/facebook/buck/test/selectors/TestSelector.class com/facebook/buck/test/selectors/TestSelectorList$1.class com/facebook/buck/test/selectors/TestSelectorList$Builder.class com/facebook/buck/test/selectors/TestSelectorList.class com/facebook/buck/test/selectors/TestSelectorParseException.class com/facebook/buck/testrunner/BaseRunner.class com/facebook/buck/testrunner/BuckBlockJUnit4ClassRunner$1.class com/facebook/buck/testrunner/BuckBlockJUnit4ClassRunner.class com/facebook/buck/testrunner/BuckXmlTestRunListener.class com/facebook/buck/testrunner/CheckDependency.class com/facebook/buck/testrunner/DelegateRunNotifier$1.class com/facebook/buck/testrunner/DelegateRunNotifier$2.class com/facebook/buck/testrunner/DelegateRunNotifier.class com/facebook/buck/testrunner/DelegateRunnerWithTimeout$1.class com/facebook/buck/testrunner/DelegateRunnerWithTimeout.class com/facebook/buck/testrunner/InstrumentationMain.class com/facebook/buck/testrunner/InstrumentationTestRunner$1.class com/facebook/buck/testrunner/InstrumentationTestRunner$Nullable.class com/facebook/buck/testrunner/InstrumentationTestRunner.class com/facebook/buck/testrunner/JUnitMain.class com/facebook/buck/testrunner/JUnitRunner$1.class com/facebook/buck/testrunner/JUnitRunner$2$1.class com/facebook/buck/testrunner/JUnitRunner$2.class com/facebook/buck/testrunner/JUnitRunner$RecordingFilter.class com/facebook/buck/testrunner/JUnitRunner$TestListener.class com/facebook/buck/testrunner/JUnitRunner.class com/facebook/buck/testrunner/JulLogFormatter$1.class com/facebook/buck/testrunner/JulLogFormatter.class com/facebook/buck/testrunner/SameThreadFailOnTimeout.class com/facebook/buck/testrunner/TestNGMain.class com/facebook/buck/testrunner/TestNGRunner$1.class com/facebook/buck/testrunner/TestNGRunner$FilteringAnnotationTransformer.class com/facebook/buck/testrunner/TestNGRunner$JUnitReportReporterWithMethodParameters.class com/facebook/buck/testrunner/TestNGRunner$TestListener.class com/facebook/buck/testrunner/TestNGRunner.class com/facebook/buck/testrunner/TestResult.class com/facebook/buck/util/concurrent/MostExecutors$1.class com/facebook/buck/util/concurrent/MostExecutors$NamedThreadFactory.class com/facebook/buck/util/concurrent/MostExecutors.class com/facebook/buck/util/environment/Architecture.class com/facebook/buck/util/environment/Platform.class com/facebook/buck/util/environment/PlatformType.class """ class TestAppend(unittest.TestCase): def test_allowed_jar_entries(self): with pkg_resources.resource_stream(__name__, "testrunner-bin-fixed.jar") as r: with ZipFile(r) as zip_file: for zip_file_entry in zip_file.namelist(): entry = zip_file_entry.encode("utf-8") if not entry.endswith("/"): self.assertTrue( entry in ALLOWED_ENTRIES, "Found unexpected entry in testrunner jar: %s" % entry, )
canvasnetworks/canvas
refs/heads/master
common/boto/ec2/buyreservation.py
56
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/ # # 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, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing 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 MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR 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. import boto.ec2 from boto.sdb.db.property import StringProperty, IntegerProperty from boto.manage import propget InstanceTypes = ['m1.small', 'm1.large', 'm1.xlarge', 'c1.medium', 'c1.xlarge', 'm2.xlarge', 'm2.2xlarge', 'm2.4xlarge', 'cc1.4xlarge', 't1.micro'] class BuyReservation(object): def get_region(self, params): if not params.get('region', None): prop = StringProperty(name='region', verbose_name='EC2 Region', choices=boto.ec2.regions) params['region'] = propget.get(prop, choices=boto.ec2.regions) def get_instance_type(self, params): if not params.get('instance_type', None): prop = StringProperty(name='instance_type', verbose_name='Instance Type', choices=InstanceTypes) params['instance_type'] = propget.get(prop) def get_quantity(self, params): if not params.get('quantity', None): prop = IntegerProperty(name='quantity', verbose_name='Number of Instances') params['quantity'] = propget.get(prop) def get_zone(self, params): if not params.get('zone', None): prop = StringProperty(name='zone', verbose_name='EC2 Availability Zone', choices=self.ec2.get_all_zones) params['zone'] = propget.get(prop) def get(self, params): self.get_region(params) self.ec2 = params['region'].connect() self.get_instance_type(params) self.get_zone(params) self.get_quantity(params) if __name__ == "__main__": obj = BuyReservation() params = {} obj.get(params) offerings = obj.ec2.get_all_reserved_instances_offerings(instance_type=params['instance_type'], availability_zone=params['zone'].name) print '\nThe following Reserved Instances Offerings are available:\n' for offering in offerings: offering.describe() prop = StringProperty(name='offering', verbose_name='Offering', choices=offerings) offering = propget.get(prop) print '\nYou have chosen this offering:' offering.describe() unit_price = float(offering.fixed_price) total_price = unit_price * params['quantity'] print '!!! You are about to purchase %d of these offerings for a total of $%.2f !!!' % (params['quantity'], total_price) answer = raw_input('Are you sure you want to do this? If so, enter YES: ') if answer.strip().lower() == 'yes': offering.purchase(params['quantity']) else: print 'Purchase cancelled'
sursum/buckanjaren
refs/heads/master
buckanjaren/lib/python3.5/site-packages/django/contrib/sites/migrations/0002_alter_domain_unique.py
379
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.contrib.sites.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.AlterField( model_name='site', name='domain', field=models.CharField( max_length=100, unique=True, validators=[django.contrib.sites.models._simple_domain_name_validator], verbose_name='domain name' ), ), ]
jacobajit/ion
refs/heads/master
intranet/apps/eighth/migrations/0023_auto_20150530_0026.py
1
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('eighth', '0022_schedactivity_comments_to_title')] operations = [ migrations.AddField(model_name='eighthscheduledactivity', name='comments', field=models.CharField(max_length=1000, blank=True),), migrations.AlterField(model_name='eighthscheduledactivity', name='title', field=models.CharField(max_length=1000, blank=True),), ]
OscarSwanros/swift
refs/heads/master
utils/pass-pipeline/src/passes.py
22
from pass_pipeline import Pass # TODO: This should not be hard coded. Create a tool in the compiler that knows # how to dump the passes and the pipelines themselves. AADumper = Pass('AADumper') ABCOpt = Pass('ABCOpt') AddressLowering = Pass('AddressLowering') AllocBoxToStack = Pass('AllocBoxToStack') CFGPrinter = Pass('CFGPrinter') COWArrayOpts = Pass('COWArrayOpts') CSE = Pass('CSE') CapturePromotion = Pass('CapturePromotion') CapturePropagation = Pass('CapturePropagation') ClosureSpecializer = Pass('ClosureSpecializer') CodeMotion = Pass('CodeMotion') CopyForwarding = Pass('CopyForwarding') DCE = Pass('DCE') DeadFunctionElimination = Pass('DeadFunctionElimination') DeadObjectElimination = Pass('DeadObjectElimination') DefiniteInitialization = Pass('DefiniteInitialization') DiagnoseUnreachable = Pass('DiagnoseUnreachable') DiagnosticConstantPropagation = Pass('DiagnosticConstantPropagation') EarlyInliner = Pass('EarlyInliner') EmitDFDiagnostics = Pass('EmitDFDiagnostics') FunctionSignatureOpts = Pass('FunctionSignatureOpts') GlobalARCOpts = Pass('GlobalARCOpts') GlobalLoadStoreOpts = Pass('GlobalLoadStoreOpts') GlobalOpt = Pass('GlobalOpt') IVInfoPrinter = Pass('IVInfoPrinter') InstCount = Pass('InstCount') LICM = Pass('LICM') LateInliner = Pass('LateInliner') LoopInfoPrinter = Pass('LoopInfoPrinter') LoopRotate = Pass('LoopRotate') LowerAggregateInstrs = Pass('LowerAggregateInstrs') MandatoryInlining = Pass('MandatoryInlining') Mem2Reg = Pass('Mem2Reg') NoReturnFolding = Pass('NoReturnFolding') PerfInliner = Pass('PerfInliner') PerformanceConstantPropagation = Pass('PerformanceConstantPropagation') PredictableMemoryOptimizations = Pass('PredictableMemoryOptimizations') SILCleanup = Pass('SILCleanup') SILCombine = Pass('SILCombine') SILLinker = Pass('SILLinker') SROA = Pass('SROA') SimplifyCFG = Pass('SimplifyCFG') SpeculativeDevirtualizer = Pass('SpeculativeDevirtualizer') SplitAllCriticalEdges = Pass('SplitAllCriticalEdges') SplitNonCondBrCriticalEdges = Pass('SplitNonCondBrCriticalEdges') StripDebugInfo = Pass('StripDebugInfo') SwiftArrayOpts = Pass('SwiftArrayOpts') PASSES = [ AADumper, ABCOpt, AddressLowering, AllocBoxToStack, CFGPrinter, COWArrayOpts, CSE, CapturePromotion, CapturePropagation, ClosureSpecializer, CodeMotion, CopyForwarding, DCE, DeadFunctionElimination, DeadObjectElimination, DefiniteInitialization, DiagnoseUnreachable, DiagnosticConstantPropagation, EarlyInliner, EmitDFDiagnostics, FunctionSignatureOpts, GlobalARCOpts, GlobalLoadStoreOpts, GlobalOpt, IVInfoPrinter, InstCount, LICM, LateInliner, LoopInfoPrinter, LoopRotate, LowerAggregateInstrs, MandatoryInlining, Mem2Reg, NoReturnFolding, PerfInliner, PerformanceConstantPropagation, PredictableMemoryOptimizations, SILCleanup, SILCombine, SILLinker, SROA, SimplifyCFG, SpeculativeDevirtualizer, SplitAllCriticalEdges, SplitNonCondBrCriticalEdges, StripDebugInfo, SwiftArrayOpts, ]
bgxavier/nova
refs/heads/master
nova/cmd/novncproxy.py
38
# Copyright (c) 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Websocket proxy that is compatible with OpenStack Nova noVNC consoles. Leverages websockify.py by Joel Martin """ import sys from oslo_config import cfg from nova.cmd import baseproxy from nova import config opts = [ cfg.StrOpt('novncproxy_host', default='0.0.0.0', help='Host on which to listen for incoming requests'), cfg.IntOpt('novncproxy_port', default=6080, help='Port on which to listen for incoming requests'), ] CONF = cfg.CONF CONF.register_cli_opts(opts) def main(): # set default web flag option CONF.set_default('web', '/usr/share/novnc') config.parse_args(sys.argv) baseproxy.proxy( host=CONF.novncproxy_host, port=CONF.novncproxy_port)
Algomorph/gpxanalyzer
refs/heads/master
perf_test.py
1
''' Created on Mar 7, 2014 @author: algomorph ''' import gpxanalyzer.utils.tilecombiner as tc import gpxanalyzer.utils.data as dm import gpxanalyzer.filters.cl_manager as clm import gpxanalyzer.filters.color_structure as cs import gpxanalyzer.utils.system as system import pyopencl as cl import libMPEG7 as mp7 import timeit import unittest import numpy as np import os from PIL import Image class Test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testCSspeed(self): gpu = system.get_devices_of_type(cl.device_type.GPU) mgr = clm.FilterCLManager.generate(gpu, (4096, 4096), cell_shape=(256,256),verbose=True) extr = cs.CSDescriptorExtractor(mgr) cells256_folder = "/mnt/sdb2/Data/gigapan/107000" img_names = dm.get_raster_names(cells256_folder) tiles_x, tiles_y = tc.get_cell_counts(img_names) tiles = [] for name in img_names: tiles.append(np.array(Image.open(cells256_folder + os.path.sep + name))) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
lamer547/suncoin
refs/heads/master
share/qt/extract_strings_qt.py
2945
#!/usr/bin/python ''' Extract _("...") strings for translation and convert to Qt4 stringdefs so that they can be picked up by Qt linguist. ''' from subprocess import Popen, PIPE import glob import operator OUT_CPP="src/qt/bitcoinstrings.cpp" EMPTY=['""'] def parse_po(text): """ Parse 'po' format produced by xgettext. Return a list of (msgid,msgstr) tuples. """ messages = [] msgid = [] msgstr = [] in_msgid = False in_msgstr = False for line in text.split('\n'): line = line.rstrip('\r') if line.startswith('msgid '): if in_msgstr: messages.append((msgid, msgstr)) in_msgstr = False # message start in_msgid = True msgid = [line[6:]] elif line.startswith('msgstr '): in_msgid = False in_msgstr = True msgstr = [line[7:]] elif line.startswith('"'): if in_msgid: msgid.append(line) if in_msgstr: msgstr.append(line) if in_msgstr: messages.append((msgid, msgstr)) return messages files = glob.glob('src/*.cpp') + glob.glob('src/*.h') # xgettext -n --keyword=_ $FILES child = Popen(['xgettext','--output=-','-n','--keyword=_'] + files, stdout=PIPE) (out, err) = child.communicate() messages = parse_po(out) f = open(OUT_CPP, 'w') f.write("""#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif """) f.write('static const char UNUSED *bitcoin_strings[] = {\n') messages.sort(key=operator.itemgetter(0)) for (msgid, msgstr) in messages: if msgid != EMPTY: f.write('QT_TRANSLATE_NOOP("bitcoin-core", %s),\n' % ('\n'.join(msgid))) f.write('};') f.close()
lexyan/SickBeard
refs/heads/master
autoProcessTV/hellaToSickBeard.py
57
#!/usr/bin/env python # Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import sys import autoProcessTV if len(sys.argv) < 4: print "No folder supplied - is this being called from HellaVCR?" sys.exit() else: autoProcessTV.processEpisode(sys.argv[3], sys.argv[2])
robert-digit/superset
refs/heads/master
superset/migrations/versions/db0c65b146bd_update_slice_model_json.py
9
"""update_slice_model_json Revision ID: db0c65b146bd Revises: f18570e03440 Create Date: 2017-01-24 12:31:06.541746 """ # revision identifiers, used by Alembic. revision = 'db0c65b146bd' down_revision = 'f18570e03440' from alembic import op import json from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Text from superset import db from superset.legacy import cast_form_data Base = declarative_base() class Slice(Base): """Declarative class to do query in upgrade""" __tablename__ = 'slices' id = Column(Integer, primary_key=True) datasource_type = Column(String(200)) slice_name = Column(String(200)) params = Column(Text) def upgrade(): bind = op.get_bind() session = db.Session(bind=bind) slices = session.query(Slice).all() slice_len = len(slices) for i, slc in enumerate(slices): try: d = json.loads(slc.params or '{}') d = cast_form_data(d) slc.params = json.dumps(d, indent=2, sort_keys=True) session.merge(slc) session.commit() print('Upgraded ({}/{}): {}'.format(i, slice_len, slc.slice_name)) except Exception as e: print(slc.slice_name + ' error: ' + str(e)) session.close() def downgrade(): pass
orsonwang/shadowsocks
refs/heads/master
shadowsocks/encrypt.py
990
#!/usr/bin/env python # # Copyright 2012-2015 clowwindy # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import, division, print_function, \ with_statement import os import sys import hashlib import logging from shadowsocks import common from shadowsocks.crypto import rc4_md5, openssl, sodium, table method_supported = {} method_supported.update(rc4_md5.ciphers) method_supported.update(openssl.ciphers) method_supported.update(sodium.ciphers) method_supported.update(table.ciphers) def random_string(length): return os.urandom(length) cached_keys = {} def try_cipher(key, method=None): Encryptor(key, method) def EVP_BytesToKey(password, key_len, iv_len): # equivalent to OpenSSL's EVP_BytesToKey() with count 1 # so that we make the same key and iv as nodejs version cached_key = '%s-%d-%d' % (password, key_len, iv_len) r = cached_keys.get(cached_key, None) if r: return r m = [] i = 0 while len(b''.join(m)) < (key_len + iv_len): md5 = hashlib.md5() data = password if i > 0: data = m[i - 1] + password md5.update(data) m.append(md5.digest()) i += 1 ms = b''.join(m) key = ms[:key_len] iv = ms[key_len:key_len + iv_len] cached_keys[cached_key] = (key, iv) return key, iv class Encryptor(object): def __init__(self, key, method): self.key = key self.method = method self.iv = None self.iv_sent = False self.cipher_iv = b'' self.decipher = None method = method.lower() self._method_info = self.get_method_info(method) if self._method_info: self.cipher = self.get_cipher(key, method, 1, random_string(self._method_info[1])) else: logging.error('method %s not supported' % method) sys.exit(1) def get_method_info(self, method): method = method.lower() m = method_supported.get(method) return m def iv_len(self): return len(self.cipher_iv) def get_cipher(self, password, method, op, iv): password = common.to_bytes(password) m = self._method_info if m[0] > 0: key, iv_ = EVP_BytesToKey(password, m[0], m[1]) else: # key_length == 0 indicates we should use the key directly key, iv = password, b'' iv = iv[:m[1]] if op == 1: # this iv is for cipher not decipher self.cipher_iv = iv[:m[1]] return m[2](method, key, iv, op) def encrypt(self, buf): if len(buf) == 0: return buf if self.iv_sent: return self.cipher.update(buf) else: self.iv_sent = True return self.cipher_iv + self.cipher.update(buf) def decrypt(self, buf): if len(buf) == 0: return buf if self.decipher is None: decipher_iv_len = self._method_info[1] decipher_iv = buf[:decipher_iv_len] self.decipher = self.get_cipher(self.key, self.method, 0, iv=decipher_iv) buf = buf[decipher_iv_len:] if len(buf) == 0: return buf return self.decipher.update(buf) def encrypt_all(password, method, op, data): result = [] method = method.lower() (key_len, iv_len, m) = method_supported[method] if key_len > 0: key, _ = EVP_BytesToKey(password, key_len, iv_len) else: key = password if op: iv = random_string(iv_len) result.append(iv) else: iv = data[:iv_len] data = data[iv_len:] cipher = m(method, key, iv, op) result.append(cipher.update(data)) return b''.join(result) CIPHERS_TO_TEST = [ 'aes-128-cfb', 'aes-256-cfb', 'rc4-md5', 'salsa20', 'chacha20', 'table', ] def test_encryptor(): from os import urandom plain = urandom(10240) for method in CIPHERS_TO_TEST: logging.warn(method) encryptor = Encryptor(b'key', method) decryptor = Encryptor(b'key', method) cipher = encryptor.encrypt(plain) plain2 = decryptor.decrypt(cipher) assert plain == plain2 def test_encrypt_all(): from os import urandom plain = urandom(10240) for method in CIPHERS_TO_TEST: logging.warn(method) cipher = encrypt_all(b'key', method, 1, plain) plain2 = encrypt_all(b'key', method, 0, cipher) assert plain == plain2 if __name__ == '__main__': test_encrypt_all() test_encryptor()
twamarc/schemaorg
refs/heads/master
lib/markdown/extensions/sane_lists.py
67
""" Sane List Extension for Python-Markdown ======================================= Modify the behavior of Lists in Python-Markdown to act in a sane manor. See <https://pythonhosted.org/Markdown/extensions/sane_lists.html> for documentation. Original code Copyright 2011 [Waylan Limberg](http://achinghead.com) All changes Copyright 2011-2014 The Python Markdown Project License: [BSD](http://www.opensource.org/licenses/bsd-license.php) """ from __future__ import absolute_import from __future__ import unicode_literals from . import Extension from ..blockprocessors import OListProcessor, UListProcessor import re class SaneOListProcessor(OListProcessor): SIBLING_TAGS = ['ol'] def __init__(self, parser): super(SaneOListProcessor, self).__init__(parser) self.CHILD_RE = re.compile(r'^[ ]{0,%d}((\d+\.))[ ]+(.*)' % (self.tab_length - 1)) class SaneUListProcessor(UListProcessor): SIBLING_TAGS = ['ul'] def __init__(self, parser): super(SaneUListProcessor, self).__init__(parser) self.CHILD_RE = re.compile(r'^[ ]{0,%d}(([*+-]))[ ]+(.*)' % (self.tab_length - 1)) class SaneListExtension(Extension): """ Add sane lists to Markdown. """ def extendMarkdown(self, md, md_globals): """ Override existing Processors. """ md.parser.blockprocessors['olist'] = SaneOListProcessor(md.parser) md.parser.blockprocessors['ulist'] = SaneUListProcessor(md.parser) def makeExtension(*args, **kwargs): return SaneListExtension(*args, **kwargs)
CenterForOpenScience/waterbutler
refs/heads/develop
waterbutler/auth/osf/handler.py
2
import logging import datetime import jwe import jwt import aiohttp from aiohttp.client_exceptions import ClientError, ContentTypeError from waterbutler.core import exceptions from waterbutler.auth.osf import settings from waterbutler.core.auth import AuthType, BaseAuthHandler from waterbutler.settings import MFR_IDENTIFYING_HEADER JWE_KEY = jwe.kdf(settings.JWE_SECRET.encode(), settings.JWE_SALT.encode()) logger = logging.getLogger(__name__) class OsfAuthHandler(BaseAuthHandler): """Identity lookup via the Open Science Framework""" ACTION_MAP = { 'put': 'upload', 'get': 'download', 'head': 'metadata', 'delete': 'delete', } def build_payload(self, bundle, view_only=None, cookie=None): query_params = {} if cookie: bundle['cookie'] = cookie if view_only: # View only must go outside of the jwt query_params['view_only'] = view_only raw_payload = jwe.encrypt(jwt.encode({ 'data': bundle, 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.JWT_EXPIRATION) }, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM), JWE_KEY) # Note: `aiohttp3` uses `yarl` which only supports string parameters query_params['payload'] = raw_payload.decode("utf-8") return query_params async def make_request(self, params, headers, cookies): try: # Note: with simple request whose response is handled right afterwards without "being passed # further along", use the context manager so WB doesn't need to handle the sessions. async with aiohttp.request( 'get', settings.API_URL, params=params, headers=headers, cookies=cookies, ) as response: if response.status != 200: try: data = await response.json() except (ValueError, ContentTypeError): data = await response.read() raise exceptions.AuthError(data, code=response.status) try: raw = await response.json() signed_jwt = jwe.decrypt(raw['payload'].encode(), JWE_KEY) data = jwt.decode(signed_jwt, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM, options={'require_exp': True}) return data['data'] except (jwt.InvalidTokenError, KeyError): raise exceptions.AuthError(data, code=response.status) except ClientError: raise exceptions.AuthError('Unable to connect to auth sever', code=503) async def fetch(self, request, bundle): """Used for v0""" headers = {'Content-Type': 'application/json'} if 'Authorization' in request.headers: headers['Authorization'] = request.headers['Authorization'] cookie = request.query_arguments.get('cookie') if cookie: cookie = cookie[0].decode() view_only = request.query_arguments.get('view_only') if view_only: view_only = view_only[0].decode() payload = (await self.make_request( self.build_payload(bundle, cookie=cookie, view_only=view_only), headers, dict(request.cookies) )) payload['auth']['callback_url'] = payload['callback_url'] return payload async def get(self, resource, provider, request, action=None, auth_type=AuthType.SOURCE, path='', version=None): """Used for v1. Requests credentials and configuration from the OSF for the given resource (project) and provider. Auth credentials sent by the user to WB are passed onto the OSF so it can determine the user. Auth payload also includes some metrics and metadata to help the OSF with resource tallies and permission optimizations. """ (permissions_req, intent) = self._determine_actions(resource, provider, request, action, auth_type, path, version) headers = {'Content-Type': 'application/json'} if 'Authorization' in request.headers: headers['Authorization'] = request.headers['Authorization'] if MFR_IDENTIFYING_HEADER in request.headers: headers[MFR_IDENTIFYING_HEADER] = request.headers[MFR_IDENTIFYING_HEADER] cookie = request.query_arguments.get('cookie') if cookie: cookie = cookie[0].decode() view_only = request.query_arguments.get('view_only') if view_only: # View only must go outside of the jwt view_only = view_only[0].decode() payload = await self.make_request( self.build_payload({ 'nid': resource, 'provider': provider, 'action': permissions_req, # what permissions does the user need? 'intent': intent, # what is the user trying to do? 'path': path, 'version': version, 'metrics': { 'referrer': request.headers.get('Referer'), 'user_agent': request.headers.get('User-Agent'), 'origin': request.headers.get('Origin'), 'uri': request.uri, } }, cookie=cookie, view_only=view_only), headers, dict(request.cookies) ) payload['auth']['callback_url'] = payload['callback_url'] return payload def _determine_actions(self, resource, provider, request, action=None, auth_type=AuthType.SOURCE, path='', version=None): """Decide what the user is trying to achieve and what permissions they need to achieve it. Returns two values, ``osf_action`` and ``intended_action``. ``intended_action`` is a tag that describes what the user is trying to accomplish. This tag can have many values, currently including: ``copyfrom``, ``copyto``, ``create_dir``, ``create_file``, ``daz``, ``delete``, ``download``, ``export``, ``metadata``, ``movefrom``, ``moveto``, ``rename``, ``render``, ``revisions``, ``update_file`` ``osf_action`` describes the permissions needed, but ofuscated with some legacy cruft. In theory, it only needs to be one of two values, ``readonly`` or `readwrite``. However, it used to be overloaded to convey intent in addition to permissions. For back-compat reasons, we are not changing the current returned value. Its possible values are a subset of the ``intended_actions`` from which the OSF can infer whether ``ro`` or ``rw`` permissions are needed. The current mapping is: Implies ``readonly``: ``metadata``, ``download``, ``render``, ``export``. Implies ``readwrite``: ``upload``, ``delete``. """ method = request.method.lower() osf_action, intended_action = None, None if method == 'post' and action: post_action_map = { 'copy': 'download' if auth_type is AuthType.SOURCE else 'upload', 'move': 'delete' if auth_type is AuthType.SOURCE else 'upload', 'rename': 'upload', } intended_post_action_map = { 'copy': 'copyfrom' if auth_type is AuthType.SOURCE else 'copyto', 'move': 'movefrom' if auth_type is AuthType.SOURCE else 'moveto', 'rename': 'rename', } try: osf_action = post_action_map[action.lower()] intended_action = intended_post_action_map[action.lower()] except KeyError: raise exceptions.UnsupportedActionError(method, supported=post_action_map.keys()) elif method == 'put': osf_action = 'upload' if not path.endswith('/'): intended_action = 'update_file' elif request.query_arguments.get('kind', '') == 'folder': intended_action = 'create_dir' else: intended_action = 'create_file' elif method == 'head' and settings.MFR_ACTION_HEADER in request.headers: mfr_action_map = {'render': 'render', 'export': 'export'} mfr_action = request.headers[settings.MFR_ACTION_HEADER].lower() try: osf_action = mfr_action_map[mfr_action] intended_action = mfr_action except KeyError: raise exceptions.UnsupportedActionError(mfr_action, supported=mfr_action_map.keys()) else: try: if method == 'get': if path.endswith('/'): # path isa folder # folders ignore 'revisions' query param if 'zip' in request.query_arguments: osf_action = 'download' intended_action = 'daz' else: osf_action = 'metadata' intended_action = 'metadata' else: # path isa file, not folder # files ignore 'zip' query param # precedence order is 'meta', 'zip', default if 'meta' in request.query_arguments: osf_action = 'metadata' intended_action = 'metadata' elif 'revisions' in request.query_arguments: osf_action = 'revisions' intended_action = 'revisions' else: osf_action = 'download' intended_action = 'download' else: osf_action = self.ACTION_MAP[method] intended_action = self.ACTION_MAP[method] except KeyError: raise exceptions.UnsupportedHTTPMethodError(method, supported=self.ACTION_MAP.keys()) return (osf_action, intended_action)
unaizalakain/django
refs/heads/master
tests/template_tests/filter_tests/test_unordered_list.py
204
from django.template.defaultfilters import unordered_list from django.test import SimpleTestCase, ignore_warnings from django.utils.deprecation import RemovedInDjango110Warning from django.utils.encoding import python_2_unicode_compatible from django.utils.safestring import mark_safe from ..utils import setup class UnorderedListTests(SimpleTestCase): @setup({'unordered_list01': '{{ a|unordered_list }}'}) def test_unordered_list01(self): output = self.engine.render_to_string('unordered_list01', {'a': ['x>', ['<y']]}) self.assertEqual(output, '\t<li>x&gt;\n\t<ul>\n\t\t<li>&lt;y</li>\n\t</ul>\n\t</li>') @ignore_warnings(category=RemovedInDjango110Warning) @setup({'unordered_list02': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'}) def test_unordered_list02(self): output = self.engine.render_to_string('unordered_list02', {'a': ['x>', ['<y']]}) self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') @setup({'unordered_list03': '{{ a|unordered_list }}'}) def test_unordered_list03(self): output = self.engine.render_to_string('unordered_list03', {'a': ['x>', [mark_safe('<y')]]}) self.assertEqual(output, '\t<li>x&gt;\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') @setup({'unordered_list04': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'}) def test_unordered_list04(self): output = self.engine.render_to_string('unordered_list04', {'a': ['x>', [mark_safe('<y')]]}) self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') @setup({'unordered_list05': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'}) def test_unordered_list05(self): output = self.engine.render_to_string('unordered_list05', {'a': ['x>', ['<y']]}) self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') @ignore_warnings(category=RemovedInDjango110Warning) class DeprecatedUnorderedListSyntaxTests(SimpleTestCase): @setup({'unordered_list01': '{{ a|unordered_list }}'}) def test_unordered_list01(self): output = self.engine.render_to_string('unordered_list01', {'a': ['x>', [['<y', []]]]}) self.assertEqual(output, '\t<li>x&gt;\n\t<ul>\n\t\t<li>&lt;y</li>\n\t</ul>\n\t</li>') @setup({'unordered_list02': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'}) def test_unordered_list02(self): output = self.engine.render_to_string('unordered_list02', {'a': ['x>', [['<y', []]]]}) self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') @setup({'unordered_list03': '{{ a|unordered_list }}'}) def test_unordered_list03(self): output = self.engine.render_to_string('unordered_list03', {'a': ['x>', [[mark_safe('<y'), []]]]}) self.assertEqual(output, '\t<li>x&gt;\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') @setup({'unordered_list04': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'}) def test_unordered_list04(self): output = self.engine.render_to_string('unordered_list04', {'a': ['x>', [[mark_safe('<y'), []]]]}) self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') @setup({'unordered_list05': '{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}'}) def test_unordered_list05(self): output = self.engine.render_to_string('unordered_list05', {'a': ['x>', [['<y', []]]]}) self.assertEqual(output, '\t<li>x>\n\t<ul>\n\t\t<li><y</li>\n\t</ul>\n\t</li>') class FunctionTests(SimpleTestCase): def test_list(self): self.assertEqual(unordered_list(['item 1', 'item 2']), '\t<li>item 1</li>\n\t<li>item 2</li>') def test_nested(self): self.assertEqual( unordered_list(['item 1', ['item 1.1']]), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>', ) def test_nested2(self): self.assertEqual( unordered_list(['item 1', ['item 1.1', 'item1.2'], 'item 2']), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item1.2' '</li>\n\t</ul>\n\t</li>\n\t<li>item 2</li>', ) def test_nested3(self): self.assertEqual( unordered_list(['item 1', 'item 2', ['item 2.1']]), '\t<li>item 1</li>\n\t<li>item 2\n\t<ul>\n\t\t<li>item 2.1' '</li>\n\t</ul>\n\t</li>', ) def test_nested_multiple(self): self.assertEqual( unordered_list(['item 1', ['item 1.1', ['item 1.1.1', ['item 1.1.1.1']]]]), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1\n\t\t<ul>\n\t\t\t<li>' 'item 1.1.1\n\t\t\t<ul>\n\t\t\t\t<li>item 1.1.1.1</li>\n\t\t\t' '</ul>\n\t\t\t</li>\n\t\t</ul>\n\t\t</li>\n\t</ul>\n\t</li>', ) def test_nested_multiple2(self): self.assertEqual( unordered_list(['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]), '\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>' 'Lawrence</li>\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>' '\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>', ) def test_autoescape(self): self.assertEqual( unordered_list(['<a>item 1</a>', 'item 2']), '\t<li>&lt;a&gt;item 1&lt;/a&gt;</li>\n\t<li>item 2</li>', ) def test_autoescape_off(self): self.assertEqual( unordered_list(['<a>item 1</a>', 'item 2'], autoescape=False), '\t<li><a>item 1</a></li>\n\t<li>item 2</li>', ) def test_ulitem(self): @python_2_unicode_compatible class ULItem(object): def __init__(self, title): self.title = title def __str__(self): return 'ulitem-%s' % str(self.title) a = ULItem('a') b = ULItem('b') c = ULItem('<a>c</a>') self.assertEqual( unordered_list([a, b, c]), '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>', ) def item_generator(): yield a yield b yield c self.assertEqual( unordered_list(item_generator()), '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>', ) def test_ulitem_autoescape_off(self): @python_2_unicode_compatible class ULItem(object): def __init__(self, title): self.title = title def __str__(self): return 'ulitem-%s' % str(self.title) a = ULItem('a') b = ULItem('b') c = ULItem('<a>c</a>') self.assertEqual( unordered_list([a, b, c], autoescape=False), '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>', ) def item_generator(): yield a yield b yield c self.assertEqual( unordered_list(item_generator(), autoescape=False), '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-<a>c</a></li>', ) @ignore_warnings(category=RemovedInDjango110Warning) def test_legacy(self): """ Old format for unordered lists should still work """ self.assertEqual(unordered_list(['item 1', []]), '\t<li>item 1</li>') self.assertEqual( unordered_list(['item 1', [['item 1.1', []]]]), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>', ) self.assertEqual( unordered_list(['item 1', [['item 1.1', []], ['item 1.2', []]]]), '\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1' '</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>', ) self.assertEqual( unordered_list(['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]), '\t<li>States\n\t<ul>\n\t\t<li>Kansas\n\t\t<ul>\n\t\t\t<li>Lawrence</li>' '\n\t\t\t<li>Topeka</li>\n\t\t</ul>\n\t\t</li>\n\t\t<li>Illinois</li>\n\t</ul>\n\t</li>', )
Pretagonist/Flexget
refs/heads/develop
tests/test_crossmatch.py
2
from __future__ import unicode_literals, division, absolute_import class TestCrossmatch(object): config = """ tasks: test_title: mock: - title: entry 1 - title: entry 2 crossmatch: from: - mock: - title: entry 2 action: reject fields: [title] """ def test_reject_title(self, execute_task): task = execute_task('test_title') assert task.find_entry('rejected', title='entry 2') assert len(task.rejected) == 1
ofrobots/grpc
refs/heads/master
src/python/grpcio/grpc/framework/face/implementations.py
38
# Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Entry points into the Face layer of RPC Framework.""" from grpc.framework.common import cardinality from grpc.framework.common import style from grpc.framework.base import exceptions as _base_exceptions from grpc.framework.base import interfaces as base_interfaces from grpc.framework.face import _calls from grpc.framework.face import _service from grpc.framework.face import exceptions from grpc.framework.face import interfaces class _BaseServicer(base_interfaces.Servicer): def __init__(self, methods, multi_method): self._methods = methods self._multi_method = multi_method def service(self, name, context, output_consumer): method = self._methods.get(name, None) if method is not None: return method(output_consumer, context) elif self._multi_method is not None: try: return self._multi_method.service(name, output_consumer, context) except exceptions.NoSuchMethodError: raise _base_exceptions.NoSuchMethodError() else: raise _base_exceptions.NoSuchMethodError() class _UnaryUnaryMultiCallable(interfaces.UnaryUnaryMultiCallable): def __init__(self, front, name): self._front = front self._name = name def __call__(self, request, timeout): return _calls.blocking_value_in_value_out( self._front, self._name, request, timeout, 'unused trace ID') def future(self, request, timeout): return _calls.future_value_in_value_out( self._front, self._name, request, timeout, 'unused trace ID') def event(self, request, response_callback, abortion_callback, timeout): return _calls.event_value_in_value_out( self._front, self._name, request, response_callback, abortion_callback, timeout, 'unused trace ID') class _UnaryStreamMultiCallable(interfaces.UnaryStreamMultiCallable): def __init__(self, front, name): self._front = front self._name = name def __call__(self, request, timeout): return _calls.inline_value_in_stream_out( self._front, self._name, request, timeout, 'unused trace ID') def event(self, request, response_consumer, abortion_callback, timeout): return _calls.event_value_in_stream_out( self._front, self._name, request, response_consumer, abortion_callback, timeout, 'unused trace ID') class _StreamUnaryMultiCallable(interfaces.StreamUnaryMultiCallable): def __init__(self, front, name, pool): self._front = front self._name = name self._pool = pool def __call__(self, request_iterator, timeout): return _calls.blocking_stream_in_value_out( self._front, self._name, request_iterator, timeout, 'unused trace ID') def future(self, request_iterator, timeout): return _calls.future_stream_in_value_out( self._front, self._name, request_iterator, timeout, 'unused trace ID', self._pool) def event(self, response_callback, abortion_callback, timeout): return _calls.event_stream_in_value_out( self._front, self._name, response_callback, abortion_callback, timeout, 'unused trace ID') class _StreamStreamMultiCallable(interfaces.StreamStreamMultiCallable): def __init__(self, front, name, pool): self._front = front self._name = name self._pool = pool def __call__(self, request_iterator, timeout): return _calls.inline_stream_in_stream_out( self._front, self._name, request_iterator, timeout, 'unused trace ID', self._pool) def event(self, response_consumer, abortion_callback, timeout): return _calls.event_stream_in_stream_out( self._front, self._name, response_consumer, abortion_callback, timeout, 'unused trace ID') class _GenericStub(interfaces.GenericStub): """An interfaces.GenericStub implementation.""" def __init__(self, front, pool): self._front = front self._pool = pool def blocking_value_in_value_out(self, name, request, timeout): return _calls.blocking_value_in_value_out( self._front, name, request, timeout, 'unused trace ID') def future_value_in_value_out(self, name, request, timeout): return _calls.future_value_in_value_out( self._front, name, request, timeout, 'unused trace ID') def inline_value_in_stream_out(self, name, request, timeout): return _calls.inline_value_in_stream_out( self._front, name, request, timeout, 'unused trace ID') def blocking_stream_in_value_out(self, name, request_iterator, timeout): return _calls.blocking_stream_in_value_out( self._front, name, request_iterator, timeout, 'unused trace ID') def future_stream_in_value_out(self, name, request_iterator, timeout): return _calls.future_stream_in_value_out( self._front, name, request_iterator, timeout, 'unused trace ID', self._pool) def inline_stream_in_stream_out(self, name, request_iterator, timeout): return _calls.inline_stream_in_stream_out( self._front, name, request_iterator, timeout, 'unused trace ID', self._pool) def event_value_in_value_out( self, name, request, response_callback, abortion_callback, timeout): return _calls.event_value_in_value_out( self._front, name, request, response_callback, abortion_callback, timeout, 'unused trace ID') def event_value_in_stream_out( self, name, request, response_consumer, abortion_callback, timeout): return _calls.event_value_in_stream_out( self._front, name, request, response_consumer, abortion_callback, timeout, 'unused trace ID') def event_stream_in_value_out( self, name, response_callback, abortion_callback, timeout): return _calls.event_stream_in_value_out( self._front, name, response_callback, abortion_callback, timeout, 'unused trace ID') def event_stream_in_stream_out( self, name, response_consumer, abortion_callback, timeout): return _calls.event_stream_in_stream_out( self._front, name, response_consumer, abortion_callback, timeout, 'unused trace ID') def unary_unary_multi_callable(self, name): return _UnaryUnaryMultiCallable(self._front, name) def unary_stream_multi_callable(self, name): return _UnaryStreamMultiCallable(self._front, name) def stream_unary_multi_callable(self, name): return _StreamUnaryMultiCallable(self._front, name, self._pool) def stream_stream_multi_callable(self, name): return _StreamStreamMultiCallable(self._front, name, self._pool) class _DynamicStub(interfaces.DynamicStub): """An interfaces.DynamicStub implementation.""" def __init__(self, cardinalities, front, pool): self._cardinalities = cardinalities self._front = front self._pool = pool def __getattr__(self, attr): method_cardinality = self._cardinalities.get(attr) if method_cardinality is cardinality.Cardinality.UNARY_UNARY: return _UnaryUnaryMultiCallable(self._front, attr) elif method_cardinality is cardinality.Cardinality.UNARY_STREAM: return _UnaryStreamMultiCallable(self._front, attr) elif method_cardinality is cardinality.Cardinality.STREAM_UNARY: return _StreamUnaryMultiCallable(self._front, attr, self._pool) elif method_cardinality is cardinality.Cardinality.STREAM_STREAM: return _StreamStreamMultiCallable(self._front, attr, self._pool) else: raise AttributeError('_DynamicStub object has no attribute "%s"!' % attr) def _adapt_method_implementations(method_implementations, pool): adapted_implementations = {} for name, method_implementation in method_implementations.iteritems(): if method_implementation.style is style.Service.INLINE: if method_implementation.cardinality is cardinality.Cardinality.UNARY_UNARY: adapted_implementations[name] = _service.adapt_inline_value_in_value_out( method_implementation.unary_unary_inline) elif method_implementation.cardinality is cardinality.Cardinality.UNARY_STREAM: adapted_implementations[name] = _service.adapt_inline_value_in_stream_out( method_implementation.unary_stream_inline) elif method_implementation.cardinality is cardinality.Cardinality.STREAM_UNARY: adapted_implementations[name] = _service.adapt_inline_stream_in_value_out( method_implementation.stream_unary_inline, pool) elif method_implementation.cardinality is cardinality.Cardinality.STREAM_STREAM: adapted_implementations[name] = _service.adapt_inline_stream_in_stream_out( method_implementation.stream_stream_inline, pool) elif method_implementation.style is style.Service.EVENT: if method_implementation.cardinality is cardinality.Cardinality.UNARY_UNARY: adapted_implementations[name] = _service.adapt_event_value_in_value_out( method_implementation.unary_unary_event) elif method_implementation.cardinality is cardinality.Cardinality.UNARY_STREAM: adapted_implementations[name] = _service.adapt_event_value_in_stream_out( method_implementation.unary_stream_event) elif method_implementation.cardinality is cardinality.Cardinality.STREAM_UNARY: adapted_implementations[name] = _service.adapt_event_stream_in_value_out( method_implementation.stream_unary_event) elif method_implementation.cardinality is cardinality.Cardinality.STREAM_STREAM: adapted_implementations[name] = _service.adapt_event_stream_in_stream_out( method_implementation.stream_stream_event) return adapted_implementations def servicer(pool, method_implementations, multi_method_implementation): """Creates a base_interfaces.Servicer. It is guaranteed that any passed interfaces.MultiMethodImplementation will only be called to service an RPC if there is no interfaces.MethodImplementation for the RPC method in the passed method_implementations dictionary. Args: pool: A thread pool. method_implementations: A dictionary from RPC method name to interfaces.MethodImplementation object to be used to service the named RPC method. multi_method_implementation: An interfaces.MultiMethodImplementation to be used to service any RPCs not serviced by the interfaces.MethodImplementations given in the method_implementations dictionary, or None. Returns: A base_interfaces.Servicer that services RPCs via the given implementations. """ adapted_implementations = _adapt_method_implementations( method_implementations, pool) return _BaseServicer(adapted_implementations, multi_method_implementation) def generic_stub(front, pool): """Creates an interfaces.GenericStub. Args: front: A base_interfaces.Front. pool: A futures.ThreadPoolExecutor. Returns: An interfaces.GenericStub that performs RPCs via the given base_interfaces.Front. """ return _GenericStub(front, pool) def dynamic_stub(cardinalities, front, pool, prefix): """Creates an interfaces.DynamicStub. Args: cardinalities: A dict from RPC method name to cardinality.Cardinality value identifying the cardinality of every RPC method to be supported by the created interfaces.DynamicStub. front: A base_interfaces.Front. pool: A futures.ThreadPoolExecutor. prefix: A string to prepend when mapping requested attribute name to RPC method name during attribute access on the created interfaces.DynamicStub. Returns: An interfaces.DynamicStub that performs RPCs via the given base_interfaces.Front. """ return _DynamicStub(cardinalities, front, pool)
ml-lab/NearPy
refs/heads/master
nearpy/engine.py
3
# -*- coding: utf-8 -*- # Copyright (c) 2013 Ole Krause-Sparmann # 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. import json from nearpy.hashes import RandomBinaryProjections from nearpy.filters import NearestFilter from nearpy.distances import EuclideanDistance from nearpy.storage import MemoryStorage class Engine(object): """ Objects with this type perform the actual ANN search and vector indexing. They can be configured by selecting implementations of the Hash, Distance, Filter and Storage interfaces. There are four different modes of the engine: (1) Full configuration - All arguments are defined. In this case the distance and vector filters are applied to the bucket contents to deliver the resulting list of filtered (vector, data, distance) tuples. (2) No distance - The distance argument is None. In this case only the vector filters are applied to the bucket contents and the result is a list of filtered (vector, data) tuples. (3) No vector filter - The vector_filter argument is None. In this case only the distance is applied to the bucket contents and the result is a list of unsorted/unfiltered (vector, data, distance) tuples. (4) No vector filter and no distance - Both arguments are None. In this case the result is just the content from the buckets as an unsorted/unfiltered list of (vector, data) tuples. """ def __init__(self, dim, lshashes=[RandomBinaryProjections('default', 10)], distance=EuclideanDistance(), vector_filters=[NearestFilter(10)], storage=MemoryStorage()): """ Keeps the configuration. """ self.lshashes = lshashes self.distance = distance self.vector_filters = vector_filters self.storage = storage # Initialize all hashes for the data space dimension. for lshash in self.lshashes: lshash.reset(dim) def store_vector(self, v, data=None): """ Hashes vector v and stores it in all matching buckets in the storage. The data argument must be JSON-serializable. It is stored with the vector and will be returned in search results. """ # Store vector in each bucket of all hashes for lshash in self.lshashes: for bucket_key in lshash.hash_vector(v): self.storage.store_vector(lshash.hash_name, bucket_key, v, data) def neighbours(self, v): """ Hashes vector v, collects all candidate vectors from the matching buckets in storage, applys the (optional) distance function and finally the (optional) filter function to construct the returned list of either (vector, data, distance) tuples or (vector, data) tuples. """ # Collect candidates from all buckets from all hashes candidates = [] for lshash in self.lshashes: for bucket_key in lshash.hash_vector(v): bucket_content = self.storage.get_bucket(lshash.hash_name, bucket_key) candidates.extend(bucket_content) # Apply distance implementation if specified if self.distance: candidates = [(x[0], x[1], self.distance.distance(x[0], v)) for x in candidates] # Apply vector filters if specified and return filtered list if self.vector_filters: filter_input = candidates for vector_filter in self.vector_filters: filter_input = vector_filter.filter_vectors(filter_input) # Return output of last filter return filter_input # If there is no vector filter, just return list of candidates return candidates def clean_all_buckets(self): """ Clears buckets in storage (removes all vectors and their data). """ self.storage.clean_all_buckets() def clean_buckets(self, hash_name): """ Clears buckets in storage (removes all vectors and their data). """ self.storage.clean_buckets(hash_name)
PyFilesystem/pyfilesystem
refs/heads/master
fs/expose/xmlrpc.py
12
""" fs.expose.xmlrpc ================ Server to expose an FS via XML-RPC This module provides the necessary infrastructure to expose an FS object over XML-RPC. The main class is 'RPCFSServer', a SimpleXMLRPCServer subclass designed to expose an underlying FS. If you need to use a more powerful server than SimpleXMLRPCServer, you can use the RPCFSInterface class to provide an XML-RPC-compatible wrapper around an FS object, which can then be exposed using whatever server you choose (e.g. Twisted's XML-RPC server). """ import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer from datetime import datetime import base64 import six from six import PY3 class RPCFSInterface(object): """Wrapper to expose an FS via a XML-RPC compatible interface. The only real trick is using xmlrpclib.Binary objects to transport the contents of files. """ # info keys are restricted to a subset known to work over xmlrpc # This fixes an issue with transporting Longs on Py3 _allowed_info = ["size", "created_time", "modified_time", "accessed_time", "st_size", "st_mode", "type"] def __init__(self, fs): super(RPCFSInterface, self).__init__() self.fs = fs def encode_path(self, path): """Encode a filesystem path for sending over the wire. Unfortunately XMLRPC only supports ASCII strings, so this method must return something that can be represented in ASCII. The default is base64-encoded UTF-8. """ #return path return six.text_type(base64.b64encode(path.encode("utf8")), 'ascii') def decode_path(self, path): """Decode paths arriving over the wire.""" return six.text_type(base64.b64decode(path.encode('ascii')), 'utf8') def getmeta(self, meta_name): meta = self.fs.getmeta(meta_name) if isinstance(meta, basestring): meta = self.decode_path(meta) return meta def getmeta_default(self, meta_name, default): meta = self.fs.getmeta(meta_name, default) if isinstance(meta, basestring): meta = self.decode_path(meta) return meta def hasmeta(self, meta_name): return self.fs.hasmeta(meta_name) def get_contents(self, path, mode="rb"): path = self.decode_path(path) data = self.fs.getcontents(path, mode) return xmlrpclib.Binary(data) def set_contents(self, path, data): path = self.decode_path(path) self.fs.setcontents(path, data.data) def exists(self, path): path = self.decode_path(path) return self.fs.exists(path) def isdir(self, path): path = self.decode_path(path) return self.fs.isdir(path) def isfile(self, path): path = self.decode_path(path) return self.fs.isfile(path) def listdir(self, path="./", wildcard=None, full=False, absolute=False, dirs_only=False, files_only=False): path = self.decode_path(path) entries = self.fs.listdir(path, wildcard, full, absolute, dirs_only, files_only) return [self.encode_path(e) for e in entries] def makedir(self, path, recursive=False, allow_recreate=False): path = self.decode_path(path) return self.fs.makedir(path, recursive, allow_recreate) def remove(self, path): path = self.decode_path(path) return self.fs.remove(path) def removedir(self, path, recursive=False, force=False): path = self.decode_path(path) return self.fs.removedir(path, recursive, force) def rename(self, src, dst): src = self.decode_path(src) dst = self.decode_path(dst) return self.fs.rename(src, dst) def settimes(self, path, accessed_time, modified_time): path = self.decode_path(path) if isinstance(accessed_time, xmlrpclib.DateTime): accessed_time = datetime.strptime(accessed_time.value, "%Y%m%dT%H:%M:%S") if isinstance(modified_time, xmlrpclib.DateTime): modified_time = datetime.strptime(modified_time.value, "%Y%m%dT%H:%M:%S") return self.fs.settimes(path, accessed_time, modified_time) def getinfo(self, path): path = self.decode_path(path) info = self.fs.getinfo(path) info = dict((k, v) for k, v in info.iteritems() if k in self._allowed_info) return info def desc(self, path): path = self.decode_path(path) return self.fs.desc(path) def getxattr(self, path, attr, default=None): path = self.decode_path(path) attr = self.decode_path(attr) return self.fs.getxattr(path, attr, default) def setxattr(self, path, attr, value): path = self.decode_path(path) attr = self.decode_path(attr) return self.fs.setxattr(path, attr, value) def delxattr(self, path, attr): path = self.decode_path(path) attr = self.decode_path(attr) return self.fs.delxattr(path, attr) def listxattrs(self, path): path = self.decode_path(path) return [self.encode_path(a) for a in self.fs.listxattrs(path)] def copy(self, src, dst, overwrite=False, chunk_size=16384): src = self.decode_path(src) dst = self.decode_path(dst) return self.fs.copy(src, dst, overwrite, chunk_size) def move(self, src, dst, overwrite=False, chunk_size=16384): src = self.decode_path(src) dst = self.decode_path(dst) return self.fs.move(src, dst, overwrite, chunk_size) def movedir(self, src, dst, overwrite=False, ignore_errors=False, chunk_size=16384): src = self.decode_path(src) dst = self.decode_path(dst) return self.fs.movedir(src, dst, overwrite, ignore_errors, chunk_size) def copydir(self, src, dst, overwrite=False, ignore_errors=False, chunk_size=16384): src = self.decode_path(src) dst = self.decode_path(dst) return self.fs.copydir(src, dst, overwrite, ignore_errors, chunk_size) class RPCFSServer(SimpleXMLRPCServer): """Server to expose an FS object via XML-RPC. This class takes as its first argument an FS instance, and as its second argument a (hostname,port) tuple on which to listen for XML-RPC requests. Example:: fs = OSFS('/var/srv/myfiles') s = RPCFSServer(fs,("",8080)) s.serve_forever() To cleanly shut down the server after calling serve_forever, set the attribute "serve_more_requests" to False. """ def __init__(self, fs, addr, requestHandler=None, logRequests=None): kwds = dict(allow_none=True) if requestHandler is not None: kwds['requestHandler'] = requestHandler if logRequests is not None: kwds['logRequests'] = logRequests self.serve_more_requests = True SimpleXMLRPCServer.__init__(self, addr, **kwds) self.register_instance(RPCFSInterface(fs)) def serve_forever(self): """Override serve_forever to allow graceful shutdown.""" while self.serve_more_requests: self.handle_request()
scorphus/thefuck
refs/heads/master
tests/rules/test_git_stash.py
5
import pytest from thefuck.rules.git_stash import match, get_new_command from thefuck.types import Command cherry_pick_error = ( 'error: Your local changes would be overwritten by cherry-pick.\n' 'hint: Commit your changes or stash them to proceed.\n' 'fatal: cherry-pick failed') rebase_error = ( 'Cannot rebase: Your index contains uncommitted changes.\n' 'Please commit or stash them.') @pytest.mark.parametrize('command', [ Command('git cherry-pick a1b2c3d', cherry_pick_error), Command('git rebase -i HEAD~7', rebase_error)]) def test_match(command): assert match(command) @pytest.mark.parametrize('command', [ Command('git cherry-pick a1b2c3d', ''), Command('git rebase -i HEAD~7', '')]) def test_not_match(command): assert not match(command) @pytest.mark.parametrize('command, new_command', [ (Command('git cherry-pick a1b2c3d', cherry_pick_error), 'git stash && git cherry-pick a1b2c3d'), (Command('git rebase -i HEAD~7', rebase_error), 'git stash && git rebase -i HEAD~7')]) def test_get_new_command(command, new_command): assert get_new_command(command) == new_command
umitproject/tease-o-matic
refs/heads/master
django/contrib/gis/sitemaps/views.py
250
from django.http import HttpResponse, Http404 from django.template import loader from django.contrib.sites.models import get_current_site from django.core import urlresolvers from django.core.paginator import EmptyPage, PageNotAnInteger from django.contrib.gis.db.models.fields import GeometryField from django.db import connections, DEFAULT_DB_ALIAS from django.db.models import get_model from django.utils.encoding import smart_str from django.contrib.gis.shortcuts import render_to_kml, render_to_kmz def index(request, sitemaps): """ This view generates a sitemap index that uses the proper view for resolving geographic section sitemap URLs. """ current_site = get_current_site(request) sites = [] protocol = request.is_secure() and 'https' or 'http' for section, site in sitemaps.items(): if callable(site): pages = site().paginator.num_pages else: pages = site.paginator.num_pages sitemap_url = urlresolvers.reverse('django.contrib.gis.sitemaps.views.sitemap', kwargs={'section': section}) sites.append('%s://%s%s' % (protocol, current_site.domain, sitemap_url)) if pages > 1: for page in range(2, pages+1): sites.append('%s://%s%s?p=%s' % (protocol, current_site.domain, sitemap_url, page)) xml = loader.render_to_string('sitemap_index.xml', {'sitemaps': sites}) return HttpResponse(xml, mimetype='application/xml') def sitemap(request, sitemaps, section=None): """ This view generates a sitemap with additional geographic elements defined by Google. """ maps, urls = [], [] if section is not None: if section not in sitemaps: raise Http404("No sitemap available for section: %r" % section) maps.append(sitemaps[section]) else: maps = sitemaps.values() page = request.GET.get("p", 1) current_site = get_current_site(request) for site in maps: try: if callable(site): urls.extend(site().get_urls(page=page, site=current_site)) else: urls.extend(site.get_urls(page=page, site=current_site)) except EmptyPage: raise Http404("Page %s empty" % page) except PageNotAnInteger: raise Http404("No page '%s'" % page) xml = smart_str(loader.render_to_string('gis/sitemaps/geo_sitemap.xml', {'urlset': urls})) return HttpResponse(xml, mimetype='application/xml') def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS): """ This view generates KML for the given app label, model, and field name. The model's default manager must be GeoManager, and the field name must be that of a geographic field. """ placemarks = [] klass = get_model(label, model) if not klass: raise Http404('You must supply a valid app label and module name. Got "%s.%s"' % (label, model)) if field_name: try: info = klass._meta.get_field_by_name(field_name) if not isinstance(info[0], GeometryField): raise Exception except: raise Http404('Invalid geometry field.') connection = connections[using] if connection.ops.postgis: # PostGIS will take care of transformation. placemarks = klass._default_manager.using(using).kml(field_name=field_name) else: # There's no KML method on Oracle or MySQL, so we use the `kml` # attribute of the lazy geometry instead. placemarks = [] if connection.ops.oracle: qs = klass._default_manager.using(using).transform(4326, field_name=field_name) else: qs = klass._default_manager.using(using).all() for mod in qs: mod.kml = getattr(mod, field_name).kml placemarks.append(mod) # Getting the render function and rendering to the correct. if compress: render = render_to_kmz else: render = render_to_kml return render('gis/kml/placemarks.kml', {'places' : placemarks}) def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS): """ This view returns KMZ for the given app label, model, and field name. """ return kml(request, label, model, field_name, compress=True, using=using)
firebitsbr/infernal-twin
refs/heads/master
build/reportlab/build/lib.linux-i686-2.7/reportlab/graphics/widgets/table.py
32
#!/usr/bin/env python #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/graphics/widgets/grids.py __version__=''' $Id$ ''' from reportlab.graphics.widgetbase import Widget from reportlab.graphics.charts.textlabels import Label from reportlab.graphics import shapes from reportlab.lib import colors from reportlab.lib.validators import * from reportlab.lib.attrmap import * from reportlab.graphics.shapes import Drawing class TableWidget(Widget): """A two dimensions table of labels """ _attrMap = AttrMap( x = AttrMapValue(isNumber, desc="x position of left edge of table"), y = AttrMapValue(isNumber, desc="y position of bottom edge of table"), width = AttrMapValue(isNumber, desc="table width"), height = AttrMapValue(isNumber, desc="table height"), borderStrokeColor = AttrMapValue(isColorOrNone, desc="table border color"), fillColor = AttrMapValue(isColorOrNone, desc="table fill color"), borderStrokeWidth = AttrMapValue(isNumber, desc="border line width"), horizontalDividerStrokeColor = AttrMapValue(isColorOrNone, desc="table inner horizontal lines color"), verticalDividerStrokeColor = AttrMapValue(isColorOrNone, desc="table inner vertical lines color"), horizontalDividerStrokeWidth = AttrMapValue(isNumber, desc="table inner horizontal lines width"), verticalDividerStrokeWidth = AttrMapValue(isNumber, desc="table inner vertical lines width"), dividerDashArray = AttrMapValue(isListOfNumbersOrNone, desc='Dash array for dividerLines.'), data = AttrMapValue(None, desc="a list of list of strings to be displayed in the cells"), boxAnchor = AttrMapValue(isBoxAnchor, desc="location of the table anchoring point"), fontName = AttrMapValue(isString, desc="text font in the table"), fontSize = AttrMapValue(isNumber, desc="font size of the table"), fontColor = AttrMapValue(isColorOrNone, desc="font color"), alignment = AttrMapValue(OneOf("left", "right"), desc="Alignment of text within cells"), textAnchor = AttrMapValue(OneOf('start','middle','end','numeric'), desc="Alignment of text within cells"), ) def __init__(self, x=10, y=10, **kw): self.x = x self.y = y self.width = 200 self.height = 100 self.borderStrokeColor = colors.black self.fillColor = None self.borderStrokeWidth = 0.5 self.horizontalDividerStrokeColor = colors.black self.verticalDividerStrokeColor = colors.black self.horizontalDividerStrokeWidth = 0.5 self.verticalDividerStrokeWidth = 0.25 self.dividerDashArray = None self.data = [['North','South','East','West'],[100,110,120,130],['A','B','C','D']] # list of rows each row is a list of columns self.boxAnchor = 'nw' #self.fontName = None self.fontSize = 8 self.fontColor = colors.black self.alignment = 'right' self.textAnchor = 'start' for k, v in kw.items(): if k in list(self.__class__._attrMap.keys()): setattr(self, k, v) else: raise ValueError('invalid argument supplied for class %s'%self.__class__) def demo(self): """ returns a sample of this widget with data """ d = Drawing(400, 200) t = TableWidget() d.add(t, name='table') d.table.dividerDashArray = (1, 3, 2) d.table.verticalDividerStrokeColor = None d.table.borderStrokeWidth = 0 d.table.borderStrokeColor = colors.red return d def draw(self): """ returns a group of shapes """ g = shapes.Group() #overall border and fill if self.borderStrokeColor or self.fillColor: # adds border and filling color rect = shapes.Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = self.borderStrokeColor rect.strokeWidth = self.borderStrokeWidth g.add(rect) #special case - for an empty table we want to avoid divide-by-zero data = self.preProcessData(self.data) rows = len(self.data) cols = len(self.data[0]) #print "(rows,cols)=(%s, %s)"%(rows,cols) row_step = self.height / float(rows) col_step = self.width / float(cols) #print "(row_step,col_step)=(%s, %s)"%(row_step,col_step) # draw the grid if self.horizontalDividerStrokeColor: for i in range(rows): # make horizontal lines x1 = self.x x2 = self.x + self.width y = self.y + row_step*i #print 'line (%s, %s), (%s, %s)'%(x1, y, x2, y) line = shapes.Line(x1, y, x2, y) line.strokeDashArray = self.dividerDashArray line.strokeWidth = self.horizontalDividerStrokeWidth line.strokeColor = self.horizontalDividerStrokeColor g.add(line) if self.verticalDividerStrokeColor: for i in range(cols): # make vertical lines x = self.x+col_step*i y1 = self.y y2 = self.y + self.height #print 'line (%s, %s), (%s, %s)'%(x, y1, x, y2) line = shapes.Line(x, y1, x, y2) line.strokeDashArray = self.dividerDashArray line.strokeWidth = self.verticalDividerStrokeWidth line.strokeColor = self.verticalDividerStrokeColor g.add(line) # since we plot data from down up, we reverse the list self.data.reverse() for (j, row) in enumerate(self.data): y = self.y + j*row_step + 0.5*row_step - 0.5 * self.fontSize for (i, datum) in enumerate(row): if datum: x = self.x + i*col_step + 0.5*col_step s = shapes.String(x, y, str(datum), textAnchor=self.textAnchor) s.fontName = self.fontName s.fontSize = self.fontSize s.fillColor = self.fontColor g.add(s) return g def preProcessData(self, data): """preprocess and return a new array with at least one row and column (use a None) if needed, and all rows the same length (adding Nones if needed) """ if not data: return [[None]] #make all rows have similar number of cells, append None when needed max_row = max( [len(x) for x in data] ) for rowNo, row in enumerate(data): if len(row) < max_row: row.extend([None]*(max_row-len(row))) return data #test if __name__ == '__main__': d = TableWidget().demo() import os d.save(formats=['pdf'],outDir=os.getcwd(),fnRoot=None)
Francis-Liu/animated-broccoli
refs/heads/master
nova/api/openstack/compute/legacy_v2/contrib/extended_ips.py
79
# Copyright 2013 Nebula, 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. """The Extended Ips API extension.""" import itertools from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute authorize = extensions.soft_extension_authorizer('compute', 'extended_ips') class ExtendedIpsController(wsgi.Controller): def __init__(self, *args, **kwargs): super(ExtendedIpsController, self).__init__(*args, **kwargs) self.compute_api = compute.API() def _extend_server(self, context, server, instance): key = "%s:type" % Extended_ips.alias networks = common.get_networks_for_instance(context, instance) for label, network in networks.items(): # NOTE(vish): ips are hidden in some states via the # hide_server_addresses extension. if label in server['addresses']: all_ips = itertools.chain(network["ips"], network["floating_ips"]) for i, ip in enumerate(all_ips): server['addresses'][label][i][key] = ip['type'] @wsgi.extends def show(self, req, resp_obj, id): context = req.environ['nova.context'] if authorize(context): server = resp_obj.obj['server'] db_instance = req.get_db_instance(server['id']) # server['id'] is guaranteed to be in the cache due to # the core API adding it in its 'show' method. self._extend_server(context, server, db_instance) @wsgi.extends def detail(self, req, resp_obj): context = req.environ['nova.context'] if authorize(context): servers = list(resp_obj.obj['servers']) for server in servers: db_instance = req.get_db_instance(server['id']) # server['id'] is guaranteed to be in the cache due to # the core API adding it in its 'detail' method. self._extend_server(context, server, db_instance) class Extended_ips(extensions.ExtensionDescriptor): """Adds type parameter to the ip list.""" name = "ExtendedIps" alias = "OS-EXT-IPS" namespace = ("http://docs.openstack.org/compute/ext/" "extended_ips/api/v1.1") updated = "2013-01-06T00:00:00Z" def get_controller_extensions(self): controller = ExtendedIpsController() extension = extensions.ControllerExtension(self, 'servers', controller) return [extension]
aimejeux/enigma2
refs/heads/master
lib/python/Screens/VideoWizard.py
2
from boxbranding import getBoxType, getMachineName from Screens.Wizard import WizardSummary from Screens.WizardLanguage import WizardLanguage from Screens.Rc import Rc from Components.AVSwitch import iAVSwitch from Screens.Screen import Screen from Components.Pixmap import Pixmap from Components.config import config, ConfigBoolean, configfile from Tools.Directories import resolveFilename, SCOPE_SKIN, SCOPE_ACTIVE_SKIN from Tools.HardwareInfo import HardwareInfo config.misc.showtestcard = ConfigBoolean(default = False) boxtype = getBoxType() has_rca = False has_dvi = False if boxtype in ('gbquad', 'gbquadplus', 'et5x00', 'et6000', 'classm', 'axodin', 'axodinc', 'genius', 'evo', 'geniuse3hd', 'evoe3hd', 'axase3', 'axase3c', 'starsatlx', 'mixosf7', 'mixoslumi', 'tmnano', 'azboxme', 'azboxminime', 'optimussos1', 'optimussos2', 'gb800seplus', 'gb800ueplus', 'sezam1000hd', 'mbmini', 'atemio5x00', 'ixussone', 'ixusszero', 'enfinity', 'force1'): has_rca = True if boxtype == 'dm8000' or boxtype == 'dm800': has_dvi = True class VideoWizardSummary(WizardSummary): skin = ( """<screen name="VideoWizardSummary" position="0,0" size="132,64" id="1"> <widget name="text" position="6,4" size="120,40" font="Regular;12" transparent="1" /> <widget source="parent.list" render="Label" position="6,40" size="120,21" font="Regular;14"> <convert type="StringListSelection" /> </widget> <!--widget name="pic" pixmap="%s" position="6,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/--> </screen>""", """<screen name="VideoWizardSummary" position="0,0" size="96,64" id="2"> <widget name="text" position="0,4" size="96,40" font="Regular;12" transparent="1" /> <widget source="parent.list" render="Label" position="0,40" size="96,21" font="Regular;14"> <convert type="StringListSelection" /> </widget> <!--widget name="pic" pixmap="%s" position="0,22" zPosition="10" size="64,64" transparent="1" alphatest="on"/--> </screen>""") #% (resolveFilename(SCOPE_PLUGINS, "SystemPlugins/Videomode/lcd_Scart.png")) def __init__(self, session, parent): WizardSummary.__init__(self, session, parent) #self["pic"] = Pixmap() def setLCDPicCallback(self): self.parent.setLCDTextCallback(self.setText) def setLCDPic(self, file): self["pic"].instance.setPixmapFromFile(file) class VideoWizard(WizardLanguage, Rc): skin = """ <screen position="fill" title="Welcome..." flags="wfNoBorder" > <panel name="WizardMarginsTemplate"/> <panel name="WizardPictureLangTemplate"/> <panel name="RemoteControlTemplate"/> <panel position="left" size="10,*" /> <panel position="right" size="10,*" /> <panel position="fill"> <widget name="text" position="top" size="*,270" font="Regular;23" valign="center" /> <panel position="fill"> <panel position="left" size="150,*"> <widget name="portpic" position="top" zPosition="10" size="150,150" transparent="1" alphatest="on"/> </panel> <panel position="fill" layout="stack"> <widget source="list" render="Listbox" position="fill" scrollbarMode="showOnDemand" > <convert type="StringList" /> </widget> <!--<widget name="config" position="fill" zPosition="1" scrollbarMode="showOnDemand" />--> </panel> </panel> </panel> </screen>""" def __init__(self, session): # FIXME anyone knows how to use relative paths from the plugin's directory? self.xmlfile = resolveFilename(SCOPE_SKIN, "videowizard.xml") self.hw = iAVSwitch WizardLanguage.__init__(self, session, showSteps = False, showStepSlider = False) Rc.__init__(self) self["wizard"] = Pixmap() self["portpic"] = Pixmap() Screen.setTitle(self, _("Welcome...")) self.port = None self.mode = None self.rate = None def createSummary(self): return VideoWizardSummary def markDone(self): self.hw.saveMode(self.port, self.mode, self.rate) config.misc.videowizardenabled.value = 0 config.misc.videowizardenabled.save() configfile.save() def listInputChannels(self): hw_type = HardwareInfo().get_device_name() has_hdmi = HardwareInfo().has_hdmi() list = [] for port in self.hw.getPortList(): if self.hw.isPortUsed(port): descr = port if descr == 'HDMI' and has_dvi: descr = 'DVI' if descr == 'Scart' and has_rca: descr = 'RCA' if port != "DVI-PC": list.append((descr,port)) list.sort(key = lambda x: x[0]) print "listInputChannels:", list return list def inputSelectionMade(self, index): print "inputSelectionMade:", index self.port = index self.inputSelect(index) def inputSelectionMoved(self): hw_type = HardwareInfo().get_device_name() has_hdmi = HardwareInfo().has_hdmi() print "input selection moved:", self.selection self.inputSelect(self.selection) if self["portpic"].instance is not None: picname = self.selection if picname == 'HDMI' and has_dvi: picname = "DVI" if picname == 'Scart' and has_rca: picname = "RCA" self["portpic"].instance.setPixmapFromFile(resolveFilename(SCOPE_ACTIVE_SKIN, "icons/" + picname + ".png")) def inputSelect(self, port): print "inputSelect:", port modeList = self.hw.getModeList(self.selection) print "modeList:", modeList self.port = port if len(modeList) > 0: ratesList = self.listRates(modeList[0][0]) self.hw.setMode(port = port, mode = modeList[0][0], rate = ratesList[0][0]) def listModes(self): list = [] print "modes for port", self.port for mode in self.hw.getModeList(self.port): #if mode[0] != "PC": list.append((mode[0], mode[0])) print "modeslist:", list return list def modeSelectionMade(self, index): print "modeSelectionMade:", index self.mode = index self.modeSelect(index) def modeSelectionMoved(self): print "mode selection moved:", self.selection self.modeSelect(self.selection) def modeSelect(self, mode): ratesList = self.listRates(mode) print "ratesList:", ratesList if self.port == "HDMI" and mode in ("720p", "1080i", "1080p"): self.rate = "multi" self.hw.setMode(port = self.port, mode = mode, rate = "multi") else: self.hw.setMode(port = self.port, mode = mode, rate = ratesList[0][0]) def listRates(self, querymode = None): if querymode is None: querymode = self.mode list = [] print "modes for port", self.port, "and mode", querymode for mode in self.hw.getModeList(self.port): print mode if mode[0] == querymode: for rate in mode[1]: if self.port == "DVI-PC": print "rate:", rate if rate == "640x480": list.insert(0, (rate, rate)) continue list.append((rate, rate)) return list def rateSelectionMade(self, index): print "rateSelectionMade:", index self.rate = index self.rateSelect(index) def rateSelectionMoved(self): print "rate selection moved:", self.selection self.rateSelect(self.selection) def rateSelect(self, rate): self.hw.setMode(port = self.port, mode = self.mode, rate = rate) def showTestCard(self, selection = None): if selection is None: selection = self.selection print "set config.misc.showtestcard to", {'yes': True, 'no': False}[selection] if selection == "yes": config.misc.showtestcard.value = True else: config.misc.showtestcard.value = False def keyNumberGlobal(self, number): if number in (1,2,3): if number == 1: self.hw.saveMode("HDMI", "720p", "multi") elif number == 2: self.hw.saveMode("HDMI", "1080i", "multi") elif number == 3: self.hw.saveMode("Scart", "Multi", "multi") self.hw.setConfiguredMode() self.close() WizardLanguage.keyNumberGlobal(self, number)
JulianVolodia/Politikon
refs/heads/master
accounts/migrations/0007_auto_20151107_0037.py
3
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_userprofile_reputation'), ] operations = [ migrations.AddField( model_name='userprofile', name='is_vip', field=models.BooleanField(default=False, verbose_name='VIP'), ), migrations.AddField( model_name='userprofile', name='unused_reput', field=models.IntegerField(default=0, verbose_name='wolne reputy'), ), ]
code-google-com/openshadinglanguage
refs/heads/master
testsuite/spline/run.py
4
#!/usr/bin/python import os import sys path = "" command = "" if len(sys.argv) > 2 : os.chdir (sys.argv[1]) path = sys.argv[2] + "/" # A command to run command = path + "oslc/oslc test.osl > out.txt" command = command + "; " + path + "testshade/testshade -g 256 256 -od uint8 -o Cspline color.tif -o DxCspline dcolor.tif -o Fspline float.tif -o DxFspline dfloat.tif -o NumKnots numknots.tif test >> out.txt" # Outputs to check against references outputs = [ "out.txt", "color.tif", "dcolor.tif", "float.tif", "dfloat.tif", "numknots.tif" ] # Files that need to be cleaned up, IN ADDITION to outputs cleanfiles = [ ] # boilerplate sys.path = [".."] + sys.path import runtest ret = runtest.runtest (command, outputs, cleanfiles) sys.exit (ret)
bealdav/OCB
refs/heads/patch-1
openerp/fields.py
1
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013-2014 OpenERP (<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/>. # ############################################################################## """ High-level objects for fields. """ from copy import copy from datetime import date, datetime from functools import partial from operator import attrgetter import logging import pytz import xmlrpclib from types import NoneType from openerp.tools import float_round, ustr, html_sanitize from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT as DATETIME_FORMAT DATE_LENGTH = len(date.today().strftime(DATE_FORMAT)) DATETIME_LENGTH = len(datetime.now().strftime(DATETIME_FORMAT)) _logger = logging.getLogger(__name__) class SpecialValue(object): """ Encapsulates a value in the cache in place of a normal value. """ def __init__(self, value): self.value = value def get(self): return self.value class FailedValue(SpecialValue): """ Special value that encapsulates an exception instead of a value. """ def __init__(self, exception): self.exception = exception def get(self): raise self.exception def _check_value(value): """ Return `value`, or call its getter if `value` is a :class:`SpecialValue`. """ return value.get() if isinstance(value, SpecialValue) else value def resolve_all_mro(cls, name, reverse=False): """ Return the (successively overridden) values of attribute `name` in `cls` in mro order, or inverse mro order if `reverse` is true. """ klasses = reversed(cls.__mro__) if reverse else cls.__mro__ for klass in klasses: if name in klass.__dict__: yield klass.__dict__[name] def default_compute(field, value): """ Return a compute function for the given default `value`; `value` is either a constant, or a unary function returning the default value. """ name = field.name func = value if callable(value) else lambda rec: value def compute(recs): for rec in recs: rec[name] = func(rec) return compute class MetaField(type): """ Metaclass for field classes. """ by_type = {} def __init__(cls, name, bases, attrs): super(MetaField, cls).__init__(name, bases, attrs) if cls.type: cls.by_type[cls.type] = cls # compute class attributes to avoid calling dir() on fields cls.column_attrs = [] cls.related_attrs = [] cls.description_attrs = [] for attr in dir(cls): if attr.startswith('_column_'): cls.column_attrs.append((attr[8:], attr)) elif attr.startswith('_related_'): cls.related_attrs.append((attr[9:], attr)) elif attr.startswith('_description_'): cls.description_attrs.append((attr[13:], attr)) class Field(object): """ The field descriptor contains the field definition, and manages accesses and assignments of the corresponding field on records. The following attributes may be provided when instanciating a field: :param string: the label of the field seen by users (string); if not set, the ORM takes the field name in the class (capitalized). :param help: the tooltip of the field seen by users (string) :param readonly: whether the field is readonly (boolean, by default ``False``) :param required: whether the value of the field is required (boolean, by default ``False``) :param index: whether the field is indexed in database (boolean, by default ``False``) :param default: the default value for the field; this is either a static value, or a function taking a recordset and returning a value :param states: a dictionary mapping state values to lists of UI attribute-value pairs; possible attributes are: 'readonly', 'required', 'invisible'. Note: Any state-based condition requires the ``state`` field value to be available on the client-side UI. This is typically done by including it in the relevant views, possibly made invisible if not relevant for the end-user. :param groups: comma-separated list of group xml ids (string); this restricts the field access to the users of the given groups only :param bool copy: whether the field value should be copied when the record is duplicated (default: ``True`` for normal fields, ``False`` for ``one2many`` and computed fields, including property fields and related fields) .. _field-computed: .. rubric:: Computed fields One can define a field whose value is computed instead of simply being read from the database. The attributes that are specific to computed fields are given below. To define such a field, simply provide a value for the attribute `compute`. :param compute: name of a method that computes the field :param inverse: name of a method that inverses the field (optional) :param search: name of a method that implement search on the field (optional) :param store: whether the field is stored in database (boolean, by default ``False`` on computed fields) The methods given for `compute`, `inverse` and `search` are model methods. Their signature is shown in the following example:: upper = fields.Char(compute='_compute_upper', inverse='_inverse_upper', search='_search_upper') @api.depends('name') def _compute_upper(self): for rec in self: self.upper = self.name.upper() if self.name else False def _inverse_upper(self): for rec in self: self.name = self.upper.lower() if self.upper else False def _search_upper(self, operator, value): if operator == 'like': operator = 'ilike' return [('name', operator, value)] The compute method has to assign the field on all records of the invoked recordset. The decorator :meth:`openerp.api.depends` must be applied on the compute method to specify the field dependencies; those dependencies are used to determine when to recompute the field; recomputation is automatic and guarantees cache/database consistency. Note that the same method can be used for several fields, you simply have to assign all the given fields in the method; the method will be invoked once for all those fields. By default, a computed field is not stored to the database, and is computed on-the-fly. Adding the attribute ``store=True`` will store the field's values in the database. The advantage of a stored field is that searching on that field is done by the database itself. The disadvantage is that it requires database updates when the field must be recomputed. The inverse method, as its name says, does the inverse of the compute method: the invoked records have a value for the field, and you must apply the necessary changes on the field dependencies such that the computation gives the expected value. Note that a computed field without an inverse method is readonly by default. The search method is invoked when processing domains before doing an actual search on the model. It must return a domain equivalent to the condition: `field operator value`. .. _field-related: .. rubric:: Related fields The value of a related field is given by following a sequence of relational fields and reading a field on the reached model. The complete sequence of fields to traverse is specified by the attribute :param related: sequence of field names The value of some attributes from related fields are automatically taken from the source field, when it makes sense. Examples are the attributes `string` or `selection` on selection fields. By default, the values of related fields are not stored to the database. Add the attribute ``store=True`` to make it stored, just like computed fields. Related fields are automatically recomputed when their dependencies are modified. .. _field-company-dependent: .. rubric:: Company-dependent fields Formerly known as 'property' fields, the value of those fields depends on the company. In other words, users that belong to different companies may see different values for the field on a given record. :param company_dependent: whether the field is company-dependent (boolean) .. _field-incremental-definition: .. rubric:: Incremental definition A field is defined as class attribute on a model class. If the model is extended (see :class:`~openerp.models.Model`), one can also extend the field definition by redefining a field with the same name and same type on the subclass. In that case, the attributes of the field are taken from the parent class and overridden by the ones given in subclasses. For instance, the second class below only adds a tooltip on the field ``state``:: class First(models.Model): _name = 'foo' state = fields.Selection([...], required=True) class Second(models.Model): _inherit = 'foo' state = fields.Selection(help="Blah blah blah") """ __metaclass__ = MetaField _attrs = None # dictionary with all field attributes _free_attrs = None # list of semantic-free attribute names automatic = False # whether the field is automatically created ("magic" field) _origin = None # the column or field interfaced by self, if any name = None # name of the field type = None # type of the field (string) relational = False # whether the field is a relational one model_name = None # name of the model of this field comodel_name = None # name of the model of values (if relational) inverse_fields = None # list of inverse fields (objects) store = True # whether the field is stored in database index = False # whether the field is indexed in database manual = False # whether the field is a custom field copyable = True # whether the field is copied over by BaseModel.copy() depends = () # collection of field dependencies recursive = False # whether self depends on itself compute = None # compute(recs) computes field on recs inverse = None # inverse(recs) inverses field on recs search = None # search(recs, operator, value) searches on self related = None # sequence of field names, for related fields related_sudo = True # whether related fields should be read as admin company_dependent = False # whether `self` is company-dependent (property field) default = None # default value string = None # field label help = None # field tooltip readonly = False required = False states = None groups = False # csv list of group xml ids change_default = None # whether the field may trigger a "user-onchange" deprecated = None # whether the field is ... deprecated def __init__(self, string=None, **kwargs): kwargs['string'] = string self._attrs = {key: val for key, val in kwargs.iteritems() if val is not None} self._free_attrs = [] def copy(self, **kwargs): """ copy(item) -> test make a copy of `self`, possibly modified with parameters `kwargs` """ field = copy(self) field._attrs = {key: val for key, val in kwargs.iteritems() if val is not None} field._free_attrs = list(self._free_attrs) return field def set_class_name(self, cls, name): """ Assign the model class and field name of `self`. """ self.model_name = cls._name self.name = name # determine all inherited field attributes attrs = {} for field in resolve_all_mro(cls, name, reverse=True): if isinstance(field, type(self)): attrs.update(field._attrs) else: attrs.clear() attrs.update(self._attrs) # necessary in case self is not in cls # initialize `self` with `attrs` if attrs.get('compute'): # by default, computed fields are not stored, not copied and readonly attrs['store'] = attrs.get('store', False) attrs['copy'] = attrs.get('copy', False) attrs['readonly'] = attrs.get('readonly', not attrs.get('inverse')) if attrs.get('related'): # by default, related fields are not stored attrs['store'] = attrs.get('store', False) if 'copy' in attrs: # attribute is copyable because there is also a copy() method attrs['copyable'] = attrs.pop('copy') for attr, value in attrs.iteritems(): if not hasattr(self, attr): self._free_attrs.append(attr) setattr(self, attr, value) if not self.string: self.string = name.replace('_', ' ').capitalize() self.reset() def __str__(self): return "%s.%s" % (self.model_name, self.name) def __repr__(self): return "%s.%s" % (self.model_name, self.name) ############################################################################ # # Field setup # def reset(self): """ Prepare `self` for a new setup. """ self._setup_done = False # self._triggers is a set of pairs (field, path) that represents the # computed fields that depend on `self`. When `self` is modified, it # invalidates the cache of each `field`, and registers the records to # recompute based on `path`. See method `modified` below for details. self._triggers = set() self.inverse_fields = [] def setup(self, env): """ Complete the setup of `self` (dependencies, recomputation triggers, and other properties). This method is idempotent: it has no effect if `self` has already been set up. """ if not self._setup_done: self._setup_done = True self._setup(env) def _setup(self, env): """ Do the actual setup of `self`. """ if self.related: self._setup_related(env) else: self._setup_regular(env) # put invalidation/recomputation triggers on field dependencies model = env[self.model_name] for path in self.depends: self._setup_dependency([], model, path.split('.')) # put invalidation triggers on model dependencies for dep_model_name, field_names in model._depends.iteritems(): dep_model = env[dep_model_name] for field_name in field_names: field = dep_model._fields[field_name] field._triggers.add((self, None)) # # Setup of related fields # def _setup_related(self, env): """ Setup the attributes of a related field. """ # fix the type of self.related if necessary if isinstance(self.related, basestring): self.related = tuple(self.related.split('.')) # determine the related field, and make sure it is set up recs = env[self.model_name] for name in self.related[:-1]: recs = recs[name] field = self.related_field = recs._fields[self.related[-1]] field.setup(env) # check type consistency if self.type != field.type: raise Warning("Type of related field %s is inconsistent with %s" % (self, field)) # determine dependencies, compute, inverse, and search self.depends = ('.'.join(self.related),) self.compute = self._compute_related self.inverse = self._inverse_related if field._description_searchable(env): self.search = self._search_related # copy attributes from field to self (string, help, etc.) for attr, prop in self.related_attrs: if not getattr(self, attr): setattr(self, attr, getattr(field, prop)) def _compute_related(self, records): """ Compute the related field `self` on `records`. """ # when related_sudo, bypass access rights checks when reading values others = records.sudo() if self.related_sudo else records for record, other in zip(records, others): if not record.id: # draft record, do not switch to another environment other = record # traverse the intermediate fields; follow the first record at each step for name in self.related[:-1]: other = other[name][:1] record[self.name] = other[self.related[-1]] def _inverse_related(self, records): """ Inverse the related field `self` on `records`. """ for record in records: other = record # traverse the intermediate fields, and keep at most one record for name in self.related[:-1]: other = other[name][:1] if other: other[self.related[-1]] = record[self.name] def _search_related(self, records, operator, value): """ Determine the domain to search on field `self`. """ return [('.'.join(self.related), operator, value)] # properties used by _setup_related() to copy values from related field _related_string = property(attrgetter('string')) _related_help = property(attrgetter('help')) _related_readonly = property(attrgetter('readonly')) _related_groups = property(attrgetter('groups')) # # Setup of non-related fields # def _setup_regular(self, env): """ Setup the attributes of a non-related field. """ recs = env[self.model_name] def make_depends(deps): return tuple(deps(recs) if callable(deps) else deps) # transform self.default into self.compute if self.default is not None and self.compute is None: self.compute = default_compute(self, self.default) # convert compute into a callable and determine depends if isinstance(self.compute, basestring): # if the compute method has been overridden, concatenate all their _depends self.depends = () for method in resolve_all_mro(type(recs), self.compute, reverse=True): self.depends += make_depends(getattr(method, '_depends', ())) self.compute = getattr(type(recs), self.compute) else: self.depends = make_depends(getattr(self.compute, '_depends', ())) # convert inverse and search into callables if isinstance(self.inverse, basestring): self.inverse = getattr(type(recs), self.inverse) if isinstance(self.search, basestring): self.search = getattr(type(recs), self.search) def _setup_dependency(self, path0, model, path1): """ Make `self` depend on `model`; `path0 + path1` is a dependency of `self`, and `path0` is the sequence of field names from `self.model` to `model`. """ env = model.env head, tail = path1[0], path1[1:] if head == '*': # special case: add triggers on all fields of model (except self) fields = set(model._fields.itervalues()) - set([self]) else: fields = [model._fields[head]] for field in fields: if field == self: _logger.debug("Field %s is recursively defined", self) self.recursive = True continue field.setup(env) #_logger.debug("Add trigger on %s to recompute %s", field, self) field._triggers.add((self, '.'.join(path0 or ['id']))) # add trigger on inverse fields, too for invf in field.inverse_fields: #_logger.debug("Add trigger on %s to recompute %s", invf, self) invf._triggers.add((self, '.'.join(path0 + [head]))) # recursively traverse the dependency if tail: comodel = env[field.comodel_name] self._setup_dependency(path0 + [head], comodel, tail) @property def dependents(self): """ Return the computed fields that depend on `self`. """ return (field for field, path in self._triggers) ############################################################################ # # Field description # def get_description(self, env): """ Return a dictionary that describes the field `self`. """ desc = {'type': self.type} for attr, prop in self.description_attrs: value = getattr(self, prop) if callable(value): value = value(env) if value is not None: desc[attr] = value return desc # properties used by get_description() def _description_store(self, env): if self.store: # if the corresponding column is a function field, check the column column = env[self.model_name]._columns.get(self.name) return bool(getattr(column, 'store', True)) return False def _description_searchable(self, env): return self._description_store(env) or bool(self.search) _description_manual = property(attrgetter('manual')) _description_depends = property(attrgetter('depends')) _description_related = property(attrgetter('related')) _description_company_dependent = property(attrgetter('company_dependent')) _description_readonly = property(attrgetter('readonly')) _description_required = property(attrgetter('required')) _description_states = property(attrgetter('states')) _description_groups = property(attrgetter('groups')) _description_change_default = property(attrgetter('change_default')) _description_deprecated = property(attrgetter('deprecated')) def _description_string(self, env): if self.string and env.lang: name = "%s,%s" % (self.model_name, self.name) trans = env['ir.translation']._get_source(name, 'field', env.lang) return trans or self.string return self.string def _description_help(self, env): if self.help and env.lang: name = "%s,%s" % (self.model_name, self.name) trans = env['ir.translation']._get_source(name, 'help', env.lang) return trans or self.help return self.help ############################################################################ # # Conversion to column instance # def to_column(self): """ return a low-level field object corresponding to `self` """ assert self.store if self._origin: assert isinstance(self._origin, fields._column) return self._origin _logger.debug("Create fields._column for Field %s", self) args = {} for attr, prop in self.column_attrs: args[attr] = getattr(self, prop) for attr in self._free_attrs: args[attr] = getattr(self, attr) if self.company_dependent: # company-dependent fields are mapped to former property fields args['type'] = self.type args['relation'] = self.comodel_name return fields.property(**args) return getattr(fields, self.type)(**args) # properties used by to_column() to create a column instance _column_copy = property(attrgetter('copyable')) _column_select = property(attrgetter('index')) _column_manual = property(attrgetter('manual')) _column_string = property(attrgetter('string')) _column_help = property(attrgetter('help')) _column_readonly = property(attrgetter('readonly')) _column_required = property(attrgetter('required')) _column_states = property(attrgetter('states')) _column_groups = property(attrgetter('groups')) _column_change_default = property(attrgetter('change_default')) _column_deprecated = property(attrgetter('deprecated')) ############################################################################ # # Conversion of values # def null(self, env): """ return the null value for this field in the given environment """ return False def convert_to_cache(self, value, record, validate=True): """ convert `value` to the cache level in `env`; `value` may come from an assignment, or have the format of methods :meth:`BaseModel.read` or :meth:`BaseModel.write` :param record: the target record for the assignment, or an empty recordset :param bool validate: when True, field-specific validation of `value` will be performed """ return value def convert_to_read(self, value, use_name_get=True): """ convert `value` from the cache to a value as returned by method :meth:`BaseModel.read` :param bool use_name_get: when True, value's diplay name will be computed using :meth:`BaseModel.name_get`, if relevant for the field """ return False if value is None else value def convert_to_write(self, value, target=None, fnames=None): """ convert `value` from the cache to a valid value for method :meth:`BaseModel.write`. :param target: optional, the record to be modified with this value :param fnames: for relational fields only, an optional collection of field names to convert """ return self.convert_to_read(value) def convert_to_onchange(self, value): """ convert `value` from the cache to a valid value for an onchange method v7. """ return self.convert_to_write(value) def convert_to_export(self, value, env): """ convert `value` from the cache to a valid value for export. The parameter `env` is given for managing translations. """ if env.context.get('export_raw_data'): return value return bool(value) and ustr(value) def convert_to_display_name(self, value): """ convert `value` from the cache to a suitable display name. """ return ustr(value) ############################################################################ # # Descriptor methods # def __get__(self, record, owner): """ return the value of field `self` on `record` """ if record is None: return self # the field is accessed through the owner class if not record: # null record -> return the null value for this field return self.null(record.env) # only a single record may be accessed record.ensure_one() try: return record._cache[self] except KeyError: pass # cache miss, retrieve value if record.id: # normal record -> read or compute value for this field self.determine_value(record) else: # new record -> compute default value for this field record.add_default_value(self) # the result should be in cache now return record._cache[self] def __set__(self, record, value): """ set the value of field `self` on `record` """ env = record.env # only a single record may be updated record.ensure_one() # adapt value to the cache level value = self.convert_to_cache(value, record) if env.in_draft or not record.id: # determine dependent fields spec = self.modified_draft(record) # set value in cache, inverse field, and mark record as dirty record._cache[self] = value if env.in_onchange: for invf in self.inverse_fields: invf._update(value, record) record._dirty = True # determine more dependent fields, and invalidate them if self.relational: spec += self.modified_draft(record) env.invalidate(spec) else: # simply write to the database, and update cache record.write({self.name: self.convert_to_write(value)}) record._cache[self] = value ############################################################################ # # Computation of field values # def _compute_value(self, records): """ Invoke the compute method on `records`. """ # mark the computed fields failed in cache, so that access before # computation raises an exception exc = Warning("Field %s is accessed before being computed." % self) for field in self.computed_fields: records._cache[field] = FailedValue(exc) records.env.computed[field].update(records._ids) self.compute(records) for field in self.computed_fields: records.env.computed[field].difference_update(records._ids) def compute_value(self, records): """ Invoke the compute method on `records`; the results are in cache. """ with records.env.do_in_draft(): try: self._compute_value(records) except (AccessError, MissingError): # some record is forbidden or missing, retry record by record for record in records: try: self._compute_value(record) except Exception as exc: record._cache[self.name] = FailedValue(exc) def determine_value(self, record): """ Determine the value of `self` for `record`. """ env = record.env if self.store and not (self.depends and env.in_draft): # this is a stored field if self.depends: # this is a stored computed field, check for recomputation recs = record._recompute_check(self) if recs: # recompute the value (only in cache) self.compute_value(recs) # HACK: if result is in the wrong cache, copy values if recs.env != env: for source, target in zip(recs, recs.with_env(env)): try: values = target._convert_to_cache({ f.name: source[f.name] for f in self.computed_fields }, validate=False) except MissingError as e: values = FailedValue(e) target._cache.update(values) # the result is saved to database by BaseModel.recompute() return # read the field from database record._prefetch_field(self) elif self.compute: # this is either a non-stored computed field, or a stored computed # field in draft mode if self.recursive: self.compute_value(record) else: recs = record._in_cache_without(self) self.compute_value(recs) else: # this is a non-stored non-computed field record._cache[self] = self.null(env) def determine_default(self, record): """ determine the default value of field `self` on `record` """ if self.compute: self._compute_value(record) else: record._cache[self] = SpecialValue(self.null(record.env)) def determine_inverse(self, records): """ Given the value of `self` on `records`, inverse the computation. """ if self.inverse: self.inverse(records) def determine_domain(self, records, operator, value): """ Return a domain representing a condition on `self`. """ if self.search: return self.search(records, operator, value) else: return [(self.name, operator, value)] ############################################################################ # # Notification when fields are modified # def modified(self, records): """ Notify that field `self` has been modified on `records`: prepare the fields/records to recompute, and return a spec indicating what to invalidate. """ # invalidate the fields that depend on self, and prepare recomputation spec = [(self, records._ids)] for field, path in self._triggers: if path and field.store: # don't move this line to function top, see log env = records.env(user=SUPERUSER_ID, context={'active_test': False}) target = env[field.model_name].search([(path, 'in', records.ids)]) if target: spec.append((field, target._ids)) target.with_env(records.env)._recompute_todo(field) else: spec.append((field, None)) return spec def modified_draft(self, records): """ Same as :meth:`modified`, but in draft mode. """ env = records.env # invalidate the fields on the records in cache that depend on # `records`, except fields currently being computed spec = [] for field, path in self._triggers: target = env[field.model_name] computed = target.browse(env.computed[field]) if path == 'id': target = records - computed elif path: target = (target.browse(env.cache[field]) - computed).filtered( lambda rec: rec._mapped_cache(path) & records ) else: target = target.browse(env.cache[field]) - computed if target: spec.append((field, target._ids)) return spec class Boolean(Field): type = 'boolean' def convert_to_cache(self, value, record, validate=True): return bool(value) def convert_to_export(self, value, env): if env.context.get('export_raw_data'): return value return ustr(value) class Integer(Field): type = 'integer' def convert_to_cache(self, value, record, validate=True): return int(value or 0) def convert_to_read(self, value, use_name_get=True): # Integer values greater than 2^31-1 are not supported in pure XMLRPC, # so we have to pass them as floats :-( if value and value > xmlrpclib.MAXINT: return float(value) return value def _update(self, records, value): # special case, when an integer field is used as inverse for a one2many records._cache[self] = value.id or 0 class Float(Field): """ The precision digits are given by the attribute :param digits: a pair (total, decimal), or a function taking a database cursor and returning a pair (total, decimal) """ type = 'float' _digits = None # digits argument passed to class initializer digits = None # digits as computed by setup() def __init__(self, string=None, digits=None, **kwargs): super(Float, self).__init__(string=string, _digits=digits, **kwargs) def _setup_regular(self, env): super(Float, self)._setup_regular(env) self.digits = self._digits(env.cr) if callable(self._digits) else self._digits _related_digits = property(attrgetter('digits')) _description_digits = property(attrgetter('digits')) _column_digits = property(lambda self: not callable(self._digits) and self._digits) _column_digits_compute = property(lambda self: callable(self._digits) and self._digits) def convert_to_cache(self, value, record, validate=True): # apply rounding here, otherwise value in cache may be wrong! if self.digits: return float_round(float(value or 0.0), precision_digits=self.digits[1]) else: return float(value or 0.0) class _String(Field): """ Abstract class for string fields. """ translate = False _column_translate = property(attrgetter('translate')) _related_translate = property(attrgetter('translate')) _description_translate = property(attrgetter('translate')) class Char(_String): """ Basic string field, can be length-limited, usually displayed as a single-line string in clients :param int size: the maximum size of values stored for that field :param bool translate: whether the values of this field can be translated """ type = 'char' size = None _column_size = property(attrgetter('size')) _related_size = property(attrgetter('size')) _description_size = property(attrgetter('size')) def convert_to_cache(self, value, record, validate=True): if value is None or value is False: return False return ustr(value)[:self.size] class Text(_String): """ Text field. Very similar to :class:`~.Char` but used for longer contents and displayed as a multiline text box :param translate: whether the value of this field can be translated """ type = 'text' def convert_to_cache(self, value, record, validate=True): if value is None or value is False: return False return ustr(value) class Html(_String): type = 'html' sanitize = True # whether value must be sanitized _column_sanitize = property(attrgetter('sanitize')) _related_sanitize = property(attrgetter('sanitize')) _description_sanitize = property(attrgetter('sanitize')) def convert_to_cache(self, value, record, validate=True): if value is None or value is False: return False if validate and self.sanitize: return html_sanitize(value) return value class Date(Field): type = 'date' @staticmethod def today(*args): """ Return the current day in the format expected by the ORM. This function may be used to compute default values. """ return date.today().strftime(DATE_FORMAT) @staticmethod def context_today(record, timestamp=None): """ Return the current date as seen in the client's timezone in a format fit for date fields. This method may be used to compute default values. :param datetime timestamp: optional datetime value to use instead of the current date and time (must be a datetime, regular dates can't be converted between timezones.) :rtype: str """ today = timestamp or datetime.now() context_today = None tz_name = record._context.get('tz') or record.env.user.tz if tz_name: try: today_utc = pytz.timezone('UTC').localize(today, is_dst=False) # UTC = no DST context_today = today_utc.astimezone(pytz.timezone(tz_name)) except Exception: _logger.debug("failed to compute context/client-specific today date, using UTC value for `today`", exc_info=True) return (context_today or today).strftime(DATE_FORMAT) @staticmethod def from_string(value): """ Convert an ORM `value` into a :class:`date` value. """ value = value[:DATE_LENGTH] return datetime.strptime(value, DATE_FORMAT).date() @staticmethod def to_string(value): """ Convert a :class:`date` value into the format expected by the ORM. """ return value.strftime(DATE_FORMAT) def convert_to_cache(self, value, record, validate=True): if not value: return False if isinstance(value, basestring): if validate: # force parsing for validation self.from_string(value) return value[:DATE_LENGTH] return self.to_string(value) def convert_to_export(self, value, env): if value and env.context.get('export_raw_data'): return self.from_string(value) return bool(value) and ustr(value) class Datetime(Field): type = 'datetime' @staticmethod def now(*args): """ Return the current day and time in the format expected by the ORM. This function may be used to compute default values. """ return datetime.now().strftime(DATETIME_FORMAT) @staticmethod def context_timestamp(record, timestamp): """Returns the given timestamp converted to the client's timezone. This method is *not* meant for use as a _defaults initializer, because datetime fields are automatically converted upon display on client side. For _defaults you :meth:`fields.datetime.now` should be used instead. :param datetime timestamp: naive datetime value (expressed in UTC) to be converted to the client timezone :rtype: datetime :return: timestamp converted to timezone-aware datetime in context timezone """ assert isinstance(timestamp, datetime), 'Datetime instance expected' tz_name = record._context.get('tz') or record.env.user.tz if tz_name: try: utc = pytz.timezone('UTC') context_tz = pytz.timezone(tz_name) utc_timestamp = utc.localize(timestamp, is_dst=False) # UTC = no DST return utc_timestamp.astimezone(context_tz) except Exception: _logger.debug("failed to compute context/client-specific timestamp, " "using the UTC value", exc_info=True) return timestamp @staticmethod def from_string(value): """ Convert an ORM `value` into a :class:`datetime` value. """ value = value[:DATETIME_LENGTH] if len(value) == DATE_LENGTH: value += " 00:00:00" return datetime.strptime(value, DATETIME_FORMAT) @staticmethod def to_string(value): """ Convert a :class:`datetime` value into the format expected by the ORM. """ return value.strftime(DATETIME_FORMAT) def convert_to_cache(self, value, record, validate=True): if not value: return False if isinstance(value, basestring): if validate: # force parsing for validation self.from_string(value) value = value[:DATETIME_LENGTH] if len(value) == DATE_LENGTH: value += " 00:00:00" return value return self.to_string(value) def convert_to_export(self, value, env): if value and env.context.get('export_raw_data'): return self.from_string(value) return bool(value) and ustr(value) class Binary(Field): type = 'binary' class Selection(Field): """ :param selection: specifies the possible values for this field. It is given as either a list of pairs (`value`, `string`), or a model method, or a method name. :param selection_add: provides an extension of the selection in the case of an overridden field. It is a list of pairs (`value`, `string`). The attribute `selection` is mandatory except in the case of :ref:`related fields <field-related>` or :ref:`field extensions <field-incremental-definition>`. """ type = 'selection' selection = None # [(value, string), ...], function or method name selection_add = None # [(value, string), ...] def __init__(self, selection=None, string=None, **kwargs): if callable(selection): from openerp import api selection = api.expected(api.model, selection) super(Selection, self).__init__(selection=selection, string=string, **kwargs) def _setup_related(self, env): super(Selection, self)._setup_related(env) # selection must be computed on related field field = self.related_field self.selection = lambda model: field._description_selection(model.env) def _setup_regular(self, env): super(Selection, self)._setup_regular(env) # determine selection (applying extensions) cls = type(env[self.model_name]) selection = None for field in resolve_all_mro(cls, self.name, reverse=True): if isinstance(field, type(self)): # We cannot use field.selection or field.selection_add here # because those attributes are overridden by `set_class_name`. if 'selection' in field._attrs: selection = field._attrs['selection'] if 'selection_add' in field._attrs: selection = selection + field._attrs['selection_add'] else: selection = None self.selection = selection def _description_selection(self, env): """ return the selection list (pairs (value, label)); labels are translated according to context language """ selection = self.selection if isinstance(selection, basestring): return getattr(env[self.model_name], selection)() if callable(selection): return selection(env[self.model_name]) # translate selection labels if env.lang: name = "%s,%s" % (self.model_name, self.name) translate = partial( env['ir.translation']._get_source, name, 'selection', env.lang) return [(value, translate(label)) for value, label in selection] else: return selection @property def _column_selection(self): if isinstance(self.selection, basestring): method = self.selection return lambda self, *a, **kw: getattr(self, method)(*a, **kw) else: return self.selection def get_values(self, env): """ return a list of the possible values """ selection = self.selection if isinstance(selection, basestring): selection = getattr(env[self.model_name], selection)() elif callable(selection): selection = selection(env[self.model_name]) return [value for value, _ in selection] def convert_to_cache(self, value, record, validate=True): if not validate: return value or False if value in self.get_values(record.env): return value elif not value: return False raise ValueError("Wrong value for %s: %r" % (self, value)) def convert_to_export(self, value, env): if not isinstance(self.selection, list): # FIXME: this reproduces an existing buggy behavior! return value for item in self._description_selection(env): if item[0] == value: return item[1] return False class Reference(Selection): type = 'reference' size = 128 def __init__(self, selection=None, string=None, **kwargs): super(Reference, self).__init__(selection=selection, string=string, **kwargs) _related_size = property(attrgetter('size')) _column_size = property(attrgetter('size')) def convert_to_cache(self, value, record, validate=True): if isinstance(value, BaseModel): if ((not validate or value._name in self.get_values(record.env)) and len(value) <= 1): return value.with_env(record.env) or False elif isinstance(value, basestring): res_model, res_id = value.split(',') return record.env[res_model].browse(int(res_id)) elif not value: return False raise ValueError("Wrong value for %s: %r" % (self, value)) def convert_to_read(self, value, use_name_get=True): return "%s,%s" % (value._name, value.id) if value else False def convert_to_export(self, value, env): return bool(value) and value.name_get()[0][1] def convert_to_display_name(self, value): return ustr(value and value.display_name) class _Relational(Field): """ Abstract class for relational fields. """ relational = True domain = None # domain for searching values context = None # context for searching values _description_relation = property(attrgetter('comodel_name')) _description_context = property(attrgetter('context')) def _description_domain(self, env): return self.domain(env[self.model_name]) if callable(self.domain) else self.domain _column_obj = property(attrgetter('comodel_name')) _column_domain = property(attrgetter('domain')) _column_context = property(attrgetter('context')) def null(self, env): return env[self.comodel_name] def modified(self, records): # Invalidate cache for self.inverse_fields, too. Note that recomputation # of fields that depend on self.inverse_fields is already covered by the # triggers (see above). spec = super(_Relational, self).modified(records) for invf in self.inverse_fields: spec.append((invf, None)) return spec class Many2one(_Relational): """ The value of such a field is a recordset of size 0 (no record) or 1 (a single record). :param comodel_name: name of the target model (string) :param domain: an optional domain to set on candidate values on the client side (domain or string) :param context: an optional context to use on the client side when handling that field (dictionary) :param ondelete: what to do when the referred record is deleted; possible values are: ``'set null'``, ``'restrict'``, ``'cascade'`` :param auto_join: whether JOINs are generated upon search through that field (boolean, by default ``False``) :param delegate: set it to ``True`` to make fields of the target model accessible from the current model (corresponds to ``_inherits``) The attribute `comodel_name` is mandatory except in the case of related fields or field extensions. """ type = 'many2one' ondelete = 'set null' # what to do when value is deleted auto_join = False # whether joins are generated upon search delegate = False # whether self implements delegation def __init__(self, comodel_name=None, string=None, **kwargs): super(Many2one, self).__init__(comodel_name=comodel_name, string=string, **kwargs) def _setup_regular(self, env): super(Many2one, self)._setup_regular(env) # self.inverse_fields is populated by the corresponding One2many field # determine self.delegate self.delegate = self.name in env[self.model_name]._inherits.values() _column_ondelete = property(attrgetter('ondelete')) _column_auto_join = property(attrgetter('auto_join')) def _update(self, records, value): """ Update the cached value of `self` for `records` with `value`. """ records._cache[self] = value def convert_to_cache(self, value, record, validate=True): if isinstance(value, (NoneType, int)): return record.env[self.comodel_name].browse(value) if isinstance(value, BaseModel): if value._name == self.comodel_name and len(value) <= 1: return value.with_env(record.env) raise ValueError("Wrong value for %s: %r" % (self, value)) elif isinstance(value, tuple): return record.env[self.comodel_name].browse(value[0]) elif isinstance(value, dict): return record.env[self.comodel_name].new(value) else: return record.env[self.comodel_name].browse(value) def convert_to_read(self, value, use_name_get=True): if use_name_get and value: # evaluate name_get() as superuser, because the visibility of a # many2one field value (id and name) depends on the current record's # access rights, and not the value's access rights. return value.sudo().name_get()[0] else: return value.id def convert_to_write(self, value, target=None, fnames=None): return value.id def convert_to_onchange(self, value): return value.id def convert_to_export(self, value, env): return bool(value) and value.name_get()[0][1] def convert_to_display_name(self, value): return ustr(value.display_name) def determine_default(self, record): super(Many2one, self).determine_default(record) if self.delegate: # special case: fields that implement inheritance between models value = record[self.name] if not value: # the default value cannot be null, use a new record instead record[self.name] = record.env[self.comodel_name].new() class UnionUpdate(SpecialValue): """ Placeholder for a value update; when this value is taken from the cache, it returns ``record[field.name] | value`` and stores it in the cache. """ def __init__(self, field, record, value): self.args = (field, record, value) def get(self): field, record, value = self.args # in order to read the current field's value, remove self from cache del record._cache[field] # read the current field's value, and update it in cache only record._cache[field] = new_value = record[field.name] | value return new_value class _RelationalMulti(_Relational): """ Abstract class for relational fields *2many. """ def _update(self, records, value): """ Update the cached value of `self` for `records` with `value`. """ for record in records: if self in record._cache: record._cache[self] = record[self.name] | value else: record._cache[self] = UnionUpdate(self, record, value) def convert_to_cache(self, value, record, validate=True): if isinstance(value, BaseModel): if value._name == self.comodel_name: return value.with_env(record.env) elif isinstance(value, list): # value is a list of record ids or commands if not record.id: record = record.browse() # new record has no value result = record[self.name] # modify result with the commands; # beware to not introduce duplicates in result for command in value: if isinstance(command, (tuple, list)): if command[0] == 0: result += result.new(command[2]) elif command[0] == 1: result.browse(command[1]).update(command[2]) result += result.browse(command[1]) - result elif command[0] == 2: # note: the record will be deleted by write() result -= result.browse(command[1]) elif command[0] == 3: result -= result.browse(command[1]) elif command[0] == 4: result += result.browse(command[1]) - result elif command[0] == 5: result = result.browse() elif command[0] == 6: result = result.browse(command[2]) elif isinstance(command, dict): result += result.new(command) else: result += result.browse(command) - result return result elif not value: return self.null(record.env) raise ValueError("Wrong value for %s: %s" % (self, value)) def convert_to_read(self, value, use_name_get=True): return value.ids def convert_to_write(self, value, target=None, fnames=None): # remove/delete former records if target is None: set_ids = [] result = [(6, 0, set_ids)] add_existing = lambda id: set_ids.append(id) else: tag = 2 if self.type == 'one2many' else 3 result = [(tag, record.id) for record in target[self.name] - value] add_existing = lambda id: result.append((4, id)) if fnames is None: # take all fields in cache, except the inverses of self fnames = set(value._fields) - set(MAGIC_COLUMNS) for invf in self.inverse_fields: fnames.discard(invf.name) # add new and existing records for record in value: if not record.id or record._dirty: values = dict((k, v) for k, v in record._cache.iteritems() if k in fnames) values = record._convert_to_write(values) if not record.id: result.append((0, 0, values)) else: result.append((1, record.id, values)) else: add_existing(record.id) return result def convert_to_export(self, value, env): return bool(value) and ','.join(name for id, name in value.name_get()) def convert_to_display_name(self, value): raise NotImplementedError() def _compute_related(self, records): """ Compute the related field `self` on `records`. """ for record in records: value = record # traverse the intermediate fields, and keep at most one record for name in self.related[:-1]: value = value[name][:1] record[self.name] = value[self.related[-1]] class One2many(_RelationalMulti): """ One2many field; the value of such a field is the recordset of all the records in `comodel_name` such that the field `inverse_name` is equal to the current record. :param comodel_name: name of the target model (string) :param inverse_name: name of the inverse `Many2one` field in `comodel_name` (string) :param domain: an optional domain to set on candidate values on the client side (domain or string) :param context: an optional context to use on the client side when handling that field (dictionary) :param auto_join: whether JOINs are generated upon search through that field (boolean, by default ``False``) :param limit: optional limit to use upon read (integer) The attributes `comodel_name` and `inverse_name` are mandatory except in the case of related fields or field extensions. """ type = 'one2many' inverse_name = None # name of the inverse field auto_join = False # whether joins are generated upon search limit = None # optional limit to use upon read copyable = False # o2m are not copied by default def __init__(self, comodel_name=None, inverse_name=None, string=None, **kwargs): super(One2many, self).__init__( comodel_name=comodel_name, inverse_name=inverse_name, string=string, **kwargs ) def _setup_regular(self, env): super(One2many, self)._setup_regular(env) if self.inverse_name: # link self to its inverse field and vice-versa invf = env[self.comodel_name]._fields[self.inverse_name] # In some rare cases, a `One2many` field can link to `Int` field # (res_model/res_id pattern). Only inverse the field if this is # a `Many2one` field. if isinstance(invf, Many2one): self.inverse_fields.append(invf) invf.inverse_fields.append(self) _description_relation_field = property(attrgetter('inverse_name')) _column_fields_id = property(attrgetter('inverse_name')) _column_auto_join = property(attrgetter('auto_join')) _column_limit = property(attrgetter('limit')) class Many2many(_RelationalMulti): """ Many2many field; the value of such a field is the recordset. :param comodel_name: name of the target model (string) The attribute `comodel_name` is mandatory except in the case of related fields or field extensions. :param relation: optional name of the table that stores the relation in the database (string) :param column1: optional name of the column referring to "these" records in the table `relation` (string) :param column2: optional name of the column referring to "those" records in the table `relation` (string) The attributes `relation`, `column1` and `column2` are optional. If not given, names are automatically generated from model names, provided `model_name` and `comodel_name` are different! :param domain: an optional domain to set on candidate values on the client side (domain or string) :param context: an optional context to use on the client side when handling that field (dictionary) :param limit: optional limit to use upon read (integer) """ type = 'many2many' relation = None # name of table column1 = None # column of table referring to model column2 = None # column of table referring to comodel limit = None # optional limit to use upon read def __init__(self, comodel_name=None, relation=None, column1=None, column2=None, string=None, **kwargs): super(Many2many, self).__init__( comodel_name=comodel_name, relation=relation, column1=column1, column2=column2, string=string, **kwargs ) def _setup_regular(self, env): super(Many2many, self)._setup_regular(env) if self.store and not self.relation: model = env[self.model_name] column = model._columns[self.name] if not isinstance(column, fields.function): self.relation, self.column1, self.column2 = column._sql_names(model) if self.relation: m2m = env.registry._m2m # if inverse field has already been setup, it is present in m2m invf = m2m.get((self.relation, self.column2, self.column1)) if invf: self.inverse_fields.append(invf) invf.inverse_fields.append(self) else: # add self in m2m, so that its inverse field can find it m2m[(self.relation, self.column1, self.column2)] = self _column_rel = property(attrgetter('relation')) _column_id1 = property(attrgetter('column1')) _column_id2 = property(attrgetter('column2')) _column_limit = property(attrgetter('limit')) class Id(Field): """ Special case for field 'id'. """ store = True #: Can't write this! readonly = True def __init__(self, string=None, **kwargs): super(Id, self).__init__(type='integer', string=string, **kwargs) def to_column(self): """ to_column() -> fields._column Whatever """ return fields.integer('ID') def __get__(self, record, owner): if record is None: return self # the field is accessed through the class owner if not record: return False return record.ensure_one()._ids[0] def __set__(self, record, value): raise TypeError("field 'id' cannot be assigned") # imported here to avoid dependency cycle issues from openerp import SUPERUSER_ID from .exceptions import Warning, AccessError, MissingError from .models import BaseModel, MAGIC_COLUMNS from .osv import fields
piran9/Project
refs/heads/master
src/flow-monitor/bindings/modulegen__gcc_ILP32.py
4
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.flow_monitor', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## flow-monitor-helper.h (module 'flow-monitor'): ns3::FlowMonitorHelper [class] module.add_class('FlowMonitorHelper') ## histogram.h (module 'flow-monitor'): ns3::Histogram [class] module.add_class('Histogram') ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## 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-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-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', 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']) ## 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') ## timer.h (module 'core'): ns3::Timer [class] module.add_class('Timer', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration] module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::State [enumeration] module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer-impl.h (module 'core'): ns3::TimerImpl [class] module.add_class('TimerImpl', allow_subclassing=True, 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') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'CS1', 'AF11', 'AF12', 'AF13', 'CS2', 'AF21', 'AF22', 'AF23', 'CS3', 'AF31', 'AF32', 'AF33', 'CS4', 'AF41', 'AF42', 'AF43', 'CS5', 'EF', 'CS6', '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', ['NotECT', 'ECT1', 'ECT0', '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']) ## 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::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::FlowClassifier', 'ns3::empty', 'ns3::DefaultDeleter<ns3::FlowClassifier>'], 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::FlowProbe, ns3::empty, ns3::DefaultDeleter<ns3::FlowProbe> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::FlowProbe', 'ns3::empty', 'ns3::DefaultDeleter<ns3::FlowProbe>'], 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::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## 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> >']) ## flow-classifier.h (module 'flow-monitor'): ns3::FlowClassifier [class] module.add_class('FlowClassifier', parent=root_module['ns3::SimpleRefCount< ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >']) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor [class] module.add_class('FlowMonitor', parent=root_module['ns3::Object']) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats [struct] module.add_class('FlowStats', outer_class=root_module['ns3::FlowMonitor']) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe [class] module.add_class('FlowProbe', parent=root_module['ns3::SimpleRefCount< ns3::FlowProbe, ns3::empty, ns3::DefaultDeleter<ns3::FlowProbe> >']) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats [struct] module.add_class('FlowStats', outer_class=root_module['ns3::FlowProbe']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol [class] module.add_class('IpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus [enumeration] module.add_enum('RxStatus', ['RX_OK', 'RX_CSUM_FAILED', 'RX_ENDPOINT_CLOSED', 'RX_ENDPOINT_UNREACH'], outer_class=root_module['ns3::IpL4Protocol'], import_from_module='ns.internet') ## 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-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier [class] module.add_class('Ipv4FlowClassifier', parent=root_module['ns3::FlowClassifier']) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple [struct] module.add_class('FiveTuple', outer_class=root_module['ns3::Ipv4FlowClassifier']) ## ipv4-flow-probe.h (module 'flow-monitor'): ns3::Ipv4FlowProbe [class] module.add_class('Ipv4FlowProbe', parent=root_module['ns3::FlowProbe']) ## ipv4-flow-probe.h (module 'flow-monitor'): ns3::Ipv4FlowProbe::DropReason [enumeration] module.add_enum('DropReason', ['DROP_NO_ROUTE', 'DROP_TTL_EXPIRE', 'DROP_BAD_CHECKSUM', 'DROP_QUEUE', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT', 'DROP_INVALID_REASON'], outer_class=root_module['ns3::Ipv4FlowProbe']) ## 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-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-interface.h (module 'internet'): ns3::Ipv6Interface [class] module.add_class('Ipv6Interface', 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::TimeChecker [class] module.add_class('TimeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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< unsigned int >', 'unsigned int', container_type='vector') module.add_container('std::vector< unsigned long long >', 'long long unsigned int', container_type='vector') module.add_container('std::map< unsigned int, ns3::FlowMonitor::FlowStats >', ('unsigned int', 'ns3::FlowMonitor::FlowStats'), container_type='map') module.add_container('std::vector< ns3::Ptr< ns3::FlowProbe > >', 'ns3::Ptr< ns3::FlowProbe >', container_type='vector') module.add_container('std::map< unsigned int, ns3::FlowProbe::FlowStats >', ('unsigned int', 'ns3::FlowProbe::FlowStats'), container_type='map') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map') typehandlers.add_type_alias('uint32_t', 'ns3::FlowPacketId') typehandlers.add_type_alias('uint32_t*', 'ns3::FlowPacketId*') typehandlers.add_type_alias('uint32_t&', 'ns3::FlowPacketId&') typehandlers.add_type_alias('uint32_t', 'ns3::FlowId') typehandlers.add_type_alias('uint32_t*', 'ns3::FlowId*') typehandlers.add_type_alias('uint32_t&', 'ns3::FlowId&') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3FlowMonitorHelper_methods(root_module, root_module['ns3::FlowMonitorHelper']) register_Ns3Histogram_methods(root_module, root_module['ns3::Histogram']) register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) 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_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_Ns3Timer_methods(root_module, root_module['ns3::Timer']) register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_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_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__Ns3FlowClassifier_Ns3Empty_Ns3DefaultDeleter__lt__ns3FlowClassifier__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >']) register_Ns3SimpleRefCount__Ns3FlowProbe_Ns3Empty_Ns3DefaultDeleter__lt__ns3FlowProbe__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::FlowProbe, ns3::empty, ns3::DefaultDeleter<ns3::FlowProbe> >']) 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_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) 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_Ns3FlowClassifier_methods(root_module, root_module['ns3::FlowClassifier']) register_Ns3FlowMonitor_methods(root_module, root_module['ns3::FlowMonitor']) register_Ns3FlowMonitorFlowStats_methods(root_module, root_module['ns3::FlowMonitor::FlowStats']) register_Ns3FlowProbe_methods(root_module, root_module['ns3::FlowProbe']) register_Ns3FlowProbeFlowStats_methods(root_module, root_module['ns3::FlowProbe::FlowStats']) register_Ns3IpL4Protocol_methods(root_module, root_module['ns3::IpL4Protocol']) 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_Ns3Ipv4FlowClassifier_methods(root_module, root_module['ns3::Ipv4FlowClassifier']) register_Ns3Ipv4FlowClassifierFiveTuple_methods(root_module, root_module['ns3::Ipv4FlowClassifier::FiveTuple']) register_Ns3Ipv4FlowProbe_methods(root_module, root_module['ns3::Ipv4FlowProbe']) 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_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6Interface_methods(root_module, root_module['ns3::Ipv6Interface']) 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_Ns3TimeChecker_methods(root_module, root_module['ns3::TimeChecker']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_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_Ns3FlowMonitorHelper_methods(root_module, cls): ## flow-monitor-helper.h (module 'flow-monitor'): ns3::FlowMonitorHelper::FlowMonitorHelper(ns3::FlowMonitorHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::FlowMonitorHelper const &', 'arg0')]) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::FlowMonitorHelper::FlowMonitorHelper() [constructor] cls.add_constructor([]) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowClassifier> ns3::FlowMonitorHelper::GetClassifier() [member function] cls.add_method('GetClassifier', 'ns3::Ptr< ns3::FlowClassifier >', []) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowMonitor> ns3::FlowMonitorHelper::GetMonitor() [member function] cls.add_method('GetMonitor', 'ns3::Ptr< ns3::FlowMonitor >', []) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowMonitor> ns3::FlowMonitorHelper::Install(ns3::NodeContainer nodes) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::FlowMonitor >', [param('ns3::NodeContainer', 'nodes')]) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowMonitor> ns3::FlowMonitorHelper::Install(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::FlowMonitor >', [param('ns3::Ptr< ns3::Node >', 'node')]) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowMonitor> ns3::FlowMonitorHelper::InstallAll() [member function] cls.add_method('InstallAll', 'ns3::Ptr< ns3::FlowMonitor >', []) ## flow-monitor-helper.h (module 'flow-monitor'): void ns3::FlowMonitorHelper::SetMonitorAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetMonitorAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) return def register_Ns3Histogram_methods(root_module, cls): ## histogram.h (module 'flow-monitor'): ns3::Histogram::Histogram(ns3::Histogram const & arg0) [copy constructor] cls.add_constructor([param('ns3::Histogram const &', 'arg0')]) ## histogram.h (module 'flow-monitor'): ns3::Histogram::Histogram(double binWidth) [constructor] cls.add_constructor([param('double', 'binWidth')]) ## histogram.h (module 'flow-monitor'): ns3::Histogram::Histogram() [constructor] cls.add_constructor([]) ## histogram.h (module 'flow-monitor'): void ns3::Histogram::AddValue(double value) [member function] cls.add_method('AddValue', 'void', [param('double', 'value')]) ## histogram.h (module 'flow-monitor'): uint32_t ns3::Histogram::GetBinCount(uint32_t index) [member function] cls.add_method('GetBinCount', 'uint32_t', [param('uint32_t', 'index')]) ## histogram.h (module 'flow-monitor'): double ns3::Histogram::GetBinEnd(uint32_t index) [member function] cls.add_method('GetBinEnd', 'double', [param('uint32_t', 'index')]) ## histogram.h (module 'flow-monitor'): double ns3::Histogram::GetBinStart(uint32_t index) [member function] cls.add_method('GetBinStart', 'double', [param('uint32_t', 'index')]) ## histogram.h (module 'flow-monitor'): double ns3::Histogram::GetBinWidth(uint32_t index) const [member function] cls.add_method('GetBinWidth', 'double', [param('uint32_t', 'index')], is_const=True) ## histogram.h (module 'flow-monitor'): uint32_t ns3::Histogram::GetNBins() const [member function] cls.add_method('GetNBins', 'uint32_t', [], is_const=True) ## histogram.h (module 'flow-monitor'): void ns3::Histogram::SerializeToXmlStream(std::ostream & os, int indent, std::string elementName) const [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent'), param('std::string', 'elementName')], is_const=True) ## histogram.h (module 'flow-monitor'): void ns3::Histogram::SetDefaultBinWidth(double binWidth) [member function] cls.add_method('SetDefaultBinWidth', 'void', [param('double', 'binWidth')]) return def register_Ns3IntToType__0_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')]) return def register_Ns3IntToType__1_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')]) return def register_Ns3IntToType__2_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')]) return def register_Ns3IntToType__3_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')]) return def register_Ns3IntToType__4_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')]) return def register_Ns3IntToType__5_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')]) return def register_Ns3IntToType__6_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')]) 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_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function] cls.add_method('IsIpv4MappedAddress', 'bool', []) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_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'): 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_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_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_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_Ns3Timer_methods(root_module, cls): ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Timer const &', 'arg0')]) ## timer.h (module 'core'): ns3::Timer::Timer() [constructor] cls.add_constructor([]) ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor] cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')]) ## timer.h (module 'core'): void ns3::Timer::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function] cls.add_method('GetState', 'ns3::Timer::State', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function] cls.add_method('IsSuspended', 'bool', [], is_const=True) ## timer.h (module 'core'): void ns3::Timer::Remove() [member function] cls.add_method('Remove', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Resume() [member function] cls.add_method('Resume', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule() [member function] cls.add_method('Schedule', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function] cls.add_method('Schedule', 'void', [param('ns3::Time', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function] cls.add_method('SetDelay', 'void', [param('ns3::Time const &', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::Suspend() [member function] cls.add_method('Suspend', 'void', []) return def register_Ns3TimerImpl_methods(root_module, cls): ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor] cls.add_constructor([]) ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')]) ## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function] cls.add_method('Invoke', 'void', [], is_pure_virtual=True, is_virtual=True) ## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function] cls.add_method('Schedule', 'ns3::EventId', [param('ns3::Time const &', 'delay')], is_pure_virtual=True, is_virtual=True) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_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::Start() [member function] cls.add_method('Start', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3FlowClassifier_Ns3Empty_Ns3DefaultDeleter__lt__ns3FlowClassifier__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >::SimpleRefCount(ns3::SimpleRefCount<ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter< ns3::FlowClassifier > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3FlowProbe_Ns3Empty_Ns3DefaultDeleter__lt__ns3FlowProbe__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FlowProbe, ns3::empty, ns3::DefaultDeleter<ns3::FlowProbe> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FlowProbe, ns3::empty, ns3::DefaultDeleter<ns3::FlowProbe> >::SimpleRefCount(ns3::SimpleRefCount<ns3::FlowProbe, ns3::empty, ns3::DefaultDeleter<ns3::FlowProbe> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::FlowProbe, ns3::empty, ns3::DefaultDeleter< ns3::FlowProbe > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::FlowProbe, ns3::empty, ns3::DefaultDeleter<ns3::FlowProbe> >::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'): 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::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::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'): 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_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_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('ns3::Time const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_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_Ns3FlowClassifier_methods(root_module, cls): ## flow-classifier.h (module 'flow-monitor'): ns3::FlowClassifier::FlowClassifier() [constructor] cls.add_constructor([]) ## flow-classifier.h (module 'flow-monitor'): void ns3::FlowClassifier::SerializeToXmlStream(std::ostream & os, int indent) const [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent')], is_pure_virtual=True, is_const=True, is_virtual=True) ## flow-classifier.h (module 'flow-monitor'): ns3::FlowId ns3::FlowClassifier::GetNewFlowId() [member function] cls.add_method('GetNewFlowId', 'ns3::FlowId', [], visibility='protected') return def register_Ns3FlowMonitor_methods(root_module, cls): ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowMonitor(ns3::FlowMonitor const & arg0) [copy constructor] cls.add_constructor([param('ns3::FlowMonitor const &', 'arg0')]) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowMonitor() [constructor] cls.add_constructor([]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::AddProbe(ns3::Ptr<ns3::FlowProbe> probe) [member function] cls.add_method('AddProbe', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::CheckForLostPackets() [member function] cls.add_method('CheckForLostPackets', 'void', []) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::CheckForLostPackets(ns3::Time maxDelay) [member function] cls.add_method('CheckForLostPackets', 'void', [param('ns3::Time', 'maxDelay')]) ## flow-monitor.h (module 'flow-monitor'): std::vector<ns3::Ptr<ns3::FlowProbe>, std::allocator<ns3::Ptr<ns3::FlowProbe> > > ns3::FlowMonitor::GetAllProbes() const [member function] cls.add_method('GetAllProbes', 'std::vector< ns3::Ptr< ns3::FlowProbe > >', [], is_const=True) ## flow-monitor.h (module 'flow-monitor'): std::map<unsigned int, ns3::FlowMonitor::FlowStats, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, ns3::FlowMonitor::FlowStats> > > ns3::FlowMonitor::GetFlowStats() const [member function] cls.add_method('GetFlowStats', 'std::map< unsigned int, ns3::FlowMonitor::FlowStats >', [], is_const=True) ## flow-monitor.h (module 'flow-monitor'): ns3::TypeId ns3::FlowMonitor::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## flow-monitor.h (module 'flow-monitor'): static ns3::TypeId ns3::FlowMonitor::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::ReportDrop(ns3::Ptr<ns3::FlowProbe> probe, ns3::FlowId flowId, ns3::FlowPacketId packetId, uint32_t packetSize, uint32_t reasonCode) [member function] cls.add_method('ReportDrop', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe'), param('ns3::FlowId', 'flowId'), param('ns3::FlowPacketId', 'packetId'), param('uint32_t', 'packetSize'), param('uint32_t', 'reasonCode')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::ReportFirstTx(ns3::Ptr<ns3::FlowProbe> probe, ns3::FlowId flowId, ns3::FlowPacketId packetId, uint32_t packetSize) [member function] cls.add_method('ReportFirstTx', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe'), param('ns3::FlowId', 'flowId'), param('ns3::FlowPacketId', 'packetId'), param('uint32_t', 'packetSize')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::ReportForwarding(ns3::Ptr<ns3::FlowProbe> probe, ns3::FlowId flowId, ns3::FlowPacketId packetId, uint32_t packetSize) [member function] cls.add_method('ReportForwarding', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe'), param('ns3::FlowId', 'flowId'), param('ns3::FlowPacketId', 'packetId'), param('uint32_t', 'packetSize')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::ReportLastRx(ns3::Ptr<ns3::FlowProbe> probe, ns3::FlowId flowId, ns3::FlowPacketId packetId, uint32_t packetSize) [member function] cls.add_method('ReportLastRx', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe'), param('ns3::FlowId', 'flowId'), param('ns3::FlowPacketId', 'packetId'), param('uint32_t', 'packetSize')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::SerializeToXmlFile(std::string fileName, bool enableHistograms, bool enableProbes) [member function] cls.add_method('SerializeToXmlFile', 'void', [param('std::string', 'fileName'), param('bool', 'enableHistograms'), param('bool', 'enableProbes')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::SerializeToXmlStream(std::ostream & os, int indent, bool enableHistograms, bool enableProbes) [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent'), param('bool', 'enableHistograms'), param('bool', 'enableProbes')]) ## flow-monitor.h (module 'flow-monitor'): std::string ns3::FlowMonitor::SerializeToXmlString(int indent, bool enableHistograms, bool enableProbes) [member function] cls.add_method('SerializeToXmlString', 'std::string', [param('int', 'indent'), param('bool', 'enableHistograms'), param('bool', 'enableProbes')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::SetFlowClassifier(ns3::Ptr<ns3::FlowClassifier> classifier) [member function] cls.add_method('SetFlowClassifier', 'void', [param('ns3::Ptr< ns3::FlowClassifier >', 'classifier')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::Start(ns3::Time const & time) [member function] cls.add_method('Start', 'void', [param('ns3::Time const &', 'time')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::StartRightNow() [member function] cls.add_method('StartRightNow', 'void', []) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::StopRightNow() [member function] cls.add_method('StopRightNow', 'void', []) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3FlowMonitorFlowStats_methods(root_module, cls): ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::FlowStats() [constructor] cls.add_constructor([]) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::FlowStats(ns3::FlowMonitor::FlowStats const & arg0) [copy constructor] cls.add_constructor([param('ns3::FlowMonitor::FlowStats const &', 'arg0')]) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::bytesDropped [variable] cls.add_instance_attribute('bytesDropped', 'std::vector< unsigned long long >', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::delayHistogram [variable] cls.add_instance_attribute('delayHistogram', 'ns3::Histogram', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::delaySum [variable] cls.add_instance_attribute('delaySum', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::flowInterruptionsHistogram [variable] cls.add_instance_attribute('flowInterruptionsHistogram', 'ns3::Histogram', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::jitterHistogram [variable] cls.add_instance_attribute('jitterHistogram', 'ns3::Histogram', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::jitterSum [variable] cls.add_instance_attribute('jitterSum', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::lastDelay [variable] cls.add_instance_attribute('lastDelay', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::lostPackets [variable] cls.add_instance_attribute('lostPackets', 'uint32_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::packetSizeHistogram [variable] cls.add_instance_attribute('packetSizeHistogram', 'ns3::Histogram', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::packetsDropped [variable] cls.add_instance_attribute('packetsDropped', 'std::vector< unsigned int >', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::rxBytes [variable] cls.add_instance_attribute('rxBytes', 'uint64_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::rxPackets [variable] cls.add_instance_attribute('rxPackets', 'uint32_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timeFirstRxPacket [variable] cls.add_instance_attribute('timeFirstRxPacket', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timeFirstTxPacket [variable] cls.add_instance_attribute('timeFirstTxPacket', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timeLastRxPacket [variable] cls.add_instance_attribute('timeLastRxPacket', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timeLastTxPacket [variable] cls.add_instance_attribute('timeLastTxPacket', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timesForwarded [variable] cls.add_instance_attribute('timesForwarded', 'uint32_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::txBytes [variable] cls.add_instance_attribute('txBytes', 'uint64_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::txPackets [variable] cls.add_instance_attribute('txPackets', 'uint32_t', is_const=False) return def register_Ns3FlowProbe_methods(root_module, cls): ## flow-probe.h (module 'flow-monitor'): void ns3::FlowProbe::AddPacketDropStats(ns3::FlowId flowId, uint32_t packetSize, uint32_t reasonCode) [member function] cls.add_method('AddPacketDropStats', 'void', [param('ns3::FlowId', 'flowId'), param('uint32_t', 'packetSize'), param('uint32_t', 'reasonCode')]) ## flow-probe.h (module 'flow-monitor'): void ns3::FlowProbe::AddPacketStats(ns3::FlowId flowId, uint32_t packetSize, ns3::Time delayFromFirstProbe) [member function] cls.add_method('AddPacketStats', 'void', [param('ns3::FlowId', 'flowId'), param('uint32_t', 'packetSize'), param('ns3::Time', 'delayFromFirstProbe')]) ## flow-probe.h (module 'flow-monitor'): std::map<unsigned int, ns3::FlowProbe::FlowStats, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, ns3::FlowProbe::FlowStats> > > ns3::FlowProbe::GetStats() const [member function] cls.add_method('GetStats', 'std::map< unsigned int, ns3::FlowProbe::FlowStats >', [], is_const=True) ## flow-probe.h (module 'flow-monitor'): void ns3::FlowProbe::SerializeToXmlStream(std::ostream & os, int indent, uint32_t index) const [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent'), param('uint32_t', 'index')], is_const=True) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowProbe(ns3::Ptr<ns3::FlowMonitor> flowMonitor) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::FlowMonitor >', 'flowMonitor')], visibility='protected') return def register_Ns3FlowProbeFlowStats_methods(root_module, cls): ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::FlowStats(ns3::FlowProbe::FlowStats const & arg0) [copy constructor] cls.add_constructor([param('ns3::FlowProbe::FlowStats const &', 'arg0')]) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::FlowStats() [constructor] cls.add_constructor([]) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::bytes [variable] cls.add_instance_attribute('bytes', 'uint64_t', is_const=False) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::bytesDropped [variable] cls.add_instance_attribute('bytesDropped', 'std::vector< unsigned long long >', is_const=False) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::delayFromFirstProbeSum [variable] cls.add_instance_attribute('delayFromFirstProbeSum', 'ns3::Time', is_const=False) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::packets [variable] cls.add_instance_attribute('packets', 'uint32_t', is_const=False) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::packetsDropped [variable] cls.add_instance_attribute('packetsDropped', 'std::vector< unsigned int >', is_const=False) return def register_Ns3IpL4Protocol_methods(root_module, cls): ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol() [constructor] cls.add_constructor([]) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol(ns3::IpL4Protocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::IpL4Protocol const &', 'arg0')]) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget() const [member function] cls.add_method('GetDownTarget', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget6() const [member function] cls.add_method('GetDownTarget6', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): int ns3::IpL4Protocol::GetProtocolNumber() const [member function] cls.add_method('GetProtocolNumber', 'int', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::IpL4Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::Ipv4Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::Ipv4Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address & src, ns3::Ipv6Address & dst, ns3::Ptr<ns3::Ipv6Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address &', 'src'), param('ns3::Ipv6Address &', 'dst'), param('ns3::Ptr< ns3::Ipv6Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv4Address payloadSource, ns3::Ipv4Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv4Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv4Address', 'payloadSource'), param('ns3::Ipv4Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv6Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv6Address payloadSource, ns3::Ipv6Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv6Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv6Address', 'payloadSource'), param('ns3::Ipv6Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget6(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget6', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, 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'): 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_Ns3Ipv4FlowClassifier_methods(root_module, cls): ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::Ipv4FlowClassifier() [constructor] cls.add_constructor([]) ## ipv4-flow-classifier.h (module 'flow-monitor'): bool ns3::Ipv4FlowClassifier::Classify(ns3::Ipv4Header const & ipHeader, ns3::Ptr<const ns3::Packet> ipPayload, uint32_t * out_flowId, uint32_t * out_packetId) [member function] cls.add_method('Classify', 'bool', [param('ns3::Ipv4Header const &', 'ipHeader'), param('ns3::Ptr< ns3::Packet const >', 'ipPayload'), param('uint32_t *', 'out_flowId'), param('uint32_t *', 'out_packetId')]) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple ns3::Ipv4FlowClassifier::FindFlow(ns3::FlowId flowId) const [member function] cls.add_method('FindFlow', 'ns3::Ipv4FlowClassifier::FiveTuple', [param('ns3::FlowId', 'flowId')], is_const=True) ## ipv4-flow-classifier.h (module 'flow-monitor'): void ns3::Ipv4FlowClassifier::SerializeToXmlStream(std::ostream & os, int indent) const [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent')], is_const=True, is_virtual=True) return def register_Ns3Ipv4FlowClassifierFiveTuple_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('==') ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::FiveTuple() [constructor] cls.add_constructor([]) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::FiveTuple(ns3::Ipv4FlowClassifier::FiveTuple const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4FlowClassifier::FiveTuple const &', 'arg0')]) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::destinationAddress [variable] cls.add_instance_attribute('destinationAddress', 'ns3::Ipv4Address', is_const=False) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::destinationPort [variable] cls.add_instance_attribute('destinationPort', 'uint16_t', is_const=False) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::protocol [variable] cls.add_instance_attribute('protocol', 'uint8_t', is_const=False) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::sourceAddress [variable] cls.add_instance_attribute('sourceAddress', 'ns3::Ipv4Address', is_const=False) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::sourcePort [variable] cls.add_instance_attribute('sourcePort', 'uint16_t', is_const=False) return def register_Ns3Ipv4FlowProbe_methods(root_module, cls): ## ipv4-flow-probe.h (module 'flow-monitor'): ns3::Ipv4FlowProbe::Ipv4FlowProbe(ns3::Ptr<ns3::FlowMonitor> monitor, ns3::Ptr<ns3::Ipv4FlowClassifier> classifier, ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::FlowMonitor >', 'monitor'), param('ns3::Ptr< ns3::Ipv4FlowClassifier >', 'classifier'), param('ns3::Ptr< ns3::Node >', 'node')]) 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::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'): 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_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_Ns3Ipv6Interface_methods(root_module, cls): ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface(ns3::Ipv6Interface const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Interface const &', 'arg0')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface() [constructor] cls.add_constructor([]) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::AddAddress(ns3::Ipv6InterfaceAddress iface) [member function] cls.add_method('AddAddress', 'bool', [param('ns3::Ipv6InterfaceAddress', 'iface')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddress(uint32_t index) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddressMatchingDestination(ns3::Ipv6Address dst) [member function] cls.add_method('GetAddressMatchingDestination', 'ns3::Ipv6InterfaceAddress', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetBaseReachableTime() const [member function] cls.add_method('GetBaseReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint8_t ns3::Ipv6Interface::GetCurHopLimit() const [member function] cls.add_method('GetCurHopLimit', 'uint8_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6Interface::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True, is_virtual=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetLinkLocalAddress() const [member function] cls.add_method('GetLinkLocalAddress', 'ns3::Ipv6InterfaceAddress', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetMetric() const [member function] cls.add_method('GetMetric', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint32_t ns3::Ipv6Interface::GetNAddresses() const [member function] cls.add_method('GetNAddresses', 'uint32_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetReachableTime() const [member function] cls.add_method('GetReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetRetransTimer() const [member function] cls.add_method('GetRetransTimer', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv6Interface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsDown() const [member function] cls.add_method('IsDown', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsForwarding() const [member function] cls.add_method('IsForwarding', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsUp() const [member function] cls.add_method('IsUp', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(uint32_t index) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address dest) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address', 'dest')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetBaseReachableTime(uint16_t baseReachableTime) [member function] cls.add_method('SetBaseReachableTime', 'void', [param('uint16_t', 'baseReachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetCurHopLimit(uint8_t curHopLimit) [member function] cls.add_method('SetCurHopLimit', 'void', [param('uint8_t', 'curHopLimit')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDown() [member function] cls.add_method('SetDown', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetForwarding(bool forward) [member function] cls.add_method('SetForwarding', 'void', [param('bool', 'forward')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetMetric(uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint16_t', 'metric')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNsDadUid(ns3::Ipv6Address address, uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('ns3::Ipv6Address', 'address'), param('uint32_t', 'uid')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetReachableTime(uint16_t reachableTime) [member function] cls.add_method('SetReachableTime', 'void', [param('uint16_t', 'reachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetRetransTimer(uint16_t retransTimer) [member function] cls.add_method('SetRetransTimer', 'void', [param('uint16_t', 'retransTimer')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetState(ns3::Ipv6Address address, ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetUp() [member function] cls.add_method('SetUp', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) 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::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) return def register_Ns3TimeChecker_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker(ns3::TimeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeChecker const &', 'arg0')]) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) return def register_functions_ns3_FatalImpl(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()
chloerh/avocado-vt
refs/heads/master
virttest/utils_sasl.py
5
""" tools to manage sasl. """ import logging import aexpect from avocado.core import exceptions from avocado.utils import path from avocado.utils import process from virttest import propcan from virttest import remote from virttest import virsh from virttest.compat_52lts import decode_to_text class SASL(propcan.PropCanBase): """ Base class of a connection between server and client. """ __slots__ = ("sasl_pwd_cmd", "sasl_user_pwd", "sasl_user_cmd", "auto_recover", "linesep", "prompt", "session", "server_ip", "server_user", "server_pwd", "client", "port") def __init__(self, *args, **dargs): """ Initialize instance """ init_dict = dict(*args, **dargs) init_dict["sasl_pwd_cmd"] = path.find_command("saslpasswd2") init_dict["sasl_user_cmd"] = path.find_command("sasldblistusers2") init_dict["sasl_user_pwd"] = init_dict.get("sasl_user_pwd") init_dict["auto_recover"] = init_dict.get("auto_recover", False) init_dict["client"] = init_dict.get("client", "ssh") init_dict["port"] = init_dict.get("port", "22") init_dict["linesep"] = init_dict.get("linesep", "\n") init_dict["prompt"] = init_dict.get("prompt", r"[\#\$]\s*$") self.__dict_set__('session', None) super(SASL, self).__init__(init_dict) def __del__(self): """ Close opened session and clear test environment """ self.close_session() if self.auto_recover: try: self.cleanup() except Exception: raise exceptions.TestError( "Failed to clean up test environment!") def _new_session(self): """ Build a new server session. """ port = self.port prompt = self.prompt host = self.server_ip client = self.client username = self.server_user password = self.server_pwd try: session = remote.wait_for_login(client, host, port, username, password, prompt) except remote.LoginTimeoutError: raise exceptions.TestError( "Got a timeout error when login to server.") except remote.LoginAuthenticationError: raise exceptions.TestError( "Authentication failed to login to server.") except remote.LoginProcessTerminatedError: raise exceptions.TestError( "Host terminates during login to server.") except remote.LoginError: raise exceptions.TestError( "Some error occurs login to client server.") return session def get_session(self): """ Make sure the session is alive and available """ session = self.__dict_get__('session') if (session is not None) and (session.is_alive()): return session else: session = self._new_session() self.__dict_set__('session', session) return session def close_session(self): """ If session exists then close it """ if self.session: self.session.close() def list_users(self, remote=True, sasldb_path="/etc/libvirt/passwd.db"): """ List users in sasldb """ cmd = "%s -f %s" % (self.sasl_user_cmd, sasldb_path) try: if remote: self.session = self.get_session() return self.session.cmd_output(cmd) else: return decode_to_text(process.system_output(cmd)) except process.CmdError: logging.error("Failed to set a user's sasl password %s", cmd) def setup(self, remote=True): """ Create sasl users with password """ for sasl_user, sasl_pwd in eval(self.sasl_user_pwd): cmd = "echo %s |%s -p -a libvirt %s" % (sasl_pwd, self.sasl_pwd_cmd, sasl_user) try: if remote: self.session = self.get_session() self.session.cmd(cmd) else: process.system(cmd) except process.CmdError: logging.error("Failed to set a user's sasl password %s", cmd) def cleanup(self, remote=True): """ Clear created sasl users """ for sasl_user, sasl_pwd in eval(self.sasl_user_pwd): cmd = "%s -a libvirt -d %s" % (self.sasl_pwd_cmd, sasl_user) try: if remote: self.session = self.get_session() self.session.cmd(cmd) else: process.system(cmd) except process.CmdError: logging.error("Failed to disable a user's access %s", cmd) class VirshSessionSASL(virsh.VirshSession): """ A wrap class for virsh session which used SASL infrastructure. """ def __init__(self, params): self.virsh_exec = virsh.VIRSH_EXEC self.sasl_user = params.get('sasl_user') self.sasl_pwd = params.get('sasl_pwd') self.remote_ip = params.get('remote_ip') self.remote_user = params.get('remote_user') self.remote_pwd = params.get('remote_pwd') self.remote_auth = False if self.remote_ip: self.remote_auth = True super(VirshSessionSASL, self).__init__(virsh_exec=self.virsh_exec, remote_ip=self.remote_ip, remote_user=self.remote_user, remote_pwd=self.remote_pwd, ssh_remote_auth=self.remote_auth, auto_close=True, check_libvirtd=False) self.sendline('connect') self.sendline(self.sasl_user) self.sendline(self.sasl_pwd) # make sure session is connected successfully if self.cmd_status('list', timeout=60) != 0: logging.debug("Persistent virsh session is not responding, " "libvirtd may be dead.") raise aexpect.ShellStatusError(virsh.VIRSH_EXEC, 'list')
flowdas/meta
refs/heads/master
tests/test_primitives.py
1
# coding=utf-8 from __future__ import print_function import cmath import datetime import decimal import math import time import uuid import pytest from flowdas import meta from flowdas.meta.compat import * from tests import * class SimpleEntity(meta.Entity): a = meta.Boolean() entity = SimpleEntity() entity.a = True def check_json(value): assert isinstance(value, (basestring_types, integer_types, float, list, tuple, dict)) if isinstance(value, (list, tuple)): for v in value: check_json(v) elif isinstance(value, dict): for k, v in value.items(): assert isinstance(k, str) check_json(v) @pytest.mark.parametrize('P', [meta.String, meta.Unicode, meta.Bytes]) def test_string(P): class X(meta.Entity): p = P() success = ['한', u'한', b'\xed\x95\x9c'] failure = [False, True, 0, 1, long_type(1), 1.0, 0.1, [1], (1,), ['a'], ('b',), {'a': 1}, entity] x = X() for value in success: x.p = value if P not in (meta.Unicode, meta.Bytes): assert value == x.p x.validate() if P == meta.Unicode: assert unicode_type == type(x.p) elif P == meta.Bytes: assert bytes_type == type(x.p) else: assert type(value) == type(x.p) decoded = X.p.load(value) encoded = X.p.dump(decoded) check_json(encoded) assert encoded == decoded for value in failure: with pytest.raises(ValueError): x.p = value # # allow_empty # class X(meta.Entity): p = P(allow_empty=False) x = X() x.p = 'x' with pytest.raises(ValueError): x.p = '' # # encoding # if P != meta.String: class X(meta.Entity): p = P(default_encoding='cp949') x = X() x.p = '' for value in (u'한', b'\xc7\xd1'): if P == meta.Unicode: x.p = value assert x.p == u'한' with pytest.raises(ValueError): x.p = b'\xed\x95\x9c' else: x.p = value assert x.p == b'\xc7\xd1' x.p = b'\xed\x95\x9c' @pytest.mark.parametrize('P', [meta.Number, meta.Integer, meta.Float]) def test_number(P): class X(meta.Entity): p = P() success = [0, 1, long_type(1), 1.0, MAX_SAFE_INTEGER + 1, -MAX_SAFE_INTEGER - 1] failure = ['한', u'한', b'\xed\x95\x9c', False, True, [1], (1,), ['a'], ('b',), {'a': 1}, entity, float('nan'), float('inf'), float('-inf')] x = X() if P != meta.Integer: success.append(0.1) else: failure.append(0.1) for value in success: x.p = value assert value == x.p x.validate() if P == meta.Integer: assert isinstance(x.p, integer_types) elif P == meta.Float: assert float == type(x.p) else: assert type(value) == type(x.p) decoded = X.p.load(value) encoded = X.p.dump(decoded) check_json(encoded) assert encoded == decoded for value in failure: with pytest.raises(ValueError): x.p = value # # allow_bool # class X(meta.Entity): p = P(allow_bool=True) x = X() for value in (False, True): x.p = value if P == meta.Float: assert float == type(x.p) assert x.p == value else: assert int == type(x.p) assert x.p == value decoded = X.p.load(value) encoded = X.p.dump(decoded) check_json(encoded) assert encoded == decoded # # allow_nan # class X(meta.Entity): p = P(allow_nan=True) x = X() for value in (float('nan'), float('inf'), float('-inf')): if P == meta.Integer: if math.isnan(value): with pytest.raises(ValueError): x.p = value else: with pytest.raises(OverflowError): x.p = value else: x.p = value if math.isnan(value): assert math.isnan(x.p) else: assert x.p == value # # jssafe # class X(meta.Entity): p = P(jssafe=True) x = X() for value in (MAX_SAFE_INTEGER + 1, -MAX_SAFE_INTEGER - 1): with pytest.raises(ValueError): x.p = value def test_boolean(): class X(meta.Entity): p = meta.Boolean() success = [False, True] failure = ['한', u'한', b'\xed\x95\x9c', 0, 1, long_type(1), 1.0, 0.1, [1], (1,), ['a'], ('b',), {'a': 1}, entity] x = X() for value in success: x.p = value assert bool == type(x.p) assert value == x.p x.validate() decoded = X.p.load(value) encoded = X.p.dump(decoded) check_json(encoded) assert encoded == decoded for value in failure: with pytest.raises(ValueError): x.p = value def test_jsonobject(): class X(meta.Entity): p = meta.JsonObject() success = [{'a': 1, 'b': {}, 'c': []}] failure = [False, True, '한', u'한', b'\xed\x95\x9c', 0, 1, long_type(1), 1.0, 0.1, [1], (1,), ['a'], ('b',), entity, {'a': entity}, [entity], {1: 1}] x = X() for value in success: x.p = value assert dict == type(x.p) assert value == x.p x.validate() decoded = X.p.load(value) encoded = X.p.dump(decoded) check_json(encoded) assert encoded == decoded for value in failure: with pytest.raises(ValueError): x.p = value def test_jsonarray(): class X(meta.Entity): p = meta.JsonArray() success = [[1], (1,), ['a'], ('b',), [[], {'a': 1}]] failure = [False, True, '한', u'한', b'\xed\x95\x9c', 0, 1, long_type(1), 1.0, 0.1, {'a': 1}, entity, 'NaN'] x = X() for value in success: x.p = value assert type(value) == type(x.p) assert value == x.p x.validate() decoded = X.p.load(value) encoded = X.p.dump(decoded) check_json(encoded) assert encoded == decoded for value in failure: with pytest.raises(ValueError): x.p = value def test_decimal(): class X(meta.Entity): p = meta.Decimal() success = [False, True, 0, 1, long_type(1), 1.0, 0.1, MAX_SAFE_INTEGER + 1, -MAX_SAFE_INTEGER - 1, int('9' * 100)] failure = ['한', u'한', b'\xed\x95\x9c', [1], (1,), ['a'], ('b',), {'a': 1}, entity, float('nan'), float('inf'), float('-inf'), decimal.Decimal(float('nan'))] x = X() for value in success: x.p = value assert isinstance(x.p, decimal.Decimal) assert x.p == value x.validate() if not isinstance(value, bool): x.p = str(value) assert isinstance(x.p, decimal.Decimal) if isinstance(value, float): assert float(x.p) == value else: assert x.p == value encoded = X.p.dump(x.p) decoded = X.p.load(encoded) check_json(encoded) if isinstance(value, float): assert float(decoded) == value else: assert decoded == value for value in failure: with pytest.raises(ValueError): x.p = value # # allow_nan # class X(meta.Entity): p = meta.Decimal(allow_nan=True) x = X() for value in (float('nan'), float('inf'), float('-inf')): x.p = value if math.isnan(value): assert x.p.is_nan() else: assert x.p == value def test_complex(): class X(meta.Entity): p = meta.Complex() success = [False, True, 0, 1, long_type(1), 1.0, 0.1, MAX_SAFE_INTEGER + 1, -MAX_SAFE_INTEGER - 1, 1 + 1j, 1j, [1, 1], (1, 1)] failure = ['한', u'한', b'\xed\x95\x9c', [1], (1,), ['a'], ('b',), {'a': 1}, entity, float('nan'), float('inf'), float('-inf'), [], [1], [1, 2, 3], [1, 'a']] x = X() for value in success: x.p = value assert isinstance(x.p, complex) if isinstance(value, (tuple, list)): assert x.p == complex(*value) else: assert x.p == value x.validate() encoded = X.p.dump(x.p) decoded = X.p.load(encoded) check_json(encoded) if isinstance(value, (tuple, list)): assert decoded == complex(*value) else: assert decoded == value for value in failure: with pytest.raises(ValueError): x.p = value # # allow_nan # class X(meta.Entity): p = meta.Complex(allow_nan=True) x = X() nans = (float('nan'), float('inf'), float('-inf')) values = list(nans) values.extend(complex(1, x) for x in nans) values.extend(complex(x, 1) for x in nans) values.extend(complex(x, y) for x in nans for y in nans) for value in values: x.p = value if cmath.isnan(value): assert cmath.isnan(x.p) else: assert x.p == value def test_uuid(): class X(meta.Entity): p = meta.Uuid() ref = uuid.uuid4() sample = str(ref) samples = [sample] samples.append(sample.replace('-', '')) samples.append('{' + sample + '}') samples.append('{' + sample) samples.append(sample + '}') samples.append('urn:uuid:' + sample) success = [ref] success.extend(samples) if PY2: success.extend(x.decode('utf-8') for x in samples) else: success.extend(x.encode('utf-8') for x in samples) failure = ['한', u'한', b'\xed\x95\x9c', [1], (1,), ['a'], ('b',), {'a': 1}, entity, float('nan'), float('inf'), float('-inf'), [], [1], [1, 2, 3]] failure.extend(x[:-2] if x.endswith('}') else x[:-1] for x in samples) x = X() for value in success: x.p = value assert isinstance(x.p, uuid.UUID) assert x.p == ref x.validate() encoded = X.p.dump(x.p) assert encoded == str(ref) decoded = X.p.load(encoded) check_json(encoded) assert decoded == ref for value in failure: with pytest.raises(ValueError): x.p = value def test_timezone(): now = meta.DateTime.now() assert timezone.utc.tzname(now) == 'UTC+00:00' assert timezone(datetime.timedelta(hours=9)).tzname(now) == 'UTC+09:00' assert timezone(datetime.timedelta(hours=-9)).tzname(now) == 'UTC-09:00' def test_datetime(): class X(meta.Entity): p = meta.DateTime(format='unix') success = [datetime.datetime.now(), time.time(), 0, 0.0] failure = [datetime.time(), datetime.date(1999, 1, 1), '한', u'한', b'\xed\x95\x9c', [1], (1,), ['a'], ('b',), entity] x = X() for value in success: x.p = value assert isinstance(x.p, datetime.datetime) x.validate() for value in failure: with pytest.raises(ValueError): x.p = value print(value) timestamp = 1457276664.038691 utc_naive = datetime.datetime(2016, 3, 6, 15, 4, 24, 38691) kst_naive = datetime.datetime(2016, 3, 7, 0, 4, 24, 38691) utc_aware = utc_naive.replace(tzinfo=timezone.utc) kst_aware = kst_naive.replace(tzinfo=timezone(datetime.timedelta(hours=9))) assert X.p.dump(utc_naive) == timestamp assert X.p.dump(utc_aware) == timestamp assert X.p.dump(kst_aware) == timestamp assert X.p.load(timestamp).tzinfo is timezone.utc assert utc_aware == X.p.load(timestamp) assert kst_aware == X.p.load(timestamp) x.p = timestamp assert x.p == utc_aware x.p = utc_aware assert x.p == utc_aware x.p = kst_aware assert x.p == utc_aware x.p = utc_naive assert x.p == utc_naive # # now # assert meta.DateTime.now().tzinfo is timezone.utc assert -0.01 < X.p.dump(meta.DateTime.now()) - time.time() <= 0 # # iso8601 # class X(meta.Entity): p = meta.DateTime() naive_iso8601 = '2016-03-06T15:04:24.038691' utc_iso8601 = '2016-03-06T15:04:24.038691Z' kst_iso8601 = '2016-03-07T00:04:24.038691+09:00' context = meta.Context() assert X.p.dump(utc_naive, context) == naive_iso8601 assert X.p.dump(utc_aware, context) == utc_iso8601 assert X.p.dump(kst_aware, context) == kst_iso8601 assert X.p.load(utc_iso8601, context).tzinfo is timezone.utc assert utc_aware == X.p.load(utc_iso8601, context) assert kst_aware == X.p.load(utc_iso8601, context) assert X.p.load(kst_iso8601, context).utcoffset() == datetime.timedelta(hours=9) assert utc_aware == X.p.load(kst_iso8601, context) assert kst_aware == X.p.load(kst_iso8601, context) def test_time(): class X(meta.Entity): p = meta.Time(format='unix') success = [datetime.datetime.now(), datetime.datetime.now().time(), datetime.time(), time.time(), 0, 0.0] failure = [datetime.date(1999, 1, 1), '한', u'한', b'\xed\x95\x9c', [1], (1,), ['a'], ('b',), entity] x = X() for value in success: x.p = value assert isinstance(x.p, datetime.time) x.validate() for value in failure: with pytest.raises(ValueError): x.p = value print(value) timestamp = 1457276664.038691 utc_naive = datetime.datetime(2016, 3, 6, 15, 4, 24, 38691).time() kst_naive = datetime.datetime(2016, 3, 7, 0, 4, 24, 38691).time() utc_aware = utc_naive.replace(tzinfo=timezone.utc) kst_aware = kst_naive.replace(tzinfo=timezone(datetime.timedelta(hours=9))) tod = 15 * 3600 + 4 * 60 + 24.038691 assert X.p.dump(utc_naive) == tod assert X.p.dump(utc_aware) == tod assert X.p.dump(kst_aware) == tod assert X.p.load(timestamp).tzinfo is timezone.utc assert utc_aware == X.p.load(timestamp) assert X.p.load(tod).tzinfo is timezone.utc assert utc_aware == X.p.load(tod) for value in (timestamp, tod): x.p = value assert x.p == utc_aware x.p = utc_aware assert x.p == utc_aware x.p = kst_aware assert x.p == kst_aware x.p = utc_naive assert x.p == utc_naive # # iso8601 # class X(meta.Entity): p = meta.Time() naive_iso8601 = '15:04:24.038691' utc_iso8601 = '15:04:24.038691Z' kst_iso8601 = '00:04:24.038691+09:00' context = meta.Context() assert X.p.dump(utc_naive, context) == naive_iso8601 assert X.p.dump(utc_aware, context) == utc_iso8601 assert X.p.dump(kst_aware, context) == kst_iso8601 assert X.p.load(utc_iso8601, context).tzinfo is timezone.utc assert utc_aware == X.p.load(utc_iso8601, context) assert X.p.load(kst_iso8601, context).utcoffset() == datetime.timedelta(hours=9) assert kst_aware == X.p.load(kst_iso8601, context) def test_date(): class X(meta.Entity): p = meta.Date(format='unix') success = [datetime.datetime.now(), datetime.datetime.now().date(), time.time(), 0, 0.0] failure = [datetime.time(), '한', u'한', b'\xed\x95\x9c', [1], (1,), ['a'], ('b',), entity] x = X() for value in success: x.p = value assert isinstance(x.p, datetime.date) x.validate() for value in failure: with pytest.raises(ValueError): x.p = value print(value) timestamp = 1457276664.038691 utc_naive = datetime.datetime(2016, 3, 6, 15, 4, 24, 38691) kst_naive = datetime.datetime(2016, 3, 7, 0, 4, 24, 38691) utc_aware = utc_naive.replace(tzinfo=timezone.utc) kst_aware = kst_naive.replace(tzinfo=timezone(datetime.timedelta(hours=9))) sod = timestamp - (15 * 3600 + 4 * 60 + 24.038691) utc_date = datetime.date(2016, 3, 6) kst_date = datetime.date(2016, 3, 7) assert X.p.dump(utc_date) == sod assert utc_date == X.p.load(timestamp) assert utc_date == X.p.load(sod) x.p = timestamp assert x.p == utc_date x.p = utc_aware assert x.p == utc_date x.p = kst_aware assert x.p == kst_date x.p = utc_naive assert x.p == utc_date x.p = kst_date assert x.p == kst_date x.p = utc_date assert x.p == utc_date # # iso8601 # class X(meta.Entity): p = meta.Date() date_iso8601 = '2016-03-06' utc_iso8601 = '2016-03-06T15:04:24.038691Z' kst_iso8601 = '2016-03-07T00:04:24.038691+09:00' context = meta.Context() assert X.p.dump(utc_naive.date(), context) == date_iso8601 assert X.p.dump(utc_aware.date(), context) == date_iso8601 assert utc_date == X.p.load(date_iso8601, context) assert utc_date == X.p.load(utc_iso8601, context) assert kst_date == X.p.load(kst_iso8601, context) def test_rfc822format(): utc_naive = datetime.datetime(2016, 3, 6, 15, 4, 24) kst_naive = datetime.datetime(2016, 3, 7, 0, 4, 24) utc_aware = utc_naive.replace(tzinfo=timezone.utc) kst_aware = kst_naive.replace(tzinfo=timezone(datetime.timedelta(hours=9))) class X(meta.Entity): x = meta.DateTime(format='email') y = meta.Date(format='email') z = meta.Time(format='email') x = X() x.x = 'Mon, 07 Mar 2016 00:04:24 +0900' x.y = 'Mon, 07 Mar 2016 00:04:24 +0900' x.z = 'Mon, 07 Mar 2016 00:04:24 +0900' assert x.x == kst_aware assert x.y == kst_aware.date() assert x.z == kst_aware.timetz() assert x.dump()['x'] == 'Mon, 07 Mar 2016 00:04:24 +0900' assert x.dump()['y'] == 'Mon, 07 Mar 2016 00:00:00' assert x.dump()['z'] == 'Thu, 01 Jan 1970 00:04:24 +0900' x.x = 'Sun, 06 Mar 2016 15:04:24 GMT' x.y = 'Sun, 06 Mar 2016 15:04:24 GMT' x.z = 'Sun, 06 Mar 2016 15:04:24 GMT' assert x.x == utc_aware assert x.y == utc_aware.date() assert x.z == utc_aware.timetz() assert x.dump()['x'] == 'Sun, 06 Mar 2016 15:04:24 GMT' assert x.dump()['y'] == 'Sun, 06 Mar 2016 00:00:00' assert x.dump()['z'] == 'Thu, 01 Jan 1970 15:04:24 GMT' x.x = 'Sun, 06 Mar 2016 15:04:24 +0000' x.y = 'Sun, 06 Mar 2016 15:04:24 +0000' x.z = 'Sun, 06 Mar 2016 15:04:24 +0000' assert x.x == utc_aware assert x.y == utc_aware.date() assert x.z == utc_aware.timetz() assert x.dump()['x'] == 'Sun, 06 Mar 2016 15:04:24 GMT' assert x.dump()['y'] == 'Sun, 06 Mar 2016 00:00:00' assert x.dump()['z'] == 'Thu, 01 Jan 1970 15:04:24 GMT' x.x = 'Sun, 06 Mar 2016 15:04:24' x.y = 'Sun, 06 Mar 2016 15:04:24' x.z = 'Sun, 06 Mar 2016 15:04:24' assert x.x == utc_naive assert x.y == utc_naive.date() assert x.z == utc_naive.timetz() assert x.dump()['x'] == 'Sun, 06 Mar 2016 15:04:24' assert x.dump()['y'] == 'Sun, 06 Mar 2016 00:00:00' assert x.dump()['z'] == 'Thu, 01 Jan 1970 15:04:24' class X(meta.Entity): x = meta.DateTime(format='http') y = meta.Date(format='http') z = meta.Time(format='http') x = X() x.x = 'Mon, 07 Mar 2016 00:04:24 +0900' x.y = 'Mon, 07 Mar 2016 00:04:24 +0900' x.z = 'Mon, 07 Mar 2016 00:04:24 +0900' assert x.x == kst_aware assert x.y == kst_aware.date() assert x.z == kst_aware.timetz() assert x.dump()['x'] == 'Sun, 06 Mar 2016 15:04:24 GMT' assert x.dump()['y'] == 'Mon, 07 Mar 2016 00:00:00 GMT' assert x.dump()['z'] == 'Wed, 31 Dec 1969 15:04:24 GMT' x.x = 'Sun, 06 Mar 2016 15:04:24 GMT' x.y = 'Sun, 06 Mar 2016 15:04:24 GMT' x.z = 'Sun, 06 Mar 2016 15:04:24 GMT' assert x.x == utc_aware assert x.y == utc_aware.date() assert x.z == utc_aware.timetz() assert x.dump()['x'] == 'Sun, 06 Mar 2016 15:04:24 GMT' assert x.dump()['y'] == 'Sun, 06 Mar 2016 00:00:00 GMT' assert x.dump()['z'] == 'Thu, 01 Jan 1970 15:04:24 GMT' x.x = 'Sun, 06 Mar 2016 15:04:24 +0000' x.y = 'Sun, 06 Mar 2016 15:04:24 +0000' x.z = 'Sun, 06 Mar 2016 15:04:24 +0000' assert x.x == utc_aware assert x.y == utc_aware.date() assert x.z == utc_aware.timetz() assert x.dump()['x'] == 'Sun, 06 Mar 2016 15:04:24 GMT' assert x.dump()['y'] == 'Sun, 06 Mar 2016 00:00:00 GMT' assert x.dump()['z'] == 'Thu, 01 Jan 1970 15:04:24 GMT' x.x = 'Sun, 06 Mar 2016 15:04:24' x.y = 'Sun, 06 Mar 2016 15:04:24' x.z = 'Sun, 06 Mar 2016 15:04:24' assert x.x == utc_naive assert x.y == utc_naive.date() assert x.z == utc_naive.timetz() assert x.dump()['x'] == 'Sun, 06 Mar 2016 15:04:24 GMT' assert x.dump()['y'] == 'Sun, 06 Mar 2016 00:00:00 GMT' assert x.dump()['z'] == 'Thu, 01 Jan 1970 15:04:24 GMT' def test_duration(): class X(meta.Entity): t = meta.Duration() x = X() x.t = 10 assert x.t == datetime.timedelta(seconds=10) assert x.dump() == {'t': 10.0} x.t = datetime.timedelta(hours=1) assert x.dump() == {'t': 3600.0} class X(meta.Entity): t = meta.Duration(unit='hours') x = X() x.t = 10 assert x.t == datetime.timedelta(hours=10) assert x.dump() == {'t': 10.0} with pytest.raises(ValueError): x.t = '10' @pytest.mark.skipif(PY3 and PYPY, reason='no usable ipaddress') def test_ipaddress(): class X(meta.Entity): ip = meta.IpAddress() ipv4 = meta.Ipv4Address() ipv6 = meta.Ipv6Address() x = X() x.ip = '192.168.0.1' assert isinstance(x.ip, ipaddress.IPv4Address) assert x.ip == ipaddress.IPv4Address('192.168.0.1') x.ipv4 = '192.168.0.1' assert isinstance(x.ipv4, ipaddress.IPv4Address) assert x.ipv4 == ipaddress.IPv4Address('192.168.0.1') x.ip = '::1' assert isinstance(x.ip, ipaddress.IPv6Address) assert x.ip == ipaddress.IPv6Address('::1') x.ipv6 = '::1' assert isinstance(x.ipv6, ipaddress.IPv6Address) assert x.ipv6 == ipaddress.IPv6Address('::1') with pytest.raises(ValueError): x.ipv4 = '::1' with pytest.raises(ValueError): x.ipv6 = '192.168.0.1'
zapier/evernote-sdk-python
refs/heads/master
lib/evernote/edam/notestore/__init__.py
30
__all__ = ['ttypes', 'constants', 'NoteStore']
willdavidc/piel
refs/heads/master
catkin_ws/src/piel/scripts/venv/lib/python2.7/site-packages/pip/commands/hash.py
514
from __future__ import absolute_import import hashlib import logging import sys from pip.basecommand import Command from pip.status_codes import ERROR from pip.utils import read_chunks from pip.utils.hashes import FAVORITE_HASH, STRONG_HASHES logger = logging.getLogger(__name__) class HashCommand(Command): """ Compute a hash of a local package archive. These can be used with --hash in a requirements file to do repeatable installs. """ name = 'hash' usage = '%prog [options] <file> ...' summary = 'Compute hashes of package archives.' def __init__(self, *args, **kw): super(HashCommand, self).__init__(*args, **kw) self.cmd_opts.add_option( '-a', '--algorithm', dest='algorithm', choices=STRONG_HASHES, action='store', default=FAVORITE_HASH, help='The hash algorithm to use: one of %s' % ', '.join(STRONG_HASHES)) self.parser.insert_option_group(0, self.cmd_opts) def run(self, options, args): if not args: self.parser.print_usage(sys.stderr) return ERROR algorithm = options.algorithm for path in args: logger.info('%s:\n--hash=%s:%s', path, algorithm, _hash_of_file(path, algorithm)) def _hash_of_file(path, algorithm): """Return the hash digest of a file.""" with open(path, 'rb') as archive: hash = hashlib.new(algorithm) for chunk in read_chunks(archive): hash.update(chunk) return hash.hexdigest()
gfyoung/pandas
refs/heads/master
pandas/tests/arrays/test_timedeltas.py
2
import numpy as np import pytest import pandas as pd from pandas import Timedelta import pandas._testing as tm from pandas.core import nanops from pandas.core.arrays import TimedeltaArray class TestTimedeltaArrayConstructor: def test_only_1dim_accepted(self): # GH#25282 arr = np.array([0, 1, 2, 3], dtype="m8[h]").astype("m8[ns]") with pytest.raises(ValueError, match="Only 1-dimensional"): # 3-dim, we allow 2D to sneak in for ops purposes GH#29853 TimedeltaArray(arr.reshape(2, 2, 1)) with pytest.raises(ValueError, match="Only 1-dimensional"): # 0-dim TimedeltaArray(arr[[0]].squeeze()) def test_freq_validation(self): # ensure that the public constructor cannot create an invalid instance arr = np.array([0, 0, 1], dtype=np.int64) * 3600 * 10 ** 9 msg = ( "Inferred frequency None from passed values does not " "conform to passed frequency D" ) with pytest.raises(ValueError, match=msg): TimedeltaArray(arr.view("timedelta64[ns]"), freq="D") def test_non_array_raises(self): with pytest.raises(ValueError, match="list"): TimedeltaArray([1, 2, 3]) def test_other_type_raises(self): with pytest.raises(ValueError, match="dtype bool cannot be converted"): TimedeltaArray(np.array([1, 2, 3], dtype="bool")) def test_incorrect_dtype_raises(self): # TODO: why TypeError for 'category' but ValueError for i8? with pytest.raises( ValueError, match=r"category cannot be converted to timedelta64\[ns\]" ): TimedeltaArray(np.array([1, 2, 3], dtype="i8"), dtype="category") with pytest.raises( ValueError, match=r"dtype int64 cannot be converted to timedelta64\[ns\]" ): TimedeltaArray(np.array([1, 2, 3], dtype="i8"), dtype=np.dtype("int64")) def test_copy(self): data = np.array([1, 2, 3], dtype="m8[ns]") arr = TimedeltaArray(data, copy=False) assert arr._data is data arr = TimedeltaArray(data, copy=True) assert arr._data is not data assert arr._data.base is not data class TestTimedeltaArray: # TODO: de-duplicate with test_npsum below def test_np_sum(self): # GH#25282 vals = np.arange(5, dtype=np.int64).view("m8[h]").astype("m8[ns]") arr = TimedeltaArray(vals) result = np.sum(arr) assert result == vals.sum() result = np.sum(pd.TimedeltaIndex(arr)) assert result == vals.sum() def test_from_sequence_dtype(self): msg = "dtype .*object.* cannot be converted to timedelta64" with pytest.raises(ValueError, match=msg): TimedeltaArray._from_sequence([], dtype=object) @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"]) def test_astype_int(self, dtype): arr = TimedeltaArray._from_sequence([Timedelta("1H"), Timedelta("2H")]) with tm.assert_produces_warning(FutureWarning): # astype(int..) deprecated result = arr.astype(dtype) if np.dtype(dtype).kind == "u": expected_dtype = np.dtype("uint64") else: expected_dtype = np.dtype("int64") with tm.assert_produces_warning(FutureWarning): # astype(int..) deprecated expected = arr.astype(expected_dtype) assert result.dtype == expected_dtype tm.assert_numpy_array_equal(result, expected) def test_setitem_clears_freq(self): a = TimedeltaArray(pd.timedelta_range("1H", periods=2, freq="H")) a[0] = Timedelta("1H") assert a.freq is None @pytest.mark.parametrize( "obj", [ Timedelta(seconds=1), Timedelta(seconds=1).to_timedelta64(), Timedelta(seconds=1).to_pytimedelta(), ], ) def test_setitem_objects(self, obj): # make sure we accept timedelta64 and timedelta in addition to Timedelta tdi = pd.timedelta_range("2 Days", periods=4, freq="H") arr = TimedeltaArray(tdi, freq=tdi.freq) arr[0] = obj assert arr[0] == Timedelta(seconds=1) @pytest.mark.parametrize( "other", [ 1, np.int64(1), 1.0, np.datetime64("NaT"), pd.Timestamp.now(), "invalid", np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9, (np.arange(10) * 24 * 3600 * 10 ** 9).view("datetime64[ns]"), pd.Timestamp.now().to_period("D"), ], ) @pytest.mark.parametrize("index", [True, False]) def test_searchsorted_invalid_types(self, other, index): data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9 arr = TimedeltaArray(data, freq="D") if index: arr = pd.Index(arr) msg = "|".join( [ "searchsorted requires compatible dtype or scalar", "value should be a 'Timedelta', 'NaT', or array of those. Got", ] ) with pytest.raises(TypeError, match=msg): arr.searchsorted(other) class TestUnaryOps: def test_abs(self): vals = np.array([-3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]") arr = TimedeltaArray(vals) evals = np.array([3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]") expected = TimedeltaArray(evals) result = abs(arr) tm.assert_timedelta_array_equal(result, expected) def test_neg(self): vals = np.array([-3600 * 10 ** 9, "NaT", 7200 * 10 ** 9], dtype="m8[ns]") arr = TimedeltaArray(vals) evals = np.array([3600 * 10 ** 9, "NaT", -7200 * 10 ** 9], dtype="m8[ns]") expected = TimedeltaArray(evals) result = -arr tm.assert_timedelta_array_equal(result, expected) def test_neg_freq(self): tdi = pd.timedelta_range("2 Days", periods=4, freq="H") arr = TimedeltaArray(tdi, freq=tdi.freq) expected = TimedeltaArray(-tdi._data, freq=-tdi.freq) result = -arr tm.assert_timedelta_array_equal(result, expected) class TestReductions: @pytest.mark.parametrize("name", ["std", "min", "max", "median", "mean"]) @pytest.mark.parametrize("skipna", [True, False]) def test_reductions_empty(self, name, skipna): tdi = pd.TimedeltaIndex([]) arr = tdi.array result = getattr(tdi, name)(skipna=skipna) assert result is pd.NaT result = getattr(arr, name)(skipna=skipna) assert result is pd.NaT @pytest.mark.parametrize("skipna", [True, False]) def test_sum_empty(self, skipna): tdi = pd.TimedeltaIndex([]) arr = tdi.array result = tdi.sum(skipna=skipna) assert isinstance(result, Timedelta) assert result == Timedelta(0) result = arr.sum(skipna=skipna) assert isinstance(result, Timedelta) assert result == Timedelta(0) def test_min_max(self): arr = TimedeltaArray._from_sequence(["3H", "3H", "NaT", "2H", "5H", "4H"]) result = arr.min() expected = Timedelta("2H") assert result == expected result = arr.max() expected = Timedelta("5H") assert result == expected result = arr.min(skipna=False) assert result is pd.NaT result = arr.max(skipna=False) assert result is pd.NaT def test_sum(self): tdi = pd.TimedeltaIndex(["3H", "3H", "NaT", "2H", "5H", "4H"]) arr = tdi.array result = arr.sum(skipna=True) expected = Timedelta(hours=17) assert isinstance(result, Timedelta) assert result == expected result = tdi.sum(skipna=True) assert isinstance(result, Timedelta) assert result == expected result = arr.sum(skipna=False) assert result is pd.NaT result = tdi.sum(skipna=False) assert result is pd.NaT result = arr.sum(min_count=9) assert result is pd.NaT result = tdi.sum(min_count=9) assert result is pd.NaT result = arr.sum(min_count=1) assert isinstance(result, Timedelta) assert result == expected result = tdi.sum(min_count=1) assert isinstance(result, Timedelta) assert result == expected def test_npsum(self): # GH#25335 np.sum should return a Timedelta, not timedelta64 tdi = pd.TimedeltaIndex(["3H", "3H", "2H", "5H", "4H"]) arr = tdi.array result = np.sum(tdi) expected = Timedelta(hours=17) assert isinstance(result, Timedelta) assert result == expected result = np.sum(arr) assert isinstance(result, Timedelta) assert result == expected def test_sum_2d_skipna_false(self): arr = np.arange(8).astype(np.int64).view("m8[s]").astype("m8[ns]").reshape(4, 2) arr[-1, -1] = "Nat" tda = TimedeltaArray(arr) result = tda.sum(skipna=False) assert result is pd.NaT result = tda.sum(axis=0, skipna=False) expected = pd.TimedeltaIndex([Timedelta(seconds=12), pd.NaT])._values tm.assert_timedelta_array_equal(result, expected) result = tda.sum(axis=1, skipna=False) expected = pd.TimedeltaIndex( [ Timedelta(seconds=1), Timedelta(seconds=5), Timedelta(seconds=9), pd.NaT, ] )._values tm.assert_timedelta_array_equal(result, expected) # Adding a Timestamp makes this a test for DatetimeArray.std @pytest.mark.parametrize( "add", [ Timedelta(0), pd.Timestamp.now(), pd.Timestamp.now("UTC"), pd.Timestamp.now("Asia/Tokyo"), ], ) def test_std(self, add): tdi = pd.TimedeltaIndex(["0H", "4H", "NaT", "4H", "0H", "2H"]) + add arr = tdi.array result = arr.std(skipna=True) expected = Timedelta(hours=2) assert isinstance(result, Timedelta) assert result == expected result = tdi.std(skipna=True) assert isinstance(result, Timedelta) assert result == expected if getattr(arr, "tz", None) is None: result = nanops.nanstd(np.asarray(arr), skipna=True) assert isinstance(result, Timedelta) assert result == expected result = arr.std(skipna=False) assert result is pd.NaT result = tdi.std(skipna=False) assert result is pd.NaT if getattr(arr, "tz", None) is None: result = nanops.nanstd(np.asarray(arr), skipna=False) assert result is pd.NaT def test_median(self): tdi = pd.TimedeltaIndex(["0H", "3H", "NaT", "5H06m", "0H", "2H"]) arr = tdi.array result = arr.median(skipna=True) expected = Timedelta(hours=2) assert isinstance(result, Timedelta) assert result == expected result = tdi.median(skipna=True) assert isinstance(result, Timedelta) assert result == expected result = arr.median(skipna=False) assert result is pd.NaT result = tdi.median(skipna=False) assert result is pd.NaT def test_mean(self): tdi = pd.TimedeltaIndex(["0H", "3H", "NaT", "5H06m", "0H", "2H"]) arr = tdi._data # manually verified result expected = Timedelta(arr.dropna()._ndarray.mean()) result = arr.mean() assert result == expected result = arr.mean(skipna=False) assert result is pd.NaT result = arr.dropna().mean(skipna=False) assert result == expected result = arr.mean(axis=0) assert result == expected def test_mean_2d(self): tdi = pd.timedelta_range("14 days", periods=6) tda = tdi._data.reshape(3, 2) result = tda.mean(axis=0) expected = tda[1] tm.assert_timedelta_array_equal(result, expected) result = tda.mean(axis=1) expected = tda[:, 0] + Timedelta(hours=12) tm.assert_timedelta_array_equal(result, expected) result = tda.mean(axis=None) expected = tdi.mean() assert result == expected
claudep/pootle
refs/heads/master
pootle/apps/pootle_log/apps.py
2
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import importlib from django.apps import AppConfig class PootleLogConfig(AppConfig): name = "pootle_log" verbose_name = "Pootle Log" version = "0.0.1" def ready(self): importlib.import_module("pootle_log.getters")
ClovisIRex/Snake-django
refs/heads/master
env/lib/python3.6/site-packages/django/utils/module_loading.py
145
import copy import os import sys from importlib import import_module from django.utils import six def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit('.', 1) except ValueError: msg = "%s doesn't look like a module path" % dotted_path six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) module = import_module(module_path) try: return getattr(module, class_name) except AttributeError: msg = 'Module "%s" does not define a "%s" attribute/class' % ( module_path, class_name) six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) def autodiscover_modules(*args, **kwargs): """ Auto-discover INSTALLED_APPS modules and fail silently when not present. This forces an import on them to register any admin bits they may want. You may provide a register_to keyword parameter as a way to access a registry. This register_to object must have a _registry instance variable to access it. """ from django.apps import apps register_to = kwargs.get('register_to') for app_config in apps.get_app_configs(): for module_to_search in args: # Attempt to import the app's module. try: if register_to: before_import_registry = copy.copy(register_to._registry) import_module('%s.%s' % (app_config.name, module_to_search)) except Exception: # Reset the registry to the state before the last import # as this import will have to reoccur on the next request and # this could raise NotRegistered and AlreadyRegistered # exceptions (see #8245). if register_to: register_to._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have the module in question, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(app_config.module, module_to_search): raise if six.PY3: from importlib.util import find_spec as importlib_find def module_has_submodule(package, module_name): """See if 'module' is in 'package'.""" try: package_name = package.__name__ package_path = package.__path__ except AttributeError: # package isn't a package. return False full_module_name = package_name + '.' + module_name return importlib_find(full_module_name, package_path) is not None else: import imp def module_has_submodule(package, module_name): """See if 'module' is in 'package'.""" name = ".".join([package.__name__, module_name]) try: # None indicates a cached miss; see mark_miss() in Python/import.c. return sys.modules[name] is not None except KeyError: pass try: package_path = package.__path__ # No __path__, then not a package. except AttributeError: # Since the remainder of this function assumes that we're dealing with # a package (module with a __path__), so if it's not, then bail here. return False for finder in sys.meta_path: if finder.find_module(name, package_path): return True for entry in package_path: try: # Try the cached finder. finder = sys.path_importer_cache[entry] if finder is None: # Implicit import machinery should be used. try: file_, _, _ = imp.find_module(module_name, [entry]) if file_: file_.close() return True except ImportError: continue # Else see if the finder knows of a loader. elif finder.find_module(name): return True else: continue except KeyError: # No cached finder, so try and make one. for hook in sys.path_hooks: try: finder = hook(entry) # XXX Could cache in sys.path_importer_cache if finder.find_module(name): return True else: # Once a finder is found, stop the search. break except ImportError: # Continue the search for a finder. continue else: # No finder found. # Try the implicit import machinery if searching a directory. if os.path.isdir(entry): try: file_, _, _ = imp.find_module(module_name, [entry]) if file_: file_.close() return True except ImportError: pass # XXX Could insert None or NullImporter else: # Exhausted the search, so the module cannot be found. return False def module_dir(module): """ Find the name of the directory that contains a module, if possible. Raise ValueError otherwise, e.g. for namespace packages that are split over several directories. """ # Convert to list because _NamespacePath does not support indexing on 3.3. paths = list(getattr(module, '__path__', [])) if len(paths) == 1: return paths[0] else: filename = getattr(module, '__file__', None) if filename is not None: return os.path.dirname(filename) raise ValueError("Cannot determine directory containing %s" % module)
LEPT-Development/aura_kernel_lge_c50
refs/heads/master
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Util.py
12527
# Util.py - Python extension for perf script, miscellaneous utility code # # Copyright (C) 2010 by Tom Zanussi <tzanussi@gmail.com> # # This software may be distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. import errno, os FUTEX_WAIT = 0 FUTEX_WAKE = 1 FUTEX_PRIVATE_FLAG = 128 FUTEX_CLOCK_REALTIME = 256 FUTEX_CMD_MASK = ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME) NSECS_PER_SEC = 1000000000 def avg(total, n): return total / n def nsecs(secs, nsecs): return secs * NSECS_PER_SEC + nsecs def nsecs_secs(nsecs): return nsecs / NSECS_PER_SEC def nsecs_nsecs(nsecs): return nsecs % NSECS_PER_SEC def nsecs_str(nsecs): str = "%5u.%09u" % (nsecs_secs(nsecs), nsecs_nsecs(nsecs)), return str def add_stats(dict, key, value): if not dict.has_key(key): dict[key] = (value, value, value, 1) else: min, max, avg, count = dict[key] if value < min: min = value if value > max: max = value avg = (avg + value) / 2 dict[key] = (min, max, avg, count + 1) def clear_term(): print("\x1b[H\x1b[2J") audit_package_warned = False try: import audit machine_to_id = { 'x86_64': audit.MACH_86_64, 'alpha' : audit.MACH_ALPHA, 'ia64' : audit.MACH_IA64, 'ppc' : audit.MACH_PPC, 'ppc64' : audit.MACH_PPC64, 's390' : audit.MACH_S390, 's390x' : audit.MACH_S390X, 'i386' : audit.MACH_X86, 'i586' : audit.MACH_X86, 'i686' : audit.MACH_X86, } try: machine_to_id['armeb'] = audit.MACH_ARMEB except: pass machine_id = machine_to_id[os.uname()[4]] except: if not audit_package_warned: audit_package_warned = True print "Install the audit-libs-python package to get syscall names" def syscall_name(id): try: return audit.audit_syscall_to_name(id, machine_id) except: return str(id) def strerror(nr): try: return errno.errorcode[abs(nr)] except: return "Unknown %d errno" % nr
dvliman/jaikuengine
refs/heads/master
.google_appengine/lib/django-1.5/django/contrib/gis/tests/geo3d/tests.py
100
from __future__ import absolute_import, unicode_literals import os import re from django.contrib.gis.db.models import Union, Extent3D from django.contrib.gis.geos import GEOSGeometry, LineString, Point, Polygon from django.contrib.gis.utils import LayerMapping, LayerMapError from django.test import TestCase from django.utils._os import upath from .models import (City3D, Interstate2D, Interstate3D, InterstateProj2D, InterstateProj3D, Point2D, Point3D, MultiPoint3D, Polygon2D, Polygon3D) data_path = os.path.realpath(os.path.join(os.path.dirname(upath(__file__)), '..', 'data')) city_file = os.path.join(data_path, 'cities', 'cities.shp') vrt_file = os.path.join(data_path, 'test_vrt', 'test_vrt.vrt') # The coordinates of each city, with Z values corresponding to their # altitude in meters. city_data = ( ('Houston', (-95.363151, 29.763374, 18)), ('Dallas', (-96.801611, 32.782057, 147)), ('Oklahoma City', (-97.521157, 34.464642, 380)), ('Wellington', (174.783117, -41.315268, 14)), ('Pueblo', (-104.609252, 38.255001, 1433)), ('Lawrence', (-95.235060, 38.971823, 251)), ('Chicago', (-87.650175, 41.850385, 181)), ('Victoria', (-123.305196, 48.462611, 15)), ) # Reference mapping of city name to its altitude (Z value). city_dict = dict((name, coords) for name, coords in city_data) # 3D freeway data derived from the National Elevation Dataset: # http://seamless.usgs.gov/products/9arc.php interstate_data = ( ('I-45', 'LINESTRING(-95.3708481 29.7765870 11.339,-95.3694580 29.7787980 4.536,-95.3690305 29.7797359 9.762,-95.3691886 29.7812450 12.448,-95.3696447 29.7850144 10.457,-95.3702511 29.7868518 9.418,-95.3706724 29.7881286 14.858,-95.3711632 29.7896157 15.386,-95.3714525 29.7936267 13.168,-95.3717848 29.7955007 15.104,-95.3717719 29.7969804 16.516,-95.3717305 29.7982117 13.923,-95.3717254 29.8000778 14.385,-95.3719875 29.8013539 15.160,-95.3720575 29.8026785 15.544,-95.3721321 29.8040912 14.975,-95.3722074 29.8050998 15.688,-95.3722779 29.8060430 16.099,-95.3733818 29.8076750 15.197,-95.3741563 29.8103686 17.268,-95.3749458 29.8129927 19.857,-95.3763564 29.8144557 15.435)', ( 11.339, 4.536, 9.762, 12.448, 10.457, 9.418, 14.858, 15.386, 13.168, 15.104, 16.516, 13.923, 14.385, 15.16 , 15.544, 14.975, 15.688, 16.099, 15.197, 17.268, 19.857, 15.435), ), ) # Bounding box polygon for inner-loop of Houston (in projected coordinate # system 32140), with elevation values from the National Elevation Dataset # (see above). bbox_data = ( 'POLYGON((941527.97 4225693.20,962596.48 4226349.75,963152.57 4209023.95,942051.75 4208366.38,941527.97 4225693.20))', (21.71, 13.21, 9.12, 16.40, 21.71) ) class Geo3DTest(TestCase): """ Only a subset of the PostGIS routines are 3D-enabled, and this TestCase tries to test the features that can handle 3D and that are also available within GeoDjango. For more information, see the PostGIS docs on the routines that support 3D: http://postgis.refractions.net/documentation/manual-1.4/ch08.html#PostGIS_3D_Functions """ def _load_interstate_data(self): # Interstate (2D / 3D and Geographic/Projected variants) for name, line, exp_z in interstate_data: line_3d = GEOSGeometry(line, srid=4269) line_2d = LineString([l[:2] for l in line_3d.coords], srid=4269) # Creating a geographic and projected version of the # interstate in both 2D and 3D. Interstate3D.objects.create(name=name, line=line_3d) InterstateProj3D.objects.create(name=name, line=line_3d) Interstate2D.objects.create(name=name, line=line_2d) InterstateProj2D.objects.create(name=name, line=line_2d) def _load_city_data(self): for name, pnt_data in city_data: City3D.objects.create(name=name, point=Point(*pnt_data, srid=4326)) def _load_polygon_data(self): bbox_wkt, bbox_z = bbox_data bbox_2d = GEOSGeometry(bbox_wkt, srid=32140) bbox_3d = Polygon(tuple((x, y, z) for (x, y), z in zip(bbox_2d[0].coords, bbox_z)), srid=32140) Polygon2D.objects.create(name='2D BBox', poly=bbox_2d) Polygon3D.objects.create(name='3D BBox', poly=bbox_3d) def test_3d_hasz(self): """ Make sure data is 3D and has expected Z values -- shouldn't change because of coordinate system. """ self._load_interstate_data() for name, line, exp_z in interstate_data: interstate = Interstate3D.objects.get(name=name) interstate_proj = InterstateProj3D.objects.get(name=name) for i in [interstate, interstate_proj]: self.assertTrue(i.line.hasz) self.assertEqual(exp_z, tuple(i.line.z)) self._load_city_data() for name, pnt_data in city_data: city = City3D.objects.get(name=name) z = pnt_data[2] self.assertTrue(city.point.hasz) self.assertEqual(z, city.point.z) def test_3d_polygons(self): """ Test the creation of polygon 3D models. """ self._load_polygon_data() p3d = Polygon3D.objects.get(name='3D BBox') self.assertTrue(p3d.poly.hasz) self.assertIsInstance(p3d.poly, Polygon) self.assertEqual(p3d.poly.srid, 32140) def test_3d_layermapping(self): """ Testing LayerMapping on 3D models. """ point_mapping = {'point' : 'POINT'} mpoint_mapping = {'mpoint' : 'MULTIPOINT'} # The VRT is 3D, but should still be able to map sans the Z. lm = LayerMapping(Point2D, vrt_file, point_mapping, transform=False) lm.save() self.assertEqual(3, Point2D.objects.count()) # The city shapefile is 2D, and won't be able to fill the coordinates # in the 3D model -- thus, a LayerMapError is raised. self.assertRaises(LayerMapError, LayerMapping, Point3D, city_file, point_mapping, transform=False) # 3D model should take 3D data just fine. lm = LayerMapping(Point3D, vrt_file, point_mapping, transform=False) lm.save() self.assertEqual(3, Point3D.objects.count()) # Making sure LayerMapping.make_multi works right, by converting # a Point25D into a MultiPoint25D. lm = LayerMapping(MultiPoint3D, vrt_file, mpoint_mapping, transform=False) lm.save() self.assertEqual(3, MultiPoint3D.objects.count()) def test_kml(self): """ Test GeoQuerySet.kml() with Z values. """ self._load_city_data() h = City3D.objects.kml(precision=6).get(name='Houston') # KML should be 3D. # `SELECT ST_AsKML(point, 6) FROM geo3d_city3d WHERE name = 'Houston';` ref_kml_regex = re.compile(r'^<Point><coordinates>-95.363\d+,29.763\d+,18</coordinates></Point>$') self.assertTrue(ref_kml_regex.match(h.kml)) def test_geojson(self): """ Test GeoQuerySet.geojson() with Z values. """ self._load_city_data() h = City3D.objects.geojson(precision=6).get(name='Houston') # GeoJSON should be 3D # `SELECT ST_AsGeoJSON(point, 6) FROM geo3d_city3d WHERE name='Houston';` ref_json_regex = re.compile(r'^{"type":"Point","coordinates":\[-95.363151,29.763374,18(\.0+)?\]}$') self.assertTrue(ref_json_regex.match(h.geojson)) def test_union(self): """ Testing the Union aggregate of 3D models. """ # PostGIS query that returned the reference EWKT for this test: # `SELECT ST_AsText(ST_Union(point)) FROM geo3d_city3d;` self._load_city_data() ref_ewkt = 'SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433,-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18,-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)' ref_union = GEOSGeometry(ref_ewkt) union = City3D.objects.aggregate(Union('point'))['point__union'] self.assertTrue(union.hasz) self.assertEqual(ref_union, union) def test_extent(self): """ Testing the Extent3D aggregate for 3D models. """ self._load_city_data() # `SELECT ST_Extent3D(point) FROM geo3d_city3d;` ref_extent3d = (-123.305196, -41.315268, 14,174.783117, 48.462611, 1433) extent1 = City3D.objects.aggregate(Extent3D('point'))['point__extent3d'] extent2 = City3D.objects.extent3d() def check_extent3d(extent3d, tol=6): for ref_val, ext_val in zip(ref_extent3d, extent3d): self.assertAlmostEqual(ref_val, ext_val, tol) for e3d in [extent1, extent2]: check_extent3d(e3d) def test_perimeter(self): """ Testing GeoQuerySet.perimeter() on 3D fields. """ self._load_polygon_data() # Reference query for values below: # `SELECT ST_Perimeter3D(poly), ST_Perimeter2D(poly) FROM geo3d_polygon3d;` ref_perim_3d = 76859.2620451 ref_perim_2d = 76859.2577803 tol = 6 self.assertAlmostEqual(ref_perim_2d, Polygon2D.objects.perimeter().get(name='2D BBox').perimeter.m, tol) self.assertAlmostEqual(ref_perim_3d, Polygon3D.objects.perimeter().get(name='3D BBox').perimeter.m, tol) def test_length(self): """ Testing GeoQuerySet.length() on 3D fields. """ # ST_Length_Spheroid Z-aware, and thus does not need to use # a separate function internally. # `SELECT ST_Length_Spheroid(line, 'SPHEROID["GRS 1980",6378137,298.257222101]') # FROM geo3d_interstate[2d|3d];` self._load_interstate_data() tol = 3 ref_length_2d = 4368.1721949481 ref_length_3d = 4368.62547052088 self.assertAlmostEqual(ref_length_2d, Interstate2D.objects.length().get(name='I-45').length.m, tol) self.assertAlmostEqual(ref_length_3d, Interstate3D.objects.length().get(name='I-45').length.m, tol) # Making sure `ST_Length3D` is used on for a projected # and 3D model rather than `ST_Length`. # `SELECT ST_Length(line) FROM geo3d_interstateproj2d;` ref_length_2d = 4367.71564892392 # `SELECT ST_Length3D(line) FROM geo3d_interstateproj3d;` ref_length_3d = 4368.16897234101 self.assertAlmostEqual(ref_length_2d, InterstateProj2D.objects.length().get(name='I-45').length.m, tol) self.assertAlmostEqual(ref_length_3d, InterstateProj3D.objects.length().get(name='I-45').length.m, tol) def test_scale(self): """ Testing GeoQuerySet.scale() on Z values. """ self._load_city_data() # Mapping of City name to reference Z values. zscales = (-3, 4, 23) for zscale in zscales: for city in City3D.objects.scale(1.0, 1.0, zscale): self.assertEqual(city_dict[city.name][2] * zscale, city.scale.z) def test_translate(self): """ Testing GeoQuerySet.translate() on Z values. """ self._load_city_data() ztranslations = (5.23, 23, -17) for ztrans in ztranslations: for city in City3D.objects.translate(0, 0, ztrans): self.assertEqual(city_dict[city.name][2] + ztrans, city.translate.z)
mysql/mysql-utilities
refs/heads/master
mysql-test/t/mylogin_clone_db.py
1
# # Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. # # 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; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # """ mylogin_clone_db test. """ import os import mutlib from mysql.utilities.exception import MUTLibError from mysql.utilities.exception import UtilError class test(mutlib.System_test): """Simple db clone using mylogin.cnf This test executes a simple clone of a database on a single server. """ server1 = None server1_con_str = None def check_prerequisites(self): self.check_gtid_unsafe() # Check if the required tools are accessible self.check_mylogin_requisites() return self.check_num_servers(1) def setup(self): self.server1 = self.servers.get_server(0) # Get connection values con_val = self.get_connection_values(self.server1) if con_val[1]: raise MUTLibError("The use of password in the connection string " "is not supported for automatic generation of " "login-path data. Please specify a user to " "connect to the server that does not require a " "password.") # Create login_path_data self.create_login_path_data('test_mylogin_clone_db', con_val[0], con_val[2]) # Build connection string <login-path>[:<port>][:<socket>] self.server1_con_str = 'test_mylogin_clone_db' if con_val[3]: self.server1_con_str = "{0}:{1}".format(self.server1_con_str, con_val[3]) if con_val[4]: self.server1_con_str = "{0}:{1}".format(self.server1_con_str, con_val[4]) # Load database data data_file = os.path.normpath("./std_data/basic_data.sql") self.drop_all() try: self.server1.read_and_exec_SQL(data_file, self.debug) except UtilError as err: raise MUTLibError("Failed to read commands from file {0}: " "{1}".format(data_file, err.errmsg)) return True def run(self): self.res_fname = "result.txt" from_conn = "--source={0}".format(self.server1_con_str) to_conn = "--destination={0}".format(self.server1_con_str) # Test case 1 - clone a sample database using login-path authentication cmd = ("mysqldbcopy.py --skip-gtid {0} {1} " "util_test:util_db_clone ".format(from_conn, to_conn)) try: res = self.exec_util(cmd, self.res_fname) self.results.append(res) return res == 0 except Exception as err: raise MUTLibError(str(err)) def get_result(self): if self.server1 and self.results[0] == 0: query = "SHOW DATABASES LIKE 'util_%'" try: res = self.server1.exec_query(query) if res and res[0][0] == 'util_db_clone': return True, None except UtilError as err: raise MUTLibError(err.errmsg) return False, ("Result failure.\n", "Database clone not found.\n") def record(self): # Not a comparative test, returning True return True def drop_all(self): """Drops all databases and users created. """ res1 = self.drop_db(self.server1, "util_test") res2 = self.drop_db(self.server1, "util_db_clone") drop_user = ["DROP USER 'joe'@'user'", "DROP USER 'joe_wildcard'@'%'"] for drop in drop_user: try: self.server1.exec_query(drop) except UtilError: pass return res1 and res2 def cleanup(self): self.remove_login_path_data('test_mylogin_clone_db') if self.res_fname: os.unlink(self.res_fname) return self.drop_all()
tetherless-world/ecoop
refs/heads/master
pyecoop/docs/sphinxext/ipython_console_highlighting.py
112
"""reST directive for syntax-highlighting ipython interactive sessions. XXX - See what improvements can be made based on the new (as of Sept 2009) 'pycon' lexer for the python console. At the very least it will give better highlighted tracebacks. """ #----------------------------------------------------------------------------- # Needed modules # Standard library import re # Third party from pygments.lexer import Lexer, do_insertions from pygments.lexers.agile import (PythonConsoleLexer, PythonLexer, PythonTracebackLexer) from pygments.token import Comment, Generic from sphinx import highlighting #----------------------------------------------------------------------------- # Global constants line_re = re.compile('.*?\n') #----------------------------------------------------------------------------- # Code begins - classes and functions class IPythonConsoleLexer(Lexer): """ For IPython console output or doctests, such as: .. sourcecode:: ipython In [1]: a = 'foo' In [2]: a Out[2]: 'foo' In [3]: print a foo In [4]: 1 / 0 Notes: - Tracebacks are not currently supported. - It assumes the default IPython prompts, not customized ones. """ name = 'IPython console session' aliases = ['ipython'] mimetypes = ['text/x-ipython-console'] input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)") output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)") continue_prompt = re.compile(" \.\.\.+:") tb_start = re.compile("\-+") def get_tokens_unprocessed(self, text): pylexer = PythonLexer(**self.options) tblexer = PythonTracebackLexer(**self.options) curcode = '' insertions = [] for match in line_re.finditer(text): line = match.group() input_prompt = self.input_prompt.match(line) continue_prompt = self.continue_prompt.match(line.rstrip()) output_prompt = self.output_prompt.match(line) if line.startswith("#"): insertions.append((len(curcode), [(0, Comment, line)])) elif input_prompt is not None: insertions.append((len(curcode), [(0, Generic.Prompt, input_prompt.group())])) curcode += line[input_prompt.end():] elif continue_prompt is not None: insertions.append((len(curcode), [(0, Generic.Prompt, continue_prompt.group())])) curcode += line[continue_prompt.end():] elif output_prompt is not None: # Use the 'error' token for output. We should probably make # our own token, but error is typicaly in a bright color like # red, so it works fine for our output prompts. insertions.append((len(curcode), [(0, Generic.Error, output_prompt.group())])) curcode += line[output_prompt.end():] else: if curcode: for item in do_insertions(insertions, pylexer.get_tokens_unprocessed(curcode)): yield item curcode = '' insertions = [] yield match.start(), Generic.Output, line if curcode: for item in do_insertions(insertions, pylexer.get_tokens_unprocessed(curcode)): yield item def setup(app): """Setup as a sphinx extension.""" # This is only a lexer, so adding it below to pygments appears sufficient. # But if somebody knows that the right API usage should be to do that via # sphinx, by all means fix it here. At least having this setup.py # suppresses the sphinx warning we'd get without it. pass #----------------------------------------------------------------------------- # Register the extension as a valid pygments lexer highlighting.lexers['ipython'] = IPythonConsoleLexer()
openstack/heat
refs/heads/master
heat/tests/openstack/neutron/test_neutron_port.py
1
# # 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 unittest import mock from neutronclient.common import exceptions as qe from neutronclient.neutron import v2_0 as neutronV20 from neutronclient.v2_0 import client as neutronclient from oslo_serialization import jsonutils from heat.common import exception from heat.common import template_format from heat.engine import resource from heat.engine import rsrc_defn from heat.engine import scheduler from heat.tests import common from heat.tests import utils neutron_port_template = ''' heat_template_version: 2015-04-30 description: Template to test port Neutron resource resources: port: type: OS::Neutron::Port properties: network: net1234 fixed_ips: - subnet: sub1234 ip_address: 10.0.3.21 device_owner: network:dhcp ''' neutron_port_with_address_pair_template = ''' heat_template_version: 2015-04-30 description: Template to test port Neutron resource resources: port: type: OS::Neutron::Port properties: network: abcd1234 allowed_address_pairs: - ip_address: 10.0.3.21/8 mac_address: 00-B0-D0-86-BB-F7 ''' neutron_port_with_no_fixed_ips_template = ''' heat_template_version: 2015-04-30 description: Template to test port Neutron resource resources: port: type: OS::Neutron::Port properties: network: abcd1234 no_fixed_ips: true ''' neutron_port_security_template = ''' heat_template_version: 2015-04-30 description: Template to test port Neutron resource resources: port: type: OS::Neutron::Port properties: network: abcd1234 port_security_enabled: False ''' neutron_port_propagate_ul_status_template = ''' heat_template_version: 2015-04-30 description: Template to test port Neutron resource resources: port: type: OS::Neutron::Port properties: network: abcd1234 propagate_uplink_status: True ''' class NeutronPortTest(common.HeatTestCase): def setUp(self): super(NeutronPortTest, self).setUp() self.create_mock = self.patchobject( neutronclient.Client, 'create_port') self.port_show_mock = self.patchobject( neutronclient.Client, 'show_port') self.update_mock = self.patchobject( neutronclient.Client, 'update_port') self.subnet_show_mock = self.patchobject( neutronclient.Client, 'show_subnet') self.network_show_mock = self.patchobject( neutronclient.Client, 'show_network') self.find_mock = self.patchobject( neutronV20, 'find_resourceid_by_name_or_id') def test_missing_network(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties'] = {} stack = utils.parse_stack(t) port = stack['port'] self.assertRaises(exception.StackValidationFailed, port.validate) def test_missing_subnet_id(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties']['fixed_ips'][0].pop('subnet') stack = utils.parse_stack(t) self.find_mock.return_value = 'net1234' self.create_mock.return_value = { 'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766"}} self.port_show_mock.return_value = { 'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766"}} port = stack['port'] scheduler.TaskRunner(port.create)() self.assertEqual((port.CREATE, port.COMPLETE), port.state) self.create_mock.assert_called_once_with({'port': { 'network_id': u'net1234', 'fixed_ips': [ {'ip_address': u'10.0.3.21'} ], 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': '' }}) self.port_show_mock.assert_called_once_with( 'fc68ea2c-b60b-4b4f-bd82-94ec81110766') def test_missing_ip_address(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties']['fixed_ips'][0].pop('ip_address') stack = utils.parse_stack(t) self.find_mock.return_value = 'net_or_sub' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766"}} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766"}} port = stack['port'] scheduler.TaskRunner(port.create)() self.assertEqual((port.CREATE, port.COMPLETE), port.state) self.create_mock.assert_called_once_with({'port': { 'network_id': u'net_or_sub', 'fixed_ips': [ {'subnet_id': u'net_or_sub'} ], 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': '' }}) self.port_show_mock.assert_called_once_with( 'fc68ea2c-b60b-4b4f-bd82-94ec81110766') def test_missing_fixed_ips(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties'].pop('fixed_ips') stack = utils.parse_stack(t) self.find_mock.return_value = 'net1234' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766"}} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766", "fixed_ips": { "subnet_id": "d0e971a6-a6b4-4f4c-8c88-b75e9c120b7e", "ip_address": "10.0.0.2" } }} port = stack['port'] scheduler.TaskRunner(port.create)() self.create_mock.assert_called_once_with({'port': { 'network_id': u'net1234', 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': '' }}) def test_allowed_address_pair(self): t = template_format.parse(neutron_port_with_address_pair_template) t['resources']['port']['properties'][ 'allowed_address_pairs'][0]['ip_address'] = '10.0.3.21' stack = utils.parse_stack(t) self.find_mock.return_value = 'abcd1234' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" }} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" }} port = stack['port'] scheduler.TaskRunner(port.create)() self.create_mock.assert_called_once_with({'port': { 'network_id': u'abcd1234', 'allowed_address_pairs': [{ 'ip_address': u'10.0.3.21', 'mac_address': u'00-B0-D0-86-BB-F7' }], 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'binding:vnic_type': 'normal', 'device_id': '', 'device_owner': '' }}) def test_no_fixed_ips(self): t = template_format.parse(neutron_port_with_no_fixed_ips_template) stack = utils.parse_stack(t) self.find_mock.return_value = 'abcd1234' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" }} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766", }} port = stack['port'] scheduler.TaskRunner(port.create)() self.create_mock.assert_called_once_with({'port': { 'network_id': u'abcd1234', 'name': utils.PhysName(stack.name, 'port'), 'fixed_ips': [], 'admin_state_up': True, 'binding:vnic_type': 'normal', 'device_id': '', 'device_owner': '' }}) def test_port_security_enabled(self): t = template_format.parse(neutron_port_security_template) stack = utils.parse_stack(t) self.find_mock.return_value = 'abcd1234' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" }} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766", }} port = stack['port'] scheduler.TaskRunner(port.create)() self.create_mock.assert_called_once_with({'port': { 'network_id': u'abcd1234', 'port_security_enabled': False, 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'binding:vnic_type': 'normal', 'device_id': '', 'device_owner': '' }}) def test_port_propagate_uplink_status(self): t = template_format.parse(neutron_port_propagate_ul_status_template) stack = utils.parse_stack(t) self.find_mock.return_value = 'abcd1234' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" }} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766", }} port = stack['port'] scheduler.TaskRunner(port.create)() self.create_mock.assert_called_once_with({'port': { 'network_id': u'abcd1234', 'propagate_uplink_status': True, 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'binding:vnic_type': 'normal', 'device_id': '', 'device_owner': '' }}) def test_missing_mac_address(self): t = template_format.parse(neutron_port_with_address_pair_template) t['resources']['port']['properties']['allowed_address_pairs'][0].pop( 'mac_address' ) stack = utils.parse_stack(t) self.find_mock.return_value = 'abcd1234' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" }} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" }} port = stack['port'] scheduler.TaskRunner(port.create)() self.create_mock.assert_called_once_with({'port': { 'network_id': u'abcd1234', 'allowed_address_pairs': [{ 'ip_address': u'10.0.3.21/8', }], 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'binding:vnic_type': 'normal', 'device_owner': '', 'device_id': ''}}) def test_ip_address_is_cidr(self): t = template_format.parse(neutron_port_with_address_pair_template) t['resources']['port']['properties'][ 'allowed_address_pairs'][0]['ip_address'] = '10.0.3.0/24' stack = utils.parse_stack(t) self.find_mock.return_value = 'abcd1234' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "2e00180a-ff9d-42c4-b701-a0606b243447" }} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "2e00180a-ff9d-42c4-b701-a0606b243447" }} port = stack['port'] scheduler.TaskRunner(port.create)() self.create_mock.assert_called_once_with({'port': { 'network_id': u'abcd1234', 'allowed_address_pairs': [{ 'ip_address': u'10.0.3.0/24', 'mac_address': u'00-B0-D0-86-BB-F7' }], 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'binding:vnic_type': 'normal', 'device_owner': '', 'device_id': '' }}) def _mock_create_with_props(self): self.find_mock.return_value = 'net_or_sub' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766"}} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766", "dns_assignment": { "hostname": "my-vm", "ip_address": "10.0.0.15", "fqdn": "my-vm.openstack.org."} }} def test_create_with_tags(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties']['tags'] = ['tag1', 'tag2'] stack = utils.parse_stack(t) port_prop = { 'network_id': u'net_or_sub', 'fixed_ips': [ {'subnet_id': u'net_or_sub', 'ip_address': u'10.0.3.21'} ], 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': '' } set_tag_mock = self.patchobject(neutronclient.Client, 'replace_tag') self._mock_create_with_props() port = stack['port'] scheduler.TaskRunner(port.create)() self.assertEqual((port.CREATE, port.COMPLETE), port.state) self.create_mock.assert_called_once_with({'port': port_prop}) set_tag_mock.assert_called_with('ports', port.resource_id, {'tags': ['tag1', 'tag2']}) def test_security_groups(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties']['security_groups'] = [ '8a2f582a-e1cd-480f-b85d-b02631c10656', '024613dc-b489-4478-b46f-ada462738740'] stack = utils.parse_stack(t) port_prop = { 'network_id': u'net_or_sub', 'security_groups': ['8a2f582a-e1cd-480f-b85d-b02631c10656', '024613dc-b489-4478-b46f-ada462738740'], 'fixed_ips': [ {'subnet_id': u'net_or_sub', 'ip_address': u'10.0.3.21'} ], 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': '' } self._mock_create_with_props() port = stack['port'] scheduler.TaskRunner(port.create)() self.assertEqual((port.CREATE, port.COMPLETE), port.state) self.create_mock.assert_called_once_with({'port': port_prop}) def test_port_with_dns_name(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties']['dns_name'] = 'myvm' stack = utils.parse_stack(t) port_prop = { 'network_id': u'net_or_sub', 'dns_name': 'myvm', 'fixed_ips': [ {'subnet_id': u'net_or_sub', 'ip_address': u'10.0.3.21'} ], 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': '' } self._mock_create_with_props() port = stack['port'] scheduler.TaskRunner(port.create)() self.assertEqual('my-vm.openstack.org.', port.FnGetAtt('dns_assignment')['fqdn']) self.assertEqual((port.CREATE, port.COMPLETE), port.state) self.create_mock.assert_called_once_with({'port': port_prop}) def test_security_groups_empty_list(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties']['security_groups'] = [] stack = utils.parse_stack(t) port_prop = { 'network_id': u'net_or_sub', 'security_groups': [], 'fixed_ips': [ {'subnet_id': u'net_or_sub', 'ip_address': u'10.0.3.21'} ], 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': '' } self._mock_create_with_props() port = stack['port'] scheduler.TaskRunner(port.create)() self.assertEqual((port.CREATE, port.COMPLETE), port.state) self.create_mock.assert_called_once_with({'port': port_prop}) def test_update_failed_port_no_replace(self): t = template_format.parse(neutron_port_template) stack = utils.parse_stack(t) port = stack['port'] port.resource_id = 'r_id' port.state_set(port.CREATE, port.FAILED) new_props = port.properties.data.copy() new_props['name'] = 'new_one' self.find_mock.return_value = 'net_or_sub' self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766", "fixed_ips": { "subnet_id": "d0e971a6-a6b4-4f4c-8c88-b75e9c120b7e", "ip_address": "10.0.3.21"}}} update_snippet = rsrc_defn.ResourceDefinition(port.name, port.type(), new_props) scheduler.TaskRunner(port.update, update_snippet)() self.assertEqual((port.UPDATE, port.COMPLETE), port.state) self.assertEqual(1, self.update_mock.call_count) def test_port_needs_update(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties'].pop('fixed_ips') stack = utils.parse_stack(t) props = {'network_id': u'net1234', 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'device_id': '', 'binding:vnic_type': 'normal'} self.find_mock.return_value = 'net1234' self.create_mock.return_value = {'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" }} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766", "fixed_ips": { "subnet_id": "d0e971a6-a6b4-4f4c-8c88-b75e9c120b7e", "ip_address": "10.0.0.2" } }} # create port port = stack['port'] scheduler.TaskRunner(port.create)() self.create_mock.assert_called_once_with({'port': props}) new_props = props.copy() # test always replace new_props['replacement_policy'] = 'REPLACE_ALWAYS' new_props['network'] = new_props.pop('network_id') update_snippet = rsrc_defn.ResourceDefinition(port.name, port.type(), new_props) self.assertRaises(resource.UpdateReplace, port._needs_update, update_snippet, port.frozen_definition(), new_props, port.properties, None) # test deferring to Resource._needs_update new_props['replacement_policy'] = 'AUTO' update_snippet = rsrc_defn.ResourceDefinition(port.name, port.type(), new_props) self.assertTrue(port._needs_update(update_snippet, port.frozen_definition(), new_props, port.properties, None)) def test_port_needs_update_network(self): net1 = '9cfe6c74-c105-4906-9a1f-81d9064e9bca' net2 = '0064eec9-5681-4ba7-a745-6f8e32db9503' props = {'network_id': net1, 'name': 'test_port', 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': '' } create_kwargs = props.copy() create_kwargs['admin_state_up'] = True self.find_mock.side_effect = [net1] * 8 + [net2] * 2 + [net1] self.create_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" }} self.port_show_mock.return_value = {'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766", "fixed_ips": { "subnet_id": "d0e971a6-a6b4-4f4c-8c88-b75e9c120b7e", "ip_address": "10.0.0.2" } }} # create port with network_id tmpl = neutron_port_template.replace( 'network: net1234', 'network_id: 9cfe6c74-c105-4906-9a1f-81d9064e9bca') t = template_format.parse(tmpl) t['resources']['port']['properties'].pop('fixed_ips') t['resources']['port']['properties']['name'] = 'test_port' stack = utils.parse_stack(t) port = stack['port'] scheduler.TaskRunner(port.create)() self.assertEqual((port.CREATE, port.COMPLETE), port.state) self.create_mock.assert_called_once_with({'port': create_kwargs}) # Switch from network_id=ID to network=ID (no replace) new_props = props.copy() new_props['network'] = new_props.pop('network_id') update_snippet = rsrc_defn.ResourceDefinition(port.name, port.type(), new_props) scheduler.TaskRunner(port.update, update_snippet)() self.assertEqual((port.UPDATE, port.COMPLETE), port.state) self.assertEqual(0, self.update_mock.call_count) # Switch from network=ID to network=NAME (no replace) new_props['network'] = 'net1234' update_snippet = rsrc_defn.ResourceDefinition(port.name, port.type(), new_props) scheduler.TaskRunner(port.update, update_snippet)() self.assertEqual((port.UPDATE, port.COMPLETE), port.state) self.assertEqual(0, self.update_mock.call_count) # Switch to a different network (replace) new_props['network'] = 'net5678' update_snippet = rsrc_defn.ResourceDefinition(port.name, port.type(), new_props) updater = scheduler.TaskRunner(port.update, update_snippet) self.assertRaises(resource.UpdateReplace, updater) self.assertEqual(11, self.find_mock.call_count) def test_get_port_attributes(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties'].pop('fixed_ips') stack = utils.parse_stack(t) subnet_dict = {'name': 'test-subnet', 'enable_dhcp': True, 'network_id': 'net1234', 'dns_nameservers': [], 'tenant_id': '58a61fc3992944ce971404a2ece6ff98', 'ipv6_ra_mode': None, 'cidr': '10.0.0.0/24', 'allocation_pools': [{'start': '10.0.0.2', 'end': u'10.0.0.254'}], 'gateway_ip': '10.0.0.1', 'ipv6_address_mode': None, 'ip_version': 4, 'host_routes': [], 'id': 'd0e971a6-a6b4-4f4c-8c88-b75e9c120b7e'} network_dict = {'name': 'test-network', 'status': 'ACTIVE', 'router:external': False, 'availability_zone_hints': [], 'availability_zones': ['nova'], 'ipv4_address_scope': None, 'description': '', 'subnets': [subnet_dict['id']], 'port_security_enabled': True, 'propagate_uplink_status': True, 'tenant_id': '58a61fc3992944ce971404a2ece6ff98', 'tags': [], 'ipv6_address_scope': None, 'project_id': '58a61fc3992944ce971404a2ece6ff98', 'revision_number': 4, 'admin_state_up': True, 'shared': False, 'mtu': 1450, 'id': 'net1234'} self.find_mock.return_value = 'net1234' self.create_mock.return_value = {'port': { 'status': 'BUILD', 'id': 'fc68ea2c-b60b-4b4f-bd82-94ec81110766' }} self.subnet_show_mock.return_value = {'subnet': subnet_dict} self.network_show_mock.return_value = {'network': network_dict} self.port_show_mock.return_value = {'port': { 'status': 'DOWN', 'name': utils.PhysName(stack.name, 'port'), 'allowed_address_pairs': [], 'admin_state_up': True, 'network_id': 'net1234', 'device_id': 'dc68eg2c-b60g-4b3f-bd82-67ec87650532', 'mac_address': 'fa:16:3e:75:67:60', 'tenant_id': '58a61fc3992944ce971404a2ece6ff98', 'security_groups': ['5b15d80c-6b70-4a1c-89c9-253538c5ade6'], 'fixed_ips': [{'subnet_id': 'd0e971a6-a6b4-4f4c-8c88-b75e9c120b7e', 'ip_address': '10.0.0.2'}] }} port = stack['port'] scheduler.TaskRunner(port.create)() self.create_mock.assert_called_once_with({'port': { 'network_id': u'net1234', 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': '' }}) self.assertEqual('DOWN', port.FnGetAtt('status')) self.assertEqual([], port.FnGetAtt('allowed_address_pairs')) self.assertTrue(port.FnGetAtt('admin_state_up')) self.assertEqual('net1234', port.FnGetAtt('network_id')) self.assertEqual('fa:16:3e:75:67:60', port.FnGetAtt('mac_address')) self.assertEqual(utils.PhysName(stack.name, 'port'), port.FnGetAtt('name')) self.assertEqual('dc68eg2c-b60g-4b3f-bd82-67ec87650532', port.FnGetAtt('device_id')) self.assertEqual('58a61fc3992944ce971404a2ece6ff98', port.FnGetAtt('tenant_id')) self.assertEqual(['5b15d80c-6b70-4a1c-89c9-253538c5ade6'], port.FnGetAtt('security_groups')) self.assertEqual([{'subnet_id': 'd0e971a6-a6b4-4f4c-8c88-b75e9c120b7e', 'ip_address': '10.0.0.2'}], port.FnGetAtt('fixed_ips')) self.assertEqual([subnet_dict], port.FnGetAtt('subnets')) self.assertEqual(network_dict, port.FnGetAtt('network')) self.assertRaises(exception.InvalidTemplateAttribute, port.FnGetAtt, 'Foo') def test_subnet_attribute_exception(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties'].pop('fixed_ips') stack = utils.parse_stack(t) self.find_mock.return_value = 'net1234' self.create_mock.return_value = {'port': { 'status': 'BUILD', 'id': 'fc68ea2c-b60b-4b4f-bd82-94ec81110766' }} self.port_show_mock.return_value = {'port': { 'status': 'DOWN', 'name': utils.PhysName(stack.name, 'port'), 'allowed_address_pairs': [], 'admin_state_up': True, 'network_id': 'net1234', 'device_id': 'dc68eg2c-b60g-4b3f-bd82-67ec87650532', 'mac_address': 'fa:16:3e:75:67:60', 'tenant_id': '58a61fc3992944ce971404a2ece6ff98', 'security_groups': ['5b15d80c-6b70-4a1c-89c9-253538c5ade6'], 'fixed_ips': [{'subnet_id': 'd0e971a6-a6b4-4f4c-8c88-b75e9c120b7e', 'ip_address': '10.0.0.2'}] }} self.subnet_show_mock.side_effect = (qe.NeutronClientException( 'ConnectionFailed: Connection to neutron failed: Maximum ' 'attempts reached')) port = stack['port'] scheduler.TaskRunner(port.create)() self.assertIsNone(port.FnGetAtt('subnets')) log_msg = ('Failed to fetch resource attributes: ConnectionFailed: ' 'Connection to neutron failed: Maximum attempts reached') self.assertIn(log_msg, self.LOG.output) self.create_mock.assert_called_once_with({'port': { 'network_id': u'net1234', 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': ''}} ) def test_network_attribute_exception(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties'].pop('fixed_ips') stack = utils.parse_stack(t) self.find_mock.return_value = 'net1234' self.create_mock.return_value = {'port': { 'status': 'BUILD', 'id': 'fc68ea2c-b60b-4b4f-bd82-94ec81110766' }} self.port_show_mock.return_value = {'port': { 'status': 'DOWN', 'name': utils.PhysName(stack.name, 'port'), 'allowed_address_pairs': [], 'admin_state_up': True, 'network_id': 'net1234', 'device_id': 'dc68eg2c-b60g-4b3f-bd82-67ec87650532', 'mac_address': 'fa:16:3e:75:67:60', 'tenant_id': '58a61fc3992944ce971404a2ece6ff98', 'security_groups': ['5b15d80c-6b70-4a1c-89c9-253538c5ade6'], 'fixed_ips': [{'subnet_id': 'd0e971a6-a6b4-4f4c-8c88-b75e9c120b7e', 'ip_address': '10.0.0.2'}] }} self.network_show_mock.side_effect = (qe.NeutronClientException( 'ConnectionFailed: Connection to neutron failed: Maximum ' 'attempts reached')) port = stack['port'] scheduler.TaskRunner(port.create)() self.assertIsNone(port.FnGetAtt('network')) log_msg = ('Failed to fetch resource attributes: ConnectionFailed: ' 'Connection to neutron failed: Maximum attempts reached') self.assertIn(log_msg, self.LOG.output) self.create_mock.assert_called_once_with({'port': { 'network_id': u'net1234', 'name': utils.PhysName(stack.name, 'port'), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'binding:vnic_type': 'normal', 'device_id': ''}} ) def test_prepare_for_replace_port_not_created(self): t = template_format.parse(neutron_port_template) stack = utils.parse_stack(t) port = stack['port'] port._show_resource = mock.Mock() port.data_set = mock.Mock() n_client = mock.Mock() port.client = mock.Mock(return_value=n_client) self.assertIsNone(port.resource_id) # execute prepare_for_replace port.prepare_for_replace() # check, if the port is not created, do nothing in # prepare_for_replace() self.assertFalse(port._show_resource.called) self.assertFalse(port.data_set.called) self.assertFalse(n_client.update_port.called) def test_prepare_for_replace_port_not_found(self): t = template_format.parse(neutron_port_template) stack = utils.parse_stack(t) port = stack['port'] port.resource_id = 'test_res_id' port._show_resource = mock.Mock(side_effect=qe.NotFound) port.data_set = mock.Mock() n_client = mock.Mock() port.client = mock.Mock(return_value=n_client) # execute prepare_for_replace port.prepare_for_replace() # check, if the port is not found, do nothing in # prepare_for_replace() self.assertTrue(port._show_resource.called) self.assertFalse(port.data_set.called) self.assertFalse(n_client.update_port.called) def test_prepare_for_replace_port(self): t = template_format.parse(neutron_port_template) stack = utils.parse_stack(t) port = stack['port'] port.resource_id = 'test_res_id' _value = { 'fixed_ips': { 'subnet_id': 'test_subnet', 'ip_address': '42.42.42.42' } } port._show_resource = mock.Mock(return_value=_value) port.data_set = mock.Mock() n_client = mock.Mock() port.client = mock.Mock(return_value=n_client) # execute prepare_for_replace port.prepare_for_replace() # check, that data was stored port.data_set.assert_called_once_with( 'port_fip', jsonutils.dumps(_value.get('fixed_ips'))) # check, that port was updated and ip was removed expected_props = {'port': {'fixed_ips': []}} n_client.update_port.assert_called_once_with('test_res_id', expected_props) def test_restore_prev_rsrc(self): t = template_format.parse(neutron_port_template) stack = utils.parse_stack(t) new_port = stack['port'] new_port.resource_id = 'new_res_id' # mock backup stack to return only one mocked old_port old_port = mock.Mock() new_port.stack._backup_stack = mock.Mock() new_port.stack._backup_stack().resources.get.return_value = old_port old_port.resource_id = 'old_res_id' _value = { 'subnet_id': 'test_subnet', 'ip_address': '42.42.42.42' } old_port.data = mock.Mock( return_value={'port_fip': jsonutils.dumps(_value)}) n_client = mock.Mock() new_port.client = mock.Mock(return_value=n_client) # execute restore_prev_rsrc new_port.restore_prev_rsrc() # check, that ports were updated: old port get ip and # same ip was removed from old port expected_new_props = {'port': {'fixed_ips': []}} expected_old_props = {'port': {'fixed_ips': _value}} n_client.update_port.assert_has_calls([ mock.call('new_res_id', expected_new_props), mock.call('old_res_id', expected_old_props)]) def test_restore_prev_rsrc_convergence(self): t = template_format.parse(neutron_port_template) stack = utils.parse_stack(t) stack.store() # mock resource from previous template prev_rsrc = stack['port'] prev_rsrc.resource_id = 'prev-rsrc' # store in db prev_rsrc.state_set(prev_rsrc.UPDATE, prev_rsrc.COMPLETE) # mock resource from existing template and store in db existing_rsrc = stack['port'] existing_rsrc.current_template_id = stack.t.id existing_rsrc.resource_id = 'existing-rsrc' existing_rsrc.state_set(existing_rsrc.UPDATE, existing_rsrc.COMPLETE) # mock previous resource was replaced by existing resource prev_rsrc.replaced_by = existing_rsrc.id _value = { 'subnet_id': 'test_subnet', 'ip_address': '42.42.42.42' } prev_rsrc._data = {'port_fip': jsonutils.dumps(_value)} n_client = mock.Mock() prev_rsrc.client = mock.Mock(return_value=n_client) # execute restore_prev_rsrc prev_rsrc.restore_prev_rsrc(convergence=True) expected_existing_props = {'port': {'fixed_ips': []}} expected_prev_props = {'port': {'fixed_ips': _value}} n_client.update_port.assert_has_calls([ mock.call(existing_rsrc.resource_id, expected_existing_props), mock.call(prev_rsrc.resource_id, expected_prev_props)]) def test_port_get_live_state(self): t = template_format.parse(neutron_port_template) t['resources']['port']['properties']['value_specs'] = { 'binding:vif_type': 'test'} stack = utils.parse_stack(t) port = stack['port'] resp = {'port': { 'status': 'DOWN', 'binding:host_id': '', 'name': 'flip-port-xjbal77qope3', 'allowed_address_pairs': [], 'admin_state_up': True, 'network_id': 'd6859535-efef-4184-b236-e5fcae856e0f', 'dns_name': '', 'extra_dhcp_opts': [], 'mac_address': 'fa:16:3e:fe:64:79', 'qos_policy_id': 'some', 'dns_assignment': [], 'binding:vif_details': {}, 'binding:vif_type': 'unbound', 'device_owner': '', 'tenant_id': '30f466e3d14b4251853899f9c26e2b66', 'binding:profile': {}, 'port_security_enabled': True, 'propagate_uplink_status': True, 'binding:vnic_type': 'normal', 'fixed_ips': [ {'subnet_id': '02d9608f-8f30-4611-ad02-69855c82457f', 'ip_address': '10.0.3.4'}], 'id': '829bf5c1-b59c-40ad-80e3-ea15a93879f3', 'security_groups': ['c276247f-50fd-4289-862a-80fb81a55de1'], 'device_id': ''} } port.client().show_port = mock.MagicMock(return_value=resp) port.resource_id = '1234' port._data = {} port.data_set = mock.Mock() reality = port.get_live_state(port.properties) expected = { 'allowed_address_pairs': [], 'admin_state_up': True, 'device_owner': '', 'port_security_enabled': True, 'propagate_uplink_status': True, 'binding:vnic_type': 'normal', 'fixed_ips': [ {'subnet': '02d9608f-8f30-4611-ad02-69855c82457f', 'ip_address': '10.0.3.4'}], 'security_groups': ['c276247f-50fd-4289-862a-80fb81a55de1'], 'device_id': '', 'dns_name': '', 'qos_policy': 'some', 'value_specs': {'binding:vif_type': 'unbound'} } self.assertEqual(set(expected.keys()), set(reality.keys())) for key in expected: self.assertEqual(expected[key], reality[key]) class UpdatePortTest(common.HeatTestCase): scenarios = [ ('with_secgrp', dict(secgrp=['8a2f582a-e1cd-480f-b85d-b02631c10656'], name='test', value_specs={}, fixed_ips=None, addr_pair=None, vnic_type=None)), ('with_no_name', dict(secgrp=['8a2f582a-e1cd-480f-b85d-b02631c10656'], orig_name='original', name=None, value_specs={}, fixed_ips=None, addr_pair=None, vnic_type=None)), ('with_empty_values', dict(secgrp=[], name='test', value_specs={}, fixed_ips=[], addr_pair=[], vnic_type=None)), ('with_fixed_ips', dict(secgrp=None, value_specs={}, fixed_ips=[ {"subnet_id": "d0e971a6-a6b4-4f4c", "ip_address": "10.0.0.2"}], addr_pair=None, vnic_type=None)), ('with_addr_pair', dict(secgrp=None, value_specs={}, fixed_ips=None, addr_pair=[{'ip_address': '10.0.3.21', 'mac_address': '00-B0-D0-86'}], vnic_type=None)), ('with_value_specs', dict(secgrp=None, value_specs={'binding:vnic_type': 'direct'}, fixed_ips=None, addr_pair=None, vnic_type=None)), ('normal_vnic', dict(secgrp=None, value_specs={}, fixed_ips=None, addr_pair=None, vnic_type='normal')), ('direct_vnic', dict(secgrp=None, value_specs={}, fixed_ips=None, addr_pair=None, vnic_type='direct')), ('physical_direct_vnic', dict(secgrp=None, value_specs={}, fixed_ips=None, addr_pair=None, vnic_type='direct-physical')), ('baremetal_vnic', dict(secgrp=None, value_specs={}, fixed_ips=None, addr_pair=None, vnic_type='baremetal')), ('virtio_forwarder_vnic', dict(secgrp=None, value_specs={}, fixed_ips=None, addr_pair=None, vnic_type='virtio-forwarder')), ('smart_nic_vnic', dict(secgrp=None, value_specs={}, fixed_ips=None, addr_pair=None, vnic_type='smart-nic')), ('with_all', dict(secgrp=['8a2f582a-e1cd-480f-b85d-b02631c10656'], value_specs={}, fixed_ips=[ {"subnet_id": "d0e971a6-a6b4-4f4c", "ip_address": "10.0.0.2"}], addr_pair=[{'ip_address': '10.0.3.21', 'mac_address': '00-B0-D0-86-BB-F7'}], vnic_type='normal')), ] def test_update_port(self): t = template_format.parse(neutron_port_template) create_name = getattr(self, 'orig_name', None) if create_name is not None: t['resources']['port']['properties']['name'] = create_name stack = utils.parse_stack(t) def res_id(client, resource, name_or_id, cmd_resource=None): return { 'network': 'net1234', 'subnet': 'sub1234', }[resource] self.patchobject(neutronV20, 'find_resourceid_by_name_or_id', side_effect=res_id) create_port_result = { 'port': { "status": "BUILD", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766" } } show_port_result = { 'port': { "status": "ACTIVE", "id": "fc68ea2c-b60b-4b4f-bd82-94ec81110766", "fixed_ips": { "subnet_id": "d0e971a6-a6b4-4f4c-8c88-b75e9c120b7e", "ip_address": "10.0.0.2" } } } create_port = self.patchobject(neutronclient.Client, 'create_port', return_value=create_port_result) update_port = self.patchobject(neutronclient.Client, 'update_port') show_port = self.patchobject(neutronclient.Client, 'show_port', return_value=show_port_result) fake_groups_list = { 'security_groups': [ { 'tenant_id': 'dc4b074874244f7693dd65583733a758', 'id': '0389f747-7785-4757-b7bb-2ab07e4b09c3', 'name': 'default', 'security_group_rules': [], 'description': 'no protocol' } ] } self.patchobject(neutronclient.Client, 'list_security_groups', return_value=fake_groups_list) set_tag_mock = self.patchobject(neutronclient.Client, 'replace_tag') props = {'network_id': u'net1234', 'fixed_ips': [{'subnet_id': 'sub1234', 'ip_address': '10.0.3.21'}], 'name': (create_name if create_name is not None else utils.PhysName(stack.name, 'port')), 'admin_state_up': True, 'device_owner': u'network:dhcp', 'device_id': '', 'binding:vnic_type': 'normal'} update_props = props.copy() update_props['name'] = getattr(self, 'name', create_name) update_props['security_groups'] = self.secgrp update_props['value_specs'] = self.value_specs update_props['tags'] = ['test_tag'] if self.fixed_ips: update_props['fixed_ips'] = self.fixed_ips update_props['allowed_address_pairs'] = self.addr_pair update_props['binding:vnic_type'] = self.vnic_type update_dict = update_props.copy() if update_props['allowed_address_pairs'] is None: update_dict['allowed_address_pairs'] = [] if update_props['security_groups'] is None: update_dict['security_groups'] = [ '0389f747-7785-4757-b7bb-2ab07e4b09c3', ] if update_props['name'] is None: update_dict['name'] = utils.PhysName(stack.name, 'port') value_specs = update_dict.pop('value_specs') if value_specs: for value_spec in value_specs.items(): update_dict[value_spec[0]] = value_spec[1] tags = update_dict.pop('tags') # create port port = stack['port'] self.assertIsNone(scheduler.TaskRunner(port.create)()) create_port.assert_called_once_with({'port': props}) # update port update_snippet = rsrc_defn.ResourceDefinition(port.name, port.type(), update_props) self.assertIsNone(scheduler.TaskRunner(port.handle_update, update_snippet, {}, update_props)()) update_port.assert_called_once_with( 'fc68ea2c-b60b-4b4f-bd82-94ec81110766', {'port': update_dict}) set_tag_mock.assert_called_with('ports', port.resource_id, {'tags': tags}) # check, that update does not cause of Update Replace create_snippet = rsrc_defn.ResourceDefinition(port.name, port.type(), props) after_props, before_props = port._prepare_update_props(update_snippet, create_snippet) self.assertIsNotNone( port.update_template_diff_properties(after_props, before_props)) # With fixed_ips removed scheduler.TaskRunner(port.handle_update, update_snippet, {}, {'fixed_ips': None})() # update with empty prop_diff scheduler.TaskRunner(port.handle_update, update_snippet, {}, {})() self.assertEqual(1, update_port.call_count) show_port.assert_called_with('fc68ea2c-b60b-4b4f-bd82-94ec81110766')
jmcbailey/django-cached-hitcount
refs/heads/master
hitcount_example/manage.py
2
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hitcount_example.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Sir-Henry-Curtis/Ironworks
refs/heads/master
modules/home/latestNews.py
1
"""Universal feed parser Handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds Visit https://code.google.com/p/feedparser/ for the latest version Visit http://packages.python.org/feedparser/ for the latest documentation Required: Python 2.4 or later Recommended: iconv_codec <http://cjkpython.i18n.org/> """ __version__ = "5.1.2" __license__ = """ Copyright (c) 2010-2012 Kurt McKee <contactme@kurtmckee.org> Copyright (c) 2002-2008 Mark Pilgrim All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.""" __author__ = "Mark Pilgrim <http://diveintomark.org/>" __contributors__ = ["Jason Diamond <http://injektilo.org/>", "John Beimler <http://john.beimler.org/>", "Fazal Majid <http://www.majid.info/mylos/weblog/>", "Aaron Swartz <http://aaronsw.com/>", "Kevin Marks <http://epeus.blogspot.com/>", "Sam Ruby <http://intertwingly.net/>", "Ade Oshineye <http://blog.oshineye.com/>", "Martin Pool <http://sourcefrog.net/>", "Kurt McKee <http://kurtmckee.org/>"] # HTTP "User-Agent" header to send to servers when downloading feeds. # If you are embedding feedparser in a larger application, you should # change this to your application name and URL. USER_AGENT = "UniversalFeedParser/%s +https://code.google.com/p/feedparser/" % __version__ # HTTP "Accept" header to send to servers when downloading feeds. If you don't # want to send an Accept header, set this to None. ACCEPT_HEADER = "application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/xml;q=0.9,text/xml;q=0.2,*/*;q=0.1" # List of preferred XML parsers, by SAX driver name. These will be tried first, # but if they're not installed, Python will keep searching through its own list # of pre-installed parsers until it finds one that supports everything we need. PREFERRED_XML_PARSERS = ["drv_libxml2"] # If you want feedparser to automatically run HTML markup through HTML Tidy, set # this to 1. Requires mxTidy <http://www.egenix.com/files/python/mxTidy.html> # or utidylib <http://utidylib.berlios.de/>. TIDY_MARKUP = 0 # List of Python interfaces for HTML Tidy, in order of preference. Only useful # if TIDY_MARKUP = 1 PREFERRED_TIDY_INTERFACES = ["uTidy", "mxTidy"] # If you want feedparser to automatically resolve all relative URIs, set this # to 1. RESOLVE_RELATIVE_URIS = 1 # If you want feedparser to automatically sanitize all potentially unsafe # HTML content, set this to 1. SANITIZE_HTML = 1 # If you want feedparser to automatically parse microformat content embedded # in entry contents, set this to 1 PARSE_MICROFORMATS = 1 # ---------- Python 3 modules (make it work if possible) ---------- try: import rfc822 except ImportError: from email import _parseaddr as rfc822 try: # Python 3.1 introduces bytes.maketrans and simultaneously # deprecates string.maketrans; use bytes.maketrans if possible _maketrans = bytes.maketrans except (NameError, AttributeError): import string _maketrans = string.maketrans # base64 support for Atom feeds that contain embedded binary data try: import base64, binascii except ImportError: base64 = binascii = None else: # Python 3.1 deprecates decodestring in favor of decodebytes _base64decode = getattr(base64, 'decodebytes', base64.decodestring) # _s2bytes: convert a UTF-8 str to bytes if the interpreter is Python 3 # _l2bytes: convert a list of ints to bytes if the interpreter is Python 3 try: if bytes is str: # In Python 2.5 and below, bytes doesn't exist (NameError) # In Python 2.6 and above, bytes and str are the same type raise NameError except NameError: # Python 2 def _s2bytes(s): return s def _l2bytes(l): return ''.join(map(chr, l)) else: # Python 3 def _s2bytes(s): return bytes(s, 'utf8') def _l2bytes(l): return bytes(l) # If you want feedparser to allow all URL schemes, set this to () # List culled from Python's urlparse documentation at: # http://docs.python.org/library/urlparse.html # as well as from "URI scheme" at Wikipedia: # https://secure.wikimedia.org/wikipedia/en/wiki/URI_scheme # Many more will likely need to be added! ACCEPTABLE_URI_SCHEMES = ( 'file', 'ftp', 'gopher', 'h323', 'hdl', 'http', 'https', 'imap', 'magnet', 'mailto', 'mms', 'news', 'nntp', 'prospero', 'rsync', 'rtsp', 'rtspu', 'sftp', 'shttp', 'sip', 'sips', 'snews', 'svn', 'svn+ssh', 'telnet', 'wais', # Additional common-but-unofficial schemes 'aim', 'callto', 'cvs', 'facetime', 'feed', 'git', 'gtalk', 'irc', 'ircs', 'irc6', 'itms', 'mms', 'msnim', 'skype', 'ssh', 'smb', 'svn', 'ymsg', ) #ACCEPTABLE_URI_SCHEMES = () # ---------- required modules (should come with any Python distribution) ---------- import cgi import codecs import copy import datetime import re import struct import time import types import urllib import urllib2 import urlparse import warnings from htmlentitydefs import name2codepoint, codepoint2name, entitydefs try: from io import BytesIO as _StringIO except ImportError: try: from cStringIO import StringIO as _StringIO except ImportError: from StringIO import StringIO as _StringIO # ---------- optional modules (feedparser will work without these, but with reduced functionality) ---------- # gzip is included with most Python distributions, but may not be available if you compiled your own try: import gzip except ImportError: gzip = None try: import zlib except ImportError: zlib = None # If a real XML parser is available, feedparser will attempt to use it. feedparser has # been tested with the built-in SAX parser and libxml2. On platforms where the # Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some # versions of FreeBSD), feedparser will quietly fall back on regex-based parsing. try: import xml.sax from xml.sax.saxutils import escape as _xmlescape except ImportError: _XML_AVAILABLE = 0 def _xmlescape(data,entities={}): data = data.replace('&', '&amp;') data = data.replace('>', '&gt;') data = data.replace('<', '&lt;') for char, entity in entities: data = data.replace(char, entity) return data else: try: xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers except xml.sax.SAXReaderNotAvailable: _XML_AVAILABLE = 0 else: _XML_AVAILABLE = 1 # sgmllib is not available by default in Python 3; if the end user doesn't have # it available then we'll lose illformed XML parsing, content santizing, and # microformat support (at least while feedparser depends on BeautifulSoup). try: import sgmllib except ImportError: # This is probably Python 3, which doesn't include sgmllib anymore _SGML_AVAILABLE = 0 # Mock sgmllib enough to allow subclassing later on class sgmllib(object): class SGMLParser(object): def goahead(self, i): pass def parse_starttag(self, i): pass else: _SGML_AVAILABLE = 1 # sgmllib defines a number of module-level regular expressions that are # insufficient for the XML parsing feedparser needs. Rather than modify # the variables directly in sgmllib, they're defined here using the same # names, and the compiled code objects of several sgmllib.SGMLParser # methods are copied into _BaseHTMLProcessor so that they execute in # feedparser's scope instead of sgmllib's scope. charref = re.compile('&#(\d+|[xX][0-9a-fA-F]+);') tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*') attrfind = re.compile( r'\s*([a-zA-Z_][-:.a-zA-Z_0-9]*)[$]?(\s*=\s*' r'(\'[^\']*\'|"[^"]*"|[][\-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~\'"@]*))?' ) # Unfortunately, these must be copied over to prevent NameError exceptions entityref = sgmllib.entityref incomplete = sgmllib.incomplete interesting = sgmllib.interesting shorttag = sgmllib.shorttag shorttagopen = sgmllib.shorttagopen starttagopen = sgmllib.starttagopen class _EndBracketRegEx: def __init__(self): # Overriding the built-in sgmllib.endbracket regex allows the # parser to find angle brackets embedded in element attributes. self.endbracket = re.compile('''([^'"<>]|"[^"]*"(?=>|/|\s|\w+=)|'[^']*'(?=>|/|\s|\w+=))*(?=[<>])|.*?(?=[<>])''') def search(self, target, index=0): match = self.endbracket.match(target, index) if match is not None: # Returning a new object in the calling thread's context # resolves a thread-safety. return EndBracketMatch(match) return None class EndBracketMatch: def __init__(self, match): self.match = match def start(self, n): return self.match.end(n) endbracket = _EndBracketRegEx() # iconv_codec provides support for more character encodings. # It's available from http://cjkpython.i18n.org/ try: import iconv_codec except ImportError: pass # chardet library auto-detects character encodings # Download from http://chardet.feedparser.org/ try: import chardet except ImportError: chardet = None # BeautifulSoup is used to extract microformat content from HTML # feedparser is tested using BeautifulSoup 3.2.0 # http://www.crummy.com/software/BeautifulSoup/ try: import BeautifulSoup except ImportError: BeautifulSoup = None PARSE_MICROFORMATS = False try: # the utf_32 codec was introduced in Python 2.6; it's necessary to # check this as long as feedparser supports Python 2.4 and 2.5 codecs.lookup('utf_32') except LookupError: _UTF32_AVAILABLE = False else: _UTF32_AVAILABLE = True # ---------- don't touch these ---------- class ThingsNobodyCaresAboutButMe(Exception): pass class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass class UndeclaredNamespace(Exception): pass SUPPORTED_VERSIONS = {'': u'unknown', 'rss090': u'RSS 0.90', 'rss091n': u'RSS 0.91 (Netscape)', 'rss091u': u'RSS 0.91 (Userland)', 'rss092': u'RSS 0.92', 'rss093': u'RSS 0.93', 'rss094': u'RSS 0.94', 'rss20': u'RSS 2.0', 'rss10': u'RSS 1.0', 'rss': u'RSS (unknown version)', 'atom01': u'Atom 0.1', 'atom02': u'Atom 0.2', 'atom03': u'Atom 0.3', 'atom10': u'Atom 1.0', 'atom': u'Atom (unknown version)', 'cdf': u'CDF', } class FeedParserDict(dict): keymap = {'channel': 'feed', 'items': 'entries', 'guid': 'id', 'date': 'updated', 'date_parsed': 'updated_parsed', 'description': ['summary', 'subtitle'], 'description_detail': ['summary_detail', 'subtitle_detail'], 'url': ['href'], 'modified': 'updated', 'modified_parsed': 'updated_parsed', 'issued': 'published', 'issued_parsed': 'published_parsed', 'copyright': 'rights', 'copyright_detail': 'rights_detail', 'tagline': 'subtitle', 'tagline_detail': 'subtitle_detail'} def __getitem__(self, key): if key == 'category': try: return dict.__getitem__(self, 'tags')[0]['term'] except IndexError: raise KeyError, "object doesn't have key 'category'" elif key == 'enclosures': norel = lambda link: FeedParserDict([(name,value) for (name,value) in link.items() if name!='rel']) return [norel(link) for link in dict.__getitem__(self, 'links') if link['rel']==u'enclosure'] elif key == 'license': for link in dict.__getitem__(self, 'links'): if link['rel']==u'license' and 'href' in link: return link['href'] elif key == 'updated': # Temporarily help developers out by keeping the old # broken behavior that was reported in issue 310. # This fix was proposed in issue 328. if not dict.__contains__(self, 'updated') and \ dict.__contains__(self, 'published'): warnings.warn("To avoid breaking existing software while " "fixing issue 310, a temporary mapping has been created " "from `updated` to `published` if `updated` doesn't " "exist. This fallback will be removed in a future version " "of feedparser.", DeprecationWarning) return dict.__getitem__(self, 'published') return dict.__getitem__(self, 'updated') elif key == 'updated_parsed': if not dict.__contains__(self, 'updated_parsed') and \ dict.__contains__(self, 'published_parsed'): warnings.warn("To avoid breaking existing software while " "fixing issue 310, a temporary mapping has been created " "from `updated_parsed` to `published_parsed` if " "`updated_parsed` doesn't exist. This fallback will be " "removed in a future version of feedparser.", DeprecationWarning) return dict.__getitem__(self, 'published_parsed') return dict.__getitem__(self, 'updated_parsed') else: realkey = self.keymap.get(key, key) if isinstance(realkey, list): for k in realkey: if dict.__contains__(self, k): return dict.__getitem__(self, k) elif dict.__contains__(self, realkey): return dict.__getitem__(self, realkey) return dict.__getitem__(self, key) def __contains__(self, key): if key in ('updated', 'updated_parsed'): # Temporarily help developers out by keeping the old # broken behavior that was reported in issue 310. # This fix was proposed in issue 328. return dict.__contains__(self, key) try: self.__getitem__(key) except KeyError: return False else: return True has_key = __contains__ def get(self, key, default=None): try: return self.__getitem__(key) except KeyError: return default def __setitem__(self, key, value): key = self.keymap.get(key, key) if isinstance(key, list): key = key[0] return dict.__setitem__(self, key, value) def setdefault(self, key, value): if key not in self: self[key] = value return value return self[key] def __getattr__(self, key): # __getattribute__() is called first; this will be called # only if an attribute was not already found try: return self.__getitem__(key) except KeyError: raise AttributeError, "object has no attribute '%s'" % key def __hash__(self): return id(self) _cp1252 = { 128: unichr(8364), # euro sign 130: unichr(8218), # single low-9 quotation mark 131: unichr( 402), # latin small letter f with hook 132: unichr(8222), # double low-9 quotation mark 133: unichr(8230), # horizontal ellipsis 134: unichr(8224), # dagger 135: unichr(8225), # double dagger 136: unichr( 710), # modifier letter circumflex accent 137: unichr(8240), # per mille sign 138: unichr( 352), # latin capital letter s with caron 139: unichr(8249), # single left-pointing angle quotation mark 140: unichr( 338), # latin capital ligature oe 142: unichr( 381), # latin capital letter z with caron 145: unichr(8216), # left single quotation mark 146: unichr(8217), # right single quotation mark 147: unichr(8220), # left double quotation mark 148: unichr(8221), # right double quotation mark 149: unichr(8226), # bullet 150: unichr(8211), # en dash 151: unichr(8212), # em dash 152: unichr( 732), # small tilde 153: unichr(8482), # trade mark sign 154: unichr( 353), # latin small letter s with caron 155: unichr(8250), # single right-pointing angle quotation mark 156: unichr( 339), # latin small ligature oe 158: unichr( 382), # latin small letter z with caron 159: unichr( 376), # latin capital letter y with diaeresis } _urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)') def _urljoin(base, uri): uri = _urifixer.sub(r'\1\3', uri) #try: if not isinstance(uri, unicode): uri = uri.decode('utf-8', 'ignore') uri = urlparse.urljoin(base, uri) if not isinstance(uri, unicode): return uri.decode('utf-8', 'ignore') return uri #except: # uri = urlparse.urlunparse([urllib.quote(part) for part in urlparse.urlparse(uri)]) # return urlparse.urljoin(base, uri) class _FeedParserMixin: namespaces = { '': '', 'http://backend.userland.com/rss': '', 'http://blogs.law.harvard.edu/tech/rss': '', 'http://purl.org/rss/1.0/': '', 'http://my.netscape.com/rdf/simple/0.9/': '', 'http://example.com/newformat#': '', 'http://example.com/necho': '', 'http://purl.org/echo/': '', 'uri/of/echo/namespace#': '', 'http://purl.org/pie/': '', 'http://purl.org/atom/ns#': '', 'http://www.w3.org/2005/Atom': '', 'http://purl.org/rss/1.0/modules/rss091#': '', 'http://webns.net/mvcb/': 'admin', 'http://purl.org/rss/1.0/modules/aggregation/': 'ag', 'http://purl.org/rss/1.0/modules/annotate/': 'annotate', 'http://media.tangent.org/rss/1.0/': 'audio', 'http://backend.userland.com/blogChannelModule': 'blogChannel', 'http://web.resource.org/cc/': 'cc', 'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons', 'http://purl.org/rss/1.0/modules/company': 'co', 'http://purl.org/rss/1.0/modules/content/': 'content', 'http://my.theinfo.org/changed/1.0/rss/': 'cp', 'http://purl.org/dc/elements/1.1/': 'dc', 'http://purl.org/dc/terms/': 'dcterms', 'http://purl.org/rss/1.0/modules/email/': 'email', 'http://purl.org/rss/1.0/modules/event/': 'ev', 'http://rssnamespace.org/feedburner/ext/1.0': 'feedburner', 'http://freshmeat.net/rss/fm/': 'fm', 'http://xmlns.com/foaf/0.1/': 'foaf', 'http://www.w3.org/2003/01/geo/wgs84_pos#': 'geo', 'http://postneo.com/icbm/': 'icbm', 'http://purl.org/rss/1.0/modules/image/': 'image', 'http://www.itunes.com/DTDs/PodCast-1.0.dtd': 'itunes', 'http://example.com/DTDs/PodCast-1.0.dtd': 'itunes', 'http://purl.org/rss/1.0/modules/link/': 'l', 'http://search.yahoo.com/mrss': 'media', # Version 1.1.2 of the Media RSS spec added the trailing slash on the namespace 'http://search.yahoo.com/mrss/': 'media', 'http://madskills.com/public/xml/rss/module/pingback/': 'pingback', 'http://prismstandard.org/namespaces/1.2/basic/': 'prism', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf', 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs', 'http://purl.org/rss/1.0/modules/reference/': 'ref', 'http://purl.org/rss/1.0/modules/richequiv/': 'reqv', 'http://purl.org/rss/1.0/modules/search/': 'search', 'http://purl.org/rss/1.0/modules/slash/': 'slash', 'http://schemas.xmlsoap.org/soap/envelope/': 'soap', 'http://purl.org/rss/1.0/modules/servicestatus/': 'ss', 'http://hacks.benhammersley.com/rss/streaming/': 'str', 'http://purl.org/rss/1.0/modules/subscription/': 'sub', 'http://purl.org/rss/1.0/modules/syndication/': 'sy', 'http://schemas.pocketsoap.com/rss/myDescModule/': 'szf', 'http://purl.org/rss/1.0/modules/taxonomy/': 'taxo', 'http://purl.org/rss/1.0/modules/threading/': 'thr', 'http://purl.org/rss/1.0/modules/textinput/': 'ti', 'http://madskills.com/public/xml/rss/module/trackback/': 'trackback', 'http://wellformedweb.org/commentAPI/': 'wfw', 'http://purl.org/rss/1.0/modules/wiki/': 'wiki', 'http://www.w3.org/1999/xhtml': 'xhtml', 'http://www.w3.org/1999/xlink': 'xlink', 'http://www.w3.org/XML/1998/namespace': 'xml', } _matchnamespaces = {} can_be_relative_uri = set(['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'icon', 'logo']) can_contain_relative_uris = set(['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']) can_contain_dangerous_markup = set(['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']) html_types = [u'text/html', u'application/xhtml+xml'] def __init__(self, baseuri=None, baselang=None, encoding=u'utf-8'): if not self._matchnamespaces: for k, v in self.namespaces.items(): self._matchnamespaces[k.lower()] = v self.feeddata = FeedParserDict() # feed-level data self.encoding = encoding # character encoding self.entries = [] # list of entry-level data self.version = u'' # feed type/version, see SUPPORTED_VERSIONS self.namespacesInUse = {} # dictionary of namespaces defined by the feed # the following are used internally to track state; # this is really out of control and should be refactored self.infeed = 0 self.inentry = 0 self.incontent = 0 self.intextinput = 0 self.inimage = 0 self.inauthor = 0 self.incontributor = 0 self.inpublisher = 0 self.insource = 0 self.sourcedata = FeedParserDict() self.contentparams = FeedParserDict() self._summaryKey = None self.namespacemap = {} self.elementstack = [] self.basestack = [] self.langstack = [] self.baseuri = baseuri or u'' self.lang = baselang or None self.svgOK = 0 self.title_depth = -1 self.depth = 0 if baselang: self.feeddata['language'] = baselang.replace('_','-') # A map of the following form: # { # object_that_value_is_set_on: { # property_name: depth_of_node_property_was_extracted_from, # other_property: depth_of_node_property_was_extracted_from, # }, # } self.property_depth_map = {} def _normalize_attributes(self, kv): k = kv[0].lower() v = k in ('rel', 'type') and kv[1].lower() or kv[1] # the sgml parser doesn't handle entities in attributes, nor # does it pass the attribute values through as unicode, while # strict xml parsers do -- account for this difference if isinstance(self, _LooseFeedParser): v = v.replace('&amp;', '&') if not isinstance(v, unicode): v = v.decode('utf-8') return (k, v) def unknown_starttag(self, tag, attrs): # increment depth counter self.depth += 1 # normalize attrs attrs = map(self._normalize_attributes, attrs) # track xml:base and xml:lang attrsD = dict(attrs) baseuri = attrsD.get('xml:base', attrsD.get('base')) or self.baseuri if not isinstance(baseuri, unicode): baseuri = baseuri.decode(self.encoding, 'ignore') # ensure that self.baseuri is always an absolute URI that # uses a whitelisted URI scheme (e.g. not `javscript:`) if self.baseuri: self.baseuri = _makeSafeAbsoluteURI(self.baseuri, baseuri) or self.baseuri else: self.baseuri = _urljoin(self.baseuri, baseuri) lang = attrsD.get('xml:lang', attrsD.get('lang')) if lang == '': # xml:lang could be explicitly set to '', we need to capture that lang = None elif lang is None: # if no xml:lang is specified, use parent lang lang = self.lang if lang: if tag in ('feed', 'rss', 'rdf:RDF'): self.feeddata['language'] = lang.replace('_','-') self.lang = lang self.basestack.append(self.baseuri) self.langstack.append(lang) # track namespaces for prefix, uri in attrs: if prefix.startswith('xmlns:'): self.trackNamespace(prefix[6:], uri) elif prefix == 'xmlns': self.trackNamespace(None, uri) # track inline content if self.incontent and not self.contentparams.get('type', u'xml').endswith(u'xml'): if tag in ('xhtml:div', 'div'): return # typepad does this 10/2007 # element declared itself as escaped markup, but it isn't really self.contentparams['type'] = u'application/xhtml+xml' if self.incontent and self.contentparams.get('type') == u'application/xhtml+xml': if tag.find(':') <> -1: prefix, tag = tag.split(':', 1) namespace = self.namespacesInUse.get(prefix, '') if tag=='math' and namespace=='http://www.w3.org/1998/Math/MathML': attrs.append(('xmlns',namespace)) if tag=='svg' and namespace=='http://www.w3.org/2000/svg': attrs.append(('xmlns',namespace)) if tag == 'svg': self.svgOK += 1 return self.handle_data('<%s%s>' % (tag, self.strattrs(attrs)), escape=0) # match namespaces if tag.find(':') <> -1: prefix, suffix = tag.split(':', 1) else: prefix, suffix = '', tag prefix = self.namespacemap.get(prefix, prefix) if prefix: prefix = prefix + '_' # special hack for better tracking of empty textinput/image elements in illformed feeds if (not prefix) and tag not in ('title', 'link', 'description', 'name'): self.intextinput = 0 if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'): self.inimage = 0 # call special handler (if defined) or default handler methodname = '_start_' + prefix + suffix try: method = getattr(self, methodname) return method(attrsD) except AttributeError: # Since there's no handler or something has gone wrong we explicitly add the element and its attributes unknown_tag = prefix + suffix if len(attrsD) == 0: # No attributes so merge it into the encosing dictionary return self.push(unknown_tag, 1) else: # Has attributes so create it in its own dictionary context = self._getContext() context[unknown_tag] = attrsD def unknown_endtag(self, tag): # match namespaces if tag.find(':') <> -1: prefix, suffix = tag.split(':', 1) else: prefix, suffix = '', tag prefix = self.namespacemap.get(prefix, prefix) if prefix: prefix = prefix + '_' if suffix == 'svg' and self.svgOK: self.svgOK -= 1 # call special handler (if defined) or default handler methodname = '_end_' + prefix + suffix try: if self.svgOK: raise AttributeError() method = getattr(self, methodname) method() except AttributeError: self.pop(prefix + suffix) # track inline content if self.incontent and not self.contentparams.get('type', u'xml').endswith(u'xml'): # element declared itself as escaped markup, but it isn't really if tag in ('xhtml:div', 'div'): return # typepad does this 10/2007 self.contentparams['type'] = u'application/xhtml+xml' if self.incontent and self.contentparams.get('type') == u'application/xhtml+xml': tag = tag.split(':')[-1] self.handle_data('</%s>' % tag, escape=0) # track xml:base and xml:lang going out of scope if self.basestack: self.basestack.pop() if self.basestack and self.basestack[-1]: self.baseuri = self.basestack[-1] if self.langstack: self.langstack.pop() if self.langstack: # and (self.langstack[-1] is not None): self.lang = self.langstack[-1] self.depth -= 1 def handle_charref(self, ref): # called for each character reference, e.g. for '&#160;', ref will be '160' if not self.elementstack: return ref = ref.lower() if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'): text = '&#%s;' % ref else: if ref[0] == 'x': c = int(ref[1:], 16) else: c = int(ref) text = unichr(c).encode('utf-8') self.elementstack[-1][2].append(text) def handle_entityref(self, ref): # called for each entity reference, e.g. for '&copy;', ref will be 'copy' if not self.elementstack: return if ref in ('lt', 'gt', 'quot', 'amp', 'apos'): text = '&%s;' % ref elif ref in self.entities: text = self.entities[ref] if text.startswith('&#') and text.endswith(';'): return self.handle_entityref(text) else: try: name2codepoint[ref] except KeyError: text = '&%s;' % ref else: text = unichr(name2codepoint[ref]).encode('utf-8') self.elementstack[-1][2].append(text) def handle_data(self, text, escape=1): # called for each block of plain text, i.e. outside of any tag and # not containing any character or entity references if not self.elementstack: return if escape and self.contentparams.get('type') == u'application/xhtml+xml': text = _xmlescape(text) self.elementstack[-1][2].append(text) def handle_comment(self, text): # called for each comment, e.g. <!-- insert message here --> pass def handle_pi(self, text): # called for each processing instruction, e.g. <?instruction> pass def handle_decl(self, text): pass def parse_declaration(self, i): # override internal declaration handler to handle CDATA blocks if self.rawdata[i:i+9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: # CDATA block began but didn't finish k = len(self.rawdata) return k self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0) return k+3 else: k = self.rawdata.find('>', i) if k >= 0: return k+1 else: # We have an incomplete CDATA block. return k def mapContentType(self, contentType): contentType = contentType.lower() if contentType == 'text' or contentType == 'plain': contentType = u'text/plain' elif contentType == 'html': contentType = u'text/html' elif contentType == 'xhtml': contentType = u'application/xhtml+xml' return contentType def trackNamespace(self, prefix, uri): loweruri = uri.lower() if not self.version: if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/'): self.version = u'rss090' elif loweruri == 'http://purl.org/rss/1.0/': self.version = u'rss10' elif loweruri == 'http://www.w3.org/2005/atom': self.version = u'atom10' if loweruri.find(u'backend.userland.com/rss') <> -1: # match any backend.userland.com namespace uri = u'http://backend.userland.com/rss' loweruri = uri if loweruri in self._matchnamespaces: self.namespacemap[prefix] = self._matchnamespaces[loweruri] self.namespacesInUse[self._matchnamespaces[loweruri]] = uri else: self.namespacesInUse[prefix or ''] = uri def resolveURI(self, uri): return _urljoin(self.baseuri or u'', uri) def decodeEntities(self, element, data): return data def strattrs(self, attrs): return ''.join([' %s="%s"' % (t[0],_xmlescape(t[1],{'"':'&quot;'})) for t in attrs]) def push(self, element, expectingText): self.elementstack.append([element, expectingText, []]) def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop() if self.version == u'atom10' and self.contentparams.get('type', u'text') == u'application/xhtml+xml': # remove enclosing child element, but only if it is a <div> and # only if all the remaining content is nested underneath it. # This means that the divs would be retained in the following: # <div>foo</div><div>bar</div> while pieces and len(pieces)>1 and not pieces[-1].strip(): del pieces[-1] while pieces and len(pieces)>1 and not pieces[0].strip(): del pieces[0] if pieces and (pieces[0] == '<div>' or pieces[0].startswith('<div ')) and pieces[-1]=='</div>': depth = 0 for piece in pieces[:-1]: if piece.startswith('</'): depth -= 1 if depth == 0: break elif piece.startswith('<') and not piece.endswith('/>'): depth += 1 else: pieces = pieces[1:-1] # Ensure each piece is a str for Python 3 for (i, v) in enumerate(pieces): if not isinstance(v, unicode): pieces[i] = v.decode('utf-8') output = u''.join(pieces) if stripWhitespace: output = output.strip() if not expectingText: return output # decode base64 content if base64 and self.contentparams.get('base64', 0): try: output = _base64decode(output) except binascii.Error: pass except binascii.Incomplete: pass except TypeError: # In Python 3, base64 takes and outputs bytes, not str # This may not be the most correct way to accomplish this output = _base64decode(output.encode('utf-8')).decode('utf-8') # resolve relative URIs if (element in self.can_be_relative_uri) and output: output = self.resolveURI(output) # decode entities within embedded markup if not self.contentparams.get('base64', 0): output = self.decodeEntities(element, output) # some feed formats require consumers to guess # whether the content is html or plain text if not self.version.startswith(u'atom') and self.contentparams.get('type') == u'text/plain': if self.lookslikehtml(output): self.contentparams['type'] = u'text/html' # remove temporary cruft from contentparams try: del self.contentparams['mode'] except KeyError: pass try: del self.contentparams['base64'] except KeyError: pass is_htmlish = self.mapContentType(self.contentparams.get('type', u'text/html')) in self.html_types # resolve relative URIs within embedded markup if is_htmlish and RESOLVE_RELATIVE_URIS: if element in self.can_contain_relative_uris: output = _resolveRelativeURIs(output, self.baseuri, self.encoding, self.contentparams.get('type', u'text/html')) # parse microformats # (must do this before sanitizing because some microformats # rely on elements that we sanitize) if PARSE_MICROFORMATS and is_htmlish and element in ['content', 'description', 'summary']: mfresults = _parseMicroformats(output, self.baseuri, self.encoding) if mfresults: for tag in mfresults.get('tags', []): self._addTag(tag['term'], tag['scheme'], tag['label']) for enclosure in mfresults.get('enclosures', []): self._start_enclosure(enclosure) for xfn in mfresults.get('xfn', []): self._addXFN(xfn['relationships'], xfn['href'], xfn['name']) vcard = mfresults.get('vcard') if vcard: self._getContext()['vcard'] = vcard # sanitize embedded markup if is_htmlish and SANITIZE_HTML: if element in self.can_contain_dangerous_markup: output = _sanitizeHTML(output, self.encoding, self.contentparams.get('type', u'text/html')) if self.encoding and not isinstance(output, unicode): output = output.decode(self.encoding, 'ignore') # address common error where people take data that is already # utf-8, presume that it is iso-8859-1, and re-encode it. if self.encoding in (u'utf-8', u'utf-8_INVALID_PYTHON_3') and isinstance(output, unicode): try: output = output.encode('iso-8859-1').decode('utf-8') except (UnicodeEncodeError, UnicodeDecodeError): pass # map win-1252 extensions to the proper code points if isinstance(output, unicode): output = output.translate(_cp1252) # categories/tags/keywords/whatever are handled in _end_category if element == 'category': return output if element == 'title' and -1 < self.title_depth <= self.depth: return output # store output in appropriate place(s) if self.inentry and not self.insource: if element == 'content': self.entries[-1].setdefault(element, []) contentparams = copy.deepcopy(self.contentparams) contentparams['value'] = output self.entries[-1][element].append(contentparams) elif element == 'link': if not self.inimage: # query variables in urls in link elements are improperly # converted from `?a=1&b=2` to `?a=1&b;=2` as if they're # unhandled character references. fix this special case. output = re.sub("&([A-Za-z0-9_]+);", "&\g<1>", output) self.entries[-1][element] = output if output: self.entries[-1]['links'][-1]['href'] = output else: if element == 'description': element = 'summary' old_value_depth = self.property_depth_map.setdefault(self.entries[-1], {}).get(element) if old_value_depth is None or self.depth <= old_value_depth: self.property_depth_map[self.entries[-1]][element] = self.depth self.entries[-1][element] = output if self.incontent: contentparams = copy.deepcopy(self.contentparams) contentparams['value'] = output self.entries[-1][element + '_detail'] = contentparams elif (self.infeed or self.insource):# and (not self.intextinput) and (not self.inimage): context = self._getContext() if element == 'description': element = 'subtitle' context[element] = output if element == 'link': # fix query variables; see above for the explanation output = re.sub("&([A-Za-z0-9_]+);", "&\g<1>", output) context[element] = output context['links'][-1]['href'] = output elif self.incontent: contentparams = copy.deepcopy(self.contentparams) contentparams['value'] = output context[element + '_detail'] = contentparams return output def pushContent(self, tag, attrsD, defaultContentType, expectingText): self.incontent += 1 if self.lang: self.lang=self.lang.replace('_','-') self.contentparams = FeedParserDict({ 'type': self.mapContentType(attrsD.get('type', defaultContentType)), 'language': self.lang, 'base': self.baseuri}) self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams) self.push(tag, expectingText) def popContent(self, tag): value = self.pop(tag) self.incontent -= 1 self.contentparams.clear() return value # a number of elements in a number of RSS variants are nominally plain # text, but this is routinely ignored. This is an attempt to detect # the most common cases. As false positives often result in silent # data loss, this function errs on the conservative side. @staticmethod def lookslikehtml(s): # must have a close tag or an entity reference to qualify if not (re.search(r'</(\w+)>',s) or re.search("&#?\w+;",s)): return # all tags must be in a restricted subset of valid HTML tags if filter(lambda t: t.lower() not in _HTMLSanitizer.acceptable_elements, re.findall(r'</?(\w+)',s)): return # all entities must have been defined as valid HTML entities if filter(lambda e: e not in entitydefs.keys(), re.findall(r'&(\w+);', s)): return return 1 def _mapToStandardPrefix(self, name): colonpos = name.find(':') if colonpos <> -1: prefix = name[:colonpos] suffix = name[colonpos+1:] prefix = self.namespacemap.get(prefix, prefix) name = prefix + ':' + suffix return name def _getAttribute(self, attrsD, name): return attrsD.get(self._mapToStandardPrefix(name)) def _isBase64(self, attrsD, contentparams): if attrsD.get('mode', '') == 'base64': return 1 if self.contentparams['type'].startswith(u'text/'): return 0 if self.contentparams['type'].endswith(u'+xml'): return 0 if self.contentparams['type'].endswith(u'/xml'): return 0 return 1 def _itsAnHrefDamnIt(self, attrsD): href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None))) if href: try: del attrsD['url'] except KeyError: pass try: del attrsD['uri'] except KeyError: pass attrsD['href'] = href return attrsD def _save(self, key, value, overwrite=False): context = self._getContext() if overwrite: context[key] = value else: context.setdefault(key, value) def _start_rss(self, attrsD): versionmap = {'0.91': u'rss091u', '0.92': u'rss092', '0.93': u'rss093', '0.94': u'rss094'} #If we're here then this is an RSS feed. #If we don't have a version or have a version that starts with something #other than RSS then there's been a mistake. Correct it. if not self.version or not self.version.startswith(u'rss'): attr_version = attrsD.get('version', '') version = versionmap.get(attr_version) if version: self.version = version elif attr_version.startswith('2.'): self.version = u'rss20' else: self.version = u'rss' def _start_channel(self, attrsD): self.infeed = 1 self._cdf_common(attrsD) def _cdf_common(self, attrsD): if 'lastmod' in attrsD: self._start_modified({}) self.elementstack[-1][-1] = attrsD['lastmod'] self._end_modified() if 'href' in attrsD: self._start_link({}) self.elementstack[-1][-1] = attrsD['href'] self._end_link() def _start_feed(self, attrsD): self.infeed = 1 versionmap = {'0.1': u'atom01', '0.2': u'atom02', '0.3': u'atom03'} if not self.version: attr_version = attrsD.get('version') version = versionmap.get(attr_version) if version: self.version = version else: self.version = u'atom' def _end_channel(self): self.infeed = 0 _end_feed = _end_channel def _start_image(self, attrsD): context = self._getContext() if not self.inentry: context.setdefault('image', FeedParserDict()) self.inimage = 1 self.title_depth = -1 self.push('image', 0) def _end_image(self): self.pop('image') self.inimage = 0 def _start_textinput(self, attrsD): context = self._getContext() context.setdefault('textinput', FeedParserDict()) self.intextinput = 1 self.title_depth = -1 self.push('textinput', 0) _start_textInput = _start_textinput def _end_textinput(self): self.pop('textinput') self.intextinput = 0 _end_textInput = _end_textinput def _start_author(self, attrsD): self.inauthor = 1 self.push('author', 1) # Append a new FeedParserDict when expecting an author context = self._getContext() context.setdefault('authors', []) context['authors'].append(FeedParserDict()) _start_managingeditor = _start_author _start_dc_author = _start_author _start_dc_creator = _start_author _start_itunes_author = _start_author def _end_author(self): self.pop('author') self.inauthor = 0 self._sync_author_detail() _end_managingeditor = _end_author _end_dc_author = _end_author _end_dc_creator = _end_author _end_itunes_author = _end_author def _start_itunes_owner(self, attrsD): self.inpublisher = 1 self.push('publisher', 0) def _end_itunes_owner(self): self.pop('publisher') self.inpublisher = 0 self._sync_author_detail('publisher') def _start_contributor(self, attrsD): self.incontributor = 1 context = self._getContext() context.setdefault('contributors', []) context['contributors'].append(FeedParserDict()) self.push('contributor', 0) def _end_contributor(self): self.pop('contributor') self.incontributor = 0 def _start_dc_contributor(self, attrsD): self.incontributor = 1 context = self._getContext() context.setdefault('contributors', []) context['contributors'].append(FeedParserDict()) self.push('name', 0) def _end_dc_contributor(self): self._end_name() self.incontributor = 0 def _start_name(self, attrsD): self.push('name', 0) _start_itunes_name = _start_name def _end_name(self): value = self.pop('name') if self.inpublisher: self._save_author('name', value, 'publisher') elif self.inauthor: self._save_author('name', value) elif self.incontributor: self._save_contributor('name', value) elif self.intextinput: context = self._getContext() context['name'] = value _end_itunes_name = _end_name def _start_width(self, attrsD): self.push('width', 0) def _end_width(self): value = self.pop('width') try: value = int(value) except ValueError: value = 0 if self.inimage: context = self._getContext() context['width'] = value def _start_height(self, attrsD): self.push('height', 0) def _end_height(self): value = self.pop('height') try: value = int(value) except ValueError: value = 0 if self.inimage: context = self._getContext() context['height'] = value def _start_url(self, attrsD): self.push('href', 1) _start_homepage = _start_url _start_uri = _start_url def _end_url(self): value = self.pop('href') if self.inauthor: self._save_author('href', value) elif self.incontributor: self._save_contributor('href', value) _end_homepage = _end_url _end_uri = _end_url def _start_email(self, attrsD): self.push('email', 0) _start_itunes_email = _start_email def _end_email(self): value = self.pop('email') if self.inpublisher: self._save_author('email', value, 'publisher') elif self.inauthor: self._save_author('email', value) elif self.incontributor: self._save_contributor('email', value) _end_itunes_email = _end_email def _getContext(self): if self.insource: context = self.sourcedata elif self.inimage and 'image' in self.feeddata: context = self.feeddata['image'] elif self.intextinput: context = self.feeddata['textinput'] elif self.inentry: context = self.entries[-1] else: context = self.feeddata return context def _save_author(self, key, value, prefix='author'): context = self._getContext() context.setdefault(prefix + '_detail', FeedParserDict()) context[prefix + '_detail'][key] = value self._sync_author_detail() context.setdefault('authors', [FeedParserDict()]) context['authors'][-1][key] = value def _save_contributor(self, key, value): context = self._getContext() context.setdefault('contributors', [FeedParserDict()]) context['contributors'][-1][key] = value def _sync_author_detail(self, key='author'): context = self._getContext() detail = context.get('%s_detail' % key) if detail: name = detail.get('name') email = detail.get('email') if name and email: context[key] = u'%s (%s)' % (name, email) elif name: context[key] = name elif email: context[key] = email else: author, email = context.get(key), None if not author: return emailmatch = re.search(ur'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))(\?subject=\S+)?''', author) if emailmatch: email = emailmatch.group(0) # probably a better way to do the following, but it passes all the tests author = author.replace(email, u'') author = author.replace(u'()', u'') author = author.replace(u'<>', u'') author = author.replace(u'&lt;&gt;', u'') author = author.strip() if author and (author[0] == u'('): author = author[1:] if author and (author[-1] == u')'): author = author[:-1] author = author.strip() if author or email: context.setdefault('%s_detail' % key, FeedParserDict()) if author: context['%s_detail' % key]['name'] = author if email: context['%s_detail' % key]['email'] = email def _start_subtitle(self, attrsD): self.pushContent('subtitle', attrsD, u'text/plain', 1) _start_tagline = _start_subtitle _start_itunes_subtitle = _start_subtitle def _end_subtitle(self): self.popContent('subtitle') _end_tagline = _end_subtitle _end_itunes_subtitle = _end_subtitle def _start_rights(self, attrsD): self.pushContent('rights', attrsD, u'text/plain', 1) _start_dc_rights = _start_rights _start_copyright = _start_rights def _end_rights(self): self.popContent('rights') _end_dc_rights = _end_rights _end_copyright = _end_rights def _start_item(self, attrsD): self.entries.append(FeedParserDict()) self.push('item', 0) self.inentry = 1 self.guidislink = 0 self.title_depth = -1 id = self._getAttribute(attrsD, 'rdf:about') if id: context = self._getContext() context['id'] = id self._cdf_common(attrsD) _start_entry = _start_item def _end_item(self): self.pop('item') self.inentry = 0 _end_entry = _end_item def _start_dc_language(self, attrsD): self.push('language', 1) _start_language = _start_dc_language def _end_dc_language(self): self.lang = self.pop('language') _end_language = _end_dc_language def _start_dc_publisher(self, attrsD): self.push('publisher', 1) _start_webmaster = _start_dc_publisher def _end_dc_publisher(self): self.pop('publisher') self._sync_author_detail('publisher') _end_webmaster = _end_dc_publisher def _start_published(self, attrsD): self.push('published', 1) _start_dcterms_issued = _start_published _start_issued = _start_published _start_pubdate = _start_published def _end_published(self): value = self.pop('published') self._save('published_parsed', _parse_date(value), overwrite=True) _end_dcterms_issued = _end_published _end_issued = _end_published _end_pubdate = _end_published def _start_updated(self, attrsD): self.push('updated', 1) _start_modified = _start_updated _start_dcterms_modified = _start_updated _start_dc_date = _start_updated _start_lastbuilddate = _start_updated def _end_updated(self): value = self.pop('updated') parsed_value = _parse_date(value) self._save('updated_parsed', parsed_value, overwrite=True) _end_modified = _end_updated _end_dcterms_modified = _end_updated _end_dc_date = _end_updated _end_lastbuilddate = _end_updated def _start_created(self, attrsD): self.push('created', 1) _start_dcterms_created = _start_created def _end_created(self): value = self.pop('created') self._save('created_parsed', _parse_date(value), overwrite=True) _end_dcterms_created = _end_created def _start_expirationdate(self, attrsD): self.push('expired', 1) def _end_expirationdate(self): self._save('expired_parsed', _parse_date(self.pop('expired')), overwrite=True) def _start_cc_license(self, attrsD): context = self._getContext() value = self._getAttribute(attrsD, 'rdf:resource') attrsD = FeedParserDict() attrsD['rel'] = u'license' if value: attrsD['href']=value context.setdefault('links', []).append(attrsD) def _start_creativecommons_license(self, attrsD): self.push('license', 1) _start_creativeCommons_license = _start_creativecommons_license def _end_creativecommons_license(self): value = self.pop('license') context = self._getContext() attrsD = FeedParserDict() attrsD['rel'] = u'license' if value: attrsD['href'] = value context.setdefault('links', []).append(attrsD) del context['license'] _end_creativeCommons_license = _end_creativecommons_license def _addXFN(self, relationships, href, name): context = self._getContext() xfn = context.setdefault('xfn', []) value = FeedParserDict({'relationships': relationships, 'href': href, 'name': name}) if value not in xfn: xfn.append(value) def _addTag(self, term, scheme, label): context = self._getContext() tags = context.setdefault('tags', []) if (not term) and (not scheme) and (not label): return value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label}) if value not in tags: tags.append(value) def _start_category(self, attrsD): term = attrsD.get('term') scheme = attrsD.get('scheme', attrsD.get('domain')) label = attrsD.get('label') self._addTag(term, scheme, label) self.push('category', 1) _start_dc_subject = _start_category _start_keywords = _start_category def _start_media_category(self, attrsD): attrsD.setdefault('scheme', u'http://search.yahoo.com/mrss/category_schema') self._start_category(attrsD) def _end_itunes_keywords(self): for term in self.pop('itunes_keywords').split(','): if term.strip(): self._addTag(term.strip(), u'http://www.itunes.com/', None) def _start_itunes_category(self, attrsD): self._addTag(attrsD.get('text'), u'http://www.itunes.com/', None) self.push('category', 1) def _end_category(self): value = self.pop('category') if not value: return context = self._getContext() tags = context['tags'] if value and len(tags) and not tags[-1]['term']: tags[-1]['term'] = value else: self._addTag(value, None, None) _end_dc_subject = _end_category _end_keywords = _end_category _end_itunes_category = _end_category _end_media_category = _end_category def _start_cloud(self, attrsD): self._getContext()['cloud'] = FeedParserDict(attrsD) def _start_link(self, attrsD): attrsD.setdefault('rel', u'alternate') if attrsD['rel'] == u'self': attrsD.setdefault('type', u'application/atom+xml') else: attrsD.setdefault('type', u'text/html') context = self._getContext() attrsD = self._itsAnHrefDamnIt(attrsD) if 'href' in attrsD: attrsD['href'] = self.resolveURI(attrsD['href']) expectingText = self.infeed or self.inentry or self.insource context.setdefault('links', []) if not (self.inentry and self.inimage): context['links'].append(FeedParserDict(attrsD)) if 'href' in attrsD: expectingText = 0 if (attrsD.get('rel') == u'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types): context['link'] = attrsD['href'] else: self.push('link', expectingText) def _end_link(self): value = self.pop('link') def _start_guid(self, attrsD): self.guidislink = (attrsD.get('ispermalink', 'true') == 'true') self.push('id', 1) _start_id = _start_guid def _end_guid(self): value = self.pop('id') self._save('guidislink', self.guidislink and 'link' not in self._getContext()) if self.guidislink: # guid acts as link, but only if 'ispermalink' is not present or is 'true', # and only if the item doesn't already have a link element self._save('link', value) _end_id = _end_guid def _start_title(self, attrsD): if self.svgOK: return self.unknown_starttag('title', attrsD.items()) self.pushContent('title', attrsD, u'text/plain', self.infeed or self.inentry or self.insource) _start_dc_title = _start_title _start_media_title = _start_title def _end_title(self): if self.svgOK: return value = self.popContent('title') if not value: return self.title_depth = self.depth _end_dc_title = _end_title def _end_media_title(self): title_depth = self.title_depth self._end_title() self.title_depth = title_depth def _start_description(self, attrsD): context = self._getContext() if 'summary' in context: self._summaryKey = 'content' self._start_content(attrsD) else: self.pushContent('description', attrsD, u'text/html', self.infeed or self.inentry or self.insource) _start_dc_description = _start_description def _start_abstract(self, attrsD): self.pushContent('description', attrsD, u'text/plain', self.infeed or self.inentry or self.insource) def _end_description(self): if self._summaryKey == 'content': self._end_content() else: value = self.popContent('description') self._summaryKey = None _end_abstract = _end_description _end_dc_description = _end_description def _start_info(self, attrsD): self.pushContent('info', attrsD, u'text/plain', 1) _start_feedburner_browserfriendly = _start_info def _end_info(self): self.popContent('info') _end_feedburner_browserfriendly = _end_info def _start_generator(self, attrsD): if attrsD: attrsD = self._itsAnHrefDamnIt(attrsD) if 'href' in attrsD: attrsD['href'] = self.resolveURI(attrsD['href']) self._getContext()['generator_detail'] = FeedParserDict(attrsD) self.push('generator', 1) def _end_generator(self): value = self.pop('generator') context = self._getContext() if 'generator_detail' in context: context['generator_detail']['name'] = value def _start_admin_generatoragent(self, attrsD): self.push('generator', 1) value = self._getAttribute(attrsD, 'rdf:resource') if value: self.elementstack[-1][2].append(value) self.pop('generator') self._getContext()['generator_detail'] = FeedParserDict({'href': value}) def _start_admin_errorreportsto(self, attrsD): self.push('errorreportsto', 1) value = self._getAttribute(attrsD, 'rdf:resource') if value: self.elementstack[-1][2].append(value) self.pop('errorreportsto') def _start_summary(self, attrsD): context = self._getContext() if 'summary' in context: self._summaryKey = 'content' self._start_content(attrsD) else: self._summaryKey = 'summary' self.pushContent(self._summaryKey, attrsD, u'text/plain', 1) _start_itunes_summary = _start_summary def _end_summary(self): if self._summaryKey == 'content': self._end_content() else: self.popContent(self._summaryKey or 'summary') self._summaryKey = None _end_itunes_summary = _end_summary def _start_enclosure(self, attrsD): attrsD = self._itsAnHrefDamnIt(attrsD) context = self._getContext() attrsD['rel'] = u'enclosure' context.setdefault('links', []).append(FeedParserDict(attrsD)) def _start_source(self, attrsD): if 'url' in attrsD: # This means that we're processing a source element from an RSS 2.0 feed self.sourcedata['href'] = attrsD[u'url'] self.push('source', 1) self.insource = 1 self.title_depth = -1 def _end_source(self): self.insource = 0 value = self.pop('source') if value: self.sourcedata['title'] = value self._getContext()['source'] = copy.deepcopy(self.sourcedata) self.sourcedata.clear() def _start_content(self, attrsD): self.pushContent('content', attrsD, u'text/plain', 1) src = attrsD.get('src') if src: self.contentparams['src'] = src self.push('content', 1) def _start_body(self, attrsD): self.pushContent('content', attrsD, u'application/xhtml+xml', 1) _start_xhtml_body = _start_body def _start_content_encoded(self, attrsD): self.pushContent('content', attrsD, u'text/html', 1) _start_fullitem = _start_content_encoded def _end_content(self): copyToSummary = self.mapContentType(self.contentparams.get('type')) in ([u'text/plain'] + self.html_types) value = self.popContent('content') if copyToSummary: self._save('summary', value) _end_body = _end_content _end_xhtml_body = _end_content _end_content_encoded = _end_content _end_fullitem = _end_content def _start_itunes_image(self, attrsD): self.push('itunes_image', 0) if attrsD.get('href'): self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')}) elif attrsD.get('url'): self._getContext()['image'] = FeedParserDict({'href': attrsD.get('url')}) _start_itunes_link = _start_itunes_image def _end_itunes_block(self): value = self.pop('itunes_block', 0) self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0 def _end_itunes_explicit(self): value = self.pop('itunes_explicit', 0) # Convert 'yes' -> True, 'clean' to False, and any other value to None # False and None both evaluate as False, so the difference can be ignored # by applications that only need to know if the content is explicit. self._getContext()['itunes_explicit'] = (None, False, True)[(value == 'yes' and 2) or value == 'clean' or 0] def _start_media_content(self, attrsD): context = self._getContext() context.setdefault('media_content', []) context['media_content'].append(attrsD) def _start_media_thumbnail(self, attrsD): context = self._getContext() context.setdefault('media_thumbnail', []) self.push('url', 1) # new context['media_thumbnail'].append(attrsD) def _end_media_thumbnail(self): url = self.pop('url') context = self._getContext() if url != None and len(url.strip()) != 0: if 'url' not in context['media_thumbnail'][-1]: context['media_thumbnail'][-1]['url'] = url def _start_media_player(self, attrsD): self.push('media_player', 0) self._getContext()['media_player'] = FeedParserDict(attrsD) def _end_media_player(self): value = self.pop('media_player') context = self._getContext() context['media_player']['content'] = value def _start_newlocation(self, attrsD): self.push('newlocation', 1) def _end_newlocation(self): url = self.pop('newlocation') context = self._getContext() # don't set newlocation if the context isn't right if context is not self.feeddata: return context['newlocation'] = _makeSafeAbsoluteURI(self.baseuri, url.strip()) if _XML_AVAILABLE: class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler): def __init__(self, baseuri, baselang, encoding): xml.sax.handler.ContentHandler.__init__(self) _FeedParserMixin.__init__(self, baseuri, baselang, encoding) self.bozo = 0 self.exc = None self.decls = {} def startPrefixMapping(self, prefix, uri): if not uri: return # Jython uses '' instead of None; standardize on None prefix = prefix or None self.trackNamespace(prefix, uri) if prefix and uri == 'http://www.w3.org/1999/xlink': self.decls['xmlns:' + prefix] = uri def startElementNS(self, name, qname, attrs): namespace, localname = name lowernamespace = str(namespace or '').lower() if lowernamespace.find(u'backend.userland.com/rss') <> -1: # match any backend.userland.com namespace namespace = u'http://backend.userland.com/rss' lowernamespace = namespace if qname and qname.find(':') > 0: givenprefix = qname.split(':')[0] else: givenprefix = None prefix = self._matchnamespaces.get(lowernamespace, givenprefix) if givenprefix and (prefix == None or (prefix == '' and lowernamespace == '')) and givenprefix not in self.namespacesInUse: raise UndeclaredNamespace, "'%s' is not associated with a namespace" % givenprefix localname = str(localname).lower() # qname implementation is horribly broken in Python 2.1 (it # doesn't report any), and slightly broken in Python 2.2 (it # doesn't report the xml: namespace). So we match up namespaces # with a known list first, and then possibly override them with # the qnames the SAX parser gives us (if indeed it gives us any # at all). Thanks to MatejC for helping me test this and # tirelessly telling me that it didn't work yet. attrsD, self.decls = self.decls, {} if localname=='math' and namespace=='http://www.w3.org/1998/Math/MathML': attrsD['xmlns']=namespace if localname=='svg' and namespace=='http://www.w3.org/2000/svg': attrsD['xmlns']=namespace if prefix: localname = prefix.lower() + ':' + localname elif namespace and not qname: #Expat for name,value in self.namespacesInUse.items(): if name and value == namespace: localname = name + ':' + localname break for (namespace, attrlocalname), attrvalue in attrs.items(): lowernamespace = (namespace or '').lower() prefix = self._matchnamespaces.get(lowernamespace, '') if prefix: attrlocalname = prefix + ':' + attrlocalname attrsD[str(attrlocalname).lower()] = attrvalue for qname in attrs.getQNames(): attrsD[str(qname).lower()] = attrs.getValueByQName(qname) self.unknown_starttag(localname, attrsD.items()) def characters(self, text): self.handle_data(text) def endElementNS(self, name, qname): namespace, localname = name lowernamespace = str(namespace or '').lower() if qname and qname.find(':') > 0: givenprefix = qname.split(':')[0] else: givenprefix = '' prefix = self._matchnamespaces.get(lowernamespace, givenprefix) if prefix: localname = prefix + ':' + localname elif namespace and not qname: #Expat for name,value in self.namespacesInUse.items(): if name and value == namespace: localname = name + ':' + localname break localname = str(localname).lower() self.unknown_endtag(localname) def error(self, exc): self.bozo = 1 self.exc = exc # drv_libxml2 calls warning() in some cases warning = error def fatalError(self, exc): self.error(exc) raise exc class _BaseHTMLProcessor(sgmllib.SGMLParser): special = re.compile('''[<>'"]''') bare_ampersand = re.compile("&(?!#\d+;|#x[0-9a-fA-F]+;|\w+;)") elements_no_end_tag = set([ 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr' ]) def __init__(self, encoding, _type): self.encoding = encoding self._type = _type sgmllib.SGMLParser.__init__(self) def reset(self): self.pieces = [] sgmllib.SGMLParser.reset(self) def _shorttag_replace(self, match): tag = match.group(1) if tag in self.elements_no_end_tag: return '<' + tag + ' />' else: return '<' + tag + '></' + tag + '>' # By declaring these methods and overriding their compiled code # with the code from sgmllib, the original code will execute in # feedparser's scope instead of sgmllib's. This means that the # `tagfind` and `charref` regular expressions will be found as # they're declared above, not as they're declared in sgmllib. def goahead(self, i): pass goahead.func_code = sgmllib.SGMLParser.goahead.func_code def __parse_starttag(self, i): pass __parse_starttag.func_code = sgmllib.SGMLParser.parse_starttag.func_code def parse_starttag(self,i): j = self.__parse_starttag(i) if self._type == 'application/xhtml+xml': if j>2 and self.rawdata[j-2:j]=='/>': self.unknown_endtag(self.lasttag) return j def feed(self, data): data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'&lt;!\1', data) data = re.sub(r'<([^<>\s]+?)\s*/>', self._shorttag_replace, data) data = data.replace('&#39;', "'") data = data.replace('&#34;', '"') try: bytes if bytes is str: raise NameError self.encoding = self.encoding + u'_INVALID_PYTHON_3' except NameError: if self.encoding and isinstance(data, unicode): data = data.encode(self.encoding) sgmllib.SGMLParser.feed(self, data) sgmllib.SGMLParser.close(self) def normalize_attrs(self, attrs): if not attrs: return attrs # utility method to be called by descendants attrs = dict([(k.lower(), v) for k, v in attrs]).items() attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] attrs.sort() return attrs def unknown_starttag(self, tag, attrs): # called for each start tag # attrs is a list of (attr, value) tuples # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')] uattrs = [] strattrs='' if attrs: for key, value in attrs: value=value.replace('>','&gt;').replace('<','&lt;').replace('"','&quot;') value = self.bare_ampersand.sub("&amp;", value) # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds if not isinstance(value, unicode): value = value.decode(self.encoding, 'ignore') try: # Currently, in Python 3 the key is already a str, and cannot be decoded again uattrs.append((unicode(key, self.encoding), value)) except TypeError: uattrs.append((key, value)) strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs]) if self.encoding: try: strattrs = strattrs.encode(self.encoding) except (UnicodeEncodeError, LookupError): pass if tag in self.elements_no_end_tag: self.pieces.append('<%s%s />' % (tag, strattrs)) else: self.pieces.append('<%s%s>' % (tag, strattrs)) def unknown_endtag(self, tag): # called for each end tag, e.g. for </pre>, tag will be 'pre' # Reconstruct the original end tag. if tag not in self.elements_no_end_tag: self.pieces.append("</%s>" % tag) def handle_charref(self, ref): # called for each character reference, e.g. for '&#160;', ref will be '160' # Reconstruct the original character reference. if ref.startswith('x'): value = int(ref[1:], 16) else: value = int(ref) if value in _cp1252: self.pieces.append('&#%s;' % hex(ord(_cp1252[value]))[1:]) else: self.pieces.append('&#%s;' % ref) def handle_entityref(self, ref): # called for each entity reference, e.g. for '&copy;', ref will be 'copy' # Reconstruct the original entity reference. if ref in name2codepoint or ref == 'apos': self.pieces.append('&%s;' % ref) else: self.pieces.append('&amp;%s' % ref) def handle_data(self, text): # called for each block of plain text, i.e. outside of any tag and # not containing any character or entity references # Store the original text verbatim. self.pieces.append(text) def handle_comment(self, text): # called for each HTML comment, e.g. <!-- insert Javascript code here --> # Reconstruct the original comment. self.pieces.append('<!--%s-->' % text) def handle_pi(self, text): # called for each processing instruction, e.g. <?instruction> # Reconstruct original processing instruction. self.pieces.append('<?%s>' % text) def handle_decl(self, text): # called for the DOCTYPE, if present, e.g. # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" # "http://www.w3.org/TR/html4/loose.dtd"> # Reconstruct original DOCTYPE self.pieces.append('<!%s>' % text) _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match def _scan_name(self, i, declstartpos): rawdata = self.rawdata n = len(rawdata) if i == n: return None, -1 m = self._new_declname_match(rawdata, i) if m: s = m.group() name = s.strip() if (i + len(s)) == n: return None, -1 # end of buffer return name.lower(), m.end() else: self.handle_data(rawdata) # self.updatepos(declstartpos, i) return None, -1 def convert_charref(self, name): return '&#%s;' % name def convert_entityref(self, name): return '&%s;' % name def output(self): '''Return processed HTML as a single string''' return ''.join([str(p) for p in self.pieces]) def parse_declaration(self, i): try: return sgmllib.SGMLParser.parse_declaration(self, i) except sgmllib.SGMLParseError: # escape the doctype declaration and continue parsing self.handle_data('&lt;') return i+1 class _LooseFeedParser(_FeedParserMixin, _BaseHTMLProcessor): def __init__(self, baseuri, baselang, encoding, entities): sgmllib.SGMLParser.__init__(self) _FeedParserMixin.__init__(self, baseuri, baselang, encoding) _BaseHTMLProcessor.__init__(self, encoding, 'application/xhtml+xml') self.entities=entities def decodeEntities(self, element, data): data = data.replace('&#60;', '&lt;') data = data.replace('&#x3c;', '&lt;') data = data.replace('&#x3C;', '&lt;') data = data.replace('&#62;', '&gt;') data = data.replace('&#x3e;', '&gt;') data = data.replace('&#x3E;', '&gt;') data = data.replace('&#38;', '&amp;') data = data.replace('&#x26;', '&amp;') data = data.replace('&#34;', '&quot;') data = data.replace('&#x22;', '&quot;') data = data.replace('&#39;', '&apos;') data = data.replace('&#x27;', '&apos;') if not self.contentparams.get('type', u'xml').endswith(u'xml'): data = data.replace('&lt;', '<') data = data.replace('&gt;', '>') data = data.replace('&amp;', '&') data = data.replace('&quot;', '"') data = data.replace('&apos;', "'") return data def strattrs(self, attrs): return ''.join([' %s="%s"' % (n,v.replace('"','&quot;')) for n,v in attrs]) class _MicroformatsParser: STRING = 1 DATE = 2 URI = 3 NODE = 4 EMAIL = 5 known_xfn_relationships = set(['contact', 'acquaintance', 'friend', 'met', 'co-worker', 'coworker', 'colleague', 'co-resident', 'coresident', 'neighbor', 'child', 'parent', 'sibling', 'brother', 'sister', 'spouse', 'wife', 'husband', 'kin', 'relative', 'muse', 'crush', 'date', 'sweetheart', 'me']) known_binary_extensions = set(['zip','rar','exe','gz','tar','tgz','tbz2','bz2','z','7z','dmg','img','sit','sitx','hqx','deb','rpm','bz2','jar','rar','iso','bin','msi','mp2','mp3','ogg','ogm','mp4','m4v','m4a','avi','wma','wmv']) def __init__(self, data, baseuri, encoding): self.document = BeautifulSoup.BeautifulSoup(data) self.baseuri = baseuri self.encoding = encoding if isinstance(data, unicode): data = data.encode(encoding) self.tags = [] self.enclosures = [] self.xfn = [] self.vcard = None def vcardEscape(self, s): if isinstance(s, basestring): s = s.replace(',', '\\,').replace(';', '\\;').replace('\n', '\\n') return s def vcardFold(self, s): s = re.sub(';+$', '', s) sFolded = '' iMax = 75 sPrefix = '' while len(s) > iMax: sFolded += sPrefix + s[:iMax] + '\n' s = s[iMax:] sPrefix = ' ' iMax = 74 sFolded += sPrefix + s return sFolded def normalize(self, s): return re.sub(r'\s+', ' ', s).strip() def unique(self, aList): results = [] for element in aList: if element not in results: results.append(element) return results def toISO8601(self, dt): return time.strftime('%Y-%m-%dT%H:%M:%SZ', dt) def getPropertyValue(self, elmRoot, sProperty, iPropertyType=4, bAllowMultiple=0, bAutoEscape=0): all = lambda x: 1 sProperty = sProperty.lower() bFound = 0 bNormalize = 1 propertyMatch = {'class': re.compile(r'\b%s\b' % sProperty)} if bAllowMultiple and (iPropertyType != self.NODE): snapResults = [] containers = elmRoot(['ul', 'ol'], propertyMatch) for container in containers: snapResults.extend(container('li')) bFound = (len(snapResults) != 0) if not bFound: snapResults = elmRoot(all, propertyMatch) bFound = (len(snapResults) != 0) if (not bFound) and (sProperty == 'value'): snapResults = elmRoot('pre') bFound = (len(snapResults) != 0) bNormalize = not bFound if not bFound: snapResults = [elmRoot] bFound = (len(snapResults) != 0) arFilter = [] if sProperty == 'vcard': snapFilter = elmRoot(all, propertyMatch) for node in snapFilter: if node.findParent(all, propertyMatch): arFilter.append(node) arResults = [] for node in snapResults: if node not in arFilter: arResults.append(node) bFound = (len(arResults) != 0) if not bFound: if bAllowMultiple: return [] elif iPropertyType == self.STRING: return '' elif iPropertyType == self.DATE: return None elif iPropertyType == self.URI: return '' elif iPropertyType == self.NODE: return None else: return None arValues = [] for elmResult in arResults: sValue = None if iPropertyType == self.NODE: if bAllowMultiple: arValues.append(elmResult) continue else: return elmResult sNodeName = elmResult.name.lower() if (iPropertyType == self.EMAIL) and (sNodeName == 'a'): sValue = (elmResult.get('href') or '').split('mailto:').pop().split('?')[0] if sValue: sValue = bNormalize and self.normalize(sValue) or sValue.strip() if (not sValue) and (sNodeName == 'abbr'): sValue = elmResult.get('title') if sValue: sValue = bNormalize and self.normalize(sValue) or sValue.strip() if (not sValue) and (iPropertyType == self.URI): if sNodeName == 'a': sValue = elmResult.get('href') elif sNodeName == 'img': sValue = elmResult.get('src') elif sNodeName == 'object': sValue = elmResult.get('data') if sValue: sValue = bNormalize and self.normalize(sValue) or sValue.strip() if (not sValue) and (sNodeName == 'img'): sValue = elmResult.get('alt') if sValue: sValue = bNormalize and self.normalize(sValue) or sValue.strip() if not sValue: sValue = elmResult.renderContents() sValue = re.sub(r'<\S[^>]*>', '', sValue) sValue = sValue.replace('\r\n', '\n') sValue = sValue.replace('\r', '\n') if sValue: sValue = bNormalize and self.normalize(sValue) or sValue.strip() if not sValue: continue if iPropertyType == self.DATE: sValue = _parse_date_iso8601(sValue) if bAllowMultiple: arValues.append(bAutoEscape and self.vcardEscape(sValue) or sValue) else: return bAutoEscape and self.vcardEscape(sValue) or sValue return arValues def findVCards(self, elmRoot, bAgentParsing=0): sVCards = '' if not bAgentParsing: arCards = self.getPropertyValue(elmRoot, 'vcard', bAllowMultiple=1) else: arCards = [elmRoot] for elmCard in arCards: arLines = [] def processSingleString(sProperty): sValue = self.getPropertyValue(elmCard, sProperty, self.STRING, bAutoEscape=1).decode(self.encoding) if sValue: arLines.append(self.vcardFold(sProperty.upper() + ':' + sValue)) return sValue or u'' def processSingleURI(sProperty): sValue = self.getPropertyValue(elmCard, sProperty, self.URI) if sValue: sContentType = '' sEncoding = '' sValueKey = '' if sValue.startswith('data:'): sEncoding = ';ENCODING=b' sContentType = sValue.split(';')[0].split('/').pop() sValue = sValue.split(',', 1).pop() else: elmValue = self.getPropertyValue(elmCard, sProperty) if elmValue: if sProperty != 'url': sValueKey = ';VALUE=uri' sContentType = elmValue.get('type', '').strip().split('/').pop().strip() sContentType = sContentType.upper() if sContentType == 'OCTET-STREAM': sContentType = '' if sContentType: sContentType = ';TYPE=' + sContentType.upper() arLines.append(self.vcardFold(sProperty.upper() + sEncoding + sContentType + sValueKey + ':' + sValue)) def processTypeValue(sProperty, arDefaultType, arForceType=None): arResults = self.getPropertyValue(elmCard, sProperty, bAllowMultiple=1) for elmResult in arResults: arType = self.getPropertyValue(elmResult, 'type', self.STRING, 1, 1) if arForceType: arType = self.unique(arForceType + arType) if not arType: arType = arDefaultType sValue = self.getPropertyValue(elmResult, 'value', self.EMAIL, 0) if sValue: arLines.append(self.vcardFold(sProperty.upper() + ';TYPE=' + ','.join(arType) + ':' + sValue)) # AGENT # must do this before all other properties because it is destructive # (removes nested class="vcard" nodes so they don't interfere with # this vcard's other properties) arAgent = self.getPropertyValue(elmCard, 'agent', bAllowMultiple=1) for elmAgent in arAgent: if re.compile(r'\bvcard\b').search(elmAgent.get('class')): sAgentValue = self.findVCards(elmAgent, 1) + '\n' sAgentValue = sAgentValue.replace('\n', '\\n') sAgentValue = sAgentValue.replace(';', '\\;') if sAgentValue: arLines.append(self.vcardFold('AGENT:' + sAgentValue)) # Completely remove the agent element from the parse tree elmAgent.extract() else: sAgentValue = self.getPropertyValue(elmAgent, 'value', self.URI, bAutoEscape=1); if sAgentValue: arLines.append(self.vcardFold('AGENT;VALUE=uri:' + sAgentValue)) # FN (full name) sFN = processSingleString('fn') # N (name) elmName = self.getPropertyValue(elmCard, 'n') if elmName: sFamilyName = self.getPropertyValue(elmName, 'family-name', self.STRING, bAutoEscape=1) sGivenName = self.getPropertyValue(elmName, 'given-name', self.STRING, bAutoEscape=1) arAdditionalNames = self.getPropertyValue(elmName, 'additional-name', self.STRING, 1, 1) + self.getPropertyValue(elmName, 'additional-names', self.STRING, 1, 1) arHonorificPrefixes = self.getPropertyValue(elmName, 'honorific-prefix', self.STRING, 1, 1) + self.getPropertyValue(elmName, 'honorific-prefixes', self.STRING, 1, 1) arHonorificSuffixes = self.getPropertyValue(elmName, 'honorific-suffix', self.STRING, 1, 1) + self.getPropertyValue(elmName, 'honorific-suffixes', self.STRING, 1, 1) arLines.append(self.vcardFold('N:' + sFamilyName + ';' + sGivenName + ';' + ','.join(arAdditionalNames) + ';' + ','.join(arHonorificPrefixes) + ';' + ','.join(arHonorificSuffixes))) elif sFN: # implied "N" optimization # http://microformats.org/wiki/hcard#Implied_.22N.22_Optimization arNames = self.normalize(sFN).split() if len(arNames) == 2: bFamilyNameFirst = (arNames[0].endswith(',') or len(arNames[1]) == 1 or ((len(arNames[1]) == 2) and (arNames[1].endswith('.')))) if bFamilyNameFirst: arLines.append(self.vcardFold('N:' + arNames[0] + ';' + arNames[1])) else: arLines.append(self.vcardFold('N:' + arNames[1] + ';' + arNames[0])) # SORT-STRING sSortString = self.getPropertyValue(elmCard, 'sort-string', self.STRING, bAutoEscape=1) if sSortString: arLines.append(self.vcardFold('SORT-STRING:' + sSortString)) # NICKNAME arNickname = self.getPropertyValue(elmCard, 'nickname', self.STRING, 1, 1) if arNickname: arLines.append(self.vcardFold('NICKNAME:' + ','.join(arNickname))) # PHOTO processSingleURI('photo') # BDAY dtBday = self.getPropertyValue(elmCard, 'bday', self.DATE) if dtBday: arLines.append(self.vcardFold('BDAY:' + self.toISO8601(dtBday))) # ADR (address) arAdr = self.getPropertyValue(elmCard, 'adr', bAllowMultiple=1) for elmAdr in arAdr: arType = self.getPropertyValue(elmAdr, 'type', self.STRING, 1, 1) if not arType: arType = ['intl','postal','parcel','work'] # default adr types, see RFC 2426 section 3.2.1 sPostOfficeBox = self.getPropertyValue(elmAdr, 'post-office-box', self.STRING, 0, 1) sExtendedAddress = self.getPropertyValue(elmAdr, 'extended-address', self.STRING, 0, 1) sStreetAddress = self.getPropertyValue(elmAdr, 'street-address', self.STRING, 0, 1) sLocality = self.getPropertyValue(elmAdr, 'locality', self.STRING, 0, 1) sRegion = self.getPropertyValue(elmAdr, 'region', self.STRING, 0, 1) sPostalCode = self.getPropertyValue(elmAdr, 'postal-code', self.STRING, 0, 1) sCountryName = self.getPropertyValue(elmAdr, 'country-name', self.STRING, 0, 1) arLines.append(self.vcardFold('ADR;TYPE=' + ','.join(arType) + ':' + sPostOfficeBox + ';' + sExtendedAddress + ';' + sStreetAddress + ';' + sLocality + ';' + sRegion + ';' + sPostalCode + ';' + sCountryName)) # LABEL processTypeValue('label', ['intl','postal','parcel','work']) # TEL (phone number) processTypeValue('tel', ['voice']) # EMAIL processTypeValue('email', ['internet'], ['internet']) # MAILER processSingleString('mailer') # TZ (timezone) processSingleString('tz') # GEO (geographical information) elmGeo = self.getPropertyValue(elmCard, 'geo') if elmGeo: sLatitude = self.getPropertyValue(elmGeo, 'latitude', self.STRING, 0, 1) sLongitude = self.getPropertyValue(elmGeo, 'longitude', self.STRING, 0, 1) arLines.append(self.vcardFold('GEO:' + sLatitude + ';' + sLongitude)) # TITLE processSingleString('title') # ROLE processSingleString('role') # LOGO processSingleURI('logo') # ORG (organization) elmOrg = self.getPropertyValue(elmCard, 'org') if elmOrg: sOrganizationName = self.getPropertyValue(elmOrg, 'organization-name', self.STRING, 0, 1) if not sOrganizationName: # implied "organization-name" optimization # http://microformats.org/wiki/hcard#Implied_.22organization-name.22_Optimization sOrganizationName = self.getPropertyValue(elmCard, 'org', self.STRING, 0, 1) if sOrganizationName: arLines.append(self.vcardFold('ORG:' + sOrganizationName)) else: arOrganizationUnit = self.getPropertyValue(elmOrg, 'organization-unit', self.STRING, 1, 1) arLines.append(self.vcardFold('ORG:' + sOrganizationName + ';' + ';'.join(arOrganizationUnit))) # CATEGORY arCategory = self.getPropertyValue(elmCard, 'category', self.STRING, 1, 1) + self.getPropertyValue(elmCard, 'categories', self.STRING, 1, 1) if arCategory: arLines.append(self.vcardFold('CATEGORIES:' + ','.join(arCategory))) # NOTE processSingleString('note') # REV processSingleString('rev') # SOUND processSingleURI('sound') # UID processSingleString('uid') # URL processSingleURI('url') # CLASS processSingleString('class') # KEY processSingleURI('key') if arLines: arLines = [u'BEGIN:vCard',u'VERSION:3.0'] + arLines + [u'END:vCard'] # XXX - this is super ugly; properly fix this with issue 148 for i, s in enumerate(arLines): if not isinstance(s, unicode): arLines[i] = s.decode('utf-8', 'ignore') sVCards += u'\n'.join(arLines) + u'\n' return sVCards.strip() def isProbablyDownloadable(self, elm): attrsD = elm.attrMap if 'href' not in attrsD: return 0 linktype = attrsD.get('type', '').strip() if linktype.startswith('audio/') or \ linktype.startswith('video/') or \ (linktype.startswith('application/') and not linktype.endswith('xml')): return 1 path = urlparse.urlparse(attrsD['href'])[2] if path.find('.') == -1: return 0 fileext = path.split('.').pop().lower() return fileext in self.known_binary_extensions def findTags(self): all = lambda x: 1 for elm in self.document(all, {'rel': re.compile(r'\btag\b')}): href = elm.get('href') if not href: continue urlscheme, domain, path, params, query, fragment = \ urlparse.urlparse(_urljoin(self.baseuri, href)) segments = path.split('/') tag = segments.pop() if not tag: if segments: tag = segments.pop() else: # there are no tags continue tagscheme = urlparse.urlunparse((urlscheme, domain, '/'.join(segments), '', '', '')) if not tagscheme.endswith('/'): tagscheme += '/' self.tags.append(FeedParserDict({"term": tag, "scheme": tagscheme, "label": elm.string or ''})) def findEnclosures(self): all = lambda x: 1 enclosure_match = re.compile(r'\benclosure\b') for elm in self.document(all, {'href': re.compile(r'.+')}): if not enclosure_match.search(elm.get('rel', u'')) and not self.isProbablyDownloadable(elm): continue if elm.attrMap not in self.enclosures: self.enclosures.append(elm.attrMap) if elm.string and not elm.get('title'): self.enclosures[-1]['title'] = elm.string def findXFN(self): all = lambda x: 1 for elm in self.document(all, {'rel': re.compile('.+'), 'href': re.compile('.+')}): rels = elm.get('rel', u'').split() xfn_rels = [r for r in rels if r in self.known_xfn_relationships] if xfn_rels: self.xfn.append({"relationships": xfn_rels, "href": elm.get('href', ''), "name": elm.string}) def _parseMicroformats(htmlSource, baseURI, encoding): if not BeautifulSoup: return try: p = _MicroformatsParser(htmlSource, baseURI, encoding) except UnicodeEncodeError: # sgmllib throws this exception when performing lookups of tags # with non-ASCII characters in them. return p.vcard = p.findVCards(p.document) p.findTags() p.findEnclosures() p.findXFN() return {"tags": p.tags, "enclosures": p.enclosures, "xfn": p.xfn, "vcard": p.vcard} class _RelativeURIResolver(_BaseHTMLProcessor): relative_uris = set([('a', 'href'), ('applet', 'codebase'), ('area', 'href'), ('blockquote', 'cite'), ('body', 'background'), ('del', 'cite'), ('form', 'action'), ('frame', 'longdesc'), ('frame', 'src'), ('iframe', 'longdesc'), ('iframe', 'src'), ('head', 'profile'), ('img', 'longdesc'), ('img', 'src'), ('img', 'usemap'), ('input', 'src'), ('input', 'usemap'), ('ins', 'cite'), ('link', 'href'), ('object', 'classid'), ('object', 'codebase'), ('object', 'data'), ('object', 'usemap'), ('q', 'cite'), ('script', 'src')]) def __init__(self, baseuri, encoding, _type): _BaseHTMLProcessor.__init__(self, encoding, _type) self.baseuri = baseuri def resolveURI(self, uri): return _makeSafeAbsoluteURI(self.baseuri, uri.strip()) def unknown_starttag(self, tag, attrs): attrs = self.normalize_attrs(attrs) attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs] _BaseHTMLProcessor.unknown_starttag(self, tag, attrs) def _resolveRelativeURIs(htmlSource, baseURI, encoding, _type): if not _SGML_AVAILABLE: return htmlSource p = _RelativeURIResolver(baseURI, encoding, _type) p.feed(htmlSource) return p.output() def _makeSafeAbsoluteURI(base, rel=None): # bail if ACCEPTABLE_URI_SCHEMES is empty if not ACCEPTABLE_URI_SCHEMES: try: return _urljoin(base, rel or u'') except ValueError: return u'' if not base: return rel or u'' if not rel: try: scheme = urlparse.urlparse(base)[0] except ValueError: return u'' if not scheme or scheme in ACCEPTABLE_URI_SCHEMES: return base return u'' try: uri = _urljoin(base, rel) except ValueError: return u'' if uri.strip().split(':', 1)[0] not in ACCEPTABLE_URI_SCHEMES: return u'' return uri class _HTMLSanitizer(_BaseHTMLProcessor): acceptable_elements = set(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset', 'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins', 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter', 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option', 'p', 'pre', 'progress', 'q', 's', 'samp', 'section', 'select', 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video', 'noscript']) acceptable_attributes = set(['abbr', 'accept', 'accept-charset', 'accesskey', 'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis', 'background', 'balance', 'bgcolor', 'bgproperties', 'border', 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding', 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff', 'choff', 'charset', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'compact', 'contenteditable', 'controls', 'coords', 'data', 'datafld', 'datapagesize', 'datasrc', 'datetime', 'default', 'delay', 'dir', 'disabled', 'draggable', 'dynsrc', 'enctype', 'end', 'face', 'for', 'form', 'frame', 'galleryimg', 'gutter', 'headers', 'height', 'hidefocus', 'hidden', 'high', 'href', 'hreflang', 'hspace', 'icon', 'id', 'inputmode', 'ismap', 'keytype', 'label', 'leftspacing', 'lang', 'list', 'longdesc', 'loop', 'loopcount', 'loopend', 'loopstart', 'low', 'lowsrc', 'max', 'maxlength', 'media', 'method', 'min', 'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'open', 'optimum', 'pattern', 'ping', 'point-size', 'prompt', 'pqg', 'radiogroup', 'readonly', 'rel', 'repeat-max', 'repeat-min', 'replace', 'required', 'rev', 'rightspacing', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size', 'span', 'src', 'start', 'step', 'summary', 'suppress', 'tabindex', 'target', 'template', 'title', 'toppadding', 'type', 'unselectable', 'usemap', 'urn', 'valign', 'value', 'variable', 'volume', 'vspace', 'vrml', 'width', 'wrap', 'xml:lang']) unacceptable_elements_with_end_tag = set(['script', 'applet', 'style']) acceptable_css_properties = set(['azimuth', 'background-color', 'border-bottom-color', 'border-collapse', 'border-color', 'border-left-color', 'border-right-color', 'border-top-color', 'clear', 'color', 'cursor', 'direction', 'display', 'elevation', 'float', 'font', 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'overflow', 'pause', 'pause-after', 'pause-before', 'pitch', 'pitch-range', 'richness', 'speak', 'speak-header', 'speak-numeral', 'speak-punctuation', 'speech-rate', 'stress', 'text-align', 'text-decoration', 'text-indent', 'unicode-bidi', 'vertical-align', 'voice-family', 'volume', 'white-space', 'width']) # survey of common keywords found in feeds acceptable_css_keywords = set(['auto', 'aqua', 'black', 'block', 'blue', 'bold', 'both', 'bottom', 'brown', 'center', 'collapse', 'dashed', 'dotted', 'fuchsia', 'gray', 'green', '!important', 'italic', 'left', 'lime', 'maroon', 'medium', 'none', 'navy', 'normal', 'nowrap', 'olive', 'pointer', 'purple', 'red', 'right', 'solid', 'silver', 'teal', 'top', 'transparent', 'underline', 'white', 'yellow']) valid_css_values = re.compile('^(#[0-9a-f]+|rgb\(\d+%?,\d*%?,?\d*%?\)?|' + '\d{0,2}\.?\d{0,2}(cm|em|ex|in|mm|pc|pt|px|%|,|\))?)$') mathml_elements = set(['annotation', 'annotation-xml', 'maction', 'math', 'merror', 'mfenced', 'mfrac', 'mi', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'none', 'semantics']) mathml_attributes = set(['actiontype', 'align', 'columnalign', 'columnalign', 'columnalign', 'close', 'columnlines', 'columnspacing', 'columnspan', 'depth', 'display', 'displaystyle', 'encoding', 'equalcolumns', 'equalrows', 'fence', 'fontstyle', 'fontweight', 'frame', 'height', 'linethickness', 'lspace', 'mathbackground', 'mathcolor', 'mathvariant', 'mathvariant', 'maxsize', 'minsize', 'open', 'other', 'rowalign', 'rowalign', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'scriptlevel', 'selection', 'separator', 'separators', 'stretchy', 'width', 'width', 'xlink:href', 'xlink:show', 'xlink:type', 'xmlns', 'xmlns:xlink']) # svgtiny - foreignObject + linearGradient + radialGradient + stop svg_elements = set(['a', 'animate', 'animateColor', 'animateMotion', 'animateTransform', 'circle', 'defs', 'desc', 'ellipse', 'foreignObject', 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern', 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph', 'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use']) # svgtiny + class + opacity + offset + xmlns + xmlns:xlink svg_attributes = set(['accent-height', 'accumulate', 'additive', 'alphabetic', 'arabic-form', 'ascent', 'attributeName', 'attributeType', 'baseProfile', 'bbox', 'begin', 'by', 'calcMode', 'cap-height', 'class', 'color', 'color-rendering', 'content', 'cx', 'cy', 'd', 'dx', 'dy', 'descent', 'display', 'dur', 'end', 'fill', 'fill-opacity', 'fill-rule', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'from', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'gradientUnits', 'hanging', 'height', 'horiz-adv-x', 'horiz-origin-x', 'id', 'ideographic', 'k', 'keyPoints', 'keySplines', 'keyTimes', 'lang', 'mathematical', 'marker-end', 'marker-mid', 'marker-start', 'markerHeight', 'markerUnits', 'markerWidth', 'max', 'min', 'name', 'offset', 'opacity', 'orient', 'origin', 'overline-position', 'overline-thickness', 'panose-1', 'path', 'pathLength', 'points', 'preserveAspectRatio', 'r', 'refX', 'refY', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'rotate', 'rx', 'ry', 'slope', 'stemh', 'stemv', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'systemLanguage', 'target', 'text-anchor', 'to', 'transform', 'type', 'u1', 'u2', 'underline-position', 'underline-thickness', 'unicode', 'unicode-range', 'units-per-em', 'values', 'version', 'viewBox', 'visibility', 'width', 'widths', 'x', 'x-height', 'x1', 'x2', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'xmlns', 'xmlns:xlink', 'y', 'y1', 'y2', 'zoomAndPan']) svg_attr_map = None svg_elem_map = None acceptable_svg_properties = set([ 'fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin', 'stroke-opacity']) def reset(self): _BaseHTMLProcessor.reset(self) self.unacceptablestack = 0 self.mathmlOK = 0 self.svgOK = 0 def unknown_starttag(self, tag, attrs): acceptable_attributes = self.acceptable_attributes keymap = {} if not tag in self.acceptable_elements or self.svgOK: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack += 1 # add implicit namespaces to html5 inline svg/mathml if self._type.endswith('html'): if not dict(attrs).get('xmlns'): if tag=='svg': attrs.append( ('xmlns','http://www.w3.org/2000/svg') ) if tag=='math': attrs.append( ('xmlns','http://www.w3.org/1998/Math/MathML') ) # not otherwise acceptable, perhaps it is MathML or SVG? if tag=='math' and ('xmlns','http://www.w3.org/1998/Math/MathML') in attrs: self.mathmlOK += 1 if tag=='svg' and ('xmlns','http://www.w3.org/2000/svg') in attrs: self.svgOK += 1 # chose acceptable attributes based on tag class, else bail if self.mathmlOK and tag in self.mathml_elements: acceptable_attributes = self.mathml_attributes elif self.svgOK and tag in self.svg_elements: # for most vocabularies, lowercasing is a good idea. Many # svg elements, however, are camel case if not self.svg_attr_map: lower=[attr.lower() for attr in self.svg_attributes] mix=[a for a in self.svg_attributes if a not in lower] self.svg_attributes = lower self.svg_attr_map = dict([(a.lower(),a) for a in mix]) lower=[attr.lower() for attr in self.svg_elements] mix=[a for a in self.svg_elements if a not in lower] self.svg_elements = lower self.svg_elem_map = dict([(a.lower(),a) for a in mix]) acceptable_attributes = self.svg_attributes tag = self.svg_elem_map.get(tag,tag) keymap = self.svg_attr_map elif not tag in self.acceptable_elements: return # declare xlink namespace, if needed if self.mathmlOK or self.svgOK: if filter(lambda (n,v): n.startswith('xlink:'),attrs): if not ('xmlns:xlink','http://www.w3.org/1999/xlink') in attrs: attrs.append(('xmlns:xlink','http://www.w3.org/1999/xlink')) clean_attrs = [] for key, value in self.normalize_attrs(attrs): if key in acceptable_attributes: key=keymap.get(key,key) # make sure the uri uses an acceptable uri scheme if key == u'href': value = _makeSafeAbsoluteURI(value) clean_attrs.append((key,value)) elif key=='style': clean_value = self.sanitize_style(value) if clean_value: clean_attrs.append((key,clean_value)) _BaseHTMLProcessor.unknown_starttag(self, tag, clean_attrs) def unknown_endtag(self, tag): if not tag in self.acceptable_elements: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack -= 1 if self.mathmlOK and tag in self.mathml_elements: if tag == 'math' and self.mathmlOK: self.mathmlOK -= 1 elif self.svgOK and tag in self.svg_elements: tag = self.svg_elem_map.get(tag,tag) if tag == 'svg' and self.svgOK: self.svgOK -= 1 else: return _BaseHTMLProcessor.unknown_endtag(self, tag) def handle_pi(self, text): pass def handle_decl(self, text): pass def handle_data(self, text): if not self.unacceptablestack: _BaseHTMLProcessor.handle_data(self, text) def sanitize_style(self, style): # disallow urls style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style) # gauntlet if not re.match("""^([:,;#%.\sa-zA-Z0-9!]|\w-\w|'[\s\w]+'|"[\s\w]+"|\([\d,\s]+\))*$""", style): return '' # This replaced a regexp that used re.match and was prone to pathological back-tracking. if re.sub("\s*[-\w]+\s*:\s*[^:;]*;?", '', style).strip(): return '' clean = [] for prop,value in re.findall("([-\w]+)\s*:\s*([^:;]*)",style): if not value: continue if prop.lower() in self.acceptable_css_properties: clean.append(prop + ': ' + value + ';') elif prop.split('-')[0].lower() in ['background','border','margin','padding']: for keyword in value.split(): if not keyword in self.acceptable_css_keywords and \ not self.valid_css_values.match(keyword): break else: clean.append(prop + ': ' + value + ';') elif self.svgOK and prop.lower() in self.acceptable_svg_properties: clean.append(prop + ': ' + value + ';') return ' '.join(clean) def parse_comment(self, i, report=1): ret = _BaseHTMLProcessor.parse_comment(self, i, report) if ret >= 0: return ret # if ret == -1, this may be a malicious attempt to circumvent # sanitization, or a page-destroying unclosed comment match = re.compile(r'--[^>]*>').search(self.rawdata, i+4) if match: return match.end() # unclosed comment; deliberately fail to handle_data() return len(self.rawdata) def _sanitizeHTML(htmlSource, encoding, _type): if not _SGML_AVAILABLE: return htmlSource p = _HTMLSanitizer(encoding, _type) htmlSource = htmlSource.replace('<![CDATA[', '&lt;![CDATA[') p.feed(htmlSource) data = p.output() if TIDY_MARKUP: # loop through list of preferred Tidy interfaces looking for one that's installed, # then set up a common _tidy function to wrap the interface-specific API. _tidy = None for tidy_interface in PREFERRED_TIDY_INTERFACES: try: if tidy_interface == "uTidy": from tidy import parseString as _utidy def _tidy(data, **kwargs): return str(_utidy(data, **kwargs)) break elif tidy_interface == "mxTidy": from mx.Tidy import Tidy as _mxtidy def _tidy(data, **kwargs): nerrors, nwarnings, data, errordata = _mxtidy.tidy(data, **kwargs) return data break except: pass if _tidy: utf8 = isinstance(data, unicode) if utf8: data = data.encode('utf-8') data = _tidy(data, output_xhtml=1, numeric_entities=1, wrap=0, char_encoding="utf8") if utf8: data = unicode(data, 'utf-8') if data.count('<body'): data = data.split('<body', 1)[1] if data.count('>'): data = data.split('>', 1)[1] if data.count('</body'): data = data.split('</body', 1)[0] data = data.strip().replace('\r\n', '\n') return data class _FeedURLHandler(urllib2.HTTPDigestAuthHandler, urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler): def http_error_default(self, req, fp, code, msg, headers): # The default implementation just raises HTTPError. # Forget that. fp.status = code return fp def http_error_301(self, req, fp, code, msg, hdrs): result = urllib2.HTTPRedirectHandler.http_error_301(self, req, fp, code, msg, hdrs) result.status = code result.newurl = result.geturl() return result # The default implementations in urllib2.HTTPRedirectHandler # are identical, so hardcoding a http_error_301 call above # won't affect anything http_error_300 = http_error_301 http_error_302 = http_error_301 http_error_303 = http_error_301 http_error_307 = http_error_301 def http_error_401(self, req, fp, code, msg, headers): # Check if # - server requires digest auth, AND # - we tried (unsuccessfully) with basic auth, AND # If all conditions hold, parse authentication information # out of the Authorization header we sent the first time # (for the username and password) and the WWW-Authenticate # header the server sent back (for the realm) and retry # the request with the appropriate digest auth headers instead. # This evil genius hack has been brought to you by Aaron Swartz. host = urlparse.urlparse(req.get_full_url())[1] if base64 is None or 'Authorization' not in req.headers \ or 'WWW-Authenticate' not in headers: return self.http_error_default(req, fp, code, msg, headers) auth = _base64decode(req.headers['Authorization'].split(' ')[1]) user, passw = auth.split(':') realm = re.findall('realm="([^"]*)"', headers['WWW-Authenticate'])[0] self.add_password(realm, host, user, passw) retry = self.http_error_auth_reqed('www-authenticate', host, req, headers) self.reset_retry_count() return retry def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, request_headers): """URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object is guaranteed to have all the basic stdio read methods (read, readline, readlines). Just .close() the object when you're done with it. If the etag argument is supplied, it will be used as the value of an If-None-Match request header. If the modified argument is supplied, it can be a tuple of 9 integers (as returned by gmtime() in the standard Python time module) or a date string in any format supported by feedparser. Regardless, it MUST be in GMT (Greenwich Mean Time). It will be reformatted into an RFC 1123-compliant date and used as the value of an If-Modified-Since request header. If the agent argument is supplied, it will be used as the value of a User-Agent request header. If the referrer argument is supplied, it will be used as the value of a Referer[sic] request header. If handlers is supplied, it is a list of handlers used to build a urllib2 opener. if request_headers is supplied it is a dictionary of HTTP request headers that will override the values generated by FeedParser. """ if hasattr(url_file_stream_or_string, 'read'): return url_file_stream_or_string if isinstance(url_file_stream_or_string, basestring) \ and urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp', 'file', 'feed'): # Deal with the feed URI scheme if url_file_stream_or_string.startswith('feed:http'): url_file_stream_or_string = url_file_stream_or_string[5:] elif url_file_stream_or_string.startswith('feed:'): url_file_stream_or_string = 'http:' + url_file_stream_or_string[5:] if not agent: agent = USER_AGENT # test for inline user:password for basic auth auth = None if base64: urltype, rest = urllib.splittype(url_file_stream_or_string) realhost, rest = urllib.splithost(rest) if realhost: user_passwd, realhost = urllib.splituser(realhost) if user_passwd: url_file_stream_or_string = '%s://%s%s' % (urltype, realhost, rest) auth = base64.standard_b64encode(user_passwd).strip() # iri support if isinstance(url_file_stream_or_string, unicode): url_file_stream_or_string = _convert_to_idn(url_file_stream_or_string) # try to open with urllib2 (to use optional headers) request = _build_urllib2_request(url_file_stream_or_string, agent, etag, modified, referrer, auth, request_headers) opener = urllib2.build_opener(*tuple(handlers + [_FeedURLHandler()])) opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent try: return opener.open(request) finally: opener.close() # JohnD # try to open with native open function (if url_file_stream_or_string is a filename) try: return open(url_file_stream_or_string, 'rb') except (IOError, UnicodeEncodeError, TypeError): # if url_file_stream_or_string is a unicode object that # cannot be converted to the encoding returned by # sys.getfilesystemencoding(), a UnicodeEncodeError # will be thrown # If url_file_stream_or_string is a string that contains NULL # (such as an XML document encoded in UTF-32), TypeError will # be thrown. pass # treat url_file_stream_or_string as string if isinstance(url_file_stream_or_string, unicode): return _StringIO(url_file_stream_or_string.encode('utf-8')) return _StringIO(url_file_stream_or_string) def _convert_to_idn(url): """Convert a URL to IDN notation""" # this function should only be called with a unicode string # strategy: if the host cannot be encoded in ascii, then # it'll be necessary to encode it in idn form parts = list(urlparse.urlsplit(url)) try: parts[1].encode('ascii') except UnicodeEncodeError: # the url needs to be converted to idn notation host = parts[1].rsplit(':', 1) newhost = [] port = u'' if len(host) == 2: port = host.pop() for h in host[0].split('.'): newhost.append(h.encode('idna').decode('utf-8')) parts[1] = '.'.join(newhost) if port: parts[1] += ':' + port return urlparse.urlunsplit(parts) else: return url def _build_urllib2_request(url, agent, etag, modified, referrer, auth, request_headers): request = urllib2.Request(url) request.add_header('User-Agent', agent) if etag: request.add_header('If-None-Match', etag) if isinstance(modified, basestring): modified = _parse_date(modified) elif isinstance(modified, datetime.datetime): modified = modified.utctimetuple() if modified: # format into an RFC 1123-compliant timestamp. We can't use # time.strftime() since the %a and %b directives can be affected # by the current locale, but RFC 2616 states that dates must be # in English. short_weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] request.add_header('If-Modified-Since', '%s, %02d %s %04d %02d:%02d:%02d GMT' % (short_weekdays[modified[6]], modified[2], months[modified[1] - 1], modified[0], modified[3], modified[4], modified[5])) if referrer: request.add_header('Referer', referrer) if gzip and zlib: request.add_header('Accept-encoding', 'gzip, deflate') elif gzip: request.add_header('Accept-encoding', 'gzip') elif zlib: request.add_header('Accept-encoding', 'deflate') else: request.add_header('Accept-encoding', '') if auth: request.add_header('Authorization', 'Basic %s' % auth) if ACCEPT_HEADER: request.add_header('Accept', ACCEPT_HEADER) # use this for whatever -- cookies, special headers, etc # [('Cookie','Something'),('x-special-header','Another Value')] for header_name, header_value in request_headers.items(): request.add_header(header_name, header_value) request.add_header('A-IM', 'feed') # RFC 3229 support return request _date_handlers = [] def registerDateHandler(func): '''Register a date handler function (takes string, returns 9-tuple date in GMT)''' _date_handlers.insert(0, func) # ISO-8601 date parsing routines written by Fazal Majid. # The ISO 8601 standard is very convoluted and irregular - a full ISO 8601 # parser is beyond the scope of feedparser and would be a worthwhile addition # to the Python library. # A single regular expression cannot parse ISO 8601 date formats into groups # as the standard is highly irregular (for instance is 030104 2003-01-04 or # 0301-04-01), so we use templates instead. # Please note the order in templates is significant because we need a # greedy match. _iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-0MM?-?DD', 'YYYY-MM', 'YYYY-?OOO', 'YY-?MM-?DD', 'YY-?OOO', 'YYYY', '-YY-?MM', '-OOO', '-YY', '--MM-?DD', '--MM', '---DD', 'CC', ''] _iso8601_re = [ tmpl.replace( 'YYYY', r'(?P<year>\d{4})').replace( 'YY', r'(?P<year>\d\d)').replace( 'MM', r'(?P<month>[01]\d)').replace( 'DD', r'(?P<day>[0123]\d)').replace( 'OOO', r'(?P<ordinal>[0123]\d\d)').replace( 'CC', r'(?P<century>\d\d$)') + r'(T?(?P<hour>\d{2}):(?P<minute>\d{2})' + r'(:(?P<second>\d{2}))?' + r'(\.(?P<fracsecond>\d+))?' + r'(?P<tz>[+-](?P<tzhour>\d{2})(:(?P<tzmin>\d{2}))?|Z)?)?' for tmpl in _iso8601_tmpl] try: del tmpl except NameError: pass _iso8601_matches = [re.compile(regex).match for regex in _iso8601_re] try: del regex except NameError: pass def _parse_date_iso8601(dateString): '''Parse a variety of ISO-8601-compatible formats like 20040105''' m = None for _iso8601_match in _iso8601_matches: m = _iso8601_match(dateString) if m: break if not m: return if m.span() == (0, 0): return params = m.groupdict() ordinal = params.get('ordinal', 0) if ordinal: ordinal = int(ordinal) else: ordinal = 0 year = params.get('year', '--') if not year or year == '--': year = time.gmtime()[0] elif len(year) == 2: # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993 year = 100 * int(time.gmtime()[0] / 100) + int(year) else: year = int(year) month = params.get('month', '-') if not month or month == '-': # ordinals are NOT normalized by mktime, we simulate them # by setting month=1, day=ordinal if ordinal: month = 1 else: month = time.gmtime()[1] month = int(month) day = params.get('day', 0) if not day: # see above if ordinal: day = ordinal elif params.get('century', 0) or \ params.get('year', 0) or params.get('month', 0): day = 1 else: day = time.gmtime()[2] else: day = int(day) # special case of the century - is the first year of the 21st century # 2000 or 2001 ? The debate goes on... if 'century' in params: year = (int(params['century']) - 1) * 100 + 1 # in ISO 8601 most fields are optional for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']: if not params.get(field, None): params[field] = 0 hour = int(params.get('hour', 0)) minute = int(params.get('minute', 0)) second = int(float(params.get('second', 0))) # weekday is normalized by mktime(), we can ignore it weekday = 0 daylight_savings_flag = -1 tm = [year, month, day, hour, minute, second, weekday, ordinal, daylight_savings_flag] # ISO 8601 time zone adjustments tz = params.get('tz') if tz and tz != 'Z': if tz[0] == '-': tm[3] += int(params.get('tzhour', 0)) tm[4] += int(params.get('tzmin', 0)) elif tz[0] == '+': tm[3] -= int(params.get('tzhour', 0)) tm[4] -= int(params.get('tzmin', 0)) else: return None # Python's time.mktime() is a wrapper around the ANSI C mktime(3c) # which is guaranteed to normalize d/m/y/h/m/s. # Many implementations have bugs, but we'll pretend they don't. return time.localtime(time.mktime(tuple(tm))) registerDateHandler(_parse_date_iso8601) # 8-bit date handling routines written by ytrewq1. _korean_year = u'\ub144' # b3e2 in euc-kr _korean_month = u'\uc6d4' # bff9 in euc-kr _korean_day = u'\uc77c' # c0cf in euc-kr _korean_am = u'\uc624\uc804' # bfc0 c0fc in euc-kr _korean_pm = u'\uc624\ud6c4' # bfc0 c8c4 in euc-kr _korean_onblog_date_re = \ re.compile('(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % \ (_korean_year, _korean_month, _korean_day)) _korean_nate_date_re = \ re.compile(u'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % \ (_korean_am, _korean_pm)) def _parse_date_onblog(dateString): '''Parse a string according to the OnBlog 8-bit date format''' m = _korean_onblog_date_re.match(dateString) if not m: return w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \ {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\ 'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\ 'zonediff': '+09:00'} return _parse_date_w3dtf(w3dtfdate) registerDateHandler(_parse_date_onblog) def _parse_date_nate(dateString): '''Parse a string according to the Nate 8-bit date format''' m = _korean_nate_date_re.match(dateString) if not m: return hour = int(m.group(5)) ampm = m.group(4) if (ampm == _korean_pm): hour += 12 hour = str(hour) if len(hour) == 1: hour = '0' + hour w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \ {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\ 'hour': hour, 'minute': m.group(6), 'second': m.group(7),\ 'zonediff': '+09:00'} return _parse_date_w3dtf(w3dtfdate) registerDateHandler(_parse_date_nate) # Unicode strings for Greek date strings _greek_months = \ { \ u'\u0399\u03b1\u03bd': u'Jan', # c9e1ed in iso-8859-7 u'\u03a6\u03b5\u03b2': u'Feb', # d6e5e2 in iso-8859-7 u'\u039c\u03ac\u03ce': u'Mar', # ccdcfe in iso-8859-7 u'\u039c\u03b1\u03ce': u'Mar', # cce1fe in iso-8859-7 u'\u0391\u03c0\u03c1': u'Apr', # c1f0f1 in iso-8859-7 u'\u039c\u03ac\u03b9': u'May', # ccdce9 in iso-8859-7 u'\u039c\u03b1\u03ca': u'May', # cce1fa in iso-8859-7 u'\u039c\u03b1\u03b9': u'May', # cce1e9 in iso-8859-7 u'\u0399\u03bf\u03cd\u03bd': u'Jun', # c9effded in iso-8859-7 u'\u0399\u03bf\u03bd': u'Jun', # c9efed in iso-8859-7 u'\u0399\u03bf\u03cd\u03bb': u'Jul', # c9effdeb in iso-8859-7 u'\u0399\u03bf\u03bb': u'Jul', # c9f9eb in iso-8859-7 u'\u0391\u03cd\u03b3': u'Aug', # c1fde3 in iso-8859-7 u'\u0391\u03c5\u03b3': u'Aug', # c1f5e3 in iso-8859-7 u'\u03a3\u03b5\u03c0': u'Sep', # d3e5f0 in iso-8859-7 u'\u039f\u03ba\u03c4': u'Oct', # cfeaf4 in iso-8859-7 u'\u039d\u03bf\u03ad': u'Nov', # cdefdd in iso-8859-7 u'\u039d\u03bf\u03b5': u'Nov', # cdefe5 in iso-8859-7 u'\u0394\u03b5\u03ba': u'Dec', # c4e5ea in iso-8859-7 } _greek_wdays = \ { \ u'\u039a\u03c5\u03c1': u'Sun', # caf5f1 in iso-8859-7 u'\u0394\u03b5\u03c5': u'Mon', # c4e5f5 in iso-8859-7 u'\u03a4\u03c1\u03b9': u'Tue', # d4f1e9 in iso-8859-7 u'\u03a4\u03b5\u03c4': u'Wed', # d4e5f4 in iso-8859-7 u'\u03a0\u03b5\u03bc': u'Thu', # d0e5ec in iso-8859-7 u'\u03a0\u03b1\u03c1': u'Fri', # d0e1f1 in iso-8859-7 u'\u03a3\u03b1\u03b2': u'Sat', # d3e1e2 in iso-8859-7 } _greek_date_format_re = \ re.compile(u'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)') def _parse_date_greek(dateString): '''Parse a string according to a Greek 8-bit date format.''' m = _greek_date_format_re.match(dateString) if not m: return wday = _greek_wdays[m.group(1)] month = _greek_months[m.group(3)] rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \ {'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4),\ 'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7),\ 'zonediff': m.group(8)} return _parse_date_rfc822(rfc822date) registerDateHandler(_parse_date_greek) # Unicode strings for Hungarian date strings _hungarian_months = \ { \ u'janu\u00e1r': u'01', # e1 in iso-8859-2 u'febru\u00e1ri': u'02', # e1 in iso-8859-2 u'm\u00e1rcius': u'03', # e1 in iso-8859-2 u'\u00e1prilis': u'04', # e1 in iso-8859-2 u'm\u00e1ujus': u'05', # e1 in iso-8859-2 u'j\u00fanius': u'06', # fa in iso-8859-2 u'j\u00falius': u'07', # fa in iso-8859-2 u'augusztus': u'08', u'szeptember': u'09', u'okt\u00f3ber': u'10', # f3 in iso-8859-2 u'november': u'11', u'december': u'12', } _hungarian_date_format_re = \ re.compile(u'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))') def _parse_date_hungarian(dateString): '''Parse a string according to a Hungarian 8-bit date format.''' m = _hungarian_date_format_re.match(dateString) if not m or m.group(2) not in _hungarian_months: return None month = _hungarian_months[m.group(2)] day = m.group(3) if len(day) == 1: day = '0' + day hour = m.group(4) if len(hour) == 1: hour = '0' + hour w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % \ {'year': m.group(1), 'month': month, 'day': day,\ 'hour': hour, 'minute': m.group(5),\ 'zonediff': m.group(6)} return _parse_date_w3dtf(w3dtfdate) registerDateHandler(_parse_date_hungarian) # W3DTF-style date parsing adapted from PyXML xml.utils.iso8601, written by # Drake and licensed under the Python license. Removed all range checking # for month, day, hour, minute, and second, since mktime will normalize # these later # Modified to also support MSSQL-style datetimes as defined at: # http://msdn.microsoft.com/en-us/library/ms186724.aspx # (which basically means allowing a space as a date/time/timezone separator) def _parse_date_w3dtf(dateString): def __extract_date(m): year = int(m.group('year')) if year < 100: year = 100 * int(time.gmtime()[0] / 100) + int(year) if year < 1000: return 0, 0, 0 julian = m.group('julian') if julian: julian = int(julian) month = julian / 30 + 1 day = julian % 30 + 1 jday = None while jday != julian: t = time.mktime((year, month, day, 0, 0, 0, 0, 0, 0)) jday = time.gmtime(t)[-2] diff = abs(jday - julian) if jday > julian: if diff < day: day = day - diff else: month = month - 1 day = 31 elif jday < julian: if day + diff < 28: day = day + diff else: month = month + 1 return year, month, day month = m.group('month') day = 1 if month is None: month = 1 else: month = int(month) day = m.group('day') if day: day = int(day) else: day = 1 return year, month, day def __extract_time(m): if not m: return 0, 0, 0 hours = m.group('hours') if not hours: return 0, 0, 0 hours = int(hours) minutes = int(m.group('minutes')) seconds = m.group('seconds') if seconds: seconds = int(seconds) else: seconds = 0 return hours, minutes, seconds def __extract_tzd(m): '''Return the Time Zone Designator as an offset in seconds from UTC.''' if not m: return 0 tzd = m.group('tzd') if not tzd: return 0 if tzd == 'Z': return 0 hours = int(m.group('tzdhours')) minutes = m.group('tzdminutes') if minutes: minutes = int(minutes) else: minutes = 0 offset = (hours*60 + minutes) * 60 if tzd[0] == '+': return -offset return offset __date_re = ('(?P<year>\d\d\d\d)' '(?:(?P<dsep>-|)' '(?:(?P<month>\d\d)(?:(?P=dsep)(?P<day>\d\d))?' '|(?P<julian>\d\d\d)))?') __tzd_re = ' ?(?P<tzd>[-+](?P<tzdhours>\d\d)(?::?(?P<tzdminutes>\d\d))|Z)?' __time_re = ('(?P<hours>\d\d)(?P<tsep>:|)(?P<minutes>\d\d)' '(?:(?P=tsep)(?P<seconds>\d\d)(?:[.,]\d+)?)?' + __tzd_re) __datetime_re = '%s(?:[T ]%s)?' % (__date_re, __time_re) __datetime_rx = re.compile(__datetime_re) m = __datetime_rx.match(dateString) if (m is None) or (m.group() != dateString): return gmt = __extract_date(m) + __extract_time(m) + (0, 0, 0) if gmt[0] == 0: return return time.gmtime(time.mktime(gmt) + __extract_tzd(m) - time.timezone) registerDateHandler(_parse_date_w3dtf) # Define the strings used by the RFC822 datetime parser _rfc822_months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] _rfc822_daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] # Only the first three letters of the month name matter _rfc822_month = "(?P<month>%s)(?:[a-z]*,?)" % ('|'.join(_rfc822_months)) # The year may be 2 or 4 digits; capture the century if it exists _rfc822_year = "(?P<year>(?:\d{2})?\d{2})" _rfc822_day = "(?P<day> *\d{1,2})" _rfc822_date = "%s %s %s" % (_rfc822_day, _rfc822_month, _rfc822_year) _rfc822_hour = "(?P<hour>\d{2}):(?P<minute>\d{2})(?::(?P<second>\d{2}))?" _rfc822_tz = "(?P<tz>ut|gmt(?:[+-]\d{2}:\d{2})?|[aecmp][sd]?t|[zamny]|[+-]\d{4})" _rfc822_tznames = { 'ut': 0, 'gmt': 0, 'z': 0, 'adt': -3, 'ast': -4, 'at': -4, 'edt': -4, 'est': -5, 'et': -5, 'cdt': -5, 'cst': -6, 'ct': -6, 'mdt': -6, 'mst': -7, 'mt': -7, 'pdt': -7, 'pst': -8, 'pt': -8, 'a': -1, 'n': 1, 'm': -12, 'y': 12, } # The timezone may be prefixed by 'Etc/' _rfc822_time = "%s (?:etc/)?%s" % (_rfc822_hour, _rfc822_tz) _rfc822_dayname = "(?P<dayname>%s)" % ('|'.join(_rfc822_daynames)) _rfc822_match = re.compile( "(?:%s, )?%s(?: %s)?" % (_rfc822_dayname, _rfc822_date, _rfc822_time) ).match def _parse_date_rfc822(dt): """Parse RFC 822 dates and times, with one minor difference: years may be 4DIGIT or 2DIGIT. http://tools.ietf.org/html/rfc822#section-5""" try: m = _rfc822_match(dt.lower()).groupdict(0) except AttributeError: return None # Calculate a date and timestamp for k in ('year', 'day', 'hour', 'minute', 'second'): m[k] = int(m[k]) m['month'] = _rfc822_months.index(m['month']) + 1 # If the year is 2 digits, assume everything in the 90's is the 1990's if m['year'] < 100: m['year'] += (1900, 2000)[m['year'] < 90] stamp = datetime.datetime(*[m[i] for i in ('year', 'month', 'day', 'hour', 'minute', 'second')]) # Use the timezone information to calculate the difference between # the given date and timestamp and Universal Coordinated Time tzhour = 0 tzmin = 0 if m['tz'] and m['tz'].startswith('gmt'): # Handle GMT and GMT+hh:mm timezone syntax (the trailing # timezone info will be handled by the next `if` block) m['tz'] = ''.join(m['tz'][3:].split(':')) or 'gmt' if not m['tz']: pass elif m['tz'].startswith('+'): tzhour = int(m['tz'][1:3]) tzmin = int(m['tz'][3:]) elif m['tz'].startswith('-'): tzhour = int(m['tz'][1:3]) * -1 tzmin = int(m['tz'][3:]) * -1 else: tzhour = _rfc822_tznames[m['tz']] delta = datetime.timedelta(0, 0, 0, 0, tzmin, tzhour) # Return the date and timestamp in UTC return (stamp - delta).utctimetuple() registerDateHandler(_parse_date_rfc822) def _parse_date_asctime(dt): """Parse asctime-style dates""" dayname, month, day, remainder = dt.split(None, 3) # Convert month and day into zero-padded integers month = '%02i ' % (_rfc822_months.index(month.lower()) + 1) day = '%02i ' % (int(day),) dt = month + day + remainder return time.strptime(dt, '%m %d %H:%M:%S %Y')[:-1] + (0, ) registerDateHandler(_parse_date_asctime) def _parse_date_perforce(aDateString): """parse a date in yyyy/mm/dd hh:mm:ss TTT format""" # Fri, 2006/09/15 08:19:53 EDT _my_date_pattern = re.compile( \ r'(\w{,3}), (\d{,4})/(\d{,2})/(\d{2}) (\d{,2}):(\d{2}):(\d{2}) (\w{,3})') m = _my_date_pattern.search(aDateString) if m is None: return None dow, year, month, day, hour, minute, second, tz = m.groups() months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] dateString = "%s, %s %s %s %s:%s:%s %s" % (dow, day, months[int(month) - 1], year, hour, minute, second, tz) tm = rfc822.parsedate_tz(dateString) if tm: return time.gmtime(rfc822.mktime_tz(tm)) registerDateHandler(_parse_date_perforce) def _parse_date(dateString): '''Parses a variety of date formats into a 9-tuple in GMT''' if not dateString: return None for handler in _date_handlers: try: date9tuple = handler(dateString) except (KeyError, OverflowError, ValueError): continue if not date9tuple: continue if len(date9tuple) != 9: continue return date9tuple return None def _getCharacterEncoding(http_headers, xml_data): '''Get the character encoding of the XML document http_headers is a dictionary xml_data is a raw string (not Unicode) This is so much trickier than it sounds, it's not even funny. According to RFC 3023 ('XML Media Types'), if the HTTP Content-Type is application/xml, application/*+xml, application/xml-external-parsed-entity, or application/xml-dtd, the encoding given in the charset parameter of the HTTP Content-Type takes precedence over the encoding given in the XML prefix within the document, and defaults to 'utf-8' if neither are specified. But, if the HTTP Content-Type is text/xml, text/*+xml, or text/xml-external-parsed-entity, the encoding given in the XML prefix within the document is ALWAYS IGNORED and only the encoding given in the charset parameter of the HTTP Content-Type header should be respected, and it defaults to 'us-ascii' if not specified. Furthermore, discussion on the atom-syntax mailing list with the author of RFC 3023 leads me to the conclusion that any document served with a Content-Type of text/* and no charset parameter must be treated as us-ascii. (We now do this.) And also that it must always be flagged as non-well-formed. (We now do this too.) If Content-Type is unspecified (input was local file or non-HTTP source) or unrecognized (server just got it totally wrong), then go by the encoding given in the XML prefix of the document and default to 'iso-8859-1' as per the HTTP specification (RFC 2616). Then, assuming we didn't find a character encoding in the HTTP headers (and the HTTP Content-type allowed us to look in the body), we need to sniff the first few bytes of the XML data and try to determine whether the encoding is ASCII-compatible. Section F of the XML specification shows the way here: http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info If the sniffed encoding is not ASCII-compatible, we need to make it ASCII compatible so that we can sniff further into the XML declaration to find the encoding attribute, which will tell us the true encoding. Of course, none of this guarantees that we will be able to parse the feed in the declared character encoding (assuming it was declared correctly, which many are not). iconv_codec can help a lot; you should definitely install it if you can. http://cjkpython.i18n.org/ ''' def _parseHTTPContentType(content_type): '''takes HTTP Content-Type header and returns (content type, charset) If no charset is specified, returns (content type, '') If no content type is specified, returns ('', '') Both return parameters are guaranteed to be lowercase strings ''' content_type = content_type or '' content_type, params = cgi.parse_header(content_type) charset = params.get('charset', '').replace("'", "") if not isinstance(charset, unicode): charset = charset.decode('utf-8', 'ignore') return content_type, charset sniffed_xml_encoding = u'' xml_encoding = u'' true_encoding = u'' http_content_type, http_encoding = _parseHTTPContentType(http_headers.get('content-type')) # Must sniff for non-ASCII-compatible character encodings before # searching for XML declaration. This heuristic is defined in # section F of the XML specification: # http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info try: if xml_data[:4] == _l2bytes([0x4c, 0x6f, 0xa7, 0x94]): # In all forms of EBCDIC, these four bytes correspond # to the string '<?xm'; try decoding using CP037 sniffed_xml_encoding = u'cp037' xml_data = xml_data.decode('cp037').encode('utf-8') elif xml_data[:4] == _l2bytes([0x00, 0x3c, 0x00, 0x3f]): # UTF-16BE sniffed_xml_encoding = u'utf-16be' xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == _l2bytes([0xfe, 0xff])) and (xml_data[2:4] != _l2bytes([0x00, 0x00])): # UTF-16BE with BOM sniffed_xml_encoding = u'utf-16be' xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8') elif xml_data[:4] == _l2bytes([0x3c, 0x00, 0x3f, 0x00]): # UTF-16LE sniffed_xml_encoding = u'utf-16le' xml_data = unicode(xml_data, 'utf-16le').encode('utf-8') elif (len(xml_data) >= 4) and (xml_data[:2] == _l2bytes([0xff, 0xfe])) and (xml_data[2:4] != _l2bytes([0x00, 0x00])): # UTF-16LE with BOM sniffed_xml_encoding = u'utf-16le' xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8') elif xml_data[:4] == _l2bytes([0x00, 0x00, 0x00, 0x3c]): # UTF-32BE sniffed_xml_encoding = u'utf-32be' if _UTF32_AVAILABLE: xml_data = unicode(xml_data, 'utf-32be').encode('utf-8') elif xml_data[:4] == _l2bytes([0x3c, 0x00, 0x00, 0x00]): # UTF-32LE sniffed_xml_encoding = u'utf-32le' if _UTF32_AVAILABLE: xml_data = unicode(xml_data, 'utf-32le').encode('utf-8') elif xml_data[:4] == _l2bytes([0x00, 0x00, 0xfe, 0xff]): # UTF-32BE with BOM sniffed_xml_encoding = u'utf-32be' if _UTF32_AVAILABLE: xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8') elif xml_data[:4] == _l2bytes([0xff, 0xfe, 0x00, 0x00]): # UTF-32LE with BOM sniffed_xml_encoding = u'utf-32le' if _UTF32_AVAILABLE: xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8') elif xml_data[:3] == _l2bytes([0xef, 0xbb, 0xbf]): # UTF-8 with BOM sniffed_xml_encoding = u'utf-8' xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8') else: # ASCII-compatible pass xml_encoding_match = re.compile(_s2bytes('^<\?.*encoding=[\'"](.*?)[\'"].*\?>')).match(xml_data) except UnicodeDecodeError: xml_encoding_match = None if xml_encoding_match: xml_encoding = xml_encoding_match.groups()[0].decode('utf-8').lower() if sniffed_xml_encoding and (xml_encoding in (u'iso-10646-ucs-2', u'ucs-2', u'csunicode', u'iso-10646-ucs-4', u'ucs-4', u'csucs4', u'utf-16', u'utf-32', u'utf_16', u'utf_32', u'utf16', u'u16')): xml_encoding = sniffed_xml_encoding acceptable_content_type = 0 application_content_types = (u'application/xml', u'application/xml-dtd', u'application/xml-external-parsed-entity') text_content_types = (u'text/xml', u'text/xml-external-parsed-entity') if (http_content_type in application_content_types) or \ (http_content_type.startswith(u'application/') and http_content_type.endswith(u'+xml')): acceptable_content_type = 1 true_encoding = http_encoding or xml_encoding or u'utf-8' elif (http_content_type in text_content_types) or \ (http_content_type.startswith(u'text/')) and http_content_type.endswith(u'+xml'): acceptable_content_type = 1 true_encoding = http_encoding or u'us-ascii' elif http_content_type.startswith(u'text/'): true_encoding = http_encoding or u'us-ascii' elif http_headers and 'content-type' not in http_headers: true_encoding = xml_encoding or u'iso-8859-1' else: true_encoding = xml_encoding or u'utf-8' # some feeds claim to be gb2312 but are actually gb18030. # apparently MSIE and Firefox both do the following switch: if true_encoding.lower() == u'gb2312': true_encoding = u'gb18030' return true_encoding, http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type def _toUTF8(data, encoding): '''Changes an XML data stream on the fly to specify a new encoding data is a raw sequence of bytes (not Unicode) that is presumed to be in %encoding already encoding is a string recognized by encodings.aliases ''' # strip Byte Order Mark (if present) if (len(data) >= 4) and (data[:2] == _l2bytes([0xfe, 0xff])) and (data[2:4] != _l2bytes([0x00, 0x00])): encoding = 'utf-16be' data = data[2:] elif (len(data) >= 4) and (data[:2] == _l2bytes([0xff, 0xfe])) and (data[2:4] != _l2bytes([0x00, 0x00])): encoding = 'utf-16le' data = data[2:] elif data[:3] == _l2bytes([0xef, 0xbb, 0xbf]): encoding = 'utf-8' data = data[3:] elif data[:4] == _l2bytes([0x00, 0x00, 0xfe, 0xff]): encoding = 'utf-32be' data = data[4:] elif data[:4] == _l2bytes([0xff, 0xfe, 0x00, 0x00]): encoding = 'utf-32le' data = data[4:] newdata = unicode(data, encoding) declmatch = re.compile('^<\?xml[^>]*?>') newdecl = '''<?xml version='1.0' encoding='utf-8'?>''' if declmatch.search(newdata): newdata = declmatch.sub(newdecl, newdata) else: newdata = newdecl + u'\n' + newdata return newdata.encode('utf-8') def _stripDoctype(data): '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data) rss_version may be 'rss091n' or None stripped_data is the same XML document, minus the DOCTYPE ''' start = re.search(_s2bytes('<\w'), data) start = start and start.start() or -1 head,data = data[:start+1], data[start+1:] entity_pattern = re.compile(_s2bytes(r'^\s*<!ENTITY([^>]*?)>'), re.MULTILINE) entity_results=entity_pattern.findall(head) head = entity_pattern.sub(_s2bytes(''), head) doctype_pattern = re.compile(_s2bytes(r'^\s*<!DOCTYPE([^>]*?)>'), re.MULTILINE) doctype_results = doctype_pattern.findall(head) doctype = doctype_results and doctype_results[0] or _s2bytes('') if doctype.lower().count(_s2bytes('netscape')): version = u'rss091n' else: version = None # only allow in 'safe' inline entity definitions replacement=_s2bytes('') if len(doctype_results)==1 and entity_results: safe_pattern=re.compile(_s2bytes('\s+(\w+)\s+"(&#\w+;|[^&"]*)"')) safe_entities=filter(lambda e: safe_pattern.match(e),entity_results) if safe_entities: replacement=_s2bytes('<!DOCTYPE feed [\n <!ENTITY') + _s2bytes('>\n <!ENTITY ').join(safe_entities) + _s2bytes('>\n]>') data = doctype_pattern.sub(replacement, head) + data return version, data, dict(replacement and [(k.decode('utf-8'), v.decode('utf-8')) for k, v in safe_pattern.findall(replacement)]) def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=None, request_headers=None, response_headers=None): '''Parse a feed from a URL, file, stream, or string. request_headers, if given, is a dict from http header name to value to add to the request; this overrides internally generated values. ''' if handlers is None: handlers = [] if request_headers is None: request_headers = {} if response_headers is None: response_headers = {} result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] result['bozo'] = 0 if not isinstance(handlers, list): handlers = [handlers] try: f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, request_headers) data = f.read() except Exception, e: result['bozo'] = 1 result['bozo_exception'] = e data = None f = None if hasattr(f, 'headers'): result['headers'] = dict(f.headers) # overwrite existing headers using response_headers if 'headers' in result: result['headers'].update(response_headers) elif response_headers: result['headers'] = copy.deepcopy(response_headers) # lowercase all of the HTTP headers for comparisons per RFC 2616 if 'headers' in result: http_headers = dict((k.lower(), v) for k, v in result['headers'].items()) else: http_headers = {} # if feed is gzip-compressed, decompress it if f and data and http_headers: if gzip and 'gzip' in http_headers.get('content-encoding', ''): try: data = gzip.GzipFile(fileobj=_StringIO(data)).read() except (IOError, struct.error), e: # IOError can occur if the gzip header is bad. # struct.error can occur if the data is damaged. result['bozo'] = 1 result['bozo_exception'] = e if isinstance(e, struct.error): # A gzip header was found but the data is corrupt. # Ideally, we should re-request the feed without the # 'Accept-encoding: gzip' header, but we don't. data = None elif zlib and 'deflate' in http_headers.get('content-encoding', ''): try: data = zlib.decompress(data) except zlib.error, e: try: # The data may have no headers and no checksum. data = zlib.decompress(data, -15) except zlib.error, e: result['bozo'] = 1 result['bozo_exception'] = e # save HTTP headers if http_headers: if 'etag' in http_headers: etag = http_headers.get('etag', u'') if not isinstance(etag, unicode): etag = etag.decode('utf-8', 'ignore') if etag: result['etag'] = etag if 'last-modified' in http_headers: modified = http_headers.get('last-modified', u'') if modified: result['modified'] = modified result['modified_parsed'] = _parse_date(modified) if hasattr(f, 'url'): if not isinstance(f.url, unicode): result['href'] = f.url.decode('utf-8', 'ignore') else: result['href'] = f.url result['status'] = 200 if hasattr(f, 'status'): result['status'] = f.status if hasattr(f, 'close'): f.close() if data is None: return result # there are four encodings to keep track of: # - http_encoding is the encoding declared in the Content-Type HTTP header # - xml_encoding is the encoding declared in the <?xml declaration # - sniffed_encoding is the encoding sniffed from the first 4 bytes of the XML data # - result['encoding'] is the actual encoding, as per RFC 3023 and a variety of other conflicting specifications result['encoding'], http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type = \ _getCharacterEncoding(http_headers, data) if http_headers and (not acceptable_content_type): if 'content-type' in http_headers: bozo_message = '%s is not an XML media type' % http_headers['content-type'] else: bozo_message = 'no Content-type specified' result['bozo'] = 1 result['bozo_exception'] = NonXMLContentType(bozo_message) # ensure that baseuri is an absolute uri using an acceptable URI scheme contentloc = http_headers.get('content-location', u'') href = result.get('href', u'') baseuri = _makeSafeAbsoluteURI(href, contentloc) or _makeSafeAbsoluteURI(contentloc) or href baselang = http_headers.get('content-language', None) if not isinstance(baselang, unicode) and baselang is not None: baselang = baselang.decode('utf-8', 'ignore') # if server sent 304, we're done if getattr(f, 'code', 0) == 304: result['version'] = u'' result['debug_message'] = 'The feed has not changed since you last checked, ' + \ 'so the server sent no data. This is a feature, not a bug!' return result # if there was a problem downloading, we're done if data is None: return result # determine character encoding use_strict_parser = 0 known_encoding = 0 tried_encodings = [] # try: HTTP encoding, declared XML encoding, encoding sniffed from BOM for proposed_encoding in (result['encoding'], xml_encoding, sniffed_xml_encoding): if not proposed_encoding: continue if proposed_encoding in tried_encodings: continue tried_encodings.append(proposed_encoding) try: data = _toUTF8(data, proposed_encoding) except (UnicodeDecodeError, LookupError): pass else: known_encoding = use_strict_parser = 1 break # if no luck and we have auto-detection library, try that if (not known_encoding) and chardet: proposed_encoding = unicode(chardet.detect(data)['encoding'], 'ascii', 'ignore') if proposed_encoding and (proposed_encoding not in tried_encodings): tried_encodings.append(proposed_encoding) try: data = _toUTF8(data, proposed_encoding) except (UnicodeDecodeError, LookupError): pass else: known_encoding = use_strict_parser = 1 # if still no luck and we haven't tried utf-8 yet, try that if (not known_encoding) and (u'utf-8' not in tried_encodings): proposed_encoding = u'utf-8' tried_encodings.append(proposed_encoding) try: data = _toUTF8(data, proposed_encoding) except UnicodeDecodeError: pass else: known_encoding = use_strict_parser = 1 # if still no luck and we haven't tried windows-1252 yet, try that if (not known_encoding) and (u'windows-1252' not in tried_encodings): proposed_encoding = u'windows-1252' tried_encodings.append(proposed_encoding) try: data = _toUTF8(data, proposed_encoding) except UnicodeDecodeError: pass else: known_encoding = use_strict_parser = 1 # if still no luck and we haven't tried iso-8859-2 yet, try that. if (not known_encoding) and (u'iso-8859-2' not in tried_encodings): proposed_encoding = u'iso-8859-2' tried_encodings.append(proposed_encoding) try: data = _toUTF8(data, proposed_encoding) except UnicodeDecodeError: pass else: known_encoding = use_strict_parser = 1 # if still no luck, give up if not known_encoding: result['bozo'] = 1 result['bozo_exception'] = CharacterEncodingUnknown( \ 'document encoding unknown, I tried ' + \ '%s, %s, utf-8, windows-1252, and iso-8859-2 but nothing worked' % \ (result['encoding'], xml_encoding)) result['encoding'] = u'' elif proposed_encoding != result['encoding']: result['bozo'] = 1 result['bozo_exception'] = CharacterEncodingOverride( \ 'document declared as %s, but parsed as %s' % \ (result['encoding'], proposed_encoding)) result['encoding'] = proposed_encoding result['version'], data, entities = _stripDoctype(data) if not _XML_AVAILABLE: use_strict_parser = 0 if use_strict_parser: # initialize the SAX parser feedparser = _StrictFeedParser(baseuri, baselang, 'utf-8') saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS) saxparser.setFeature(xml.sax.handler.feature_namespaces, 1) try: # disable downloading external doctype references, if possible saxparser.setFeature(xml.sax.handler.feature_external_ges, 0) except xml.sax.SAXNotSupportedException: pass saxparser.setContentHandler(feedparser) saxparser.setErrorHandler(feedparser) source = xml.sax.xmlreader.InputSource() source.setByteStream(_StringIO(data)) try: saxparser.parse(source) except xml.sax.SAXParseException, e: result['bozo'] = 1 result['bozo_exception'] = feedparser.exc or e use_strict_parser = 0 if not use_strict_parser and _SGML_AVAILABLE: feedparser = _LooseFeedParser(baseuri, baselang, 'utf-8', entities) feedparser.feed(data.decode('utf-8', 'replace')) result['feed'] = feedparser.feeddata result['entries'] = feedparser.entries result['version'] = result['version'] or feedparser.version result['namespaces'] = feedparser.namespacesInUse return result #----------------------------------------------------------------------------------------------------------------------------------- from flask import render_template, session from Ironworks import app from ironworks.noneditable import * from modules.house import currentHouse from modules.bleextop import settingsLogin from ironworks.models import xbmcServer, setting from ironworks import logger, tools, preferences @app.route('/latestNews') def latestNews(): if 'username' in session: xbmc = xbmcServer.XbmcServer() settings = setting.Setting() prefs = preferences.Prefs() # get list of servers servers = xbmc.getNumXbmcServers() if servers == 0: # check if old server settings value is set old_server = prefs.getLastXbmcServer() # create an XbmcServer entry using the legacy settings if old_server: xbmc_server = xbmc.xbmcServer(old_server["label"], old_server["position"], old_server["hostname"], old_server["port"], old_server["username"], old_server["password"], old_server["mac_address"]) try: tools.setXbmcServer(xbmc_server) servers = xbmc.getServers(orderBy="position") except: logger.log('Could not create new XbmcServer based on legacy settings', 'WARNING') active_server = settings.get_setting_value('active_server') if active_server and active_server != 'undefined': active_server = int(active_server) else: active_server = 1 # show currently playing bar? if settings.get_setting_value('show_currently_playing') is None: show_currently_playing = True else: show_currently_playing = int(settings.get_setting_value('show_currently_playing')) > 0 hackaday, io9, mentalFloss, sparkfun, google, wallStreet, tech, linux = parseFeeds() #active_server=active_server, return render_template('latestNews.html', servers=servers, show_currently_playing=show_currently_playing, hackadayFeed=hackaday, io9Feed=io9, mentalFlossFeed=mentalFloss, sparkfunFeed=sparkfun, googleFeed=google, wallStreetFeed=wallStreet, techNewsFeed=tech, linuxNewsFeed=linux ) return render_template('index.html') def parseFeeds(): # Feeds hackaday_url = 'http://feeds2.feedburner.com/hackaday/LgoM' io9_url = 'http://io9.com/rss' mental_floss_url = 'http://mentalfloss.feedsportal.com/c/35119/f/649404/index.rss' google_url = 'https://news.google.com/news?pz=1&cf=all&ned=us&siidp=a3761a02c7bb42a6b2f9e47806ce78c4bb0d&ict=ln&output=rss' wallStreet_url = 'http://online.wsj.com/xml/rss/3_7014.xml' techNews_url = "http://www.technewsworld.com/perl/syndication/rssfull.pl" linuxNews_url = "http://www.linuxinsider.com/perl/syndication/rssfull.pl" sparkfun_url = 'https://www.sparkfun.com/feeds/news' hackaday_feeds = parse(hackaday_url) io9_feeds = parse(io9_url) mental_floss_feeds = parse(mental_floss_url) sparkfun_feeds = parse(sparkfun_url) google_feeds = parse(google_url) wallStreet_feeds = parse(wallStreet_url) techNews_feeds = parse(techNews_url) linuxNews_feeds = parse(linuxNews_url) return hackaday_feeds, io9_feeds, mental_floss_feeds, sparkfun_feeds, google_feeds, wallStreet_feeds, techNews_feeds, linuxNews_feeds
SDX2000/UniShell-Python
refs/heads/master
lib/prologue.py
1
prologue = """\ """
wolfram74/numerical_methods_iserles_notes
refs/heads/master
venv/lib/python2.7/site-packages/numpy/f2py/tests/test_mixed.py
69
from __future__ import division, absolute_import, print_function import os import math from numpy.testing import * from numpy import array import util import textwrap def _path(*a): return os.path.join(*((os.path.dirname(__file__),) + a)) class TestMixed(util.F2PyTest): sources = [_path('src', 'mixed', 'foo.f'), _path('src', 'mixed', 'foo_fixed.f90'), _path('src', 'mixed', 'foo_free.f90')] @dec.slow def test_all(self): assert_( self.module.bar11() == 11) assert_( self.module.foo_fixed.bar12() == 12) assert_( self.module.foo_free.bar13() == 13) @dec.slow def test_docstring(self): expected = """ a = bar11() Wrapper for ``bar11``. Returns ------- a : int """ assert_equal(self.module.bar11.__doc__, textwrap.dedent(expected).lstrip()) if __name__ == "__main__": import nose nose.runmodule()
chongtianfeiyu/kbengine
refs/heads/master
kbe/res/scripts/common/Lib/shlex.py
80
"""A lexical analyzer class for simple shell-like syntaxes.""" # Module and documentation by Eric S. Raymond, 21 Dec 1998 # Input stacking and error message cleanup added by ESR, March 2000 # push_source() and pop_source() made explicit by ESR, January 2001. # Posix compliance, split(), string arguments, and # iterator interface by Gustavo Niemeyer, April 2003. import os import re import sys from collections import deque from io import StringIO __all__ = ["shlex", "split", "quote"] class shlex: "A lexical analyzer class for simple shell-like syntaxes." def __init__(self, instream=None, infile=None, posix=False): if isinstance(instream, str): instream = StringIO(instream) if instream is not None: self.instream = instream self.infile = infile else: self.instream = sys.stdin self.infile = None self.posix = posix if posix: self.eof = None else: self.eof = '' self.commenters = '#' self.wordchars = ('abcdfeghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_') if self.posix: self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ') self.whitespace = ' \t\r\n' self.whitespace_split = False self.quotes = '\'"' self.escape = '\\' self.escapedquotes = '"' self.state = ' ' self.pushback = deque() self.lineno = 1 self.debug = 0 self.token = '' self.filestack = deque() self.source = None if self.debug: print('shlex: reading from %s, line %d' \ % (self.instream, self.lineno)) def push_token(self, tok): "Push a token onto the stack popped by the get_token method" if self.debug >= 1: print("shlex: pushing token " + repr(tok)) self.pushback.appendleft(tok) def push_source(self, newstream, newfile=None): "Push an input source onto the lexer's input source stack." if isinstance(newstream, str): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1 if self.debug: if newfile is not None: print('shlex: pushing to file %s' % (self.infile,)) else: print('shlex: pushing to stream %s' % (self.instream,)) def pop_source(self): "Pop the input source stack." self.instream.close() (self.infile, self.instream, self.lineno) = self.filestack.popleft() if self.debug: print('shlex: popping to %s, line %d' \ % (self.instream, self.lineno)) self.state = ' ' def get_token(self): "Get a token from the input stream (or from stack if it's nonempty)" if self.pushback: tok = self.pushback.popleft() if self.debug >= 1: print("shlex: popping token " + repr(tok)) return tok # No pushback. Get a token. raw = self.read_token() # Handle inclusions if self.source is not None: while raw == self.source: spec = self.sourcehook(self.read_token()) if spec: (newfile, newstream) = spec self.push_source(newstream, newfile) raw = self.get_token() # Maybe we got EOF instead? while raw == self.eof: if not self.filestack: return self.eof else: self.pop_source() raw = self.get_token() # Neither inclusion nor EOF if self.debug >= 1: if raw != self.eof: print("shlex: token=" + repr(raw)) else: print("shlex: token=EOF") return raw def read_token(self): quoted = False escapedstate = ' ' while True: nextchar = self.instream.read(1) if nextchar == '\n': self.lineno = self.lineno + 1 if self.debug >= 3: print("shlex: in state", repr(self.state), \ "I see character:", repr(nextchar)) if self.state is None: self.token = '' # past end of file break elif self.state == ' ': if not nextchar: self.state = None # end of file break elif nextchar in self.whitespace: if self.debug >= 2: print("shlex: I see whitespace in whitespace state") if self.token or (self.posix and quoted): break # emit current token else: continue elif nextchar in self.commenters: self.instream.readline() self.lineno = self.lineno + 1 elif self.posix and nextchar in self.escape: escapedstate = 'a' self.state = nextchar elif nextchar in self.wordchars: self.token = nextchar self.state = 'a' elif nextchar in self.quotes: if not self.posix: self.token = nextchar self.state = nextchar elif self.whitespace_split: self.token = nextchar self.state = 'a' else: self.token = nextchar if self.token or (self.posix and quoted): break # emit current token else: continue elif self.state in self.quotes: quoted = True if not nextchar: # end of file if self.debug >= 2: print("shlex: I see EOF in quotes state") # XXX what error should be raised here? raise ValueError("No closing quotation") if nextchar == self.state: if not self.posix: self.token = self.token + nextchar self.state = ' ' break else: self.state = 'a' elif self.posix and nextchar in self.escape and \ self.state in self.escapedquotes: escapedstate = self.state self.state = nextchar else: self.token = self.token + nextchar elif self.state in self.escape: if not nextchar: # end of file if self.debug >= 2: print("shlex: I see EOF in escape state") # XXX what error should be raised here? raise ValueError("No escaped character") # In posix shells, only the quote itself or the escape # character may be escaped within quotes. if escapedstate in self.quotes and \ nextchar != self.state and nextchar != escapedstate: self.token = self.token + self.state self.token = self.token + nextchar self.state = escapedstate elif self.state == 'a': if not nextchar: self.state = None # end of file break elif nextchar in self.whitespace: if self.debug >= 2: print("shlex: I see whitespace in word state") self.state = ' ' if self.token or (self.posix and quoted): break # emit current token else: continue elif nextchar in self.commenters: self.instream.readline() self.lineno = self.lineno + 1 if self.posix: self.state = ' ' if self.token or (self.posix and quoted): break # emit current token else: continue elif self.posix and nextchar in self.quotes: self.state = nextchar elif self.posix and nextchar in self.escape: escapedstate = 'a' self.state = nextchar elif nextchar in self.wordchars or nextchar in self.quotes \ or self.whitespace_split: self.token = self.token + nextchar else: self.pushback.appendleft(nextchar) if self.debug >= 2: print("shlex: I see punctuation in word state") self.state = ' ' if self.token: break # emit current token else: continue result = self.token self.token = '' if self.posix and not quoted and result == '': result = None if self.debug > 1: if result: print("shlex: raw token=" + repr(result)) else: print("shlex: raw token=EOF") return result def sourcehook(self, newfile): "Hook called on a filename to be sourced." if newfile[0] == '"': newfile = newfile[1:-1] # This implements cpp-like semantics for relative-path inclusion. if isinstance(self.infile, str) and not os.path.isabs(newfile): newfile = os.path.join(os.path.dirname(self.infile), newfile) return (newfile, open(newfile, "r")) def error_leader(self, infile=None, lineno=None): "Emit a C-compiler-like, Emacs-friendly error-message leader." if infile is None: infile = self.infile if lineno is None: lineno = self.lineno return "\"%s\", line %d: " % (infile, lineno) def __iter__(self): return self def __next__(self): token = self.get_token() if token == self.eof: raise StopIteration return token def split(s, comments=False, posix=True): lex = shlex(s, posix=posix) lex.whitespace_split = True if not comments: lex.commenters = '' return list(lex) _find_unsafe = re.compile(r'[^\w@%+=:,./-]', re.ASCII).search def quote(s): """Return a shell-escaped version of the string *s*.""" if not s: return "''" if _find_unsafe(s) is None: return s # use single quotes, and put single quotes into double quotes # the string $'b is then quoted as '$'"'"'b' return "'" + s.replace("'", "'\"'\"'") + "'" if __name__ == '__main__': if len(sys.argv) == 1: lexer = shlex() else: file = sys.argv[1] lexer = shlex(open(file), file) while 1: tt = lexer.get_token() if tt: print("Token: " + repr(tt)) else: break
oscaro/django
refs/heads/oscaro-backports-1.7.10
tests/generic_views/test_forms.py
453
from __future__ import unicode_literals from django import forms from .models import Author class AuthorForm(forms.ModelForm): name = forms.CharField() slug = forms.SlugField() class Meta: model = Author fields = ['name', 'slug'] class ContactForm(forms.Form): name = forms.CharField() message = forms.CharField(widget=forms.Textarea)
ckolumbus/mikidown
refs/heads/ckol
mikidown/mikitree.py
1
""" Naming convention: * item - the visual element in MikiTree * page - denoted by item hierarchy e.g. `foo/bar` is a subpage of `foo` * file - the actual file on disk """ import os import datetime from PyQt4.QtCore import Qt, QDir, QFile, QIODevice, QSize, QTextStream from PyQt4.QtGui import (QAbstractItemView, QCursor, QMenu, QMessageBox, QTreeWidget, QTreeWidgetItem) from whoosh.index import open_dir from whoosh.qparser import QueryParser from .config import Setting from .utils import LineEditDialog class MikiTree(QTreeWidget): def __init__(self, parent=None): super(MikiTree, self).__init__(parent) self.parent = parent self.settings = parent.settings self.notePath = self.settings.notePath self.header().close() self.setAcceptDrops(True) self.setDragEnabled(True) # self.setDropIndicatorShown(True) self.setDragDropOverwriteMode(True) self.setDragDropMode(QAbstractItemView.InternalMove) # self.setSelectionMode(QAbstractItemView.ExtendedSelection) self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.contextMenu) def itemToPage(self, item): """ get item hierarchy from item """ page = '' if not hasattr(item, 'text'): return page page = item.text(0) parent = item.parent() while parent is not None: page = parent.text(0) + '/' + page parent = parent.parent() return page def pageToItem(self, page): """ get item from item hierarchy """ # strip the beginning and ending '/' character if page[0] == '/': page = page[1:len(page)] if page[-1] == '/': page = page[0:-1] # find all items named pieces[-1], then match the page name. pieces = page.split('/') itemList = self.findItems( pieces[-1], Qt.MatchExactly|Qt.MatchRecursive) if len(itemList) == 1: return itemList[0] for item in itemList: if page == self.itemToPage(item): return item def itemToFile(self, item): return self.pageToFile(self.itemToPage(item)) def pageToFile(self, page): """ get filepath from page filepath = notePath + page + fileExt fileExt is stored in notebook.conf """ # When exists foo.md, foo.mkd, foo.markdown, # the one with defExt will be returned extName = ['.md', '.mkd', '.markdown', '.rst'] defExt = self.settings.fileExt if defExt in extName: extName.remove(defExt) else: print("Warning: detected file extension name is", defExt) print(" Your config file is located in", self.notePath + "/notebook.conf") extName.insert(0, defExt) for ext in extName: filepath = os.path.join(self.notePath, page + ext) if QFile.exists(filepath): return filepath # return filename with default extension name even if file not exists. return os.path.join(self.notePath, page + defExt) def itemToHtmlFile(self, item): """ The corresponding html file path """ page = self.itemToPage(item) return os.path.join(self.settings.htmlPath, page + ".html") def itemToAttachmentDir(self, item): """ The corresponding attachment directory dirName is constructed by pageName and md5(page), so that no nesting needed and manipulation become easy """ page = self.itemToPage(item) return os.path.join(self.settings.attachmentPath, page) def currentPage(self): return self.itemToPage(self.currentItem()) def contextMenu(self): """ contextMenu shown when right click the mouse """ menu = QMenu() menu.addAction("New Page...", self.newPage) menu.addAction("New Subpage...", self.newSubpage) menu.addSeparator() menu.addAction("Collapse This Note Tree", lambda item=self.currentItem(): self.recurseCollapse(item)) menu.addAction("Uncollapse This Note Tree", lambda item=self.currentItem(): self.recurseExpand(item)) menu.addAction("Collapse All", self.collapseAll) menu.addAction("Uncollapse All", self.expandAll) menu.addSeparator() menu.addAction('Rename Page...', self.renamePage) menu.addAction("Delete Page", self.delPageWrapper) menu.exec_(QCursor.pos()) def newPage(self, name=None): if self.currentItem() is None: self.newPageCore(self, name) else: parent = self.currentItem().parent() if parent is not None: self.newPageCore(parent, name) else: self.newPageCore(self, name) def newSubpage(self, name=None): item = self.currentItem() self.newPageCore(item, name) def newPageCore(self, item, newPageName): pagePath = os.path.join(self.notePath, self.itemToPage(item)) if not newPageName: dialog = LineEditDialog(pagePath, self) if dialog.exec_(): newPageName = dialog.editor.text() if newPageName: if hasattr(item, 'text'): pagePath = os.path.join(self.notePath, pagePath + '/') if not QDir(pagePath).exists(): QDir(self.notePath).mkdir(pagePath) fileName = pagePath + newPageName + self.settings.fileExt fh = QFile(fileName) fh.open(QIODevice.WriteOnly) savestream = QTextStream(fh) savestream << '# ' + newPageName + '\n' savestream << 'Created ' + str(datetime.date.today()) + '\n\n' fh.close() QTreeWidgetItem(item, [newPageName]) newItem = self.pageToItem(pagePath + newPageName) self.sortItems(0, Qt.AscendingOrder) self.setCurrentItem(newItem) if hasattr(item, 'text'): self.expandItem(item) # create attachment folder if not exist attDir = self.itemToAttachmentDir(newItem) if not QDir(attDir).exists(): QDir().mkpath(attDir) # TODO improvement needed, can be reused somehow fileobj = open(fileName, 'r') content = fileobj.read() fileobj.close() self.ix = open_dir(self.settings.indexdir) writer = self.ix.writer() writer.add_document(path=pagePath+newPageName, content=content) writer.commit() def dropEvent(self, event): """ A note is related to four parts: note file, note folder containing child note, parent note folder, attachment folder. When drag/drop, should take care of: 1. rename note file ("rename" is just another way of saying "move") 2. rename note folder 3. if parent note has no more child, remove parent note folder 4. rename attachment folder """ # construct file/folder names before and after drag/drop sourceItem = self.currentItem() sourcePage = self.itemToPage(sourceItem) oldAttDir = self.itemToAttachmentDir(sourceItem) targetItem = self.itemAt(event.pos()) targetPage = self.itemToPage(targetItem) oldFile = self.itemToFile(sourceItem) newFile = os.path.join(targetPage, sourceItem.text(0) + self.settings.fileExt) oldDir = sourcePage newDir = os.path.join(targetPage, sourceItem.text(0)) if QFile.exists(newFile): QMessageBox.warning(self, 'Error', 'File already exists: %s' % newFile) return # rename file/folder, remove parent note folder if necessary if targetPage != '': QDir(self.notePath).mkpath(targetPage) QDir(self.notePath).rename(oldFile, newFile) if sourceItem.childCount() != 0: QDir(self.notePath).rename(oldDir, newDir) if sourceItem.parent() is not None: parentItem = sourceItem.parent() parentPage = self.itemToPage(parentItem) if parentItem.childCount() == 1: QDir(self.notePath).rmdir(parentPage) # pass the event to default implementation QTreeWidget.dropEvent(self, event) self.sortItems(0, Qt.AscendingOrder) if hasattr(targetItem, 'text'): self.expandItem(targetItem) # if attachment folder exists, rename it if QDir().exists(oldAttDir): # make sure target folder exists QDir().mkpath(self.itemToAttachmentDir(targetItem)) newAttDir = self.itemToAttachmentDir(sourceItem) QDir().rename(oldAttDir, newAttDir) self.parent.updateAttachmentView() def renamePage(self): item = self.currentItem() oldAttDir = self.itemToAttachmentDir(item) parent = item.parent() parentPage = self.itemToPage(parent) parentPath = os.path.join(self.notePath, parentPage) dialog = LineEditDialog(parentPath, self) dialog.setText(item.text(0)) if dialog.exec_(): newPageName = dialog.editor.text() # if hasattr(item, 'text'): # if item is not QTreeWidget if parentPage != '': parentPage = parentPage + '/' oldFile = self.itemToFile(item) newFile = parentPage + newPageName + self.settings.fileExt QDir(self.notePath).rename(oldFile, newFile) if item.childCount() != 0: oldDir = parentPage + item.text(0) newDir = parentPage + newPageName QDir(self.notePath).rename(oldDir, newDir) item.setText(0, newPageName) self.sortItems(0, Qt.AscendingOrder) # if attachment folder exists, rename it if QDir().exists(oldAttDir): newAttDir = self.itemToAttachmentDir(item) QDir().rename(oldAttDir, newAttDir) self.parent.updateAttachmentView() def pageExists(self, noteFullName): return QFile.exists(self.pageToFile(noteFullName)) def delPageWrapper(self): item = self.currentItem() self.delPage(item) def delPage(self, item): index = item.childCount() while index > 0: index = index - 1 self.dirname = item.child(index).text(0) self.delPage(item.child(index)) # remove attachment folder attDir = self.itemToAttachmentDir(item) for info in QDir(attDir).entryInfoList(): QDir().remove(info.absoluteFilePath()) QDir().rmdir(attDir) pagePath = self.itemToPage(item) self.ix = open_dir(self.settings.indexdir) query = QueryParser('path', self.ix.schema).parse(pagePath) writer = self.ix.writer() n = writer.delete_by_query(query) # n = writer.delete_by_term('path', pagePath) writer.commit() b = QDir(self.notePath).remove(self.pageToFile(pagePath)) parent = item.parent() parentPage = self.itemToPage(parent) if parent is not None: index = parent.indexOfChild(item) parent.takeChild(index) if parent.childCount() == 0: # if no child, dir not needed QDir(self.notePath).rmdir(parentPage) else: index = self.indexOfTopLevelItem(item) self.takeTopLevelItem(index) QDir(self.notePath).rmdir(pagePath) def sizeHint(self): return QSize(200, 0) def recurseCollapse(self, item): for i in range(item.childCount()): a_item = item.child(i) self.recurseCollapse(a_item) self.collapseItem(item) def recurseExpand(self, item): self.expandItem(item) for i in range(item.childCount()): a_item = item.child(i) self.recurseExpand(a_item) class TocTree(QTreeWidget): def __init__(self, parent=None): super(TocTree, self).__init__(parent) def sizeHint(self): return QSize(200, 0)
e-gob/plataforma-kioscos-autoatencion
refs/heads/master
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/module_utils/facts/network/openbsd.py
232
# 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 from ansible.module_utils.facts.network.base import NetworkCollector from ansible.module_utils.facts.network.generic_bsd import GenericBsdIfconfigNetwork class OpenBSDNetwork(GenericBsdIfconfigNetwork): """ This is the OpenBSD Network Class. It uses the GenericBsdIfconfigNetwork. """ platform = 'OpenBSD' # OpenBSD 'ifconfig -a' does not have information about aliases def get_interfaces_info(self, ifconfig_path, ifconfig_options='-aA'): return super(OpenBSDNetwork, self).get_interfaces_info(ifconfig_path, ifconfig_options) # Return macaddress instead of lladdr def parse_lladdr_line(self, words, current_if, ips): current_if['macaddress'] = words[1] current_if['type'] = 'ether' class OpenBSDNetworkCollector(NetworkCollector): _fact_class = OpenBSDNetwork _platform = 'OpenBSD'
ZhiweiWang/django-categories
refs/heads/master
categories/editor/templatetags/admin_tree_list_tags.py
8
import django from django.db import models from django.template import Library from django.contrib.admin.templatetags.admin_list import result_headers, _boolean_icon try: from django.contrib.admin.util import lookup_field, display_for_field, label_for_field except ImportError: from categories.editor.utils import lookup_field, display_for_field, label_for_field from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE from django.core.exceptions import ObjectDoesNotExist from django.utils.encoding import smart_unicode, force_unicode from django.utils.html import escape, conditional_escape from django.utils.safestring import mark_safe from categories.editor import settings register = Library() TREE_LIST_RESULTS_TEMPLATE = 'admin/editor/tree_list_results.html' if settings.IS_GRAPPELLI_INSTALLED: TREE_LIST_RESULTS_TEMPLATE = 'admin/editor/grappelli_tree_list_results.html' def items_for_tree_result(cl, result, form): """ Generates the actual list of data. """ first = True pk = cl.lookup_opts.pk.attname for field_name in cl.list_display: row_class = '' try: f, attr, value = lookup_field(field_name, result, cl.model_admin) except (AttributeError, ObjectDoesNotExist): result_repr = EMPTY_CHANGELIST_VALUE else: if f is None: if django.VERSION[1] == 4: if field_name == 'action_checkbox': row_class = ' class="action-checkbox disclosure"' allow_tags = getattr(attr, 'allow_tags', False) boolean = getattr(attr, 'boolean', False) if boolean: allow_tags = True result_repr = _boolean_icon(value) else: result_repr = smart_unicode(value) # Strip HTML tags in the resulting text, except if the # function has an "allow_tags" attribute set to True. if not allow_tags: result_repr = escape(result_repr) else: result_repr = mark_safe(result_repr) else: if value is None: result_repr = EMPTY_CHANGELIST_VALUE if isinstance(f.rel, models.ManyToOneRel): result_repr = escape(getattr(result, f.name)) else: result_repr = display_for_field(value, f) if isinstance(f, models.DateField) or isinstance(f, models.TimeField): row_class = ' class="nowrap"' if first: if django.VERSION[1] < 4: try: f, attr, checkbox_value = lookup_field('action_checkbox', result, cl.model_admin) if row_class: row_class = "%s%s" % (row_class[:-1], ' disclosure"') else: row_class = ' class="disclosure"' except (AttributeError, ObjectDoesNotExist): pass if force_unicode(result_repr) == '': result_repr = mark_safe('&nbsp;') # If list_display_links not defined, add the link tag to the first field if (first and not cl.list_display_links) or field_name in cl.list_display_links: if django.VERSION[1] < 4: table_tag = 'td' # {True:'th', False:'td'}[first] else: table_tag = {True: 'th', False: 'td'}[first] url = cl.url_for_result(result) # Convert the pk to something that can be used in Javascript. # Problem cases are long ints (23L) and non-ASCII strings. if cl.to_field: attr = str(cl.to_field) else: attr = pk value = result.serializable_value(attr) result_id = repr(force_unicode(value))[1:] first = False if django.VERSION[1] < 4: yield mark_safe(u'<%s%s>%s<a href="%s"%s>%s</a></%s>' % \ (table_tag, row_class, checkbox_value, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: yield mark_safe(u'<%s%s><a href="%s"%s>%s</a></%s>' % \ (table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag)) else: # By default the fields come from ModelAdmin.list_editable, but if we pull # the fields out of the form instead of list_editable custom admins # can provide fields on a per request basis if form and field_name in form.fields: bf = form[field_name] result_repr = mark_safe(force_unicode(bf.errors) + force_unicode(bf)) else: result_repr = conditional_escape(result_repr) yield mark_safe(u'<td%s>%s</td>' % (row_class, result_repr)) if form and not form[cl.model._meta.pk.name].is_hidden: yield mark_safe(u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name])) class TreeList(list): pass def tree_results(cl): if cl.formset: for res, form in zip(cl.result_list, cl.formset.forms): result = TreeList(items_for_tree_result(cl, res, form)) if hasattr(res, 'pk'): result.pk = res.pk if res.parent: result.parent_pk = res.parent.pk else: res.parent_pk = None yield result else: for res in cl.result_list: result = TreeList(items_for_tree_result(cl, res, None)) if hasattr(res, 'pk'): result.pk = res.pk if res.parent: result.parent_pk = res.parent.pk else: res.parent_pk = None yield result def result_tree_list(cl): """ Displays the headers and data list together """ import django result = {'cl': cl, 'result_headers': list(result_headers(cl)), 'results': list(tree_results(cl))} if django.VERSION[1] > 2: from django.contrib.admin.templatetags.admin_list import result_hidden_fields result['result_hidden_fields'] = list(result_hidden_fields(cl)) return result result_tree_list = register.inclusion_tag(TREE_LIST_RESULTS_TEMPLATE)(result_tree_list)
cstipkovic/spidermonkey-research
refs/heads/master
testing/puppeteer/firefox/firefox_puppeteer/ui/deck.py
1
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. from firefox_puppeteer.ui_base_lib import UIBaseLib class Panel(UIBaseLib): def __eq__(self, other): return self.element.get_attribute('id') == other.element.get_attribute('id') def __ne__(self, other): return self.element.get_attribute('id') != other.element.get_attribute('id') def __str__(self): return self.element.get_attribute('id')
Metaswitch/gmock-upstream
refs/heads/master
gtest/test/gtest_xml_output_unittest.py
1815
#!/usr/bin/env python # # Copyright 2006, 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. """Unit test for the gtest_xml_output module""" __author__ = 'eefacm@gmail.com (Sean Mcafee)' import datetime import errno import os import re import sys from xml.dom import minidom, Node import gtest_test_utils import gtest_xml_test_utils GTEST_FILTER_FLAG = '--gtest_filter' GTEST_LIST_TESTS_FLAG = '--gtest_list_tests' GTEST_OUTPUT_FLAG = "--gtest_output" GTEST_DEFAULT_OUTPUT_FILE = "test_detail.xml" GTEST_PROGRAM_NAME = "gtest_xml_output_unittest_" SUPPORTS_STACK_TRACES = False if SUPPORTS_STACK_TRACES: STACK_TRACE_TEMPLATE = '\nStack trace:\n*' else: STACK_TRACE_TEMPLATE = '' EXPECTED_NON_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="23" failures="4" disabled="2" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> </testsuite> <testsuite name="FailedTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="Fails" status="run" time="*" classname="FailedTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Value of: 2 Expected: 1%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="MixedResultTest" tests="3" failures="1" disabled="1" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="MixedResultTest"/> <testcase name="Fails" status="run" time="*" classname="MixedResultTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 2&#x0A;Expected: 1" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Value of: 2 Expected: 1%(stack)s]]></failure> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Value of: 3&#x0A;Expected: 2" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Value of: 3 Expected: 2%(stack)s]]></failure> </testcase> <testcase name="DISABLED_test" status="notrun" time="*" classname="MixedResultTest"/> </testsuite> <testsuite name="XmlQuotingTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="OutputsCData" status="run" time="*" classname="XmlQuotingTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed XML output: <?xml encoding="utf-8"><top><![CDATA[cdata text]]>]]&gt;<![CDATA[</top>%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="InvalidCharactersTest" tests="1" failures="1" disabled="0" errors="0" time="*"> <testcase name="InvalidCharactersInMessage" status="run" time="*" classname="InvalidCharactersTest"> <failure message="gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []" type=""><![CDATA[gtest_xml_output_unittest_.cc:* Failed Invalid characters in brackets []%(stack)s]]></failure> </testcase> </testsuite> <testsuite name="DisabledTest" tests="1" failures="0" disabled="1" errors="0" time="*"> <testcase name="DISABLED_test_not_run" status="notrun" time="*" classname="DisabledTest"/> </testsuite> <testsuite name="PropertyRecordingTest" tests="4" failures="0" disabled="0" errors="0" time="*" SetUpTestCase="yes" TearDownTestCase="aye"> <testcase name="OneProperty" status="run" time="*" classname="PropertyRecordingTest" key_1="1"/> <testcase name="IntValuedProperty" status="run" time="*" classname="PropertyRecordingTest" key_int="1"/> <testcase name="ThreeProperties" status="run" time="*" classname="PropertyRecordingTest" key_1="1" key_2="2" key_3="3"/> <testcase name="TwoValuesForOneKeyUsesLastValue" status="run" time="*" classname="PropertyRecordingTest" key_1="2"/> </testsuite> <testsuite name="NoFixtureTest" tests="3" failures="0" disabled="0" errors="0" time="*"> <testcase name="RecordProperty" status="run" time="*" classname="NoFixtureTest" key="1"/> <testcase name="ExternalUtilityThatCallsRecordIntValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_int="1"/> <testcase name="ExternalUtilityThatCallsRecordStringValuedProperty" status="run" time="*" classname="NoFixtureTest" key_for_utility_string="1"/> </testsuite> <testsuite name="Single/ValueParamTest" tests="4" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="HasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="AnotherTestThatHasValueParamAttribute/0" value_param="33" status="run" time="*" classname="Single/ValueParamTest" /> <testcase name="AnotherTestThatHasValueParamAttribute/1" value_param="42" status="run" time="*" classname="Single/ValueParamTest" /> </testsuite> <testsuite name="TypedTest/0" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/0" /> </testsuite> <testsuite name="TypedTest/1" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="TypedTest/1" /> </testsuite> <testsuite name="Single/TypeParameterizedTestCase/0" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/0" /> </testsuite> <testsuite name="Single/TypeParameterizedTestCase/1" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="HasTypeParamAttribute" type_param="*" status="run" time="*" classname="Single/TypeParameterizedTestCase/1" /> </testsuite> </testsuites>""" % {'stack': STACK_TRACE_TEMPLATE} EXPECTED_FILTERED_TEST_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests" ad_hoc_property="42"> <testsuite name="SuccessfulTest" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="Succeeds" status="run" time="*" classname="SuccessfulTest"/> </testsuite> </testsuites>""" EXPECTED_EMPTY_XML = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="0" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> </testsuites>""" GTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME) SUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess( [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output class GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase): """ Unit test for Google Test's XML output functionality. """ # This test currently breaks on platforms that do not support typed and # type-parameterized tests, so we don't run it under them. if SUPPORTS_TYPED_TESTS: def testNonEmptyXmlOutput(self): """ Runs a test program that generates a non-empty XML output, and tests that the XML output is expected. """ self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1) def testEmptyXmlOutput(self): """Verifies XML output for a Google Test binary without actual tests. Runs a test program that generates an empty XML output, and tests that the XML output is expected. """ self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_EMPTY_XML, 0) def testTimestampValue(self): """Checks whether the timestamp attribute in the XML output is valid. Runs a test program that generates an empty XML output, and checks if the timestamp attribute in the testsuites tag is valid. """ actual = self._GetXmlOutput('gtest_no_test_unittest', [], 0) date_time_str = actual.documentElement.getAttributeNode('timestamp').value # datetime.strptime() is only available in Python 2.5+ so we have to # parse the expected datetime manually. match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str) self.assertTrue( re.match, 'XML datettime string %s has incorrect format' % date_time_str) date_time_from_xml = datetime.datetime( year=int(match.group(1)), month=int(match.group(2)), day=int(match.group(3)), hour=int(match.group(4)), minute=int(match.group(5)), second=int(match.group(6))) time_delta = abs(datetime.datetime.now() - date_time_from_xml) # timestamp value should be near the current local time self.assertTrue(time_delta < datetime.timedelta(seconds=600), 'time_delta is %s' % time_delta) actual.unlink() def testDefaultOutputFile(self): """ Confirms that Google Test produces an XML output file with the expected default name if no name is explicitly specified. """ output_file = os.path.join(gtest_test_utils.GetTempDir(), GTEST_DEFAULT_OUTPUT_FILE) gtest_prog_path = gtest_test_utils.GetTestExecutablePath( 'gtest_no_test_unittest') try: os.remove(output_file) except OSError, e: if e.errno != errno.ENOENT: raise p = gtest_test_utils.Subprocess( [gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG], working_dir=gtest_test_utils.GetTempDir()) self.assert_(p.exited) self.assertEquals(0, p.exit_code) self.assert_(os.path.isfile(output_file)) def testSuppressedXmlOutput(self): """ Tests that no XML file is generated if the default XML listener is shut down before RUN_ALL_TESTS is invoked. """ xml_path = os.path.join(gtest_test_utils.GetTempDir(), GTEST_PROGRAM_NAME + 'out.xml') if os.path.isfile(xml_path): os.remove(xml_path) command = [GTEST_PROGRAM_PATH, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path), '--shut_down_xml'] p = gtest_test_utils.Subprocess(command) if p.terminated_by_signal: # p.signal is avalable only if p.terminated_by_signal is True. self.assertFalse( p.terminated_by_signal, '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal)) else: self.assert_(p.exited) self.assertEquals(1, p.exit_code, "'%s' exited with code %s, which doesn't match " 'the expected exit code %s.' % (command, p.exit_code, 1)) self.assert_(not os.path.isfile(xml_path)) def testFilteredTestXmlOutput(self): """Verifies XML output when a filter is applied. Runs a test program that executes only some tests and verifies that non-selected tests do not show up in the XML output. """ self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0, extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG]) def _GetXmlOutput(self, gtest_prog_name, extra_args, expected_exit_code): """ Returns the xml output generated by running the program gtest_prog_name. Furthermore, the program's exit code must be expected_exit_code. """ xml_path = os.path.join(gtest_test_utils.GetTempDir(), gtest_prog_name + 'out.xml') gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name) command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] + extra_args) p = gtest_test_utils.Subprocess(command) if p.terminated_by_signal: self.assert_(False, '%s was killed by signal %d' % (gtest_prog_name, p.signal)) else: self.assert_(p.exited) self.assertEquals(expected_exit_code, p.exit_code, "'%s' exited with code %s, which doesn't match " 'the expected exit code %s.' % (command, p.exit_code, expected_exit_code)) actual = minidom.parse(xml_path) return actual def _TestXmlOutput(self, gtest_prog_name, expected_xml, expected_exit_code, extra_args=None): """ Asserts that the XML document generated by running the program gtest_prog_name matches expected_xml, a string containing another XML document. Furthermore, the program's exit code must be expected_exit_code. """ actual = self._GetXmlOutput(gtest_prog_name, extra_args or [], expected_exit_code) expected = minidom.parseString(expected_xml) self.NormalizeXml(actual.documentElement) self.AssertEquivalentNodes(expected.documentElement, actual.documentElement) expected.unlink() actual.unlink() if __name__ == '__main__': os.environ['GTEST_STACK_TRACE_DEPTH'] = '1' gtest_test_utils.Main()
akhmadMizkat/odoo
refs/heads/master
addons/sale_timesheet/models/__init__.py
2
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import sale_timesheet import sale_service
bjori/grpc
refs/heads/master
src/python/grpcio_test/setup.py
3
# Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """A setup module for the GRPC Python interop testing package.""" import os import os.path import setuptools # Ensure we're in the proper directory whether or not we're being used by pip. os.chdir(os.path.dirname(os.path.abspath(__file__))) # Break import-style to ensure we can actually find our commands module. import commands _PACKAGES = setuptools.find_packages('.', exclude=['*._cython', '*._cython.*']) _PACKAGE_DIRECTORIES = { '': '.', } _PACKAGE_DATA = { 'grpc_interop': [ 'credentials/ca.pem', 'credentials/server1.key', 'credentials/server1.pem', ], 'grpc_protoc_plugin': [ 'test.proto', ], 'grpc_test': [ 'credentials/ca.pem', 'credentials/server1.key', 'credentials/server1.pem', ], } _SETUP_REQUIRES = ( 'pytest>=2.6', 'pytest-cov>=2.0', 'pytest-xdist>=1.11', 'pytest-timeout>=0.5', ) _INSTALL_REQUIRES = ( 'oauth2client>=1.4.7', 'grpcio>=0.11.0b0', # TODO(issue 3321): Unpin protobuf dependency. 'protobuf==3.0.0a3', ) _COMMAND_CLASS = { 'test': commands.RunTests } setuptools.setup( name='grpcio_test', version='0.11.0b0', packages=_PACKAGES, package_dir=_PACKAGE_DIRECTORIES, package_data=_PACKAGE_DATA, install_requires=_INSTALL_REQUIRES + _SETUP_REQUIRES, setup_requires=_SETUP_REQUIRES, cmdclass=_COMMAND_CLASS, )
Spe1/android
refs/heads/master
user_manual/conf.py
58
# -*- coding: utf-8 -*- # # ownCloud Documentation documentation build configuration file, created by # sphinx-quickstart on Mon Oct 22 23:16:40 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os, inspect # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) #path to this script scriptpath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo'] # Add any paths that contain templates here, relative to this directory. templates_path = [scriptpath+'/ocdoc/_shared_assets/templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'ownCloud Android App Manual' copyright = u'2013-2015, The ownCloud developers' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.6.2' # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build','scripts/*', 'ocdoc/*'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True 2 # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [scriptpath+'/ocdoc/_shared_assets/themes'] # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. #html_theme = 'bootstrap' html_theme = 'default' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. html_short_title = "Android App Manual" # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [scriptpath+'/ocdoc/_shared_assets/static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'ownCloudAndroidAppManual' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'ownCloudAndroidAppManual.tex', u'ownCloud Android App Manual', u'The ownCloud developers', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('owncloud.1', 'owncloud', u'Android synchronisation and file management utility.', [u'The ownCloud developers'], 1), ('owncloudcmd.1', 'owncloudcmd', u'ownCloud Android app.', [u'The ownCloud developers'], 1), ] # If true, show URL addresses after external links. man_show_urls = True # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'ownCloudClientManual', u'ownCloud Android App Manual', u'The ownCloud developers', 'ownCloud', 'The ownCloud Android App Manual.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'ownCloud Android App Manual' epub_author = u'The ownCloud developers' epub_publisher = u'The ownCloud developers' epub_copyright = u'2013-2015, The ownCloud developers' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Include todos? todo_include_todos = True
lucafavatella/intellij-community
refs/heads/cli-wip
python/lib/Lib/site-packages/django/contrib/localflavor/au/au_states.py
544
""" An alphabetical list of states for use as `choices` in a formfield. This exists in this standalone file so that it's only imported into memory when explicitly needed. """ STATE_CHOICES = ( ('ACT', 'Australian Capital Territory'), ('NSW', 'New South Wales'), ('NT', 'Northern Territory'), ('QLD', 'Queensland'), ('SA', 'South Australia'), ('TAS', 'Tasmania'), ('VIC', 'Victoria'), ('WA', 'Western Australia'), )
vincent-fei/cobbler
refs/heads/master
cobbler/configgen.py
16
""" configgen.py: Generate configuration data. Copyright 2010 Kelsey Hightower Kelsey Hightower <kelsey.hightower@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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA module for generating configuration manifest using autoinstall_meta data, mgmtclasses, resources, and templates for a given system (hostname) """ from Cheetah.Template import Template import simplejson as json import string from cexceptions import CX import clogger import cobbler.api as capi import cobbler.utils import utils class ConfigGen: """ Generate configuration data for Cobbler's management resources: repos, files and packages. Mainly used by Koan to configure systems. """ def __init__(self, hostname): """Constructor. Requires a Cobbler API handle.""" self.hostname = hostname self.handle = capi.CobblerAPI() self.system = self.handle.find_system(hostname=self.hostname) self.host_vars = self.get_cobbler_resource('autoinstall_meta') self.logger = clogger.Logger("/var/log/cobbler/cobbler.log") self.mgmtclasses = self.get_cobbler_resource('mgmt_classes') # ---------------------------------------------------------------------- def resolve_resource_var(self, string_data): """Substitute variables in strings.""" data = string.Template(string_data).substitute(self.host_vars) return data # ---------------------------------------------------------------------- def resolve_resource_list(self, list_data): """Substitute variables in lists. Return new list.""" new_list = [] for item in list_data: new_list.append(string.Template(item).substitute(self.host_vars)) return new_list # ---------------------------------------------------------------------- def get_cobbler_resource(self, resource): """Wrapper around cobbler blender method""" return cobbler.utils.blender(self.handle, False, self.system)[resource] # ---------------------------------------------------------------------- def gen_config_data(self): """ Generate configuration data for repos, files and packages. Returns a dict. """ config_data = { 'repo_data': self.handle.get_repo_config_for_system(self.system), 'repos_enabled': self.get_cobbler_resource('repos_enabled'), } package_set = set() file_set = set() for mgmtclass in self.mgmtclasses: _mgmtclass = self.handle.find_mgmtclass(name=mgmtclass) for package in _mgmtclass.packages: package_set.add(package) for file in _mgmtclass.files: file_set.add(file) # Generate Package data pkg_data = {} for package in package_set: _package = self.handle.find_package(name=package) if _package is None: raise CX('%s package resource is not defined' % package) else: pkg_data[package] = {} pkg_data[package]['action'] = self.resolve_resource_var(_package.action) pkg_data[package]['installer'] = _package.installer pkg_data[package]['version'] = self.resolve_resource_var(_package.version) if pkg_data[package]['version'] != "": pkg_data[package]["install_name"] = "%s-%s" % (package, pkg_data[package]['version']) else: pkg_data[package]["install_name"] = package config_data['packages'] = pkg_data # Generate File data file_data = {} for file in file_set: _file = self.handle.find_file(name=file) if _file is None: raise CX('%s file resource is not defined' % file) file_data[file] = {} file_data[file]['is_dir'] = _file.is_dir file_data[file]['action'] = self.resolve_resource_var(_file.action) file_data[file]['group'] = self.resolve_resource_var(_file.group) file_data[file]['mode'] = self.resolve_resource_var(_file.mode) file_data[file]['owner'] = self.resolve_resource_var(_file.owner) file_data[file]['path'] = self.resolve_resource_var(_file.path) if not _file.is_dir: file_data[file]['template'] = self.resolve_resource_var(_file.template) try: t = Template(file=file_data[file]['template'], searchList=[self.host_vars]) file_data[file]['content'] = t.respond() except: utils.die(self.logger, "Missing template for this file resource %s" % (file_data[file])) config_data['files'] = file_data return config_data # ---------------------------------------------------------------------- def gen_config_data_for_koan(self): """Encode configuration data. Return json object for Koan.""" json_config_data = json.JSONEncoder(sort_keys=True, indent=4).encode(self.gen_config_data()) return json_config_data
qantravon/gamers-galore
refs/heads/master
GUI/urllib3/contrib/ntlmpool.py
714
# urllib3/contrib/ntlmpool.py # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ NTLM authenticating pool, contributed by erikcederstran Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 """ try: from http.client import HTTPSConnection except ImportError: from httplib import HTTPSConnection from logging import getLogger from ntlm import ntlm from urllib3 import HTTPSConnectionPool log = getLogger(__name__) class NTLMConnectionPool(HTTPSConnectionPool): """ Implements an NTLM authentication version of an urllib3 connection pool """ scheme = 'https' def __init__(self, user, pw, authurl, *args, **kwargs): """ authurl is a random URL on the server that is protected by NTLM. user is the Windows user, probably in the DOMAIN\\username format. pw is the password for the user. """ super(NTLMConnectionPool, self).__init__(*args, **kwargs) self.authurl = authurl self.rawuser = user user_parts = user.split('\\', 1) self.domain = user_parts[0].upper() self.user = user_parts[1] self.pw = pw def _new_conn(self): # Performs the NTLM handshake that secures the connection. The socket # must be kept open while requests are performed. self.num_connections += 1 log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' % (self.num_connections, self.host, self.authurl)) headers = {} headers['Connection'] = 'Keep-Alive' req_header = 'Authorization' resp_header = 'www-authenticate' conn = HTTPSConnection(host=self.host, port=self.port) # Send negotiation message headers[req_header] = ( 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser)) log.debug('Request headers: %s' % headers) conn.request('GET', self.authurl, None, headers) res = conn.getresponse() reshdr = dict(res.getheaders()) log.debug('Response status: %s %s' % (res.status, res.reason)) log.debug('Response headers: %s' % reshdr) log.debug('Response data: %s [...]' % res.read(100)) # Remove the reference to the socket, so that it can not be closed by # the response object (we want to keep the socket open) res.fp = None # Server should respond with a challenge message auth_header_values = reshdr[resp_header].split(', ') auth_header_value = None for s in auth_header_values: if s[:5] == 'NTLM ': auth_header_value = s[5:] if auth_header_value is None: raise Exception('Unexpected %s response header: %s' % (resp_header, reshdr[resp_header])) # Send authentication message ServerChallenge, NegotiateFlags = \ ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value) auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags) headers[req_header] = 'NTLM %s' % auth_msg log.debug('Request headers: %s' % headers) conn.request('GET', self.authurl, None, headers) res = conn.getresponse() log.debug('Response status: %s %s' % (res.status, res.reason)) log.debug('Response headers: %s' % dict(res.getheaders())) log.debug('Response data: %s [...]' % res.read()[:100]) if res.status != 200: if res.status == 401: raise Exception('Server rejected request: wrong ' 'username or password') raise Exception('Wrong server response: %s %s' % (res.status, res.reason)) res.fp = None log.debug('Connection established') return conn def urlopen(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True): if headers is None: headers = {} headers['Connection'] = 'Keep-Alive' return super(NTLMConnectionPool, self).urlopen(method, url, body, headers, retries, redirect, assert_same_host)
longmen21/edx-platform
refs/heads/master
common/lib/xmodule/xmodule/modulestore/split_mongo/caching_descriptor_system.py
21
import sys import logging from contracts import contract, new_contract from fs.osfs import OSFS from lazy import lazy from xblock.runtime import KvsFieldData, KeyValueStore from xblock.fields import ScopeIds from xblock.core import XBlock from opaque_keys.edx.locator import BlockUsageLocator, LocalId, CourseLocator, LibraryLocator, DefinitionLocator from xmodule.library_tools import LibraryToolsService from xmodule.mako_module import MakoDescriptorSystem from xmodule.error_module import ErrorDescriptor from xmodule.errortracker import exc_info_to_str from xmodule.modulestore import BlockData from xmodule.modulestore.edit_info import EditInfoRuntimeMixin from xmodule.modulestore.exceptions import ItemNotFoundError from xmodule.modulestore.inheritance import inheriting_field_data, InheritanceMixin from xmodule.modulestore.split_mongo import BlockKey, CourseEnvelope from xmodule.modulestore.split_mongo.id_manager import SplitMongoIdManager from xmodule.modulestore.split_mongo.definition_lazy_loader import DefinitionLazyLoader from xmodule.modulestore.split_mongo.split_mongo_kvs import SplitMongoKVS from xmodule.x_module import XModuleMixin log = logging.getLogger(__name__) new_contract('BlockUsageLocator', BlockUsageLocator) new_contract('CourseLocator', CourseLocator) new_contract('LibraryLocator', LibraryLocator) new_contract('BlockKey', BlockKey) new_contract('BlockData', BlockData) new_contract('CourseEnvelope', CourseEnvelope) new_contract('XBlock', XBlock) class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): """ A system that has a cache of a course version's json that it will use to load modules from, with a backup of calling to the underlying modulestore for more data. Computes the settings (nee 'metadata') inheritance upon creation. """ @contract(course_entry=CourseEnvelope) def __init__(self, modulestore, course_entry, default_class, module_data, lazy, **kwargs): """ Computes the settings inheritance and sets up the cache. modulestore: the module store that can be used to retrieve additional modules course_entry: the originally fetched enveloped course_structure w/ branch and course id info. Callers to _load_item provide an override but that function ignores the provided structure and only looks at the branch and course id module_data: a dict mapping Location -> json that was cached from the underlying modulestore """ # needed by capa_problem (as runtime.filestore via this.resources_fs) if course_entry.course_key.course: root = modulestore.fs_root / course_entry.course_key.org / course_entry.course_key.course / course_entry.course_key.run else: root = modulestore.fs_root / str(course_entry.structure['_id']) root.makedirs_p() # create directory if it doesn't exist id_manager = SplitMongoIdManager(self) kwargs.setdefault('id_reader', id_manager) kwargs.setdefault('id_generator', id_manager) super(CachingDescriptorSystem, self).__init__( field_data=None, load_item=self._load_item, resources_fs=OSFS(root), **kwargs ) self.modulestore = modulestore self.course_entry = course_entry # set course_id attribute to avoid problems with subsystems that expect # it here. (grading, for example) self.course_id = course_entry.course_key self.lazy = lazy self.module_data = module_data self.default_class = default_class self.local_modules = {} self._services['library_tools'] = LibraryToolsService(modulestore) @lazy @contract(returns="dict(BlockKey: BlockKey)") def _parent_map(self): parent_map = {} for block_key, block in self.course_entry.structure['blocks'].iteritems(): for child in block.fields.get('children', []): parent_map[child] = block_key return parent_map @contract(usage_key="BlockUsageLocator | BlockKey", course_entry_override="CourseEnvelope | None") def _load_item(self, usage_key, course_entry_override=None, **kwargs): """ Instantiate the xblock fetching it either from the cache or from the structure :param course_entry_override: the course_info with the course_key to use (defaults to cached) """ # usage_key is either a UsageKey or just the block_key. if a usage_key, if isinstance(usage_key, BlockUsageLocator): # trust the passed in key to know the caller's expectations of which fields are filled in. # particularly useful for strip_keys so may go away when we're version aware course_key = usage_key.course_key if isinstance(usage_key.block_id, LocalId): try: return self.local_modules[usage_key] except KeyError: raise ItemNotFoundError else: block_key = BlockKey.from_usage_key(usage_key) version_guid = self.course_entry.course_key.version_guid else: block_key = usage_key course_info = course_entry_override or self.course_entry course_key = course_info.course_key version_guid = course_key.version_guid # look in cache cached_module = self.modulestore.get_cached_block(course_key, version_guid, block_key) if cached_module: return cached_module block_data = self.get_module_data(block_key, course_key) class_ = self.load_block_type(block_data.block_type) block = self.xblock_from_json(class_, course_key, block_key, block_data, course_entry_override, **kwargs) self.modulestore.cache_block(course_key, version_guid, block_key, block) return block @contract(block_key=BlockKey, course_key="CourseLocator | LibraryLocator") def get_module_data(self, block_key, course_key): """ Get block from module_data adding it to module_data if it's not already there but is in the structure Raises: ItemNotFoundError if block is not in the structure """ json_data = self.module_data.get(block_key) if json_data is None: # deeper than initial descendant fetch or doesn't exist self.modulestore.cache_items(self, [block_key], course_key, lazy=self.lazy) json_data = self.module_data.get(block_key) if json_data is None: raise ItemNotFoundError(block_key) return json_data # xblock's runtime does not always pass enough contextual information to figure out # which named container (course x branch) or which parent is requesting an item. Because split allows # a many:1 mapping from named containers to structures and because item's identities encode # context as well as unique identity, this function must sometimes infer whether the access is # within an unspecified named container. In most cases, course_entry_override will give the # explicit context; however, runtime.get_block(), e.g., does not. HOWEVER, there are simple heuristics # which will work 99.999% of the time: a runtime is thread & even context specific. The likelihood that # the thread is working with more than one named container pointing to the same specific structure is # low; thus, the course_entry is most likely correct. If the thread is looking at > 1 named container # pointing to the same structure, the access is likely to be chunky enough that the last known container # is the intended one when not given a course_entry_override; thus, the caching of the last branch/course id. @contract(block_key="BlockKey | None") def xblock_from_json(self, class_, course_key, block_key, block_data, course_entry_override=None, **kwargs): """ Load and return block info. """ if course_entry_override is None: course_entry_override = self.course_entry else: # most recent retrieval is most likely the right one for next caller (see comment above fn) self.course_entry = CourseEnvelope(course_entry_override.course_key, self.course_entry.structure) definition_id = block_data.definition # If no usage id is provided, generate an in-memory id if block_key is None: block_key = BlockKey(block_data.block_type, LocalId()) convert_fields = lambda field: self.modulestore.convert_references_to_keys( course_key, class_, field, self.course_entry.structure['blocks'], ) if definition_id is not None and not block_data.definition_loaded: definition_loader = DefinitionLazyLoader( self.modulestore, course_key, block_key.type, definition_id, convert_fields, ) else: definition_loader = None # If no definition id is provide, generate an in-memory id if definition_id is None: definition_id = LocalId() # Construct the Block Usage Locator: block_locator = course_key.make_usage_key( block_type=block_key.type, block_id=block_key.id, ) converted_fields = convert_fields(block_data.fields) converted_defaults = convert_fields(block_data.defaults) if block_key in self._parent_map: parent_key = self._parent_map[block_key] parent = course_key.make_usage_key(parent_key.type, parent_key.id) else: parent = None aside_fields = None # for the situation if block_data has no asides attribute # (in case it was taken from memcache) try: if block_data.asides: aside_fields = {block_key.type: {}} for aside in block_data.asides: aside_fields[block_key.type].update(aside['fields']) except AttributeError: pass try: kvs = SplitMongoKVS( definition_loader, converted_fields, converted_defaults, parent=parent, aside_fields=aside_fields, field_decorator=kwargs.get('field_decorator') ) if InheritanceMixin in self.modulestore.xblock_mixins: field_data = inheriting_field_data(kvs) else: field_data = KvsFieldData(kvs) module = self.construct_xblock_from_class( class_, ScopeIds(None, block_key.type, definition_id, block_locator), field_data, for_parent=kwargs.get('for_parent') ) except Exception: # pylint: disable=broad-except log.warning("Failed to load descriptor", exc_info=True) return ErrorDescriptor.from_json( block_data, self, course_entry_override.course_key.make_usage_key( block_type='error', block_id=block_key.id ), error_msg=exc_info_to_str(sys.exc_info()) ) edit_info = block_data.edit_info module._edited_by = edit_info.edited_by # pylint: disable=protected-access module._edited_on = edit_info.edited_on # pylint: disable=protected-access module.previous_version = edit_info.previous_version module.update_version = edit_info.update_version module.source_version = edit_info.source_version module.definition_locator = DefinitionLocator(block_key.type, definition_id) for wrapper in self.modulestore.xblock_field_data_wrappers: module._field_data = wrapper(module, module._field_data) # pylint: disable=protected-access # decache any pending field settings module.save() # If this is an in-memory block, store it in this system if isinstance(block_locator.block_id, LocalId): self.local_modules[block_locator] = module return module def get_edited_by(self, xblock): """ See :meth: cms.lib.xblock.runtime.EditInfoRuntimeMixin.get_edited_by """ return xblock._edited_by def get_edited_on(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ return xblock._edited_on @contract(xblock='XBlock') def get_subtree_edited_by(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ # pylint: disable=protected-access if not hasattr(xblock, '_subtree_edited_by'): block_data = self.module_data[BlockKey.from_usage_key(xblock.location)] if block_data.edit_info._subtree_edited_by is None: self._compute_subtree_edited_internal( block_data, xblock.location.course_key ) xblock._subtree_edited_by = block_data.edit_info._subtree_edited_by return xblock._subtree_edited_by @contract(xblock='XBlock') def get_subtree_edited_on(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ # pylint: disable=protected-access if not hasattr(xblock, '_subtree_edited_on'): block_data = self.module_data[BlockKey.from_usage_key(xblock.location)] if block_data.edit_info._subtree_edited_on is None: self._compute_subtree_edited_internal( block_data, xblock.location.course_key ) xblock._subtree_edited_on = block_data.edit_info._subtree_edited_on return xblock._subtree_edited_on def get_published_by(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ if not hasattr(xblock, '_published_by'): self.modulestore.compute_published_info_internal(xblock) return getattr(xblock, '_published_by', None) def get_published_on(self, xblock): """ See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin """ if not hasattr(xblock, '_published_on'): self.modulestore.compute_published_info_internal(xblock) return getattr(xblock, '_published_on', None) @contract(block_data='BlockData') def _compute_subtree_edited_internal(self, block_data, course_key): """ Recurse the subtree finding the max edited_on date and its corresponding edited_by. Cache it. """ # pylint: disable=protected-access max_date = block_data.edit_info.edited_on max_date_by = block_data.edit_info.edited_by for child in block_data.fields.get('children', []): child_data = self.get_module_data(BlockKey(*child), course_key) if block_data.edit_info._subtree_edited_on is None: self._compute_subtree_edited_internal(child_data, course_key) if child_data.edit_info._subtree_edited_on > max_date: max_date = child_data.edit_info._subtree_edited_on max_date_by = child_data.edit_info._subtree_edited_by block_data.edit_info._subtree_edited_on = max_date block_data.edit_info._subtree_edited_by = max_date_by def get_aside_of_type(self, block, aside_type): """ See `runtime.Runtime.get_aside_of_type` This override adds the field data from the block to the aside """ asides_cached = block.get_asides() if isinstance(block, XModuleMixin) else None if asides_cached: for aside in asides_cached: if aside.scope_ids.block_type == aside_type: return aside new_aside = super(CachingDescriptorSystem, self).get_aside_of_type(block, aside_type) new_aside._field_data = block._field_data # pylint: disable=protected-access for key, _ in new_aside.fields.iteritems(): if isinstance(key, KeyValueStore.Key) and block._field_data.has(new_aside, key): # pylint: disable=protected-access try: value = block._field_data.get(new_aside, key) # pylint: disable=protected-access except KeyError: pass else: setattr(new_aside, key, value) block.add_aside(new_aside) return new_aside
marwoodandrew/superdesk-core
refs/heads/master
apps/publish/publish_service_tests.py
7
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014, 2015 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license from bson import ObjectId from nose.tools import assert_raises from apps.publish import init_app from superdesk.errors import PublishQueueError from superdesk.publish import SUBSCRIBER_TYPES from superdesk.publish.publish_service import PublishService from superdesk.tests import TestCase class PublishServiceTests(TestCase): queue_items = [{"_id": "571075791d41c81e204c5c8c", "destination": {"name": "NITF", "delivery_type": "ftp", "format": "nitf", "config": {}}, "subscriber_id": "1", "state": "in-progress", "item_id": 1, "formatted_item": '' }] subscribers = [{"_id": "1", "name": "Test", "subscriber_type": SUBSCRIBER_TYPES.WIRE, "media_type": "media", "is_active": True, "sequence_num_settings": {"max": 10, "min": 1}, "critical_errors": {"9004": True}, "destinations": [{"name": "NITF", "delivery_type": "ftp", "format": "nitf", "config": {}}] }] def setUp(self): with self.app.app_context(): self.app.data.insert('subscribers', self.subscribers) self.queue_items[0]['_id'] = ObjectId(self.queue_items[0]['_id']) self.app.data.insert('publish_queue', self.queue_items) init_app(self.app) def test_close_subscriber_doesnt_close(self): with self.app.app_context(): subscriber = self.app.data.find('subscribers', None, None)[0] self.assertTrue(subscriber.get('is_active')) PublishService().close_transmitter(subscriber, PublishQueueError.unknown_format_error()) subscriber = self.app.data.find('subscribers', None, None)[0] self.assertTrue(subscriber.get('is_active')) def test_close_subscriber_does_close(self): with self.app.app_context(): subscriber = self.app.data.find('subscribers', None, None)[0] self.assertTrue(subscriber.get('is_active')) PublishService().close_transmitter(subscriber, PublishQueueError.bad_schedule_error()) subscriber = self.app.data.find('subscribers', None, None)[0] self.assertFalse(subscriber.get('is_active')) def test_transmit_closes_subscriber(self): def mock_transmit(*args): raise PublishQueueError.bad_schedule_error() with self.app.app_context(): subscriber = self.app.data.find('subscribers', None, None)[0] publish_service = PublishService() publish_service._transmit = mock_transmit with assert_raises(PublishQueueError): publish_service.transmit(self.queue_items[0]) subscriber = self.app.data.find('subscribers', None, None)[0] self.assertFalse(subscriber.get('is_active')) self.assertIsNotNone(subscriber.get('last_closed'))
gusai-francelabs/datafari
refs/heads/master
windows/python/Lib/idlelib/FileList.py
123
import os from Tkinter import * import tkMessageBox class FileList: # N.B. this import overridden in PyShellFileList. from idlelib.EditorWindow import EditorWindow def __init__(self, root): self.root = root self.dict = {} self.inversedict = {} self.vars = {} # For EditorWindow.getrawvar (shared Tcl variables) def open(self, filename, action=None): assert filename filename = self.canonize(filename) if os.path.isdir(filename): # This can happen when bad filename is passed on command line: tkMessageBox.showerror( "File Error", "%r is a directory." % (filename,), master=self.root) return None key = os.path.normcase(filename) if key in self.dict: edit = self.dict[key] edit.top.wakeup() return edit if action: # Don't create window, perform 'action', e.g. open in same window return action(filename) else: return self.EditorWindow(self, filename, key) def gotofileline(self, filename, lineno=None): edit = self.open(filename) if edit is not None and lineno is not None: edit.gotoline(lineno) def new(self, filename=None): return self.EditorWindow(self, filename) def close_all_callback(self, *args, **kwds): for edit in self.inversedict.keys(): reply = edit.close() if reply == "cancel": break return "break" def unregister_maybe_terminate(self, edit): try: key = self.inversedict[edit] except KeyError: print "Don't know this EditorWindow object. (close)" return if key: del self.dict[key] del self.inversedict[edit] if not self.inversedict: self.root.quit() def filename_changed_edit(self, edit): edit.saved_change_hook() try: key = self.inversedict[edit] except KeyError: print "Don't know this EditorWindow object. (rename)" return filename = edit.io.filename if not filename: if key: del self.dict[key] self.inversedict[edit] = None return filename = self.canonize(filename) newkey = os.path.normcase(filename) if newkey == key: return if newkey in self.dict: conflict = self.dict[newkey] self.inversedict[conflict] = None tkMessageBox.showerror( "Name Conflict", "You now have multiple edit windows open for %r" % (filename,), master=self.root) self.dict[newkey] = edit self.inversedict[edit] = newkey if key: try: del self.dict[key] except KeyError: pass def canonize(self, filename): if not os.path.isabs(filename): try: pwd = os.getcwd() except os.error: pass else: filename = os.path.join(pwd, filename) return os.path.normpath(filename) def _test(): from idlelib.EditorWindow import fixwordbreaks import sys root = Tk() fixwordbreaks(root) root.withdraw() flist = FileList(root) if sys.argv[1:]: for filename in sys.argv[1:]: flist.open(filename) else: flist.new() if flist.inversedict: root.mainloop() if __name__ == '__main__': _test()
HippieStation/HippieStation
refs/heads/master
tools/linux_build.py
4
#!/usr/bin/env python import subprocess import os import sys import argparse import time from subprocess import PIPE, STDOUT null = open("/dev/null", "wb") def wait(p): rc = p.wait() if rc != 0: p = play("sound/misc/compiler-failure.ogg") p.wait() assert p.returncode == 0 sys.exit(rc) def play(soundfile): p = subprocess.Popen(["play", soundfile], stdout=null, stderr=null) assert p.wait() == 0 return p def stage1(): p = subprocess.Popen("(cd tgui; /bin/bash ./build.sh)", shell=True) wait(p) play("sound/misc/compiler-stage1.ogg") def stage2(map): if map: txt = "-M{}".format(map) else: txt = '' args = "bash tools/travis/dm.sh {} hippiestation.dme".format(txt) print(args) p = subprocess.Popen(args, shell=True) wait(p) def stage3(profile_mode=False): start_time = time.time() play("sound/misc/compiler-stage2.ogg") logfile = open('server.log~','w') p = subprocess.Popen( "DreamDaemon hippiestation.dmb 25001 -trusted", shell=True, stdout=PIPE, stderr=STDOUT) try: while p.returncode is None: stdout = p.stdout.readline() if "Initializations complete" in stdout: play("sound/misc/server-ready.ogg") time_taken = time.time() - start_time print("{} seconds taken to fully start".format(time_taken)) if "Map is ready." in stdout: time_taken = time.time() - start_time print("{} seconds for initial map loading".format(time_taken)) if profile_mode: return time_taken sys.stdout.write(stdout) sys.stdout.flush() logfile.write(stdout) finally: logfile.flush() os.fsync(logfile.fileno()) logfile.close() p.kill() def main(): parser = argparse.ArgumentParser() parser.add_argument('-s','---stage',default=1,type=int) parser.add_argument('--only',action='store_true') parser.add_argument('-m','--map',type=str) parser.add_argument('--profile-mode',action='store_true') args = parser.parse_args() stage = args.stage assert stage in (1,2,3) if stage == 1: stage1() if not args.only: stage = 2 if stage == 2: stage2(args.map) if not args.only: stage = 3 if stage == 3: value = stage3(profile_mode=args.profile_mode) with open('profile~', 'a') as f: f.write("{}\n".format(value)) if __name__=='__main__': try: main() except KeyboardInterrupt: pass
CloudNcodeInc/django-celery
refs/heads/3.1-dev
tests/someappwotask/views.py
6027
# Create your views here.
archen/django
refs/heads/master
django/contrib/redirects/tests.py
112
from django import http from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, modify_settings, override_settings from django.utils import six from .middleware import RedirectFallbackMiddleware from .models import Redirect @modify_settings(MIDDLEWARE_CLASSES={'append': 'django.contrib.redirects.middleware.RedirectFallbackMiddleware'}) @override_settings(APPEND_SLASH=False, SITE_ID=1) class RedirectTests(TestCase): def setUp(self): self.site = Site.objects.get(pk=settings.SITE_ID) def test_model(self): r1 = Redirect.objects.create( site=self.site, old_path='/initial', new_path='/new_target') self.assertEqual(six.text_type(r1), "/initial ---> /new_target") def test_redirect(self): Redirect.objects.create( site=self.site, old_path='/initial', new_path='/new_target') response = self.client.get('/initial') self.assertRedirects(response, '/new_target', status_code=301, target_status_code=404) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash(self): Redirect.objects.create( site=self.site, old_path='/initial/', new_path='/new_target/') response = self.client.get('/initial') self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash_and_query_string(self): Redirect.objects.create( site=self.site, old_path='/initial/?foo', new_path='/new_target/') response = self.client.get('/initial?foo') self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404) def test_response_gone(self): """When the redirect target is '', return a 410""" Redirect.objects.create( site=self.site, old_path='/initial', new_path='') response = self.client.get('/initial') self.assertEqual(response.status_code, 410) @modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}) def test_sites_not_installed(self): with self.assertRaises(ImproperlyConfigured): RedirectFallbackMiddleware() class OverriddenRedirectFallbackMiddleware(RedirectFallbackMiddleware): # Use HTTP responses different from the defaults response_gone_class = http.HttpResponseForbidden response_redirect_class = http.HttpResponseRedirect @modify_settings(MIDDLEWARE_CLASSES={'append': 'django.contrib.redirects.tests.OverriddenRedirectFallbackMiddleware'}) @override_settings(SITE_ID=1) class OverriddenRedirectMiddlewareTests(TestCase): def setUp(self): self.site = Site.objects.get(pk=settings.SITE_ID) def test_response_gone_class(self): Redirect.objects.create( site=self.site, old_path='/initial/', new_path='') response = self.client.get('/initial/') self.assertEqual(response.status_code, 403) def test_response_redirect_class(self): Redirect.objects.create( site=self.site, old_path='/initial/', new_path='/new_target/') response = self.client.get('/initial/') self.assertEqual(response.status_code, 302)
enixdark/10gen-Courses
refs/heads/master
Relational-SQL/DjangoBlog/Blog/forms.py
1
from .models import * from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.core import validators class UserForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput(),required=True) password_confirmation = forms.CharField(widget=forms.PasswordInput(),required=True) class Meta: model = User fields = ('username','email','password','password_confirmation') def clean(self): password = self.cleaned_data.get('password') password_confirmation = self.cleaned_data.get('password_confirmation') if password and password != password_confirmation: raise forms.ValidationError("Passwords don't match") return self.cleaned_data # class AuthorForm(ModelForm): # class Meta: # model = Author # fields = ('author_id','name','email','password') class CommentForm(ModelForm): name = forms.CharField(required=True) email = forms.EmailField(required=True) comment_text = forms.CharField(widget=forms.Textarea(),required=True) class Meta: model = Comment fields = ('name','email','comment_text') class PostForm(ModelForm): title = forms.CharField(required=True) body = forms.CharField(widget=forms.Textarea(),required=True) tag_id = forms.CharField(required=True) class Meta: model = Post fields = ('title','body','tag_id') class TagForm(ModelForm): class Meta: model = Tag fields = ('tag_id','name')
clumsy/intellij-community
refs/heads/master
python/testData/refactoring/introduceVariable/substringBeforeFormatTuple.py
83
print("<selection>Hello</selection> %s" % ("World",))
ed-/solum
refs/heads/master
solum/objects/sqlalchemy/migration/alembic_migrations/versions/450600086a09_add_user_logs_table.py
1
# Copyright 2014 - Rackspace # # 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. """Add user logs table Revision ID: 450600086a09 Revises: 498adc6185ae Create Date: 2014-09-29 20:43:55.544682 """ from alembic import op import sqlalchemy as sa from solum.openstack.common import timeutils # revision identifiers, used by Alembic. revision = '450600086a09' down_revision = '498adc6185ae' def upgrade(): op.create_table( 'userlogs', sa.Column('id', sa.Integer, primary_key=True, nullable=False), sa.Column('created_at', sa.DateTime, default=timeutils.utcnow, nullable=False), sa.Column('updated_at', sa.DateTime, default=timeutils.utcnow, nullable=False), sa.Column('assembly_uuid', sa.String(36), nullable=False), sa.Column('location', sa.String(255), nullable=False), sa.Column('strategy', sa.String(255), nullable=False), sa.Column('strategy_info', sa.String(1024), nullable=False), ) def downgrade(): op.drop_table('userlogs')
qpxu007/Flask-AppBuilder
refs/heads/master
examples/oauth/run.py
28
from app import app app.run(host='0.0.0.0', port=8080, debug=True)
wfxiang08/changes
refs/heads/master
changes/api/source_details.py
2
from __future__ import absolute_import, division, unicode_literals from changes.api.base import APIView from changes.models import Source from changes.lib.coverage import get_coverage_by_source_id import logging class SourceDetailsAPIView(APIView): # this is mostly copy-pasted from ProjectSourceDetails :( def get(self, source_id): source = Source.query.filter( Source.id == source_id, ).first() if source is None: return '', 404 context = self.serialize(source) diff = source.generate_diff() if diff: files = self._get_files_from_raw_diff(diff) coverage = { c.filename: c.data for c in get_coverage_by_source_id(source_id) if c.filename in files } coverage_for_added_lines = self._filter_coverage_for_added_lines(diff, coverage) tails_info = dict(source.data) else: coverage = None coverage_for_added_lines = None tails_info = None context['diff'] = diff context['coverage'] = coverage context['coverageForAddedLines'] = coverage_for_added_lines context['tailsInfo'] = tails_info return self.respond(context) def _filter_coverage_for_added_lines(self, diff, coverage): """ This function takes a diff (text based) and a map of file names to the coverage for those files and returns an ordered list of the coverage for each "addition" line in the diff. If we don't have coverage for a specific file, we just mark the lines in those files as unknown or 'N'. """ if not diff: return None # Let's just encode it as utf-8 just in case diff_lines = diff.encode('utf-8').splitlines() current_file = None line_number = None coverage_by_added_line = [] for line in diff_lines: if line.startswith('diff'): # We're about to start a new file. current_file = None line_number = None elif current_file is None and line_number is None and (line.startswith('+++') or line.startswith('---')): # We're starting a new file if line.startswith('+++ b/'): line = line.split('\t')[0] current_file = unicode(line[6:]) elif line.startswith('@@'): # Jump to new lines within the file line_num_info = line.split('+')[1] # Strip off the trailing ' @@' so that when only the line is specified # and there is no comma, we can just parse as a number. line_num_info = line_num_info.rstrip("@ ") line_number = int(line_num_info.split(',')[0]) - 1 elif current_file is not None and line_number is not None: # Iterate through the file. if line.startswith('+'): # Make sure we have coverage for this line. Else just tag it as unknown. cov = 'N' if current_file in coverage: try: cov = coverage[current_file][line_number] except IndexError: logger = logging.getLogger('coverage') logger.info('Missing code coverage for line %d of file %s' % (line_number, current_file)) coverage_by_added_line.append(cov) if not line.startswith('-'): # Up the line count (assuming we aren't at a remove line) line_number += 1 return coverage_by_added_line def _get_files_from_raw_diff(self, diff): """ Returns a list of filenames from a diff. """ files = set() diff_lines = diff.encode('utf-8').split('\n') for line in diff_lines: if line.startswith('+++ b/'): line = line.split('\t')[0] files.add(unicode(line[6:])) return files
ewdurbin/sentry
refs/heads/master
tests/sentry/api/endpoints/test_project_rules.py
8
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.models import Rule from sentry.testutils import APITestCase class ProjectRuleListTest(APITestCase): def test_simple(self): self.login_as(user=self.user) team = self.create_team() project1 = self.create_project(team=team, name='foo') project2 = self.create_project(team=team, name='bar') url = reverse('sentry-api-0-project-rules', kwargs={ 'organization_slug': project1.organization.slug, 'project_slug': project1.slug, }) response = self.client.get(url, format='json') assert response.status_code == 200, response.content rule_count = Rule.objects.filter(project=project1).count() assert len(response.data) == rule_count
jmesteve/openerp
refs/heads/master
openerp/addons/sale_crm/__openerp__.py
54
# -*- 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': 'Opportunity to Quotation', 'version': '1.0', 'category': 'Hidden', 'description': """ This module adds a shortcut on one or several opportunity cases in the CRM. =========================================================================== This shortcut allows you to generate a sales order based on the selected case. If different cases are open (a list), it generates one sale order by case. The case is then closed and linked to the generated sales order. We suggest you to install this module, if you installed both the sale and the crm modules. """, 'author': 'OpenERP SA', 'website': 'http://www.openerp.com', 'images': ['images/crm_statistics_dashboard.jpeg', 'images/opportunity_to_quote.jpeg'], 'depends': ['sale', 'crm'], 'data': [ 'wizard/crm_make_sale_view.xml', 'sale_crm_view.xml', 'sale_crm_data.xml', 'process/sale_crm_process.xml', 'security/sale_crm_security.xml', 'security/ir.model.access.csv', 'report/sale_crm_account_invoice_report_view.xml', ], 'demo': [], 'test': ['test/sale_crm.yml'], 'installable': True, 'auto_install': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
jjingrong/PONUS-1.2
refs/heads/master
venv/build/django/django/views/decorators/csrf.py
228
from django.middleware.csrf import CsrfViewMiddleware, get_token from django.utils.decorators import decorator_from_middleware, available_attrs from functools import wraps csrf_protect = decorator_from_middleware(CsrfViewMiddleware) csrf_protect.__name__ = "csrf_protect" csrf_protect.__doc__ = """ This decorator adds CSRF protection in exactly the same way as CsrfViewMiddleware, but it can be used on a per view basis. Using both, or using the decorator multiple times, is harmless and efficient. """ class _EnsureCsrfToken(CsrfViewMiddleware): # We need this to behave just like the CsrfViewMiddleware, but not reject # requests or log warnings. def _reject(self, request, reason): return None requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken) requires_csrf_token.__name__ = 'requires_csrf_token' requires_csrf_token.__doc__ = """ Use this decorator on views that need a correct csrf_token available to RequestContext, but without the CSRF protection that csrf_protect enforces. """ class _EnsureCsrfCookie(CsrfViewMiddleware): def _reject(self, request, reason): return None def process_view(self, request, callback, callback_args, callback_kwargs): retval = super(_EnsureCsrfCookie, self).process_view(request, callback, callback_args, callback_kwargs) # Forces process_response to send the cookie get_token(request) return retval ensure_csrf_cookie = decorator_from_middleware(_EnsureCsrfCookie) ensure_csrf_cookie.__name__ = 'ensure_csrf_cookie' ensure_csrf_cookie.__doc__ = """ Use this decorator to ensure that a view sets a CSRF cookie, whether or not it uses the csrf_token template tag, or the CsrfViewMiddleware is used. """ def csrf_exempt(view_func): """ Marks a view function as being exempt from the CSRF view protection. """ # We could just do view_func.csrf_exempt = True, but decorators # are nicer if they don't have side-effects, so we return a new # function. def wrapped_view(*args, **kwargs): return view_func(*args, **kwargs) wrapped_view.csrf_exempt = True return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
ryfeus/lambda-packs
refs/heads/master
Tensorflow_LightGBM_Scipy_nightly/source/numpy/distutils/numpy_distribution.py
263
# XXX: Handle setuptools ? from __future__ import division, absolute_import, print_function from distutils.core import Distribution # This class is used because we add new files (sconscripts, and so on) with the # scons command class NumpyDistribution(Distribution): def __init__(self, attrs = None): # A list of (sconscripts, pre_hook, post_hook, src, parent_names) self.scons_data = [] # A list of installable libraries self.installed_libraries = [] # A dict of pkg_config files to generate/install self.installed_pkg_config = {} Distribution.__init__(self, attrs) def has_scons_scripts(self): return bool(self.scons_data)
shubhdev/openedx
refs/heads/master
lms/djangoapps/notifier_api/tests.py
115
import itertools import ddt from django.conf import settings from django.test.client import RequestFactory from django.test.utils import override_settings from openedx.core.djangoapps.course_groups.models import CourseUserGroup from django_comment_common.models import Role, Permission from lang_pref import LANGUAGE_KEY from notification_prefs import NOTIFICATION_PREF_KEY from notifier_api.views import NotifierUsersViewSet from opaque_keys.edx.locator import CourseLocator from student.models import CourseEnrollment from student.tests.factories import UserFactory, CourseEnrollmentFactory from openedx.core.djangoapps.user_api.models import UserPreference from openedx.core.djangoapps.user_api.tests.factories import UserPreferenceFactory from util.testing import UrlResetMixin from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory @ddt.ddt @override_settings(EDX_API_KEY="test_api_key") class NotifierUsersViewSetTest(UrlResetMixin, ModuleStoreTestCase): def setUp(self): super(NotifierUsersViewSetTest, self).setUp() self.courses = [] self.cohorts = [] self.user = UserFactory() self.notification_pref = UserPreferenceFactory( user=self.user, key=NOTIFICATION_PREF_KEY, value="notification pref test value" ) self.list_view = NotifierUsersViewSet.as_view({"get": "list"}) self.detail_view = NotifierUsersViewSet.as_view({"get": "retrieve"}) def _set_up_course(self, is_course_cohorted, is_user_cohorted, is_moderator): cohort_config = {"cohorted": True} if is_course_cohorted else {} course = CourseFactory( number=("TestCourse{}".format(len(self.courses))), cohort_config=cohort_config ) self.courses.append(course) CourseEnrollmentFactory(user=self.user, course_id=course.id) if is_user_cohorted: cohort = CourseUserGroup.objects.create( name="Test Cohort", course_id=course.id, group_type=CourseUserGroup.COHORT ) cohort.users.add(self.user) self.cohorts.append(cohort) if is_moderator: moderator_perm, _ = Permission.objects.get_or_create(name="see_all_cohorts") moderator_role = Role.objects.create(name="Moderator", course_id=course.id) moderator_role.permissions.add(moderator_perm) self.user.roles.add(moderator_role) def _assert_basic_user_info_correct(self, user, result_user): self.assertEqual(result_user["id"], user.id) self.assertEqual(result_user["email"], user.email) self.assertEqual(result_user["name"], user.profile.name) def test_without_api_key(self): request = RequestFactory().get("dummy") for view in [self.list_view, self.detail_view]: response = view(request) self.assertEqual(response.status_code, 403) # Detail view tests def _make_detail_request(self): request = RequestFactory().get("dummy", HTTP_X_EDX_API_KEY=settings.EDX_API_KEY) return self.detail_view( request, **{NotifierUsersViewSet.lookup_field: str(self.user.id)} ) def _get_detail(self): response = self._make_detail_request() self.assertEqual(response.status_code, 200) self.assertEqual( set(response.data.keys()), {"id", "email", "name", "preferences", "course_info"} ) return response.data def test_detail_invalid_user(self): UserPreference.objects.all().delete() response = self._make_detail_request() self.assertEqual(response.status_code, 404) def test_basic_user_info(self): result = self._get_detail() self._assert_basic_user_info_correct(self.user, result) def test_course_info(self): expected_course_info = {} for is_course_cohorted, is_user_cohorted, is_moderator in ( itertools.product([True, False], [True, False], [True, False]) ): self._set_up_course(is_course_cohorted, is_user_cohorted, is_moderator) expected_course_info[unicode(self.courses[-1].id)] = { "cohort_id": self.cohorts[-1].id if is_user_cohorted else None, "see_all_cohorts": is_moderator or not is_course_cohorted } result = self._get_detail() self.assertEqual(result["course_info"], expected_course_info) def test_course_info_unenrolled(self): self._set_up_course(False, False, False) course_id = self.courses[0].id CourseEnrollment.unenroll(self.user, course_id) result = self._get_detail() self.assertNotIn(unicode(course_id), result["course_info"]) def test_course_info_no_enrollments(self): result = self._get_detail() self.assertEqual(result["course_info"], {}) def test_course_info_non_existent_course_enrollment(self): CourseEnrollmentFactory( user=self.user, course_id=CourseLocator(org="dummy", course="dummy", run="non_existent") ) result = self._get_detail() self.assertEqual(result["course_info"], {}) def test_preferences(self): lang_pref = UserPreferenceFactory( user=self.user, key=LANGUAGE_KEY, value="language pref test value" ) UserPreferenceFactory(user=self.user, key="non_included_key") result = self._get_detail() self.assertEqual( result["preferences"], { NOTIFICATION_PREF_KEY: self.notification_pref.value, LANGUAGE_KEY: lang_pref.value, } ) # List view tests def _make_list_request(self, page, page_size): request = RequestFactory().get( "dummy", {"page": page, "page_size": page_size}, HTTP_X_EDX_API_KEY=settings.EDX_API_KEY ) return self.list_view(request) def _get_list(self, page=1, page_size=None): response = self._make_list_request(page, page_size) self.assertEqual(response.status_code, 200) self.assertEqual( set(response.data.keys()), {"count", "next", "previous", "results"} ) return response.data["results"] def test_no_users(self): UserPreference.objects.all().delete() results = self._get_list() self.assertEqual(len(results), 0) def test_multiple_users(self): other_user = UserFactory() other_notification_pref = UserPreferenceFactory( user=other_user, key=NOTIFICATION_PREF_KEY, value="other value" ) self._set_up_course(is_course_cohorted=True, is_user_cohorted=True, is_moderator=False) self._set_up_course(is_course_cohorted=False, is_user_cohorted=False, is_moderator=False) # Users have different sets of enrollments CourseEnrollmentFactory(user=other_user, course_id=self.courses[0].id) result_map = {result["id"]: result for result in self._get_list()} self.assertEqual(set(result_map.keys()), {self.user.id, other_user.id}) for user in [self.user, other_user]: self._assert_basic_user_info_correct(user, result_map[user.id]) self.assertEqual( result_map[self.user.id]["preferences"], {NOTIFICATION_PREF_KEY: self.notification_pref.value} ) self.assertEqual( result_map[other_user.id]["preferences"], {NOTIFICATION_PREF_KEY: other_notification_pref.value} ) self.assertEqual( result_map[self.user.id]["course_info"], { unicode(self.courses[0].id): { "cohort_id": self.cohorts[0].id, "see_all_cohorts": False, }, unicode(self.courses[1].id): { "cohort_id": None, "see_all_cohorts": True, }, } ) self.assertEqual( result_map[other_user.id]["course_info"], { unicode(self.courses[0].id): { "cohort_id": None, "see_all_cohorts": False, }, } ) @ddt.data( 3, # Factor of num of results 5, # Non-factor of num of results 12, # Num of results 15 # More than num of results ) def test_pagination(self, page_size): num_users = 12 users = [self.user] while len(users) < num_users: new_user = UserFactory() users.append(new_user) UserPreferenceFactory(user=new_user, key=NOTIFICATION_PREF_KEY) num_pages = (num_users - 1) / page_size + 1 result_list = [] for i in range(1, num_pages + 1): result_list.extend(self._get_list(page=i, page_size=page_size)) result_map = {result["id"]: result for result in result_list} self.assertEqual(len(result_list), num_users) for user in users: self._assert_basic_user_info_correct(user, result_map[user.id]) self.assertEqual( self._make_list_request(page=(num_pages + 1), page_size=page_size).status_code, 404 ) def test_db_access(self): for _ in range(10): new_user = UserFactory() UserPreferenceFactory(user=new_user, key=NOTIFICATION_PREF_KEY) # The number of queries is one for the users plus one for each prefetch # in NotifierUsersViewSet (roles__permissions does one for each table). with self.assertNumQueries(6): self._get_list()
illume/numpy3k
refs/heads/master
numpy/doc/performance.py
100
""" =========== Performance =========== Placeholder for Improving Performance documentation. """