repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
zahodi/ansible
lib/ansible/modules/cloud/openstack/os_project_facts.py
4
4919
#!/usr/bin/python # Copyright (c) 2016 Hewlett-Packard Enterprise Corporation # # This module 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 software 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 software. If not, see <http://www.gnu.org/licenses/>. try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: os_project_facts short_description: Retrieve facts about one or more OpenStack projects extends_documentation_fragment: openstack version_added: "2.1" author: "Ricardo Carrillo Cruz (@rcarrillocruz)" description: - Retrieve facts about a one or more OpenStack projects requirements: - "python >= 2.6" - "shade" options: name: description: - Name or ID of the project required: true domain: description: - Name or ID of the domain containing the project if the cloud supports domains required: false default: None filters: description: - A dictionary of meta data to use for further filtering. Elements of this dictionary may be additional dictionaries. required: false default: None ''' EXAMPLES = ''' # Gather facts about previously created projects - os_project_facts: cloud: awesomecloud - debug: var: openstack_projects # Gather facts about a previously created project by name - os_project_facts: cloud: awesomecloud name: demoproject - debug: var: openstack_projects # Gather facts about a previously created project in a specific domain - os_project_facts cloud: awesomecloud name: demoproject domain: admindomain - debug: var: openstack_projects # Gather facts about a previously created project in a specific domain with filter - os_project_facts cloud: awesomecloud name: demoproject domain: admindomain filters: enabled: False - debug: var: openstack_projects ''' RETURN = ''' openstack_projects: description: has all the OpenStack facts about projects returned: always, but can be null type: complex contains: id: description: Unique UUID. returned: success type: string name: description: Name given to the project. returned: success type: string description: description: Description of the project returned: success type: string enabled: description: Flag to indicate if the project is enabled returned: success type: bool domain_id: description: Domain ID containing the project (keystone v3 clouds only) returned: success type: bool ''' def main(): argument_spec = openstack_full_argument_spec( name=dict(required=False, default=None), domain=dict(required=False, default=None), filters=dict(required=False, type='dict', default=None), ) module = AnsibleModule(argument_spec) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') try: name = module.params['name'] domain = module.params['domain'] filters = module.params['filters'] opcloud = shade.operator_cloud(**module.params) if domain: try: # We assume admin is passing domain id dom = opcloud.get_domain(domain)['id'] domain = dom except: # If we fail, maybe admin is passing a domain name. # Note that domains have unique names, just like id. dom = opcloud.search_domains(filters={'name': domain}) if dom: domain = dom[0]['id'] else: module.fail_json(msg='Domain name or ID does not exist') if not filters: filters = {} filters['domain_id'] = domain projects = opcloud.search_projects(name, filters) module.exit_json(changed=False, ansible_facts=dict( openstack_projects=projects)) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
gpl-3.0
petemounce/ansible
lib/ansible/cli/doc.py
4
16894
# (c) 2014, James Tanner <tanner.jc@gmail.com> # # 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-vault is a script that encrypts/decrypts YAML files. See # http://docs.ansible.com/playbooks_vault.html for more details. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import datetime import os import traceback import textwrap import yaml from ansible import constants as C from ansible.cli import CLI from ansible.errors import AnsibleError, AnsibleOptionsError from ansible.module_utils.six import string_types from ansible.plugins import module_loader, action_loader, lookup_loader, callback_loader, cache_loader, connection_loader, strategy_loader, PluginLoader from ansible.utils import plugin_docs try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() class DocCLI(CLI): ''' displays information on modules installed in Ansible libraries. It displays a terse listing of plugins and their short descriptions, provides a printout of their DOCUMENTATION strings, and it can create a short "snippet" which can be pasted into a playbook. ''' def __init__(self, args): super(DocCLI, self).__init__(args) self.plugin_list = set() def parse(self): self.parser = CLI.base_parser( usage='usage: %prog [options] [plugin]', module_opts=True, desc="plugin documentation tool", epilog="See man pages for Ansible CLI options or website for tutorials https://docs.ansible.com" ) self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir', help='List available plugins') self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet', help='Show playbook snippet for specified plugin(s)') self.parser.add_option("-a", "--all", action="store_true", default=False, dest='all_plugins', help='Show documentation for all plugins') self.parser.add_option("-t", "--type", action="store", default='module', dest='type', type='choice', help='Choose which plugin type', choices=['module','cache', 'connection', 'callback', 'lookup', 'strategy', 'inventory']) super(DocCLI, self).parse() display.verbosity = self.options.verbosity def run(self): super(DocCLI, self).run() plugin_type = self.options.type # choose plugin type if plugin_type == 'cache': loader = cache_loader elif plugin_type == 'callback': loader = callback_loader elif plugin_type == 'connection': loader = connection_loader elif plugin_type == 'lookup': loader = lookup_loader elif plugin_type == 'strategy': loader = strategy_loader elif plugin_type == 'inventory': loader = PluginLoader( 'InventoryModule', 'ansible.plugins.inventory', 'inventory_plugins', 'inventory_plugins') else: loader = module_loader # add to plugin path from command line if self.options.module_path is not None: for i in self.options.module_path.split(os.pathsep): loader.add_directory(i) # list plugins for type if self.options.list_dir: paths = loader._get_paths() for path in paths: self.find_plugins(path, plugin_type) self.pager(self.get_plugin_list_text(loader)) return 0 # process all plugins of type if self.options.all_plugins: paths = loader._get_paths() for path in paths: self.find_plugins(path, plugin_type) if len(self.args) == 0: raise AnsibleOptionsError("Incorrect options passed") # process command line list text = '' for plugin in self.args: try: # if the plugin lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs filename = loader.find_plugin(plugin, mod_type='.py', ignore_deprecated=True) if filename is None: display.warning("%s %s not found in %s\n" % (plugin_type, plugin, DocCLI.print_paths(loader))) continue if any(filename.endswith(x) for x in C.BLACKLIST_EXTS): continue try: doc, plainexamples, returndocs, metadata = plugin_docs.get_docstring(filename, verbose=(self.options.verbosity > 0)) except: display.vvv(traceback.format_exc()) display.error("%s %s has a documentation error formatting or is missing documentation." % (plugin_type, plugin)) continue if doc is not None: # assign from other sections doc['plainexamples'] = plainexamples doc['returndocs'] = returndocs doc['metadata'] = metadata # generate extra data if plugin_type == 'module': # is there corresponding action plugin? if plugin in action_loader: doc['action'] = True else: doc['action'] = False doc['filename'] = filename doc['now_date'] = datetime.date.today().strftime('%Y-%m-%d') doc['docuri'] = doc[plugin_type].replace('_', '-') if self.options.show_snippet and plugin_type == 'module': text += self.get_snippet_text(doc) else: text += self.get_man_text(doc) else: # this typically means we couldn't even parse the docstring, not just that the YAML is busted, # probably a quoting issue. raise AnsibleError("Parsing produced an empty object.") except Exception as e: display.vvv(traceback.format_exc()) raise AnsibleError("%s %s missing documentation (or could not parse documentation): %s\n" % (plugin_type, plugin, str(e))) if text: self.pager(text) return 0 def find_plugins(self, path, ptype): display.vvvv("Searching %s for plugins" % path) if not os.path.exists(path): display.vvvv("%s does not exist" % path) return bkey = ptype.upper() for plugin in os.listdir(path): display.vvvv("Found %s" % plugin) full_path = '/'.join([path, plugin]) if plugin.startswith('.'): continue elif os.path.isdir(full_path): continue elif any(plugin.endswith(x) for x in C.BLACKLIST_EXTS): continue elif plugin.startswith('__'): continue elif plugin in C.IGNORE_FILES: continue elif plugin .startswith('_'): if os.path.islink(full_path): # avoids aliases continue plugin = os.path.splitext(plugin)[0] # removes the extension plugin = plugin.lstrip('_') # remove underscore from deprecated plugins if plugin not in plugin_docs.BLACKLIST.get(bkey, ()): self.plugin_list.add(plugin) display.vvvv("Added %s" % plugin) def get_plugin_list_text(self, loader): columns = display.columns displace = max(len(x) for x in self.plugin_list) linelimit = columns - displace - 5 text = [] deprecated = [] for plugin in sorted(self.plugin_list): # if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs filename = loader.find_plugin(plugin, mod_type='.py', ignore_deprecated=True) if filename is None: continue if filename.endswith(".ps1"): continue if os.path.isdir(filename): continue try: doc, plainexamples, returndocs, metadata = plugin_docs.get_docstring(filename) except: display.warning("%s has a documentation formatting error" % plugin) if not doc: desc = 'UNDOCUMENTED' display.warning("%s parsing did not produce documentation." % plugin) else: desc = self.tty_ify(doc.get('short_description', '?')).strip() if len(desc) > linelimit: desc = desc[:linelimit] + '...' if plugin.startswith('_'): # Handle deprecated deprecated.append("%-*s %-*.*s" % (displace, plugin[1:], linelimit, len(desc), desc)) else: text.append("%-*s %-*.*s" % (displace, plugin, linelimit, len(desc), desc)) if len(deprecated) > 0: text.append("\nDEPRECATED:") text.extend(deprecated) return "\n".join(text) @staticmethod def print_paths(finder): ''' Returns a string suitable for printing of the search path ''' # Uses a list to get the order right ret = [] for i in finder._get_paths(): if i not in ret: ret.append(i) return os.pathsep.join(ret) def get_snippet_text(self, doc): text = [] desc = CLI.tty_ify(doc['short_description']) text.append("- name: %s" % (desc)) text.append(" %s:" % (doc['module'])) pad = 31 subdent = " " * pad limit = display.columns - pad for o in sorted(doc['options'].keys()): opt = doc['options'][o] if isinstance(opt['description'], string_types): desc = CLI.tty_ify(opt['description']) else: desc = CLI.tty_ify(" ".join(opt['description'])) required = opt.get('required', False) if not isinstance(required, bool): raise("Incorrect value for 'Required', a boolean is needed.: %s" % required) if required: desc = "(required) %s" % desc o = '%s:' % o text.append(" %-20s # %s" % (o, textwrap.fill(desc, limit, subsequent_indent=subdent))) text.append('') return "\n".join(text) def add_fields(self, text, fields, limit, opt_indent): for o in sorted(fields): opt = fields[o] required = opt.get('required', False) if not isinstance(required, bool): raise("Incorrect value for 'Required', a boolean is needed.: %s" % required) if required: opt_leadin = "=" else: opt_leadin = "-" text.append("%s %s" % (opt_leadin, o)) if isinstance(opt['description'], list): for entry in opt['description']: text.append(textwrap.fill(CLI.tty_ify(entry), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) else: text.append(textwrap.fill(CLI.tty_ify(opt['description']), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) choices = '' if 'choices' in opt: choices = "(Choices: " + ", ".join(str(i) for i in opt['choices']) + ")" default = '' if 'default' in opt or not required: default = "[Default: " + str(opt.get('default', '(null)')) + "]" text.append(textwrap.fill(CLI.tty_ify(choices + default), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) for conf in ('config', 'env_vars', 'host_vars'): if conf in opt: text.append(textwrap.fill(CLI.tty_ify("%s: " % conf), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) for entry in opt[conf]: if isinstance(entry, dict): pre = " -" for key in entry: text.append(textwrap.fill(CLI.tty_ify("%s %s: %s" % (pre, key, entry[key])), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) pre = " " else: text.append(textwrap.fill(CLI.tty_ify(" - %s" % entry), limit, initial_indent=opt_indent, subsequent_indent=opt_indent)) def get_man_text(self, doc): opt_indent=" " text = [] text.append("> %s (%s)\n" % (doc[self.options.type].upper(), doc['filename'])) pad = display.columns * 0.20 limit = max(display.columns - int(pad), 70) if isinstance(doc['description'], list): desc = " ".join(doc['description']) else: desc = doc['description'] text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), limit, initial_indent=" ", subsequent_indent=" ")) if 'deprecated' in doc and doc['deprecated'] is not None and len(doc['deprecated']) > 0: text.append("DEPRECATED: \n%s\n" % doc['deprecated']) if 'action' in doc and doc['action']: text.append(" * note: %s\n" % "This module has a corresponding action plugin.") if 'options' in doc and doc['options']: text.append("Options (= is mandatory):\n") self.add_fields(text, doc['options'], limit, opt_indent) text.append('') if 'notes' in doc and doc['notes'] and len(doc['notes']) > 0: text.append("Notes:") for note in doc['notes']: text.append(textwrap.fill(CLI.tty_ify(note), limit-6, initial_indent=" * ", subsequent_indent=opt_indent)) if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0: req = ", ".join(doc['requirements']) text.append("Requirements:%s\n" % textwrap.fill(CLI.tty_ify(req), limit-16, initial_indent=" ", subsequent_indent=opt_indent)) if 'examples' in doc and len(doc['examples']) > 0: text.append("Example%s:\n" % ('' if len(doc['examples']) < 2 else 's')) for ex in doc['examples']: text.append("%s\n" % (ex['code'])) if 'plainexamples' in doc and doc['plainexamples'] is not None: text.append("EXAMPLES:\n") if isinstance(doc['plainexamples'], string_types): text.append(doc['plainexamples']) else: text.append(yaml.dump(doc['plainexamples'], indent=2, default_flow_style=False)) if 'returndocs' in doc and doc['returndocs'] is not None: text.append("RETURN VALUES:\n") if isinstance(doc['returndocs'], string_types): text.append(doc['returndocs']) else: text.append(yaml.dump(doc['returndocs'], indent=2, default_flow_style=False)) text.append('') maintainers = set() if 'author' in doc: if isinstance(doc['author'], string_types): maintainers.add(doc['author']) else: maintainers.update(doc['author']) if 'maintainers' in doc: if isinstance(doc['maintainers'], string_types): maintainers.add(doc['author']) else: maintainers.update(doc['author']) text.append('MAINTAINERS: ' + ', '.join(maintainers)) text.append('') if 'metadata' in doc and doc['metadata']: text.append("METADATA:") for k in doc['metadata']: if isinstance(k, list): text.append("\t%s: %s" % (k.capitalize(), ", ".join(doc['metadata'][k]))) else: text.append("\t%s: %s" % (k.capitalize(), doc['metadata'][k])) text.append('') return "\n".join(text)
gpl-3.0
goFrendiAsgard/kokoropy
kokoropy/packages/sqlalchemy/dialects/postgresql/base.py
22
88365
# postgresql/base.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: postgresql :name: PostgreSQL Sequences/SERIAL ---------------- PostgreSQL supports sequences, and SQLAlchemy uses these as the default means of creating new primary key values for integer-based primary key columns. When creating tables, SQLAlchemy will issue the ``SERIAL`` datatype for integer-based primary key columns, which generates a sequence and server side default corresponding to the column. To specify a specific named sequence to be used for primary key generation, use the :func:`~sqlalchemy.schema.Sequence` construct:: Table('sometable', metadata, Column('id', Integer, Sequence('some_id_seq'), primary_key=True) ) When SQLAlchemy issues a single INSERT statement, to fulfill the contract of having the "last insert identifier" available, a RETURNING clause is added to the INSERT statement which specifies the primary key columns should be returned after the statement completes. The RETURNING functionality only takes place if Postgresql 8.2 or later is in use. As a fallback approach, the sequence, whether specified explicitly or implicitly via ``SERIAL``, is executed independently beforehand, the returned value to be used in the subsequent insert. Note that when an :func:`~sqlalchemy.sql.expression.insert()` construct is executed using "executemany" semantics, the "last inserted identifier" functionality does not apply; no RETURNING clause is emitted nor is the sequence pre-executed in this case. To force the usage of RETURNING by default off, specify the flag ``implicit_returning=False`` to :func:`.create_engine`. .. _postgresql_isolation_level: Transaction Isolation Level --------------------------- All Postgresql dialects support setting of transaction isolation level both via a dialect-specific parameter ``isolation_level`` accepted by :func:`.create_engine`, as well as the ``isolation_level`` argument as passed to :meth:`.Connection.execution_options`. When using a non-psycopg2 dialect, this feature works by issuing the command ``SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL <level>`` for each new connection. To set isolation level using :func:`.create_engine`:: engine = create_engine( "postgresql+pg8000://scott:tiger@localhost/test", isolation_level="READ UNCOMMITTED" ) To set using per-connection execution options:: connection = engine.connect() connection = connection.execution_options( isolation_level="READ COMMITTED" ) Valid values for ``isolation_level`` include: * ``READ COMMITTED`` * ``READ UNCOMMITTED`` * ``REPEATABLE READ`` * ``SERIALIZABLE`` The :mod:`~sqlalchemy.dialects.postgresql.psycopg2` and :mod:`~sqlalchemy.dialects.postgresql.pg8000` dialects also offer the special level ``AUTOCOMMIT``. .. seealso:: :ref:`psycopg2_isolation_level` :ref:`pg8000_isolation_level` .. _postgresql_schema_reflection: Remote-Schema Table Introspection and Postgresql search_path ------------------------------------------------------------ The Postgresql dialect can reflect tables from any schema. The :paramref:`.Table.schema` argument, or alternatively the :paramref:`.MetaData.reflect.schema` argument determines which schema will be searched for the table or tables. The reflected :class:`.Table` objects will in all cases retain this ``.schema`` attribute as was specified. However, with regards to tables which these :class:`.Table` objects refer to via foreign key constraint, a decision must be made as to how the ``.schema`` is represented in those remote tables, in the case where that remote schema name is also a member of the current `Postgresql search path <http://www.postgresql.org/docs/9.0/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_. By default, the Postgresql dialect mimics the behavior encouraged by Postgresql's own ``pg_get_constraintdef()`` builtin procedure. This function returns a sample definition for a particular foreign key constraint, omitting the referenced schema name from that definition when the name is also in the Postgresql schema search path. The interaction below illustrates this behavior:: test=> CREATE TABLE test_schema.referred(id INTEGER PRIMARY KEY); CREATE TABLE test=> CREATE TABLE referring( test(> id INTEGER PRIMARY KEY, test(> referred_id INTEGER REFERENCES test_schema.referred(id)); CREATE TABLE test=> SET search_path TO public, test_schema; test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n test-> ON n.oid = c.relnamespace test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid test-> WHERE c.relname='referring' AND r.contype = 'f' test-> ; pg_get_constraintdef --------------------------------------------------- FOREIGN KEY (referred_id) REFERENCES referred(id) (1 row) Above, we created a table ``referred`` as a member of the remote schema ``test_schema``, however when we added ``test_schema`` to the PG ``search_path`` and then asked ``pg_get_constraintdef()`` for the ``FOREIGN KEY`` syntax, ``test_schema`` was not included in the output of the function. On the other hand, if we set the search path back to the typical default of ``public``:: test=> SET search_path TO public; SET The same query against ``pg_get_constraintdef()`` now returns the fully schema-qualified name for us:: test=> SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM test-> pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n test-> ON n.oid = c.relnamespace test-> JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid test-> WHERE c.relname='referring' AND r.contype = 'f'; pg_get_constraintdef --------------------------------------------------------------- FOREIGN KEY (referred_id) REFERENCES test_schema.referred(id) (1 row) SQLAlchemy will by default use the return value of ``pg_get_constraintdef()`` in order to determine the remote schema name. That is, if our ``search_path`` were set to include ``test_schema``, and we invoked a table reflection process as follows:: >>> from sqlalchemy import Table, MetaData, create_engine >>> engine = create_engine("postgresql://scott:tiger@localhost/test") >>> with engine.connect() as conn: ... conn.execute("SET search_path TO test_schema, public") ... meta = MetaData() ... referring = Table('referring', meta, ... autoload=True, autoload_with=conn) ... <sqlalchemy.engine.result.ResultProxy object at 0x101612ed0> The above process would deliver to the :attr:`.MetaData.tables` collection ``referred`` table named **without** the schema:: >>> meta.tables['referred'].schema is None True To alter the behavior of reflection such that the referred schema is maintained regardless of the ``search_path`` setting, use the ``postgresql_ignore_search_path`` option, which can be specified as a dialect-specific argument to both :class:`.Table` as well as :meth:`.MetaData.reflect`:: >>> with engine.connect() as conn: ... conn.execute("SET search_path TO test_schema, public") ... meta = MetaData() ... referring = Table('referring', meta, autoload=True, ... autoload_with=conn, ... postgresql_ignore_search_path=True) ... <sqlalchemy.engine.result.ResultProxy object at 0x1016126d0> We will now have ``test_schema.referred`` stored as schema-qualified:: >>> meta.tables['test_schema.referred'].schema 'test_schema' .. sidebar:: Best Practices for Postgresql Schema reflection The description of Postgresql schema reflection behavior is complex, and is the product of many years of dealing with widely varied use cases and user preferences. But in fact, there's no need to understand any of it if you just stick to the simplest use pattern: leave the ``search_path`` set to its default of ``public`` only, never refer to the name ``public`` as an explicit schema name otherwise, and refer to all other schema names explicitly when building up a :class:`.Table` object. The options described here are only for those users who can't, or prefer not to, stay within these guidelines. Note that **in all cases**, the "default" schema is always reflected as ``None``. The "default" schema on Postgresql is that which is returned by the Postgresql ``current_schema()`` function. On a typical Postgresql installation, this is the name ``public``. So a table that refers to another which is in the ``public`` (i.e. default) schema will always have the ``.schema`` attribute set to ``None``. .. versionadded:: 0.9.2 Added the ``postgresql_ignore_search_path`` dialect-level option accepted by :class:`.Table` and :meth:`.MetaData.reflect`. .. seealso:: `The Schema Search Path <http://www.postgresql.org/docs/9.0/static/ddl-schemas.html#DDL-SCHEMAS-PATH>`_ - on the Postgresql website. INSERT/UPDATE...RETURNING ------------------------- The dialect supports PG 8.2's ``INSERT..RETURNING``, ``UPDATE..RETURNING`` and ``DELETE..RETURNING`` syntaxes. ``INSERT..RETURNING`` is used by default for single-row INSERT statements in order to fetch newly generated primary key identifiers. To specify an explicit ``RETURNING`` clause, use the :meth:`._UpdateBase.returning` method on a per-statement basis:: # INSERT..RETURNING result = table.insert().returning(table.c.col1, table.c.col2).\\ values(name='foo') print result.fetchall() # UPDATE..RETURNING result = table.update().returning(table.c.col1, table.c.col2).\\ where(table.c.name=='foo').values(name='bar') print result.fetchall() # DELETE..RETURNING result = table.delete().returning(table.c.col1, table.c.col2).\\ where(table.c.name=='foo') print result.fetchall() .. _postgresql_match: Full Text Search ---------------- SQLAlchemy makes available the Postgresql ``@@`` operator via the :meth:`.ColumnElement.match` method on any textual column expression. On a Postgresql dialect, an expression like the following:: select([sometable.c.text.match("search string")]) will emit to the database:: SELECT text @@ to_tsquery('search string') FROM table The Postgresql text search functions such as ``to_tsquery()`` and ``to_tsvector()`` are available explicitly using the standard :attr:`.func` construct. For example:: select([ func.to_tsvector('fat cats ate rats').match('cat & rat') ]) Emits the equivalent of:: SELECT to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat') The :class:`.postgresql.TSVECTOR` type can provide for explicit CAST:: from sqlalchemy.dialects.postgresql import TSVECTOR from sqlalchemy import select, cast select([cast("some text", TSVECTOR)]) produces a statement equivalent to:: SELECT CAST('some text' AS TSVECTOR) AS anon_1 Full Text Searches in Postgresql are influenced by a combination of: the PostgresSQL setting of ``default_text_search_config``, the ``regconfig`` used to build the GIN/GiST indexes, and the ``regconfig`` optionally passed in during a query. When performing a Full Text Search against a column that has a GIN or GiST index that is already pre-computed (which is common on full text searches) one may need to explicitly pass in a particular PostgresSQL ``regconfig`` value to ensure the query-planner utilizes the index and does not re-compute the column on demand. In order to provide for this explicit query planning, or to use different search strategies, the ``match`` method accepts a ``postgresql_regconfig`` keyword argument. select([mytable.c.id]).where( mytable.c.title.match('somestring', postgresql_regconfig='english') ) Emits the equivalent of:: SELECT mytable.id FROM mytable WHERE mytable.title @@ to_tsquery('english', 'somestring') One can also specifically pass in a `'regconfig'` value to the ``to_tsvector()`` command as the initial argument. select([mytable.c.id]).where( func.to_tsvector('english', mytable.c.title )\ .match('somestring', postgresql_regconfig='english') ) produces a statement equivalent to:: SELECT mytable.id FROM mytable WHERE to_tsvector('english', mytable.title) @@ to_tsquery('english', 'somestring') It is recommended that you use the ``EXPLAIN ANALYZE...`` tool from PostgresSQL to ensure that you are generating queries with SQLAlchemy that take full advantage of any indexes you may have created for full text search. FROM ONLY ... ------------------------ The dialect supports PostgreSQL's ONLY keyword for targeting only a particular table in an inheritance hierarchy. This can be used to produce the ``SELECT ... FROM ONLY``, ``UPDATE ONLY ...``, and ``DELETE FROM ONLY ...`` syntaxes. It uses SQLAlchemy's hints mechanism:: # SELECT ... FROM ONLY ... result = table.select().with_hint(table, 'ONLY', 'postgresql') print result.fetchall() # UPDATE ONLY ... table.update(values=dict(foo='bar')).with_hint('ONLY', dialect_name='postgresql') # DELETE FROM ONLY ... table.delete().with_hint('ONLY', dialect_name='postgresql') .. _postgresql_indexes: Postgresql-Specific Index Options --------------------------------- Several extensions to the :class:`.Index` construct are available, specific to the PostgreSQL dialect. Partial Indexes ^^^^^^^^^^^^^^^^ Partial indexes add criterion to the index definition so that the index is applied to a subset of rows. These can be specified on :class:`.Index` using the ``postgresql_where`` keyword argument:: Index('my_index', my_table.c.id, postgresql_where=tbl.c.value > 10) Operator Classes ^^^^^^^^^^^^^^^^^ PostgreSQL allows the specification of an *operator class* for each column of an index (see http://www.postgresql.org/docs/8.3/interactive/indexes-opclass.html). The :class:`.Index` construct allows these to be specified via the ``postgresql_ops`` keyword argument:: Index('my_index', my_table.c.id, my_table.c.data, postgresql_ops={ 'data': 'text_pattern_ops', 'id': 'int4_ops' }) .. versionadded:: 0.7.2 ``postgresql_ops`` keyword argument to :class:`.Index` construct. Note that the keys in the ``postgresql_ops`` dictionary are the "key" name of the :class:`.Column`, i.e. the name used to access it from the ``.c`` collection of :class:`.Table`, which can be configured to be different than the actual name of the column as expressed in the database. Index Types ^^^^^^^^^^^^ PostgreSQL provides several index types: B-Tree, Hash, GiST, and GIN, as well as the ability for users to create their own (see http://www.postgresql.org/docs/8.3/static/indexes-types.html). These can be specified on :class:`.Index` using the ``postgresql_using`` keyword argument:: Index('my_index', my_table.c.data, postgresql_using='gin') The value passed to the keyword argument will be simply passed through to the underlying CREATE INDEX command, so it *must* be a valid index type for your version of PostgreSQL. """ from collections import defaultdict import re from ... import sql, schema, exc, util from ...engine import default, reflection from ...sql import compiler, expression, operators from ... import types as sqltypes try: from uuid import UUID as _python_UUID except ImportError: _python_UUID = None from sqlalchemy.types import INTEGER, BIGINT, SMALLINT, VARCHAR, \ CHAR, TEXT, FLOAT, NUMERIC, \ DATE, BOOLEAN, REAL RESERVED_WORDS = set( ["all", "analyse", "analyze", "and", "any", "array", "as", "asc", "asymmetric", "both", "case", "cast", "check", "collate", "column", "constraint", "create", "current_catalog", "current_date", "current_role", "current_time", "current_timestamp", "current_user", "default", "deferrable", "desc", "distinct", "do", "else", "end", "except", "false", "fetch", "for", "foreign", "from", "grant", "group", "having", "in", "initially", "intersect", "into", "leading", "limit", "localtime", "localtimestamp", "new", "not", "null", "of", "off", "offset", "old", "on", "only", "or", "order", "placing", "primary", "references", "returning", "select", "session_user", "some", "symmetric", "table", "then", "to", "trailing", "true", "union", "unique", "user", "using", "variadic", "when", "where", "window", "with", "authorization", "between", "binary", "cross", "current_schema", "freeze", "full", "ilike", "inner", "is", "isnull", "join", "left", "like", "natural", "notnull", "outer", "over", "overlaps", "right", "similar", "verbose" ]) _DECIMAL_TYPES = (1231, 1700) _FLOAT_TYPES = (700, 701, 1021, 1022) _INT_TYPES = (20, 21, 23, 26, 1005, 1007, 1016) class BYTEA(sqltypes.LargeBinary): __visit_name__ = 'BYTEA' class DOUBLE_PRECISION(sqltypes.Float): __visit_name__ = 'DOUBLE_PRECISION' class INET(sqltypes.TypeEngine): __visit_name__ = "INET" PGInet = INET class CIDR(sqltypes.TypeEngine): __visit_name__ = "CIDR" PGCidr = CIDR class MACADDR(sqltypes.TypeEngine): __visit_name__ = "MACADDR" PGMacAddr = MACADDR class OID(sqltypes.TypeEngine): """Provide the Postgresql OID type. .. versionadded:: 0.9.5 """ __visit_name__ = "OID" class TIMESTAMP(sqltypes.TIMESTAMP): def __init__(self, timezone=False, precision=None): super(TIMESTAMP, self).__init__(timezone=timezone) self.precision = precision class TIME(sqltypes.TIME): def __init__(self, timezone=False, precision=None): super(TIME, self).__init__(timezone=timezone) self.precision = precision class INTERVAL(sqltypes.TypeEngine): """Postgresql INTERVAL type. The INTERVAL type may not be supported on all DBAPIs. It is known to work on psycopg2 and not pg8000 or zxjdbc. """ __visit_name__ = 'INTERVAL' def __init__(self, precision=None): self.precision = precision @classmethod def _adapt_from_generic_interval(cls, interval): return INTERVAL(precision=interval.second_precision) @property def _type_affinity(self): return sqltypes.Interval PGInterval = INTERVAL class BIT(sqltypes.TypeEngine): __visit_name__ = 'BIT' def __init__(self, length=None, varying=False): if not varying: # BIT without VARYING defaults to length 1 self.length = length or 1 else: # but BIT VARYING can be unlimited-length, so no default self.length = length self.varying = varying PGBit = BIT class UUID(sqltypes.TypeEngine): """Postgresql UUID type. Represents the UUID column type, interpreting data either as natively returned by the DBAPI or as Python uuid objects. The UUID type may not be supported on all DBAPIs. It is known to work on psycopg2 and not pg8000. """ __visit_name__ = 'UUID' def __init__(self, as_uuid=False): """Construct a UUID type. :param as_uuid=False: if True, values will be interpreted as Python uuid objects, converting to/from string via the DBAPI. """ if as_uuid and _python_UUID is None: raise NotImplementedError( "This version of Python does not support " "the native UUID type." ) self.as_uuid = as_uuid def bind_processor(self, dialect): if self.as_uuid: def process(value): if value is not None: value = util.text_type(value) return value return process else: return None def result_processor(self, dialect, coltype): if self.as_uuid: def process(value): if value is not None: value = _python_UUID(value) return value return process else: return None PGUuid = UUID class TSVECTOR(sqltypes.TypeEngine): """The :class:`.postgresql.TSVECTOR` type implements the Postgresql text search type TSVECTOR. It can be used to do full text queries on natural language documents. .. versionadded:: 0.9.0 .. seealso:: :ref:`postgresql_match` """ __visit_name__ = 'TSVECTOR' class _Slice(expression.ColumnElement): __visit_name__ = 'slice' type = sqltypes.NULLTYPE def __init__(self, slice_, source_comparator): self.start = source_comparator._check_literal( source_comparator.expr, operators.getitem, slice_.start) self.stop = source_comparator._check_literal( source_comparator.expr, operators.getitem, slice_.stop) class Any(expression.ColumnElement): """Represent the clause ``left operator ANY (right)``. ``right`` must be an array expression. .. seealso:: :class:`.postgresql.ARRAY` :meth:`.postgresql.ARRAY.Comparator.any` - ARRAY-bound method """ __visit_name__ = 'any' def __init__(self, left, right, operator=operators.eq): self.type = sqltypes.Boolean() self.left = expression._literal_as_binds(left) self.right = right self.operator = operator class All(expression.ColumnElement): """Represent the clause ``left operator ALL (right)``. ``right`` must be an array expression. .. seealso:: :class:`.postgresql.ARRAY` :meth:`.postgresql.ARRAY.Comparator.all` - ARRAY-bound method """ __visit_name__ = 'all' def __init__(self, left, right, operator=operators.eq): self.type = sqltypes.Boolean() self.left = expression._literal_as_binds(left) self.right = right self.operator = operator class array(expression.Tuple): """A Postgresql ARRAY literal. This is used to produce ARRAY literals in SQL expressions, e.g.:: from sqlalchemy.dialects.postgresql import array from sqlalchemy.dialects import postgresql from sqlalchemy import select, func stmt = select([ array([1,2]) + array([3,4,5]) ]) print stmt.compile(dialect=postgresql.dialect()) Produces the SQL:: SELECT ARRAY[%(param_1)s, %(param_2)s] || ARRAY[%(param_3)s, %(param_4)s, %(param_5)s]) AS anon_1 An instance of :class:`.array` will always have the datatype :class:`.ARRAY`. The "inner" type of the array is inferred from the values present, unless the ``type_`` keyword argument is passed:: array(['foo', 'bar'], type_=CHAR) .. versionadded:: 0.8 Added the :class:`~.postgresql.array` literal type. See also: :class:`.postgresql.ARRAY` """ __visit_name__ = 'array' def __init__(self, clauses, **kw): super(array, self).__init__(*clauses, **kw) self.type = ARRAY(self.type) def _bind_param(self, operator, obj): return array([ expression.BindParameter(None, o, _compared_to_operator=operator, _compared_to_type=self.type, unique=True) for o in obj ]) def self_group(self, against=None): return self class ARRAY(sqltypes.Concatenable, sqltypes.TypeEngine): """Postgresql ARRAY type. Represents values as Python lists. An :class:`.ARRAY` type is constructed given the "type" of element:: mytable = Table("mytable", metadata, Column("data", ARRAY(Integer)) ) The above type represents an N-dimensional array, meaning Postgresql will interpret values with any number of dimensions automatically. To produce an INSERT construct that passes in a 1-dimensional array of integers:: connection.execute( mytable.insert(), data=[1,2,3] ) The :class:`.ARRAY` type can be constructed given a fixed number of dimensions:: mytable = Table("mytable", metadata, Column("data", ARRAY(Integer, dimensions=2)) ) This has the effect of the :class:`.ARRAY` type specifying that number of bracketed blocks when a :class:`.Table` is used in a CREATE TABLE statement, or when the type is used within a :func:`.expression.cast` construct; it also causes the bind parameter and result set processing of the type to optimize itself to expect exactly that number of dimensions. Note that Postgresql itself still allows N dimensions with such a type. SQL expressions of type :class:`.ARRAY` have support for "index" and "slice" behavior. The Python ``[]`` operator works normally here, given integer indexes or slices. Note that Postgresql arrays default to 1-based indexing. The operator produces binary expression constructs which will produce the appropriate SQL, both for SELECT statements:: select([mytable.c.data[5], mytable.c.data[2:7]]) as well as UPDATE statements when the :meth:`.Update.values` method is used:: mytable.update().values({ mytable.c.data[5]: 7, mytable.c.data[2:7]: [1, 2, 3] }) :class:`.ARRAY` provides special methods for containment operations, e.g.:: mytable.c.data.contains([1, 2]) For a full list of special methods see :class:`.ARRAY.Comparator`. .. versionadded:: 0.8 Added support for index and slice operations to the :class:`.ARRAY` type, including support for UPDATE statements, and special array containment operations. The :class:`.ARRAY` type may not be supported on all DBAPIs. It is known to work on psycopg2 and not pg8000. See also: :class:`.postgresql.array` - produce a literal array value. """ __visit_name__ = 'ARRAY' class Comparator(sqltypes.Concatenable.Comparator): """Define comparison operations for :class:`.ARRAY`.""" def __getitem__(self, index): shift_indexes = 1 if self.expr.type.zero_indexes else 0 if isinstance(index, slice): if shift_indexes: index = slice( index.start + shift_indexes, index.stop + shift_indexes, index.step ) index = _Slice(index, self) return_type = self.type else: index += shift_indexes return_type = self.type.item_type return self._binary_operate(self.expr, operators.getitem, index, result_type=return_type) def any(self, other, operator=operators.eq): """Return ``other operator ANY (array)`` clause. Argument places are switched, because ANY requires array expression to be on the right hand-side. E.g.:: from sqlalchemy.sql import operators conn.execute( select([table.c.data]).where( table.c.data.any(7, operator=operators.lt) ) ) :param other: expression to be compared :param operator: an operator object from the :mod:`sqlalchemy.sql.operators` package, defaults to :func:`.operators.eq`. .. seealso:: :class:`.postgresql.Any` :meth:`.postgresql.ARRAY.Comparator.all` """ return Any(other, self.expr, operator=operator) def all(self, other, operator=operators.eq): """Return ``other operator ALL (array)`` clause. Argument places are switched, because ALL requires array expression to be on the right hand-side. E.g.:: from sqlalchemy.sql import operators conn.execute( select([table.c.data]).where( table.c.data.all(7, operator=operators.lt) ) ) :param other: expression to be compared :param operator: an operator object from the :mod:`sqlalchemy.sql.operators` package, defaults to :func:`.operators.eq`. .. seealso:: :class:`.postgresql.All` :meth:`.postgresql.ARRAY.Comparator.any` """ return All(other, self.expr, operator=operator) def contains(self, other, **kwargs): """Boolean expression. Test if elements are a superset of the elements of the argument array expression. """ return self.expr.op('@>')(other) def contained_by(self, other): """Boolean expression. Test if elements are a proper subset of the elements of the argument array expression. """ return self.expr.op('<@')(other) def overlap(self, other): """Boolean expression. Test if array has elements in common with an argument array expression. """ return self.expr.op('&&')(other) def _adapt_expression(self, op, other_comparator): if isinstance(op, operators.custom_op): if op.opstring in ['@>', '<@', '&&']: return op, sqltypes.Boolean return sqltypes.Concatenable.Comparator.\ _adapt_expression(self, op, other_comparator) comparator_factory = Comparator def __init__(self, item_type, as_tuple=False, dimensions=None, zero_indexes=False): """Construct an ARRAY. E.g.:: Column('myarray', ARRAY(Integer)) Arguments are: :param item_type: The data type of items of this array. Note that dimensionality is irrelevant here, so multi-dimensional arrays like ``INTEGER[][]``, are constructed as ``ARRAY(Integer)``, not as ``ARRAY(ARRAY(Integer))`` or such. :param as_tuple=False: Specify whether return results should be converted to tuples from lists. DBAPIs such as psycopg2 return lists by default. When tuples are returned, the results are hashable. :param dimensions: if non-None, the ARRAY will assume a fixed number of dimensions. This will cause the DDL emitted for this ARRAY to include the exact number of bracket clauses ``[]``, and will also optimize the performance of the type overall. Note that PG arrays are always implicitly "non-dimensioned", meaning they can store any number of dimensions no matter how they were declared. :param zero_indexes=False: when True, index values will be converted between Python zero-based and Postgresql one-based indexes, e.g. a value of one will be added to all index values before passing to the database. .. versionadded:: 0.9.5 """ if isinstance(item_type, ARRAY): raise ValueError("Do not nest ARRAY types; ARRAY(basetype) " "handles multi-dimensional arrays of basetype") if isinstance(item_type, type): item_type = item_type() self.item_type = item_type self.as_tuple = as_tuple self.dimensions = dimensions self.zero_indexes = zero_indexes @property def python_type(self): return list def compare_values(self, x, y): return x == y def _proc_array(self, arr, itemproc, dim, collection): if dim is None: arr = list(arr) if dim == 1 or dim is None and ( # this has to be (list, tuple), or at least # not hasattr('__iter__'), since Py3K strings # etc. have __iter__ not arr or not isinstance(arr[0], (list, tuple))): if itemproc: return collection(itemproc(x) for x in arr) else: return collection(arr) else: return collection( self._proc_array( x, itemproc, dim - 1 if dim is not None else None, collection) for x in arr ) def bind_processor(self, dialect): item_proc = self.item_type.\ dialect_impl(dialect).\ bind_processor(dialect) def process(value): if value is None: return value else: return self._proc_array( value, item_proc, self.dimensions, list) return process def result_processor(self, dialect, coltype): item_proc = self.item_type.\ dialect_impl(dialect).\ result_processor(dialect, coltype) def process(value): if value is None: return value else: return self._proc_array( value, item_proc, self.dimensions, tuple if self.as_tuple else list) return process PGArray = ARRAY class ENUM(sqltypes.Enum): """Postgresql ENUM type. This is a subclass of :class:`.types.Enum` which includes support for PG's ``CREATE TYPE``. :class:`~.postgresql.ENUM` is used automatically when using the :class:`.types.Enum` type on PG assuming the ``native_enum`` is left as ``True``. However, the :class:`~.postgresql.ENUM` class can also be instantiated directly in order to access some additional Postgresql-specific options, namely finer control over whether or not ``CREATE TYPE`` should be emitted. Note that both :class:`.types.Enum` as well as :class:`~.postgresql.ENUM` feature create/drop methods; the base :class:`.types.Enum` type ultimately delegates to the :meth:`~.postgresql.ENUM.create` and :meth:`~.postgresql.ENUM.drop` methods present here. """ def __init__(self, *enums, **kw): """Construct an :class:`~.postgresql.ENUM`. Arguments are the same as that of :class:`.types.Enum`, but also including the following parameters. :param create_type: Defaults to True. Indicates that ``CREATE TYPE`` should be emitted, after optionally checking for the presence of the type, when the parent table is being created; and additionally that ``DROP TYPE`` is called when the table is dropped. When ``False``, no check will be performed and no ``CREATE TYPE`` or ``DROP TYPE`` is emitted, unless :meth:`~.postgresql.ENUM.create` or :meth:`~.postgresql.ENUM.drop` are called directly. Setting to ``False`` is helpful when invoking a creation scheme to a SQL file without access to the actual database - the :meth:`~.postgresql.ENUM.create` and :meth:`~.postgresql.ENUM.drop` methods can be used to emit SQL to a target bind. .. versionadded:: 0.7.4 """ self.create_type = kw.pop("create_type", True) super(ENUM, self).__init__(*enums, **kw) def create(self, bind=None, checkfirst=True): """Emit ``CREATE TYPE`` for this :class:`~.postgresql.ENUM`. If the underlying dialect does not support Postgresql CREATE TYPE, no action is taken. :param bind: a connectable :class:`.Engine`, :class:`.Connection`, or similar object to emit SQL. :param checkfirst: if ``True``, a query against the PG catalog will be first performed to see if the type does not exist already before creating. """ if not bind.dialect.supports_native_enum: return if not checkfirst or \ not bind.dialect.has_type( bind, self.name, schema=self.schema): bind.execute(CreateEnumType(self)) def drop(self, bind=None, checkfirst=True): """Emit ``DROP TYPE`` for this :class:`~.postgresql.ENUM`. If the underlying dialect does not support Postgresql DROP TYPE, no action is taken. :param bind: a connectable :class:`.Engine`, :class:`.Connection`, or similar object to emit SQL. :param checkfirst: if ``True``, a query against the PG catalog will be first performed to see if the type actually exists before dropping. """ if not bind.dialect.supports_native_enum: return if not checkfirst or \ bind.dialect.has_type(bind, self.name, schema=self.schema): bind.execute(DropEnumType(self)) def _check_for_name_in_memos(self, checkfirst, kw): """Look in the 'ddl runner' for 'memos', then note our name in that collection. This to ensure a particular named enum is operated upon only once within any kind of create/drop sequence without relying upon "checkfirst". """ if not self.create_type: return True if '_ddl_runner' in kw: ddl_runner = kw['_ddl_runner'] if '_pg_enums' in ddl_runner.memo: pg_enums = ddl_runner.memo['_pg_enums'] else: pg_enums = ddl_runner.memo['_pg_enums'] = set() present = self.name in pg_enums pg_enums.add(self.name) return present else: return False def _on_table_create(self, target, bind, checkfirst, **kw): if not self._check_for_name_in_memos(checkfirst, kw): self.create(bind=bind, checkfirst=checkfirst) def _on_metadata_create(self, target, bind, checkfirst, **kw): if not self._check_for_name_in_memos(checkfirst, kw): self.create(bind=bind, checkfirst=checkfirst) def _on_metadata_drop(self, target, bind, checkfirst, **kw): if not self._check_for_name_in_memos(checkfirst, kw): self.drop(bind=bind, checkfirst=checkfirst) colspecs = { sqltypes.Interval: INTERVAL, sqltypes.Enum: ENUM, } ischema_names = { 'integer': INTEGER, 'bigint': BIGINT, 'smallint': SMALLINT, 'character varying': VARCHAR, 'character': CHAR, '"char"': sqltypes.String, 'name': sqltypes.String, 'text': TEXT, 'numeric': NUMERIC, 'float': FLOAT, 'real': REAL, 'inet': INET, 'cidr': CIDR, 'uuid': UUID, 'bit': BIT, 'bit varying': BIT, 'macaddr': MACADDR, 'oid': OID, 'double precision': DOUBLE_PRECISION, 'timestamp': TIMESTAMP, 'timestamp with time zone': TIMESTAMP, 'timestamp without time zone': TIMESTAMP, 'time with time zone': TIME, 'time without time zone': TIME, 'date': DATE, 'time': TIME, 'bytea': BYTEA, 'boolean': BOOLEAN, 'interval': INTERVAL, 'interval year to month': INTERVAL, 'interval day to second': INTERVAL, 'tsvector': TSVECTOR } class PGCompiler(compiler.SQLCompiler): def visit_array(self, element, **kw): return "ARRAY[%s]" % self.visit_clauselist(element, **kw) def visit_slice(self, element, **kw): return "%s:%s" % ( self.process(element.start, **kw), self.process(element.stop, **kw), ) def visit_any(self, element, **kw): return "%s%sANY (%s)" % ( self.process(element.left, **kw), compiler.OPERATORS[element.operator], self.process(element.right, **kw) ) def visit_all(self, element, **kw): return "%s%sALL (%s)" % ( self.process(element.left, **kw), compiler.OPERATORS[element.operator], self.process(element.right, **kw) ) def visit_getitem_binary(self, binary, operator, **kw): return "%s[%s]" % ( self.process(binary.left, **kw), self.process(binary.right, **kw) ) def visit_match_op_binary(self, binary, operator, **kw): if "postgresql_regconfig" in binary.modifiers: regconfig = self.render_literal_value( binary.modifiers['postgresql_regconfig'], sqltypes.STRINGTYPE) if regconfig: return "%s @@ to_tsquery(%s, %s)" % ( self.process(binary.left, **kw), regconfig, self.process(binary.right, **kw) ) return "%s @@ to_tsquery(%s)" % ( self.process(binary.left, **kw), self.process(binary.right, **kw) ) def visit_ilike_op_binary(self, binary, operator, **kw): escape = binary.modifiers.get("escape", None) return '%s ILIKE %s' % \ (self.process(binary.left, **kw), self.process(binary.right, **kw)) \ + ( ' ESCAPE ' + self.render_literal_value(escape, sqltypes.STRINGTYPE) if escape else '' ) def visit_notilike_op_binary(self, binary, operator, **kw): escape = binary.modifiers.get("escape", None) return '%s NOT ILIKE %s' % \ (self.process(binary.left, **kw), self.process(binary.right, **kw)) \ + ( ' ESCAPE ' + self.render_literal_value(escape, sqltypes.STRINGTYPE) if escape else '' ) def render_literal_value(self, value, type_): value = super(PGCompiler, self).render_literal_value(value, type_) if self.dialect._backslash_escapes: value = value.replace('\\', '\\\\') return value def visit_sequence(self, seq): return "nextval('%s')" % self.preparer.format_sequence(seq) def limit_clause(self, select): text = "" if select._limit is not None: text += " \n LIMIT " + self.process(sql.literal(select._limit)) if select._offset is not None: if select._limit is None: text += " \n LIMIT ALL" text += " OFFSET " + self.process(sql.literal(select._offset)) return text def format_from_hint_text(self, sqltext, table, hint, iscrud): if hint.upper() != 'ONLY': raise exc.CompileError("Unrecognized hint: %r" % hint) return "ONLY " + sqltext def get_select_precolumns(self, select): if select._distinct is not False: if select._distinct is True: return "DISTINCT " elif isinstance(select._distinct, (list, tuple)): return "DISTINCT ON (" + ', '.join( [self.process(col) for col in select._distinct] ) + ") " else: return "DISTINCT ON (" + self.process(select._distinct) + ") " else: return "" def for_update_clause(self, select): if select._for_update_arg.read: tmp = " FOR SHARE" else: tmp = " FOR UPDATE" if select._for_update_arg.of: tables = util.OrderedSet( c.table if isinstance(c, expression.ColumnClause) else c for c in select._for_update_arg.of) tmp += " OF " + ", ".join( self.process(table, ashint=True) for table in tables ) if select._for_update_arg.nowait: tmp += " NOWAIT" return tmp def returning_clause(self, stmt, returning_cols): columns = [ self._label_select_column(None, c, True, False, {}) for c in expression._select_iterables(returning_cols) ] return 'RETURNING ' + ', '.join(columns) def visit_substring_func(self, func, **kw): s = self.process(func.clauses.clauses[0], **kw) start = self.process(func.clauses.clauses[1], **kw) if len(func.clauses.clauses) > 2: length = self.process(func.clauses.clauses[2], **kw) return "SUBSTRING(%s FROM %s FOR %s)" % (s, start, length) else: return "SUBSTRING(%s FROM %s)" % (s, start) class PGDDLCompiler(compiler.DDLCompiler): def get_column_specification(self, column, **kwargs): colspec = self.preparer.format_column(column) impl_type = column.type.dialect_impl(self.dialect) if column.primary_key and \ column is column.table._autoincrement_column and \ ( self.dialect.supports_smallserial or not isinstance(impl_type, sqltypes.SmallInteger) ) and ( column.default is None or ( isinstance(column.default, schema.Sequence) and column.default.optional )): if isinstance(impl_type, sqltypes.BigInteger): colspec += " BIGSERIAL" elif isinstance(impl_type, sqltypes.SmallInteger): colspec += " SMALLSERIAL" else: colspec += " SERIAL" else: colspec += " " + self.dialect.type_compiler.process(column.type) default = self.get_column_default_string(column) if default is not None: colspec += " DEFAULT " + default if not column.nullable: colspec += " NOT NULL" return colspec def visit_create_enum_type(self, create): type_ = create.element return "CREATE TYPE %s AS ENUM (%s)" % ( self.preparer.format_type(type_), ", ".join( self.sql_compiler.process(sql.literal(e), literal_binds=True) for e in type_.enums) ) def visit_drop_enum_type(self, drop): type_ = drop.element return "DROP TYPE %s" % ( self.preparer.format_type(type_) ) def visit_create_index(self, create): preparer = self.preparer index = create.element self._verify_index_table(index) text = "CREATE " if index.unique: text += "UNIQUE " text += "INDEX %s ON %s " % ( self._prepared_index_name(index, include_schema=False), preparer.format_table(index.table) ) using = index.dialect_options['postgresql']['using'] if using: text += "USING %s " % preparer.quote(using) ops = index.dialect_options["postgresql"]["ops"] text += "(%s)" \ % ( ', '.join([ self.sql_compiler.process( expr.self_group() if not isinstance(expr, expression.ColumnClause) else expr, include_table=False, literal_binds=True) + (c.key in ops and (' ' + ops[c.key]) or '') for expr, c in zip(index.expressions, index.columns)]) ) whereclause = index.dialect_options["postgresql"]["where"] if whereclause is not None: where_compiled = self.sql_compiler.process( whereclause, include_table=False, literal_binds=True) text += " WHERE " + where_compiled return text def visit_exclude_constraint(self, constraint): text = "" if constraint.name is not None: text += "CONSTRAINT %s " % \ self.preparer.format_constraint(constraint) elements = [] for c in constraint.columns: op = constraint.operators[c.name] elements.append(self.preparer.quote(c.name) + ' WITH ' + op) text += "EXCLUDE USING %s (%s)" % (constraint.using, ', '.join(elements)) if constraint.where is not None: text += ' WHERE (%s)' % self.sql_compiler.process( constraint.where, literal_binds=True) text += self.define_constraint_deferrability(constraint) return text class PGTypeCompiler(compiler.GenericTypeCompiler): def visit_TSVECTOR(self, type): return "TSVECTOR" def visit_INET(self, type_): return "INET" def visit_CIDR(self, type_): return "CIDR" def visit_MACADDR(self, type_): return "MACADDR" def visit_OID(self, type_): return "OID" def visit_FLOAT(self, type_): if not type_.precision: return "FLOAT" else: return "FLOAT(%(precision)s)" % {'precision': type_.precision} def visit_DOUBLE_PRECISION(self, type_): return "DOUBLE PRECISION" def visit_BIGINT(self, type_): return "BIGINT" def visit_HSTORE(self, type_): return "HSTORE" def visit_JSON(self, type_): return "JSON" def visit_JSONB(self, type_): return "JSONB" def visit_INT4RANGE(self, type_): return "INT4RANGE" def visit_INT8RANGE(self, type_): return "INT8RANGE" def visit_NUMRANGE(self, type_): return "NUMRANGE" def visit_DATERANGE(self, type_): return "DATERANGE" def visit_TSRANGE(self, type_): return "TSRANGE" def visit_TSTZRANGE(self, type_): return "TSTZRANGE" def visit_datetime(self, type_): return self.visit_TIMESTAMP(type_) def visit_enum(self, type_): if not type_.native_enum or not self.dialect.supports_native_enum: return super(PGTypeCompiler, self).visit_enum(type_) else: return self.visit_ENUM(type_) def visit_ENUM(self, type_): return self.dialect.identifier_preparer.format_type(type_) def visit_TIMESTAMP(self, type_): return "TIMESTAMP%s %s" % ( getattr(type_, 'precision', None) and "(%d)" % type_.precision or "", (type_.timezone and "WITH" or "WITHOUT") + " TIME ZONE" ) def visit_TIME(self, type_): return "TIME%s %s" % ( getattr(type_, 'precision', None) and "(%d)" % type_.precision or "", (type_.timezone and "WITH" or "WITHOUT") + " TIME ZONE" ) def visit_INTERVAL(self, type_): if type_.precision is not None: return "INTERVAL(%d)" % type_.precision else: return "INTERVAL" def visit_BIT(self, type_): if type_.varying: compiled = "BIT VARYING" if type_.length is not None: compiled += "(%d)" % type_.length else: compiled = "BIT(%d)" % type_.length return compiled def visit_UUID(self, type_): return "UUID" def visit_large_binary(self, type_): return self.visit_BYTEA(type_) def visit_BYTEA(self, type_): return "BYTEA" def visit_ARRAY(self, type_): return self.process(type_.item_type) + ('[]' * (type_.dimensions if type_.dimensions is not None else 1)) class PGIdentifierPreparer(compiler.IdentifierPreparer): reserved_words = RESERVED_WORDS def _unquote_identifier(self, value): if value[0] == self.initial_quote: value = value[1:-1].\ replace(self.escape_to_quote, self.escape_quote) return value def format_type(self, type_, use_schema=True): if not type_.name: raise exc.CompileError("Postgresql ENUM type requires a name.") name = self.quote(type_.name) if not self.omit_schema and use_schema and type_.schema is not None: name = self.quote_schema(type_.schema) + "." + name return name class PGInspector(reflection.Inspector): def __init__(self, conn): reflection.Inspector.__init__(self, conn) def get_table_oid(self, table_name, schema=None): """Return the oid from `table_name` and `schema`.""" return self.dialect.get_table_oid(self.bind, table_name, schema, info_cache=self.info_cache) class CreateEnumType(schema._CreateDropBase): __visit_name__ = "create_enum_type" class DropEnumType(schema._CreateDropBase): __visit_name__ = "drop_enum_type" class PGExecutionContext(default.DefaultExecutionContext): def fire_sequence(self, seq, type_): return self._execute_scalar(( "select nextval('%s')" % self.dialect.identifier_preparer.format_sequence(seq)), type_) def get_insert_default(self, column): if column.primary_key and \ column is column.table._autoincrement_column: if column.server_default and column.server_default.has_argument: # pre-execute passive defaults on primary key columns return self._execute_scalar("select %s" % column.server_default.arg, column.type) elif (column.default is None or (column.default.is_sequence and column.default.optional)): # execute the sequence associated with a SERIAL primary # key column. for non-primary-key SERIAL, the ID just # generates server side. try: seq_name = column._postgresql_seq_name except AttributeError: tab = column.table.name col = column.name tab = tab[0:29 + max(0, (29 - len(col)))] col = col[0:29 + max(0, (29 - len(tab)))] name = "%s_%s_seq" % (tab, col) column._postgresql_seq_name = seq_name = name sch = column.table.schema if sch is not None: exc = "select nextval('\"%s\".\"%s\"')" % \ (sch, seq_name) else: exc = "select nextval('\"%s\"')" % \ (seq_name, ) return self._execute_scalar(exc, column.type) return super(PGExecutionContext, self).get_insert_default(column) class PGDialect(default.DefaultDialect): name = 'postgresql' supports_alter = True max_identifier_length = 63 supports_sane_rowcount = True supports_native_enum = True supports_native_boolean = True supports_smallserial = True supports_sequences = True sequences_optional = True preexecute_autoincrement_sequences = True postfetch_lastrowid = False supports_default_values = True supports_empty_insert = False supports_multivalues_insert = True default_paramstyle = 'pyformat' ischema_names = ischema_names colspecs = colspecs statement_compiler = PGCompiler ddl_compiler = PGDDLCompiler type_compiler = PGTypeCompiler preparer = PGIdentifierPreparer execution_ctx_cls = PGExecutionContext inspector = PGInspector isolation_level = None construct_arguments = [ (schema.Index, { "using": False, "where": None, "ops": {} }), (schema.Table, { "ignore_search_path": False }) ] reflection_options = ('postgresql_ignore_search_path', ) _backslash_escapes = True def __init__(self, isolation_level=None, json_serializer=None, json_deserializer=None, **kwargs): default.DefaultDialect.__init__(self, **kwargs) self.isolation_level = isolation_level self._json_deserializer = json_deserializer self._json_serializer = json_serializer def initialize(self, connection): super(PGDialect, self).initialize(connection) self.implicit_returning = self.server_version_info > (8, 2) and \ self.__dict__.get('implicit_returning', True) self.supports_native_enum = self.server_version_info >= (8, 3) if not self.supports_native_enum: self.colspecs = self.colspecs.copy() # pop base Enum type self.colspecs.pop(sqltypes.Enum, None) # psycopg2, others may have placed ENUM here as well self.colspecs.pop(ENUM, None) # http://www.postgresql.org/docs/9.3/static/release-9-2.html#AEN116689 self.supports_smallserial = self.server_version_info >= (9, 2) self._backslash_escapes = self.server_version_info < (8, 2) or \ connection.scalar( "show standard_conforming_strings" ) == 'off' def on_connect(self): if self.isolation_level is not None: def connect(conn): self.set_isolation_level(conn, self.isolation_level) return connect else: return None _isolation_lookup = set(['SERIALIZABLE', 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ']) def set_isolation_level(self, connection, level): level = level.replace('_', ' ') if level not in self._isolation_lookup: raise exc.ArgumentError( "Invalid value '%s' for isolation_level. " "Valid isolation levels for %s are %s" % (level, self.name, ", ".join(self._isolation_lookup)) ) cursor = connection.cursor() cursor.execute( "SET SESSION CHARACTERISTICS AS TRANSACTION " "ISOLATION LEVEL %s" % level) cursor.execute("COMMIT") cursor.close() def get_isolation_level(self, connection): cursor = connection.cursor() cursor.execute('show transaction isolation level') val = cursor.fetchone()[0] cursor.close() return val.upper() def do_begin_twophase(self, connection, xid): self.do_begin(connection.connection) def do_prepare_twophase(self, connection, xid): connection.execute("PREPARE TRANSACTION '%s'" % xid) def do_rollback_twophase(self, connection, xid, is_prepared=True, recover=False): if is_prepared: if recover: # FIXME: ugly hack to get out of transaction # context when committing recoverable transactions # Must find out a way how to make the dbapi not # open a transaction. connection.execute("ROLLBACK") connection.execute("ROLLBACK PREPARED '%s'" % xid) connection.execute("BEGIN") self.do_rollback(connection.connection) else: self.do_rollback(connection.connection) def do_commit_twophase(self, connection, xid, is_prepared=True, recover=False): if is_prepared: if recover: connection.execute("ROLLBACK") connection.execute("COMMIT PREPARED '%s'" % xid) connection.execute("BEGIN") self.do_rollback(connection.connection) else: self.do_commit(connection.connection) def do_recover_twophase(self, connection): resultset = connection.execute( sql.text("SELECT gid FROM pg_prepared_xacts")) return [row[0] for row in resultset] def _get_default_schema_name(self, connection): return connection.scalar("select current_schema()") def has_schema(self, connection, schema): query = ("select nspname from pg_namespace " "where lower(nspname)=:schema") cursor = connection.execute( sql.text( query, bindparams=[ sql.bindparam( 'schema', util.text_type(schema.lower()), type_=sqltypes.Unicode)] ) ) return bool(cursor.first()) def has_table(self, connection, table_name, schema=None): # seems like case gets folded in pg_class... if schema is None: cursor = connection.execute( sql.text( "select relname from pg_class c join pg_namespace n on " "n.oid=c.relnamespace where n.nspname=current_schema() " "and relname=:name", bindparams=[ sql.bindparam('name', util.text_type(table_name), type_=sqltypes.Unicode)] ) ) else: cursor = connection.execute( sql.text( "select relname from pg_class c join pg_namespace n on " "n.oid=c.relnamespace where n.nspname=:schema and " "relname=:name", bindparams=[ sql.bindparam('name', util.text_type(table_name), type_=sqltypes.Unicode), sql.bindparam('schema', util.text_type(schema), type_=sqltypes.Unicode)] ) ) return bool(cursor.first()) def has_sequence(self, connection, sequence_name, schema=None): if schema is None: cursor = connection.execute( sql.text( "SELECT relname FROM pg_class c join pg_namespace n on " "n.oid=c.relnamespace where relkind='S' and " "n.nspname=current_schema() " "and relname=:name", bindparams=[ sql.bindparam('name', util.text_type(sequence_name), type_=sqltypes.Unicode) ] ) ) else: cursor = connection.execute( sql.text( "SELECT relname FROM pg_class c join pg_namespace n on " "n.oid=c.relnamespace where relkind='S' and " "n.nspname=:schema and relname=:name", bindparams=[ sql.bindparam('name', util.text_type(sequence_name), type_=sqltypes.Unicode), sql.bindparam('schema', util.text_type(schema), type_=sqltypes.Unicode) ] ) ) return bool(cursor.first()) def has_type(self, connection, type_name, schema=None): if schema is not None: query = """ SELECT EXISTS ( SELECT * FROM pg_catalog.pg_type t, pg_catalog.pg_namespace n WHERE t.typnamespace = n.oid AND t.typname = :typname AND n.nspname = :nspname ) """ query = sql.text(query) else: query = """ SELECT EXISTS ( SELECT * FROM pg_catalog.pg_type t WHERE t.typname = :typname AND pg_type_is_visible(t.oid) ) """ query = sql.text(query) query = query.bindparams( sql.bindparam('typname', util.text_type(type_name), type_=sqltypes.Unicode), ) if schema is not None: query = query.bindparams( sql.bindparam('nspname', util.text_type(schema), type_=sqltypes.Unicode), ) cursor = connection.execute(query) return bool(cursor.scalar()) def _get_server_version_info(self, connection): v = connection.execute("select version()").scalar() m = re.match( '.*(?:PostgreSQL|EnterpriseDB) ' '(\d+)\.(\d+)(?:\.(\d+))?(?:\.\d+)?(?:devel)?', v) if not m: raise AssertionError( "Could not determine version from string '%s'" % v) return tuple([int(x) for x in m.group(1, 2, 3) if x is not None]) @reflection.cache def get_table_oid(self, connection, table_name, schema=None, **kw): """Fetch the oid for schema.table_name. Several reflection methods require the table oid. The idea for using this method is that it can be fetched one time and cached for subsequent calls. """ table_oid = None if schema is not None: schema_where_clause = "n.nspname = :schema" else: schema_where_clause = "pg_catalog.pg_table_is_visible(c.oid)" query = """ SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE (%s) AND c.relname = :table_name AND c.relkind in ('r','v') """ % schema_where_clause # Since we're binding to unicode, table_name and schema_name must be # unicode. table_name = util.text_type(table_name) if schema is not None: schema = util.text_type(schema) s = sql.text(query).bindparams(table_name=sqltypes.Unicode) s = s.columns(oid=sqltypes.Integer) if schema: s = s.bindparams(sql.bindparam('schema', type_=sqltypes.Unicode)) c = connection.execute(s, table_name=table_name, schema=schema) table_oid = c.scalar() if table_oid is None: raise exc.NoSuchTableError(table_name) return table_oid @reflection.cache def get_schema_names(self, connection, **kw): s = """ SELECT nspname FROM pg_namespace ORDER BY nspname """ rp = connection.execute(s) # what about system tables? if util.py2k: schema_names = [row[0].decode(self.encoding) for row in rp if not row[0].startswith('pg_')] else: schema_names = [row[0] for row in rp if not row[0].startswith('pg_')] return schema_names @reflection.cache def get_table_names(self, connection, schema=None, **kw): if schema is not None: current_schema = schema else: current_schema = self.default_schema_name result = connection.execute( sql.text("SELECT relname FROM pg_class c " "WHERE relkind = 'r' " "AND '%s' = (select nspname from pg_namespace n " "where n.oid = c.relnamespace) " % current_schema, typemap={'relname': sqltypes.Unicode} ) ) return [row[0] for row in result] @reflection.cache def get_view_names(self, connection, schema=None, **kw): if schema is not None: current_schema = schema else: current_schema = self.default_schema_name s = """ SELECT relname FROM pg_class c WHERE relkind = 'v' AND '%(schema)s' = (select nspname from pg_namespace n where n.oid = c.relnamespace) """ % dict(schema=current_schema) if util.py2k: view_names = [row[0].decode(self.encoding) for row in connection.execute(s)] else: view_names = [row[0] for row in connection.execute(s)] return view_names @reflection.cache def get_view_definition(self, connection, view_name, schema=None, **kw): if schema is not None: current_schema = schema else: current_schema = self.default_schema_name s = """ SELECT definition FROM pg_views WHERE schemaname = :schema AND viewname = :view_name """ rp = connection.execute(sql.text(s), view_name=view_name, schema=current_schema) if rp: if util.py2k: view_def = rp.scalar().decode(self.encoding) else: view_def = rp.scalar() return view_def @reflection.cache def get_columns(self, connection, table_name, schema=None, **kw): table_oid = self.get_table_oid(connection, table_name, schema, info_cache=kw.get('info_cache')) SQL_COLS = """ SELECT a.attname, pg_catalog.format_type(a.atttypid, a.atttypmod), (SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) AS DEFAULT, a.attnotnull, a.attnum, a.attrelid as table_oid FROM pg_catalog.pg_attribute a WHERE a.attrelid = :table_oid AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum """ s = sql.text(SQL_COLS, bindparams=[ sql.bindparam('table_oid', type_=sqltypes.Integer)], typemap={ 'attname': sqltypes.Unicode, 'default': sqltypes.Unicode} ) c = connection.execute(s, table_oid=table_oid) rows = c.fetchall() domains = self._load_domains(connection) enums = self._load_enums(connection) # format columns columns = [] for name, format_type, default, notnull, attnum, table_oid in rows: column_info = self._get_column_info( name, format_type, default, notnull, domains, enums, schema) columns.append(column_info) return columns def _get_column_info(self, name, format_type, default, notnull, domains, enums, schema): # strip (*) from character varying(5), timestamp(5) # with time zone, geometry(POLYGON), etc. attype = re.sub(r'\(.*\)', '', format_type) # strip '[]' from integer[], etc. attype = re.sub(r'\[\]', '', attype) nullable = not notnull is_array = format_type.endswith('[]') charlen = re.search('\(([\d,]+)\)', format_type) if charlen: charlen = charlen.group(1) args = re.search('\((.*)\)', format_type) if args and args.group(1): args = tuple(re.split('\s*,\s*', args.group(1))) else: args = () kwargs = {} if attype == 'numeric': if charlen: prec, scale = charlen.split(',') args = (int(prec), int(scale)) else: args = () elif attype == 'double precision': args = (53, ) elif attype == 'integer': args = () elif attype in ('timestamp with time zone', 'time with time zone'): kwargs['timezone'] = True if charlen: kwargs['precision'] = int(charlen) args = () elif attype in ('timestamp without time zone', 'time without time zone', 'time'): kwargs['timezone'] = False if charlen: kwargs['precision'] = int(charlen) args = () elif attype == 'bit varying': kwargs['varying'] = True if charlen: args = (int(charlen),) else: args = () elif attype in ('interval', 'interval year to month', 'interval day to second'): if charlen: kwargs['precision'] = int(charlen) args = () elif charlen: args = (int(charlen),) while True: if attype in self.ischema_names: coltype = self.ischema_names[attype] break elif attype in enums: enum = enums[attype] coltype = ENUM if "." in attype: kwargs['schema'], kwargs['name'] = attype.split('.') else: kwargs['name'] = attype args = tuple(enum['labels']) break elif attype in domains: domain = domains[attype] attype = domain['attype'] # A table can't override whether the domain is nullable. nullable = domain['nullable'] if domain['default'] and not default: # It can, however, override the default # value, but can't set it to null. default = domain['default'] continue else: coltype = None break if coltype: coltype = coltype(*args, **kwargs) if is_array: coltype = ARRAY(coltype) else: util.warn("Did not recognize type '%s' of column '%s'" % (attype, name)) coltype = sqltypes.NULLTYPE # adjust the default value autoincrement = False if default is not None: match = re.search(r"""(nextval\(')([^']+)('.*$)""", default) if match is not None: autoincrement = True # the default is related to a Sequence sch = schema if '.' not in match.group(2) and sch is not None: # unconditionally quote the schema name. this could # later be enhanced to obey quoting rules / # "quote schema" default = match.group(1) + \ ('"%s"' % sch) + '.' + \ match.group(2) + match.group(3) column_info = dict(name=name, type=coltype, nullable=nullable, default=default, autoincrement=autoincrement) return column_info @reflection.cache def get_pk_constraint(self, connection, table_name, schema=None, **kw): table_oid = self.get_table_oid(connection, table_name, schema, info_cache=kw.get('info_cache')) if self.server_version_info < (8, 4): PK_SQL = """ SELECT a.attname FROM pg_class t join pg_index ix on t.oid = ix.indrelid join pg_attribute a on t.oid=a.attrelid AND %s WHERE t.oid = :table_oid and ix.indisprimary = 't' ORDER BY a.attnum """ % self._pg_index_any("a.attnum", "ix.indkey") else: # unnest() and generate_subscripts() both introduced in # version 8.4 PK_SQL = """ SELECT a.attname FROM pg_attribute a JOIN ( SELECT unnest(ix.indkey) attnum, generate_subscripts(ix.indkey, 1) ord FROM pg_index ix WHERE ix.indrelid = :table_oid AND ix.indisprimary ) k ON a.attnum=k.attnum WHERE a.attrelid = :table_oid ORDER BY k.ord """ t = sql.text(PK_SQL, typemap={'attname': sqltypes.Unicode}) c = connection.execute(t, table_oid=table_oid) cols = [r[0] for r in c.fetchall()] PK_CONS_SQL = """ SELECT conname FROM pg_catalog.pg_constraint r WHERE r.conrelid = :table_oid AND r.contype = 'p' ORDER BY 1 """ t = sql.text(PK_CONS_SQL, typemap={'conname': sqltypes.Unicode}) c = connection.execute(t, table_oid=table_oid) name = c.scalar() return {'constrained_columns': cols, 'name': name} @reflection.cache def get_foreign_keys(self, connection, table_name, schema=None, postgresql_ignore_search_path=False, **kw): preparer = self.identifier_preparer table_oid = self.get_table_oid(connection, table_name, schema, info_cache=kw.get('info_cache')) FK_SQL = """ SELECT r.conname, pg_catalog.pg_get_constraintdef(r.oid, true) as condef, n.nspname as conschema FROM pg_catalog.pg_constraint r, pg_namespace n, pg_class c WHERE r.conrelid = :table AND r.contype = 'f' AND c.oid = confrelid AND n.oid = c.relnamespace ORDER BY 1 """ # http://www.postgresql.org/docs/9.0/static/sql-createtable.html FK_REGEX = re.compile( r'FOREIGN KEY \((.*?)\) REFERENCES (?:(.*?)\.)?(.*?)\((.*?)\)' r'[\s]?(MATCH (FULL|PARTIAL|SIMPLE)+)?' r'[\s]?(ON UPDATE ' r'(CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?' r'[\s]?(ON DELETE ' r'(CASCADE|RESTRICT|NO ACTION|SET NULL|SET DEFAULT)+)?' r'[\s]?(DEFERRABLE|NOT DEFERRABLE)?' r'[\s]?(INITIALLY (DEFERRED|IMMEDIATE)+)?' ) t = sql.text(FK_SQL, typemap={ 'conname': sqltypes.Unicode, 'condef': sqltypes.Unicode}) c = connection.execute(t, table=table_oid) fkeys = [] for conname, condef, conschema in c.fetchall(): m = re.search(FK_REGEX, condef).groups() constrained_columns, referred_schema, \ referred_table, referred_columns, \ _, match, _, onupdate, _, ondelete, \ deferrable, _, initially = m if deferrable is not None: deferrable = True if deferrable == 'DEFERRABLE' else False constrained_columns = [preparer._unquote_identifier(x) for x in re.split( r'\s*,\s*', constrained_columns)] if postgresql_ignore_search_path: # when ignoring search path, we use the actual schema # provided it isn't the "default" schema if conschema != self.default_schema_name: referred_schema = conschema else: referred_schema = schema elif referred_schema: # referred_schema is the schema that we regexp'ed from # pg_get_constraintdef(). If the schema is in the search # path, pg_get_constraintdef() will give us None. referred_schema = \ preparer._unquote_identifier(referred_schema) elif schema is not None and schema == conschema: # If the actual schema matches the schema of the table # we're reflecting, then we will use that. referred_schema = schema referred_table = preparer._unquote_identifier(referred_table) referred_columns = [preparer._unquote_identifier(x) for x in re.split(r'\s*,\s', referred_columns)] fkey_d = { 'name': conname, 'constrained_columns': constrained_columns, 'referred_schema': referred_schema, 'referred_table': referred_table, 'referred_columns': referred_columns, 'options': { 'onupdate': onupdate, 'ondelete': ondelete, 'deferrable': deferrable, 'initially': initially, 'match': match } } fkeys.append(fkey_d) return fkeys def _pg_index_any(self, col, compare_to): if self.server_version_info < (8, 1): # http://www.postgresql.org/message-id/10279.1124395722@sss.pgh.pa.us # "In CVS tip you could replace this with "attnum = ANY (indkey)". # Unfortunately, most array support doesn't work on int2vector in # pre-8.1 releases, so I think you're kinda stuck with the above # for now. # regards, tom lane" return "(%s)" % " OR ".join( "%s[%d] = %s" % (compare_to, ind, col) for ind in range(0, 10) ) else: return "%s = ANY(%s)" % (col, compare_to) @reflection.cache def get_indexes(self, connection, table_name, schema, **kw): table_oid = self.get_table_oid(connection, table_name, schema, info_cache=kw.get('info_cache')) # cast indkey as varchar since it's an int2vector, # returned as a list by some drivers such as pypostgresql IDX_SQL = """ SELECT i.relname as relname, ix.indisunique, ix.indexprs, ix.indpred, a.attname, a.attnum, ix.indkey%s FROM pg_class t join pg_index ix on t.oid = ix.indrelid join pg_class i on i.oid=ix.indexrelid left outer join pg_attribute a on t.oid=a.attrelid and %s WHERE t.relkind = 'r' and t.oid = :table_oid and ix.indisprimary = 'f' ORDER BY t.relname, i.relname """ % ( # version 8.3 here was based on observing the # cast does not work in PG 8.2.4, does work in 8.3.0. # nothing in PG changelogs regarding this. "::varchar" if self.server_version_info >= (8, 3) else "", self._pg_index_any("a.attnum", "ix.indkey") ) t = sql.text(IDX_SQL, typemap={'attname': sqltypes.Unicode}) c = connection.execute(t, table_oid=table_oid) indexes = defaultdict(lambda: defaultdict(dict)) sv_idx_name = None for row in c.fetchall(): idx_name, unique, expr, prd, col, col_num, idx_key = row if expr: if idx_name != sv_idx_name: util.warn( "Skipped unsupported reflection of " "expression-based index %s" % idx_name) sv_idx_name = idx_name continue if prd and not idx_name == sv_idx_name: util.warn( "Predicate of partial index %s ignored during reflection" % idx_name) sv_idx_name = idx_name index = indexes[idx_name] if col is not None: index['cols'][col_num] = col index['key'] = [int(k.strip()) for k in idx_key.split()] index['unique'] = unique return [ {'name': name, 'unique': idx['unique'], 'column_names': [idx['cols'][i] for i in idx['key']]} for name, idx in indexes.items() ] @reflection.cache def get_unique_constraints(self, connection, table_name, schema=None, **kw): table_oid = self.get_table_oid(connection, table_name, schema, info_cache=kw.get('info_cache')) UNIQUE_SQL = """ SELECT cons.conname as name, cons.conkey as key, a.attnum as col_num, a.attname as col_name FROM pg_catalog.pg_constraint cons join pg_attribute a on cons.conrelid = a.attrelid AND a.attnum = ANY(cons.conkey) WHERE cons.conrelid = :table_oid AND cons.contype = 'u' """ t = sql.text(UNIQUE_SQL, typemap={'col_name': sqltypes.Unicode}) c = connection.execute(t, table_oid=table_oid) uniques = defaultdict(lambda: defaultdict(dict)) for row in c.fetchall(): uc = uniques[row.name] uc["key"] = row.key uc["cols"][row.col_num] = row.col_name return [ {'name': name, 'column_names': [uc["cols"][i] for i in uc["key"]]} for name, uc in uniques.items() ] def _load_enums(self, connection): if not self.supports_native_enum: return {} # Load data types for enums: SQL_ENUMS = """ SELECT t.typname as "name", -- no enum defaults in 8.4 at least -- t.typdefault as "default", pg_catalog.pg_type_is_visible(t.oid) as "visible", n.nspname as "schema", e.enumlabel as "label" FROM pg_catalog.pg_type t LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace LEFT JOIN pg_catalog.pg_enum e ON t.oid = e.enumtypid WHERE t.typtype = 'e' ORDER BY "name", e.oid -- e.oid gives us label order """ s = sql.text(SQL_ENUMS, typemap={ 'attname': sqltypes.Unicode, 'label': sqltypes.Unicode}) c = connection.execute(s) enums = {} for enum in c.fetchall(): if enum['visible']: # 'visible' just means whether or not the enum is in a # schema that's on the search path -- or not overridden by # a schema with higher precedence. If it's not visible, # it will be prefixed with the schema-name when it's used. name = enum['name'] else: name = "%s.%s" % (enum['schema'], enum['name']) if name in enums: enums[name]['labels'].append(enum['label']) else: enums[name] = { 'labels': [enum['label']], } return enums def _load_domains(self, connection): # Load data types for domains: SQL_DOMAINS = """ SELECT t.typname as "name", pg_catalog.format_type(t.typbasetype, t.typtypmod) as "attype", not t.typnotnull as "nullable", t.typdefault as "default", pg_catalog.pg_type_is_visible(t.oid) as "visible", n.nspname as "schema" FROM pg_catalog.pg_type t LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE t.typtype = 'd' """ s = sql.text(SQL_DOMAINS, typemap={'attname': sqltypes.Unicode}) c = connection.execute(s) domains = {} for domain in c.fetchall(): # strip (30) from character varying(30) attype = re.search('([^\(]+)', domain['attype']).group(1) if domain['visible']: # 'visible' just means whether or not the domain is in a # schema that's on the search path -- or not overridden by # a schema with higher precedence. If it's not visible, # it will be prefixed with the schema-name when it's used. name = domain['name'] else: name = "%s.%s" % (domain['schema'], domain['name']) domains[name] = { 'attype': attype, 'nullable': domain['nullable'], 'default': domain['default'] } return domains
mit
billiob/papyon
tests/test_file_transfer.py
3
3904
# -*- coding: utf-8 -*- # # papyon - a python client library for Msn # # Copyright (C) 2010 Collabora Ltd. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from base import * sys.path.insert(0, "") import os import papyon class FileTransferClient(TestClient): def __init__(self): opts = [('-a', '--answer', {'type': 'choice', 'default': 'ignore', 'choices': ('ignore', 'accept', 'reject'), 'help': 'what to do on incoming file'}), ('-w', '--write', {'type': 'string', 'default': '', 'help': 'path to write received file'}), ('-S', '--send', {'type': 'string', 'nargs': 2, 'help': 'send file [recipient path]'}) ] args = [] TestClient.__init__(self, "File Transfer", opts, args, FileTransferClientEvents) def connected(self): self.profile.presence = papyon.profile.Presence.ONLINE if self.options.send: gobject.timeout_add_seconds(2, self.send) def send(self): recipient, path = self.options.send # get recipient contact = self.address_book.search_or_build_contact(recipient, papyon.profile.NetworkID.MSN) # get file details filename = os.path.basename(path) data = file(path, 'r') data.seek(0, os.SEEK_END) size = data.tell() data.seek(0, os.SEEK_SET) self._session = self.ft_manager.send(contact, filename, size, data) self._session_handler = FileTransferHandler(self._session) def accept(self, session): self._session = session self._session_handler = FileTransferHandler(session) buffer = None if self.options.write: buffer = file(self.options.write, 'w') session.accept(buffer) class FileTransferClientEvents(TestClientEvents): def __init__(self, client): TestClientEvents.__init__(self, client) def on_invite_file_transfer(self, session): print "** Invite for \"%s\" (%i bytes)" % (session.filename, session.size) if self._client.options.answer == 'accept': gobject.timeout_add_seconds(2, self._client.accept, session) elif self._client.options.answer == 'reject': session.reject() class FileTransferHandler(papyon.event.P2PSessionEventInterface): def __init__(self, session): papyon.event.P2PSessionEventInterface.__init__(self, session) self._transferred = 0 def on_session_accepted(self): print "** Session has been accepted" def on_session_rejected(self): print "** Session has been rejected" def on_session_completed(self, data): print "** Session has been completed" def on_session_canceled(self): print "** Session has been canceled" def on_session_disposed(self): print "** Session has been disposed" def on_session_progressed(self, size): self._transferred += size print "** Received %i / %i" % (self._transferred, self._client.size) if __name__ == "__main__": client = FileTransferClient() client.run()
gpl-2.0
nikolas/lettuce
tests/integration/lib/Django-1.3/django/contrib/localflavor/it/forms.py
273
3027
""" IT-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode from django.contrib.localflavor.it.util import ssn_check_digit, vat_number_check_digit import re class ITZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a valid zip code.'), } def __init__(self, *args, **kwargs): super(ITZipCodeField, self).__init__(r'^\d{5}$', max_length=None, min_length=None, *args, **kwargs) class ITRegionSelect(Select): """ A Select widget that uses a list of IT regions as its choices. """ def __init__(self, attrs=None): from it_region import REGION_CHOICES super(ITRegionSelect, self).__init__(attrs, choices=REGION_CHOICES) class ITProvinceSelect(Select): """ A Select widget that uses a list of IT provinces as its choices. """ def __init__(self, attrs=None): from it_province import PROVINCE_CHOICES super(ITProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES) class ITSocialSecurityNumberField(RegexField): """ A form field that validates Italian Social Security numbers (codice fiscale). For reference see http://www.agenziaentrate.it/ and search for 'Informazioni sulla codificazione delle persone fisiche'. """ default_error_messages = { 'invalid': _(u'Enter a valid Social Security number.'), } def __init__(self, *args, **kwargs): super(ITSocialSecurityNumberField, self).__init__(r'^\w{3}\s*\w{3}\s*\w{5}\s*\w{5}$', max_length=None, min_length=None, *args, **kwargs) def clean(self, value): value = super(ITSocialSecurityNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('\s', u'', value).upper() try: check_digit = ssn_check_digit(value) except ValueError: raise ValidationError(self.error_messages['invalid']) if not value[15] == check_digit: raise ValidationError(self.error_messages['invalid']) return value class ITVatNumberField(Field): """ A form field that validates Italian VAT numbers (partita IVA). """ default_error_messages = { 'invalid': _(u'Enter a valid VAT number.'), } def clean(self, value): value = super(ITVatNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' try: vat_number = int(value) except ValueError: raise ValidationError(self.error_messages['invalid']) vat_number = str(vat_number).zfill(11) check_digit = vat_number_check_digit(vat_number[0:10]) if not vat_number[10] == check_digit: raise ValidationError(self.error_messages['invalid']) return smart_unicode(vat_number)
gpl-3.0
branden/dcos
pkgpanda/cli.py
5
8154
"""Panda package management Usage: pkgpanda activate <id>... [options] pkgpanda swap <package-id> [options] pkgpanda active [options] pkgpanda fetch --repository-url=<url> <id>... [options] pkgpanda add <package-tarball> [options] pkgpanda list [options] pkgpanda remove <id>... [options] pkgpanda setup [options] pkgpanda uninstall [options] pkgpanda check [--list] [options] Options: --config-dir=<conf-dir> Use an alternate directory for finding machine configuration (roles, setup flags). [default: {default_config_dir}] --no-systemd Don't try starting/stopping systemd services --no-block-systemd Don't block waiting for systemd services to come up. --root=<root> Testing only: Use an alternate root [default: {default_root}] --state-dir-root=<root> Testing only: Use an alternate package state directory root [default: {default_state_dir_root}] --repository=<repository> Testing only: Use an alternate local package repository directory [default: {default_repository}] --rooted-systemd Use $ROOT/dcos.target.wants for systemd management rather than /etc/systemd/system/dcos.target.wants """ import os import sys from itertools import groupby from os import umask from subprocess import CalledProcessError, check_call from docopt import docopt from pkgpanda import actions, constants, Install, PackageId, Repository from pkgpanda.exceptions import PackageError, PackageNotFound, ValidationError def print_repo_list(packages): pkg_ids = list(map(PackageId, sorted(packages))) for name, group_iter in groupby(pkg_ids, lambda x: x.name): group = list(group_iter) if len(group) == 1: print(group[0]) else: print(name + ':') for package in group: print(" " + package.version) def uninstall(install, repository): print("Uninstalling DC/OS") # Remove dcos.target # TODO(cmaloney): Make this not quite so magical print("Removing dcos.target") print(os.path.dirname(install.systemd_dir) + "/dcos.target") check_call(['rm', '-f', os.path.dirname(install.systemd_dir) + "/dcos.target"]) # Cleanup all systemd units # TODO(cmaloney): This is much more work than we need to do the job print("Deactivating all packages") install.activate([]) # NOTE: All python libs need to be loaded before this so they are in-memory before we do the delete # Remove all well known files, directories # TODO(cmaloney): This should be a method of Install. print("Removing all runtime / activation directories") active_names = install.get_active_names() new_names = [name + '.new' for name in active_names] old_names = [name + '.old' for name in active_names] all_names = active_names + new_names + old_names assert len(all_names) > 0 if '/' in all_names + [install.root]: print("Cowardly refusing to rm -rf '/' as part of uninstall.", file=sys.stderr) print("Uninstall directories: ", ','.join(all_names + [install.root]), file=sys.stderr) sys.exit(1) check_call(['rm', '-rf'] + all_names) # Removing /opt/mesosphere check_call(['rm', '-rf', install.root]) def find_checks(install, repository): checks = {} for active_package in install.get_active(): tmp_checks = {} tmp_checks[active_package] = [] package_check_dir = repository.load(active_package).check_dir if not os.path.isdir(package_check_dir): continue for check_file in sorted(os.listdir(package_check_dir)): if not os.access(os.path.join(package_check_dir, check_file), os.X_OK): print('WARNING: `{}` is not executable'.format(check_file), file=sys.stderr) continue tmp_checks[active_package].append(check_file) if tmp_checks[active_package]: checks.update(tmp_checks) return checks def list_checks(checks): for check_dir, check_files in sorted(checks.items()): print('{}'.format(check_dir)) for check_file in check_files: print(' - {}'.format(check_file)) def run_checks(checks, install, repository): exit_code = 0 for pkg_id, check_files in sorted(checks.items()): check_dir = repository.load(pkg_id).check_dir for check_file in check_files: try: check_call([os.path.join(check_dir, check_file)]) except CalledProcessError: print('Check failed: {}'.format(check_file), file=sys.stderr) exit_code = 1 return exit_code def main(): arguments = docopt( __doc__.format( default_config_dir=constants.config_dir, default_root=constants.install_root, default_repository=constants.repository_base, default_state_dir_root=constants.STATE_DIR_ROOT, ), ) umask(0o022) # NOTE: Changing root or repository will likely break actually running packages. install = Install( os.path.abspath(arguments['--root']), os.path.abspath(arguments['--config-dir']), arguments['--rooted-systemd'], not arguments['--no-systemd'], not arguments['--no-block-systemd'], manage_users=True, add_users=not os.path.exists('/etc/mesosphere/manual_host_users'), manage_state_dir=True, state_dir_root=os.path.abspath(arguments['--state-dir-root'])) repository = Repository(os.path.abspath(arguments['--repository'])) try: if arguments['setup']: actions.setup(install, repository) sys.exit(0) if arguments['list']: print_repo_list(repository.list()) sys.exit(0) if arguments['active']: for pkg in sorted(install.get_active()): print(pkg) sys.exit(0) if arguments['add']: actions.add_package_file(repository, arguments['<package-tarball>']) sys.exit(0) if arguments['fetch']: for package_id in arguments['<id>']: actions.fetch_package( repository, arguments['--repository-url'], package_id, os.getcwd()) sys.exit(0) if arguments['activate']: actions.activate_packages( install, repository, arguments['<id>'], not arguments['--no-systemd'], not arguments['--no-block-systemd']) sys.exit(0) if arguments['swap']: actions.swap_active_package( install, repository, arguments['<package-id>'], not arguments['--no-systemd'], not arguments['--no-block-systemd']) sys.exit(0) if arguments['remove']: for package_id in arguments['<id>']: try: actions.remove_package(install, repository, package_id) except PackageNotFound: pass sys.exit(0) if arguments['uninstall']: uninstall(install, repository) sys.exit(0) if arguments['check']: checks = find_checks(install, repository) if arguments['--list']: list_checks(checks) sys.exit(0) # Run all checks sys.exit(run_checks(checks, install, repository)) except ValidationError as ex: print("Validation Error: {0}".format(ex), file=sys.stderr) sys.exit(1) except PackageError as ex: print("Package Error: {0}".format(ex), file=sys.stderr) sys.exit(1) except Exception as ex: print("ERROR: {0}".format(ex), file=sys.stderr) sys.exit(1) print("unknown command", file=sys.stderr) sys.exit(1) if __name__ == "__main__": main()
apache-2.0
leeon/annotated-django
django/db/backends/creation.py
6
20276
import hashlib import sys import time from django.conf import settings from django.db.utils import load_backend from django.utils.encoding import force_bytes from django.utils.functional import cached_property from django.utils.six.moves import input from .utils import truncate_name # The prefix to put on the default database name when creating # the test database. TEST_DATABASE_PREFIX = 'test_' NO_DB_ALIAS = '__no_db__' class BaseDatabaseCreation(object): """ This class encapsulates all backend-specific differences that pertain to database *creation*, such as the column types to use for particular Django Fields, the SQL used to create and destroy tables, and the creation and destruction of test databases. """ data_types = {} data_types_suffix = {} data_type_check_constraints = {} def __init__(self, connection): self.connection = connection @cached_property def _nodb_connection(self): """ Alternative connection to be used when there is no need to access the main database, specifically for test db creation/deletion. This also prevents the production database from being exposed to potential child threads while (or after) the test database is destroyed. Refs #10868, #17786, #16969. """ settings_dict = self.connection.settings_dict.copy() settings_dict['NAME'] = None backend = load_backend(settings_dict['ENGINE']) nodb_connection = backend.DatabaseWrapper( settings_dict, alias=NO_DB_ALIAS, allow_thread_sharing=False) return nodb_connection @classmethod def _digest(cls, *args): """ Generates a 32-bit digest of a set of arguments that can be used to shorten identifying names. """ h = hashlib.md5() for arg in args: h.update(force_bytes(arg)) return h.hexdigest()[:8] def sql_create_model(self, model, style, known_models=set()): """ Returns the SQL required to create a single model, as a tuple of: (list_of_sql, pending_references_dict) """ opts = model._meta if not opts.managed or opts.proxy or opts.swapped: return [], {} final_output = [] table_output = [] pending_references = {} qn = self.connection.ops.quote_name for f in opts.local_fields: col_type = f.db_type(connection=self.connection) col_type_suffix = f.db_type_suffix(connection=self.connection) tablespace = f.db_tablespace or opts.db_tablespace if col_type is None: # Skip ManyToManyFields, because they're not represented as # database columns in this table. continue # Make the definition (e.g. 'foo VARCHAR(30)') for this field. field_output = [style.SQL_FIELD(qn(f.column)), style.SQL_COLTYPE(col_type)] # Oracle treats the empty string ('') as null, so coerce the null # option whenever '' is a possible value. null = f.null if (f.empty_strings_allowed and not f.primary_key and self.connection.features.interprets_empty_strings_as_nulls): null = True if not null: field_output.append(style.SQL_KEYWORD('NOT NULL')) if f.primary_key: field_output.append(style.SQL_KEYWORD('PRIMARY KEY')) elif f.unique: field_output.append(style.SQL_KEYWORD('UNIQUE')) if tablespace and f.unique: # We must specify the index tablespace inline, because we # won't be generating a CREATE INDEX statement for this field. tablespace_sql = self.connection.ops.tablespace_sql( tablespace, inline=True) if tablespace_sql: field_output.append(tablespace_sql) if f.rel and f.db_constraint: ref_output, pending = self.sql_for_inline_foreign_key_references( model, f, known_models, style) if pending: pending_references.setdefault(f.rel.to, []).append( (model, f)) else: field_output.extend(ref_output) if col_type_suffix: field_output.append(style.SQL_KEYWORD(col_type_suffix)) table_output.append(' '.join(field_output)) for field_constraints in opts.unique_together: table_output.append(style.SQL_KEYWORD('UNIQUE') + ' (%s)' % ", ".join( [style.SQL_FIELD(qn(opts.get_field(f).column)) for f in field_constraints])) full_statement = [style.SQL_KEYWORD('CREATE TABLE') + ' ' + style.SQL_TABLE(qn(opts.db_table)) + ' ('] for i, line in enumerate(table_output): # Combine and add commas. full_statement.append( ' %s%s' % (line, ',' if i < len(table_output) - 1 else '')) full_statement.append(')') if opts.db_tablespace: tablespace_sql = self.connection.ops.tablespace_sql( opts.db_tablespace) if tablespace_sql: full_statement.append(tablespace_sql) full_statement.append(';') final_output.append('\n'.join(full_statement)) if opts.has_auto_field: # Add any extra SQL needed to support auto-incrementing primary # keys. auto_column = opts.auto_field.db_column or opts.auto_field.name autoinc_sql = self.connection.ops.autoinc_sql(opts.db_table, auto_column) if autoinc_sql: for stmt in autoinc_sql: final_output.append(stmt) return final_output, pending_references def sql_for_inline_foreign_key_references(self, model, field, known_models, style): """ Return the SQL snippet defining the foreign key reference for a field. """ qn = self.connection.ops.quote_name rel_to = field.rel.to if rel_to in known_models or rel_to == model: output = [style.SQL_KEYWORD('REFERENCES') + ' ' + style.SQL_TABLE(qn(rel_to._meta.db_table)) + ' (' + style.SQL_FIELD(qn(rel_to._meta.get_field( field.rel.field_name).column)) + ')' + self.connection.ops.deferrable_sql() ] pending = False else: # We haven't yet created the table to which this field # is related, so save it for later. output = [] pending = True return output, pending def sql_for_pending_references(self, model, style, pending_references): """ Returns any ALTER TABLE statements to add constraints after the fact. """ opts = model._meta if not opts.managed or opts.swapped: return [] qn = self.connection.ops.quote_name final_output = [] if model in pending_references: for rel_class, f in pending_references[model]: rel_opts = rel_class._meta r_table = rel_opts.db_table r_col = f.column table = opts.db_table col = opts.get_field(f.rel.field_name).column # For MySQL, r_name must be unique in the first 64 characters. # So we are careful with character usage here. r_name = '%s_refs_%s_%s' % ( r_col, col, self._digest(r_table, table)) final_output.append(style.SQL_KEYWORD('ALTER TABLE') + ' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s;' % (qn(r_table), qn(truncate_name( r_name, self.connection.ops.max_name_length())), qn(r_col), qn(table), qn(col), self.connection.ops.deferrable_sql())) del pending_references[model] return final_output def sql_indexes_for_model(self, model, style): """ Returns the CREATE INDEX SQL statements for a single model. """ if not model._meta.managed or model._meta.proxy or model._meta.swapped: return [] output = [] for f in model._meta.local_fields: output.extend(self.sql_indexes_for_field(model, f, style)) for fs in model._meta.index_together: fields = [model._meta.get_field_by_name(f)[0] for f in fs] output.extend(self.sql_indexes_for_fields(model, fields, style)) return output def sql_indexes_for_field(self, model, f, style): """ Return the CREATE INDEX SQL statements for a single model field. """ if f.db_index and not f.unique: return self.sql_indexes_for_fields(model, [f], style) else: return [] def sql_indexes_for_fields(self, model, fields, style): if len(fields) == 1 and fields[0].db_tablespace: tablespace_sql = self.connection.ops.tablespace_sql(fields[0].db_tablespace) elif model._meta.db_tablespace: tablespace_sql = self.connection.ops.tablespace_sql(model._meta.db_tablespace) else: tablespace_sql = "" if tablespace_sql: tablespace_sql = " " + tablespace_sql field_names = [] qn = self.connection.ops.quote_name for f in fields: field_names.append(style.SQL_FIELD(qn(f.column))) index_name = "%s_%s" % (model._meta.db_table, self._digest([f.name for f in fields])) return [ style.SQL_KEYWORD("CREATE INDEX") + " " + style.SQL_TABLE(qn(truncate_name(index_name, self.connection.ops.max_name_length()))) + " " + style.SQL_KEYWORD("ON") + " " + style.SQL_TABLE(qn(model._meta.db_table)) + " " + "(%s)" % style.SQL_FIELD(", ".join(field_names)) + "%s;" % tablespace_sql, ] def sql_destroy_model(self, model, references_to_delete, style): """ Return the DROP TABLE and restraint dropping statements for a single model. """ if not model._meta.managed or model._meta.proxy or model._meta.swapped: return [] # Drop the table now qn = self.connection.ops.quote_name output = ['%s %s;' % (style.SQL_KEYWORD('DROP TABLE'), style.SQL_TABLE(qn(model._meta.db_table)))] if model in references_to_delete: output.extend(self.sql_remove_table_constraints( model, references_to_delete, style)) if model._meta.has_auto_field: ds = self.connection.ops.drop_sequence_sql(model._meta.db_table) if ds: output.append(ds) return output def sql_remove_table_constraints(self, model, references_to_delete, style): if not model._meta.managed or model._meta.proxy or model._meta.swapped: return [] output = [] qn = self.connection.ops.quote_name for rel_class, f in references_to_delete[model]: table = rel_class._meta.db_table col = f.column r_table = model._meta.db_table r_col = model._meta.get_field(f.rel.field_name).column r_name = '%s_refs_%s_%s' % ( col, r_col, self._digest(table, r_table)) output.append('%s %s %s %s;' % ( style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(table)), style.SQL_KEYWORD(self.connection.ops.drop_foreignkey_sql()), style.SQL_FIELD(qn(truncate_name( r_name, self.connection.ops.max_name_length()))) )) del references_to_delete[model] return output def sql_destroy_indexes_for_model(self, model, style): """ Returns the DROP INDEX SQL statements for a single model. """ if not model._meta.managed or model._meta.proxy or model._meta.swapped: return [] output = [] for f in model._meta.local_fields: output.extend(self.sql_destroy_indexes_for_field(model, f, style)) for fs in model._meta.index_together: fields = [model._meta.get_field_by_name(f)[0] for f in fs] output.extend(self.sql_destroy_indexes_for_fields(model, fields, style)) return output def sql_destroy_indexes_for_field(self, model, f, style): """ Return the DROP INDEX SQL statements for a single model field. """ if f.db_index and not f.unique: return self.sql_destroy_indexes_for_fields(model, [f], style) else: return [] def sql_destroy_indexes_for_fields(self, model, fields, style): if len(fields) == 1 and fields[0].db_tablespace: tablespace_sql = self.connection.ops.tablespace_sql(fields[0].db_tablespace) elif model._meta.db_tablespace: tablespace_sql = self.connection.ops.tablespace_sql(model._meta.db_tablespace) else: tablespace_sql = "" if tablespace_sql: tablespace_sql = " " + tablespace_sql field_names = [] qn = self.connection.ops.quote_name for f in fields: field_names.append(style.SQL_FIELD(qn(f.column))) index_name = "%s_%s" % (model._meta.db_table, self._digest([f.name for f in fields])) return [ style.SQL_KEYWORD("DROP INDEX") + " " + style.SQL_TABLE(qn(truncate_name(index_name, self.connection.ops.max_name_length()))) + " " + ";", ] def create_test_db(self, verbosity=1, autoclobber=False): """ Creates a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created. """ # Don't import django.core.management if it isn't needed. from django.core.management import call_command test_database_name = self._get_test_db_name() if verbosity >= 1: test_db_repr = '' if verbosity >= 2: test_db_repr = " ('%s')" % test_database_name print("Creating test database for alias '%s'%s..." % ( self.connection.alias, test_db_repr)) self._create_test_db(verbosity, autoclobber) self.connection.close() settings.DATABASES[self.connection.alias]["NAME"] = test_database_name self.connection.settings_dict["NAME"] = test_database_name # Report migrate messages at one level lower than that requested. # This ensures we don't get flooded with messages during testing # (unless you really ask to be flooded) call_command('migrate', verbosity=max(verbosity - 1, 0), interactive=False, database=self.connection.alias, load_initial_data=False, test_database=True) # We need to then do a flush to ensure that any data installed by # custom SQL has been removed. The only test data should come from # test fixtures, or autogenerated from post_migrate triggers. # This has the side effect of loading initial data (which was # intentionally skipped in the syncdb). call_command('flush', verbosity=max(verbosity - 1, 0), interactive=False, database=self.connection.alias) call_command('createcachetable', database=self.connection.alias) # Ensure a connection for the side effect of initializing the test database. self.connection.ensure_connection() return test_database_name def _get_test_db_name(self): """ Internal implementation - returns the name of the test DB that will be created. Only useful when called from create_test_db() and _create_test_db() and when no external munging is done with the 'NAME' or 'TEST_NAME' settings. """ if self.connection.settings_dict['TEST']['NAME']: return self.connection.settings_dict['TEST']['NAME'] return TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME'] def _create_test_db(self, verbosity, autoclobber): """ Internal implementation - creates the test db tables. """ suffix = self.sql_table_creation_suffix() test_database_name = self._get_test_db_name() qn = self.connection.ops.quote_name # Create the test database and connect to it. with self._nodb_connection.cursor() as cursor: try: cursor.execute( "CREATE DATABASE %s %s" % (qn(test_database_name), suffix)) except Exception as e: sys.stderr.write( "Got an error creating the test database: %s\n" % e) if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name) if autoclobber or confirm == 'yes': try: if verbosity >= 1: print("Destroying old test database '%s'..." % self.connection.alias) cursor.execute( "DROP DATABASE %s" % qn(test_database_name)) cursor.execute( "CREATE DATABASE %s %s" % (qn(test_database_name), suffix)) except Exception as e: sys.stderr.write( "Got an error recreating the test database: %s\n" % e) sys.exit(2) else: print("Tests cancelled.") sys.exit(1) return test_database_name def destroy_test_db(self, old_database_name, verbosity=1): """ Destroy a test database, prompting the user for confirmation if the database already exists. """ self.connection.close() test_database_name = self.connection.settings_dict['NAME'] if verbosity >= 1: test_db_repr = '' if verbosity >= 2: test_db_repr = " ('%s')" % test_database_name print("Destroying test database for alias '%s'%s..." % ( self.connection.alias, test_db_repr)) self._destroy_test_db(test_database_name, verbosity) def _destroy_test_db(self, test_database_name, verbosity): """ Internal implementation - remove the test db tables. """ # Remove the test database to clean up after # ourselves. Connect to the previous database (not the test database) # to do so, because it's not allowed to delete a database while being # connected to it. with self._nodb_connection.cursor() as cursor: # Wait to avoid "database is being accessed by other users" errors. time.sleep(1) cursor.execute("DROP DATABASE %s" % self.connection.ops.quote_name(test_database_name)) def sql_table_creation_suffix(self): """ SQL to append to the end of the test table creation statements. """ return '' def test_db_signature(self): """ Returns a tuple with elements of self.connection.settings_dict (a DATABASES setting value) that uniquely identify a database accordingly to the RDBMS particularities. """ settings_dict = self.connection.settings_dict return ( settings_dict['HOST'], settings_dict['PORT'], settings_dict['ENGINE'], settings_dict['NAME'] )
bsd-3-clause
BrateloSlava/SaveEnergy-2
tools/perf/util/setup.py
4998
1330
#!/usr/bin/python2 from distutils.core import setup, Extension from os import getenv from distutils.command.build_ext import build_ext as _build_ext from distutils.command.install_lib import install_lib as _install_lib class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) self.build_lib = build_lib self.build_temp = build_tmp class install_lib(_install_lib): def finalize_options(self): _install_lib.finalize_options(self) self.build_dir = build_lib cflags = ['-fno-strict-aliasing', '-Wno-write-strings'] cflags += getenv('CFLAGS', '').split() build_lib = getenv('PYTHON_EXTBUILD_LIB') build_tmp = getenv('PYTHON_EXTBUILD_TMP') ext_sources = [f.strip() for f in file('util/python-ext-sources') if len(f.strip()) > 0 and f[0] != '#'] perf = Extension('perf', sources = ext_sources, include_dirs = ['util/include'], extra_compile_args = cflags, ) setup(name='perf', version='0.1', description='Interface with the Linux profiling infrastructure', author='Arnaldo Carvalho de Melo', author_email='acme@redhat.com', license='GPLv2', url='http://perf.wiki.kernel.org', ext_modules=[perf], cmdclass={'build_ext': build_ext, 'install_lib': install_lib})
gpl-2.0
gonzolino/heat
heat/objects/fields.py
11
1156
# Copyright 2014 Intel Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_serialization import jsonutils as json from oslo_versionedobjects import fields import six class Json(fields.FieldType): def coerce(self, obj, attr, value): if isinstance(value, six.string_types): loaded = json.loads(value) return loaded return value def from_primitive(self, obj, attr, value): return self.coerce(obj, attr, value) def to_primitive(self, obj, attr, value): return json.dumps(value) class JsonField(fields.AutoTypedField): pass class ListField(fields.AutoTypedField): pass
apache-2.0
skulldreamz/bullhead_kernel
tools/perf/scripts/python/net_dropmonitor.py
2669
1738
# Monitor the system for dropped packets and proudce a report of drop locations and counts import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * drop_log = {} kallsyms = [] def get_kallsyms_table(): global kallsyms try: f = open("/proc/kallsyms", "r") except: return for line in f: loc = int(line.split()[0], 16) name = line.split()[2] kallsyms.append((loc, name)) kallsyms.sort() def get_sym(sloc): loc = int(sloc) # Invariant: kallsyms[i][0] <= loc for all 0 <= i <= start # kallsyms[i][0] > loc for all end <= i < len(kallsyms) start, end = -1, len(kallsyms) while end != start + 1: pivot = (start + end) // 2 if loc < kallsyms[pivot][0]: end = pivot else: start = pivot # Now (start == -1 or kallsyms[start][0] <= loc) # and (start == len(kallsyms) - 1 or loc < kallsyms[start + 1][0]) if start >= 0: symloc, name = kallsyms[start] return (name, loc - symloc) else: return (None, 0) def print_drop_table(): print "%25s %25s %25s" % ("LOCATION", "OFFSET", "COUNT") for i in drop_log.keys(): (sym, off) = get_sym(i) if sym == None: sym = i print "%25s %25s %25s" % (sym, off, drop_log[i]) def trace_begin(): print "Starting trace (Ctrl-C to dump results)" def trace_end(): print "Gathering kallsyms data" get_kallsyms_table() print_drop_table() # called from perf, when it finds a correspoinding event def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr, location, protocol): slocation = str(location) try: drop_log[slocation] = drop_log[slocation] + 1 except: drop_log[slocation] = 1
gpl-2.0
TathagataChakraborti/resource-conflicts
PLANROB-2015/seq-sat-lama/Python-2.5.2/Lib/test/test_peepholer.py
17
6727
import dis import sys from cStringIO import StringIO import unittest def disassemble(func): f = StringIO() tmp = sys.stdout sys.stdout = f dis.dis(func) sys.stdout = tmp result = f.getvalue() f.close() return result def dis_single(line): return disassemble(compile(line, '', 'single')) class TestTranforms(unittest.TestCase): def test_unot(self): # UNARY_NOT JUMP_IF_FALSE POP_TOP --> JUMP_IF_TRUE POP_TOP' def unot(x): if not x == 2: del x asm = disassemble(unot) for elem in ('UNARY_NOT', 'JUMP_IF_FALSE'): self.assert_(elem not in asm) for elem in ('JUMP_IF_TRUE', 'POP_TOP'): self.assert_(elem in asm) def test_elim_inversion_of_is_or_in(self): for line, elem in ( ('not a is b', '(is not)',), ('not a in b', '(not in)',), ('not a is not b', '(is)',), ('not a not in b', '(in)',), ): asm = dis_single(line) self.assert_(elem in asm) def test_none_as_constant(self): # LOAD_GLOBAL None --> LOAD_CONST None def f(x): None return x asm = disassemble(f) for elem in ('LOAD_GLOBAL',): self.assert_(elem not in asm) for elem in ('LOAD_CONST', '(None)'): self.assert_(elem in asm) def f(): 'Adding a docstring made this test fail in Py2.5.0' return None self.assert_('LOAD_CONST' in disassemble(f)) self.assert_('LOAD_GLOBAL' not in disassemble(f)) def test_while_one(self): # Skip over: LOAD_CONST trueconst JUMP_IF_FALSE xx POP_TOP def f(): while 1: pass return list asm = disassemble(f) for elem in ('LOAD_CONST', 'JUMP_IF_FALSE'): self.assert_(elem not in asm) for elem in ('JUMP_ABSOLUTE',): self.assert_(elem in asm) def test_pack_unpack(self): for line, elem in ( ('a, = a,', 'LOAD_CONST',), ('a, b = a, b', 'ROT_TWO',), ('a, b, c = a, b, c', 'ROT_THREE',), ): asm = dis_single(line) self.assert_(elem in asm) self.assert_('BUILD_TUPLE' not in asm) self.assert_('UNPACK_TUPLE' not in asm) def test_folding_of_tuples_of_constants(self): for line, elem in ( ('a = 1,2,3', '((1, 2, 3))'), ('("a","b","c")', "(('a', 'b', 'c'))"), ('a,b,c = 1,2,3', '((1, 2, 3))'), ('(None, 1, None)', '((None, 1, None))'), ('((1, 2), 3, 4)', '(((1, 2), 3, 4))'), ): asm = dis_single(line) self.assert_(elem in asm) self.assert_('BUILD_TUPLE' not in asm) # Bug 1053819: Tuple of constants misidentified when presented with: # . . . opcode_with_arg 100 unary_opcode BUILD_TUPLE 1 . . . # The following would segfault upon compilation def crater(): (~[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ],) def test_folding_of_binops_on_constants(self): for line, elem in ( ('a = 2+3+4', '(9)'), # chained fold ('"@"*4', "('@@@@')"), # check string ops ('a="abc" + "def"', "('abcdef')"), # check string ops ('a = 3**4', '(81)'), # binary power ('a = 3*4', '(12)'), # binary multiply ('a = 13//4', '(3)'), # binary floor divide ('a = 14%4', '(2)'), # binary modulo ('a = 2+3', '(5)'), # binary add ('a = 13-4', '(9)'), # binary subtract ('a = (12,13)[1]', '(13)'), # binary subscr ('a = 13 << 2', '(52)'), # binary lshift ('a = 13 >> 2', '(3)'), # binary rshift ('a = 13 & 7', '(5)'), # binary and ('a = 13 ^ 7', '(10)'), # binary xor ('a = 13 | 7', '(15)'), # binary or ): asm = dis_single(line) self.assert_(elem in asm, asm) self.assert_('BINARY_' not in asm) # Verify that unfoldables are skipped asm = dis_single('a=2+"b"') self.assert_('(2)' in asm) self.assert_("('b')" in asm) # Verify that large sequences do not result from folding asm = dis_single('a="x"*1000') self.assert_('(1000)' in asm) def test_folding_of_unaryops_on_constants(self): for line, elem in ( ('`1`', "('1')"), # unary convert ('-0.5', '(-0.5)'), # unary negative ('~-2', '(1)'), # unary invert ): asm = dis_single(line) self.assert_(elem in asm, asm) self.assert_('UNARY_' not in asm) # Verify that unfoldables are skipped for line, elem in ( ('-"abc"', "('abc')"), # unary negative ('~"abc"', "('abc')"), # unary invert ): asm = dis_single(line) self.assert_(elem in asm, asm) self.assert_('UNARY_' in asm) def test_elim_extra_return(self): # RETURN LOAD_CONST None RETURN --> RETURN def f(x): return x asm = disassemble(f) self.assert_('LOAD_CONST' not in asm) self.assert_('(None)' not in asm) self.assertEqual(asm.split().count('RETURN_VALUE'), 1) def test_main(verbose=None): import sys from test import test_support test_classes = (TestTranforms,) test_support.run_unittest(*test_classes) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print counts if __name__ == "__main__": test_main(verbose=True)
mit
benoitsteiner/tensorflow-xsmm
tensorflow/contrib/opt/python/training/addsign.py
55
6067
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Implementation of AddSign.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.training import optimizer from tensorflow.python.training import training_ops class AddSignOptimizer(optimizer.Optimizer): """Optimizer that implements the AddSign update. See [Bello et al., ICML2017], [Neural Optimizer Search with RL](https://arxiv.org/abs/1709.07417). """ def __init__(self, learning_rate=0.1, alpha=1.0, beta=0.9, sign_decay_fn=None, use_locking=False, name='AddSignOptimizer'): """Constructs a new AddSignOptimizer object. Initialization: ``` m_0 <- 0 (Initialize initial 1st moment vector) t <- 0 (Initialize timestep) ``` Update: ``` t <- t + 1 m_t <- beta1 * m_{t-1} + (1 - beta1) * g sign_decay <- sign_decay_fn(t) update <- (alpha + sign_decay * sign(g) *sign(m)) * g variable <- variable - lr_t * update ``` Example for AddSign-ld (AddSign with linear sign decay) ``` decay_steps = 1000 linear_decay_fn = sign_decays.get_linear_decay_fn(decay_steps) opt = AddSignOptimizer(learning_rate=0.1, sign_decay_fn=linear_decay_fn) ``` Args: learning_rate: learning_rate used when taking a step. alpha: alpha used in optimizer. beta: decay used for computing the moving average m. sign_decay_fn: decay function applied to the sign(g) sign(m) quantity. Takes global_step as an argument. See sign_decay.py for some examples. use_locking: If True, use locks for update operations. name: Optional name for the operations created when applying gradients. Defaults to "AddSignOptimizer". """ super(AddSignOptimizer, self).__init__(use_locking, name) self._lr = learning_rate self._alpha = alpha self._beta = beta self._sign_decay_fn = sign_decay_fn # Tensor versions of the constructor arguments, created in _prepare(). self._lr_t = None self._alpha_t = None self._beta_t = None def apply_gradients(self, grads_and_vars, global_step=None, name=None): if self._sign_decay_fn is not None: self._sign_decay_t = ops.convert_to_tensor( self._sign_decay_fn(global_step), name='sign_decay') return super(AddSignOptimizer, self).apply_gradients( grads_and_vars, global_step=global_step, name=name) def _create_slots(self, var_list): # Create slots for the first moment. for v in var_list: self._zeros_slot(v, 'm', self._name) def _prepare(self): self._lr_t = ops.convert_to_tensor(self._lr, name='learning_rate') self._beta_t = ops.convert_to_tensor(self._beta, name='beta') self._alpha_t = ops.convert_to_tensor(self._alpha, name='alpha') if self._sign_decay_fn is None: self._sign_decay_t = ops.convert_to_tensor(1.0, name='sign_decay') def _apply_dense(self, grad, var): m = self.get_slot(var, 'm') return training_ops.apply_add_sign( var, m, math_ops.cast(self._lr_t, var.dtype.base_dtype), math_ops.cast(self._alpha_t, var.dtype.base_dtype), math_ops.cast(self._sign_decay_t, var.dtype.base_dtype), math_ops.cast(self._beta_t, var.dtype.base_dtype), grad, use_locking=self._use_locking).op def _resource_apply_dense(self, grad, var): m = self.get_slot(var, 'm') return training_ops.resource_apply_add_sign( var.handle, m.handle, math_ops.cast(self._lr_t, var.dtype.base_dtype), math_ops.cast(self._alpha_t, var.dtype.base_dtype), math_ops.cast(self._sign_decay_t, var.dtype.base_dtype), math_ops.cast(self._beta_t, var.dtype.base_dtype), grad, use_locking=self._use_locking) def _apply_sparse(self, grad, var): lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype) alpha_t = math_ops.cast(self._alpha_t, var.dtype.base_dtype) beta_t = math_ops.cast(self._beta_t, var.dtype.base_dtype) m = self.get_slot(var, 'm') m_t = state_ops.assign( m, (m * beta_t) + (grad * (1 - beta_t)), use_locking=self._use_locking) sign_g = ops.IndexedSlices( math_ops.sign(grad.values), grad.indices, dense_shape=grad.dense_shape) sign_gm = ops.IndexedSlices( array_ops.gather(math_ops.sign(m_t), sign_g.indices) * sign_g.values, sign_g.indices, dense_shape=sign_g.dense_shape) sign_decayed = math_ops.cast( self._sign_decay_t, var.dtype.base_dtype) multiplier_values = alpha_t + sign_decayed * sign_gm.values multiplier = ops.IndexedSlices( multiplier_values, sign_gm.indices, dense_shape=sign_gm.dense_shape) final_update = ops.IndexedSlices( lr_t * multiplier.values * grad.values, multiplier.indices, dense_shape=multiplier.dense_shape) var_update = state_ops.scatter_sub( var, final_update.indices, final_update.values, use_locking=self._use_locking) return control_flow_ops.group(* [var_update, m_t])
apache-2.0
citrix-openstack-build/python-troveclient
troveclient/auth.py
3
8823
# Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from troveclient import exceptions def get_authenticator_cls(cls_or_name): """Factory method to retrieve Authenticator class.""" if isinstance(cls_or_name, type): return cls_or_name elif isinstance(cls_or_name, basestring): if cls_or_name == "keystone": return KeyStoneV2Authenticator elif cls_or_name == "rax": return RaxAuthenticator elif cls_or_name == "auth1.1": return Auth1_1 elif cls_or_name == "fake": return FakeAuth raise ValueError("Could not determine authenticator class from the given " "value %r." % cls_or_name) class Authenticator(object): """ Helper class to perform Keystone or other miscellaneous authentication. The "authenticate" method returns a ServiceCatalog, which can be used to obtain a token. """ URL_REQUIRED = True def __init__(self, client, type, url, username, password, tenant, region=None, service_type=None, service_name=None, service_url=None): self.client = client self.type = type self.url = url self.username = username self.password = password self.tenant = tenant self.region = region self.service_type = service_type self.service_name = service_name self.service_url = service_url def _authenticate(self, url, body, root_key='access'): """Authenticate and extract the service catalog.""" # Make sure we follow redirects when trying to reach Keystone tmp_follow_all_redirects = self.client.follow_all_redirects self.client.follow_all_redirects = True try: resp, body = self.client._time_request(url, "POST", body=body) finally: self.client.follow_all_redirects = tmp_follow_all_redirects if resp.status == 200: # content must always present try: return ServiceCatalog(body, region=self.region, service_type=self.service_type, service_name=self.service_name, service_url=self.service_url, root_key=root_key) except exceptions.AmbiguousEndpoints: print "Found more than one valid endpoint. Use a more " \ "restrictive filter" raise except KeyError: raise exceptions.AuthorizationFailure() except exceptions.EndpointNotFound: print "Could not find any suitable endpoint. Correct region?" raise elif resp.status == 305: return resp['location'] else: raise exceptions.from_response(resp, body) def authenticate(self): raise NotImplementedError("Missing authenticate method.") class KeyStoneV2Authenticator(Authenticator): def authenticate(self): if self.url is None: raise exceptions.AuthUrlNotGiven() return self._v2_auth(self.url) def _v2_auth(self, url): """Authenticate against a v2.0 auth service.""" body = {"auth": { "passwordCredentials": { "username": self.username, "password": self.password} } } if self.tenant: body['auth']['tenantName'] = self.tenant return self._authenticate(url, body) class Auth1_1(Authenticator): def authenticate(self): """Authenticate against a v2.0 auth service.""" if self.url is None: raise exceptions.AuthUrlNotGiven() auth_url = self.url body = { "credentials": { "username": self.username, "key": self.password }} return self._authenticate(auth_url, body, root_key='auth') class RaxAuthenticator(Authenticator): def authenticate(self): if self.url is None: raise exceptions.AuthUrlNotGiven() return self._rax_auth(self.url) def _rax_auth(self, url): """Authenticate against the Rackspace auth service.""" body = {'auth': { 'RAX-KSKEY:apiKeyCredentials': { 'username': self.username, 'apiKey': self.password, 'tenantName': self.tenant} } } return self._authenticate(self.url, body) class FakeAuth(Authenticator): """Useful for faking auth.""" def authenticate(self): class FakeCatalog(object): def __init__(self, auth): self.auth = auth def get_public_url(self): return "%s/%s" % ('http://localhost:8779/v1.0', self.auth.tenant) def get_token(self): return self.auth.tenant return FakeCatalog(self) class ServiceCatalog(object): """Represents a Keystone Service Catalog which describes a service. This class has methods to obtain a valid token as well as a public service url and a management url. """ def __init__(self, resource_dict, region=None, service_type=None, service_name=None, service_url=None, root_key='access'): self.catalog = resource_dict self.region = region self.service_type = service_type self.service_name = service_name self.service_url = service_url self.management_url = None self.public_url = None self.root_key = root_key self._load() def _load(self): if not self.service_url: self.public_url = self._url_for(attr='region', filter_value=self.region, endpoint_type="publicURL") self.management_url = self._url_for(attr='region', filter_value=self.region, endpoint_type="adminURL") else: self.public_url = self.service_url self.management_url = self.service_url def get_token(self): return self.catalog[self.root_key]['token']['id'] def get_management_url(self): return self.management_url def get_public_url(self): return self.public_url def _url_for(self, attr=None, filter_value=None, endpoint_type='publicURL'): """ Fetch the public URL from the Trove service for a particular endpoint attribute. If none given, return the first. """ matching_endpoints = [] if 'endpoints' in self.catalog: # We have a bastardized service catalog. Treat it special. :/ for endpoint in self.catalog['endpoints']: if not filter_value or endpoint[attr] == filter_value: matching_endpoints.append(endpoint) if not matching_endpoints: raise exceptions.EndpointNotFound() # We don't always get a service catalog back ... if 'serviceCatalog' not in self.catalog[self.root_key]: raise exceptions.EndpointNotFound() # Full catalog ... catalog = self.catalog[self.root_key]['serviceCatalog'] for service in catalog: if service.get("type") != self.service_type: continue if (self.service_name and self.service_type == 'database' and service.get('name') != self.service_name): continue endpoints = service['endpoints'] for endpoint in endpoints: if not filter_value or endpoint.get(attr) == filter_value: endpoint["serviceName"] = service.get("name") matching_endpoints.append(endpoint) if not matching_endpoints: raise exceptions.EndpointNotFound() elif len(matching_endpoints) > 1: raise exceptions.AmbiguousEndpoints(endpoints=matching_endpoints) else: return matching_endpoints[0].get(endpoint_type, None)
apache-2.0
TribeMedia/sky_engine
build/android/gn/zip.py
86
1280
#!/usr/bin/env python # # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Archives a set of files. """ import ast import optparse import os import sys import zipfile sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, 'gyp')) from util import build_utils def DoZip(inputs, output, base_dir): with zipfile.ZipFile(output, 'w') as outfile: for f in inputs: outfile.write(f, os.path.relpath(f, base_dir)) def main(): parser = optparse.OptionParser() build_utils.AddDepfileOption(parser) parser.add_option('--inputs', help='List of files to archive.') parser.add_option('--output', help='Path to output archive.') parser.add_option('--base-dir', help='If provided, the paths in the archive will be ' 'relative to this directory', default='.') options, _ = parser.parse_args() inputs = ast.literal_eval(options.inputs) output = options.output base_dir = options.base_dir DoZip(inputs, output, base_dir) if options.depfile: build_utils.WriteDepfile( options.depfile, build_utils.GetPythonDependencies()) if __name__ == '__main__': sys.exit(main())
bsd-3-clause
cardmaster/makeclub
controlers/activity.py
1
10024
'''Copyright(C): Leaf Johnson 2011 This file is part of makeclub. makeclub 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. makeclub is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Affero General Public License along with makeclub. If not, see <http://www.gnu.org/licenses/>. ''' from google.appengine.api.users import get_current_user, create_login_url, User from google.appengine.ext import webapp from google.appengine.ext import db from errors import errorPage from infopage import infoPage from access import hasActPrivilige, hasClubPrivilige from models import Activity, Membership, Club, ActivityParticipator, ActivityBill from url import urldict from template import render class ActivityBase(webapp.RequestHandler): def __init__(self, *args, **kw): super(ActivityBase, self).__init__(*args, **kw) self.actobj = None def getActModel(self): aid, = self.urlcfg.analyze(self.request.path) if (aid): id = int(aid) return Activity.get_by_id(id) else: return None def actionPath(self): return self.request.path def templateParams(self): act = self.actobj club = act.club cluburl = urldict['ClubView'].path(club.slug) templateVars = dict(club = club, cluburl = cluburl, act = act, action = self.actionPath() ) return templateVars def makeResponseText(self, act): templateVars = self.templateParams() return render(self.template, templateVars, self.request.url) def checkPrivilige(self): user = get_current_user() if (not user): errorPage ( self.response, "Not login", create_login_url(self.request.url), 403) return False if (not hasActPrivilige(user, self.actobj, self.actOperation)): errorPage ( self.response, "Not authorrized", urldict['ClubView'].path(self.actobj.club.slug), 403) return False return True def dbg(self, *args): return #Clean up debug code self.response.out.write (" ".join([str(arg) for arg in args])) self.response.out.write ("<br />\n") def get(self, *args): actobj = self.getActModel() if (actobj): self.actobj = actobj if (self.checkPrivilige()): self.response.out.write (self.makeResponseText(actobj)) else: return else: return errorPage( self.response, "No such Activity", urldict['ClubList'].path(), 404) class SpecialOp: def __init__(self, oper = '', url = '', needPost = False, data = [], display = ''): self.oper = oper if (not display): display = oper self.display = display self.url = url self.needPost = needPost self.data = data class ActivityView(ActivityBase): def __init__(self, *args, **kw): super (ActivityView, self).__init__(*args, **kw) self.template = 'activity_view.html' self.urlcfg = urldict['ActivityView'] self.actOperation = "view" def templateParams(self): defaults = super (ActivityView, self).templateParams() user = get_current_user(); aid = self.actobj.key().id() specialOps = [] if (hasActPrivilige(user, self.actobj, "edit" )): sop = SpecialOp('edit', urldict['ActivityEdit'].path(aid), False) specialOps.append(sop) urlcfg = urldict['ActivityParticipate'] soplist = ['join', 'quit', 'confirm'] if (self.actobj.isBilled): soplist.append("rebill") else: soplist.append("bill") for oper in soplist: if (hasActPrivilige(user, self.actobj, oper) ): data = [('target', user.email()), ] sop = SpecialOp(oper, urlcfg.path(aid, oper), True, data) specialOps.append(sop) defaults['specialOps'] = specialOps participatorOps = [] for oper in ('confirm', ): if (hasActPrivilige(user, self.actobj, oper) ): sop = SpecialOp(oper, urlcfg.path(aid, oper), True, []) participatorOps.append(sop) defaults['participatorOps'] = participatorOps apq = ActivityParticipator.all() apq.filter ('activity = ', self.actobj) defaults['participators'] = apq return defaults class ActivityParticipate(webapp.RequestHandler): def getActModel(self, id): try: iid = int(id) except: return None actobj = Activity.get_by_id(iid) return actobj def get(self, *args): urlcfg = urldict['ActivityParticipate'] id, oper = urlcfg.analyze(self.request.path) self.response.out.write ( 'on id %s, operation %s' % (id, oper) ) def post(self, *args): urlcfg = urldict['ActivityParticipate'] id, oper = urlcfg.analyze(self.request.path) id = int(id) actobj = self.getActModel(id) if (not actobj): return errorPage (self.response, urldict['ClubList'].path(), "No such activity", 404 ) user = get_current_user(); if (not user): return errorPage ( self.response, "Not login", create_login_url(self.request.url), 403) target = self.request.get ('target') cluburl = urldict['ClubView'].path(actobj.club.slug) if (not hasActPrivilige(user, actobj, oper,target) ): return errorPage ( self.response, "Can not access", cluburl, 403) if (target): targetUser = User(target) if(not targetUser): return errorPage ( self.response, "Illegal access", cluburl, 403) else: #if target omitted, use current user as target targetUser = user mem = Membership.between (targetUser, actobj.club) if (not mem): return errorPage ( self.response, "Not a member", cluburl, 403) acturl = urldict['ActivityView'].path(id) if (oper == 'join'): actp = ActivityParticipator.between (mem, actobj) if (not actp): actp = ActivityParticipator(member = mem, activity = actobj) actp.put() return infoPage (self.response, "Successfully Joined", "%s has join activity %s" % (mem.name, actobj.name), acturl) elif (oper == 'quit'): actp = ActivityParticipator.between(mem, actobj) if (actp): if (actp.confirmed): return errorPage ( self.response, "Cannot delete confirmed participator", acturl, 403) else: actp.delete() return infoPage (self.response, "Successfully Quited", "%s success quit activity %s" % (mem.name, actobj.name), acturl) elif (oper == 'confirm'): actp = ActivityParticipator.between(mem, actobj) if (actp): actp.confirmed = not actp.confirmed actp.put() return infoPage (self.response, "Successfully Confirmed", "success confirmed %s join activity %s" % (mem.name, actobj.name), acturl) else: return errorPage ( self.response, "No Such a Member", acturl, 404) elif (oper == 'bill' or oper == "rebill"): billobj = ActivityBill.generateBill(actobj, oper == "rebill")#If in rebill operation, we could enable rebill if (billobj): billobj.put() billDict = dict(billobj = billobj) return infoPage (self.response, "Successfully Billded", str(billobj.memberBill), acturl) else: return errorPage (self.response, "Error Will Generate Bill", acturl, 501) def extractRequestData(request, interested, dbg=None): retval = dict() for (key, valid) in interested.iteritems() : val = valid (request.get(key)) if (dbg): dbg ( "Extract:", key, "=", val) if (val): retval [key] = val return retval import re def parseDuration(times): #support only h tstr = times[:-1] print "Times String: ", tstr return float(tstr) def parseBill (billstr, dbg = None): entries = billstr.split (',') ary = [] if (dbg): dbg ("Bill String:", billstr) dbg ("Splitted:", entries) i = 1 for ent in entries: ent = ent.strip() if (i == 2): val = ent ary.append ( (key, val) ) i = 0 else : key = ent i += 1 return ary class ActivityEdit(ActivityBase): def __init__(self, *args, **kw): super (ActivityEdit, self).__init__(*args, **kw) self.template = 'activity_edit.html' self.urlcfg = urldict['ActivityEdit'] self.actobj = None self.actOperation = "edit" def parseBillDbg(self, billstr): return parseBill(billstr, self.dbg) def updateObject(self, actobj): interested = dict (name = str, intro = str, duration = parseDuration, bill = self.parseBillDbg) reqs = extractRequestData (self.request, interested, self.dbg) for (key, val) in reqs.iteritems(): self.dbg (key, "=", val) setattr (actobj, key, val) #Will read data from postdata, and update the pass-in actobj. pass def post(self, *args): actobj = self.getActModel() if (actobj): self.actobj = actobj if (self.checkPrivilige()): if (self.request.get ('delete', False)): actobj.delete() return infoPage (self.response, "Successful deleted", "Deleted Activity %s" % actobj.name, "/") self.updateObject(actobj) key = actobj.put() if (key): return errorPage( self.response, "Successfully storing this Activity", urldict['ActivityView'].path(key.id()), 200) else: return errorPage( self.response, "Error while storing this Activity", urldict['ActivityEdit'].path(actobj.key().id()), 501) else: return errorPage( self.response, "No such Activity", urldict['ClubList'].path(), 404) class ActivityNew(ActivityEdit): def getActModel(self): urlcfg = urldict['ActivityNew'] slug, = urlcfg.analyze(self.request.path) user = get_current_user() club = Club.getClubBySlug(slug) if (user and club): newact = Activity.createDefault(user, club) if (newact): newact.bill = [('Filed Expense', 80), ('Balls Expense', 30)] return newact else: return None def checkPrivilige(self): user = get_current_user() if (not user): errorPage ( self.response, "Not login", create_login_url(self.request.url), 403) return False if (not hasClubPrivilige(user, self.actobj.club, "newact")): errorPage ( self.response, "Not Authorized to edit", urldict['ClubView'].path(self.actobj.club.slug), 403) return False return True
agpl-3.0
soedinglab/PEnG-motif
lib/gtest-1.8.0/googletest/scripts/upload.py
2511
51024
#!/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. """Tool for uploading diffs from a version control system to the codereview app. Usage summary: upload.py [options] [-- diff_options] Diff options are passed to the diff command of the underlying system. Supported version control systems: Git Mercurial Subversion It is important for Git/Mercurial users to specify a tree/node/branch to diff against by using the '--rev' option. """ # This code is derived from appcfg.py in the App Engine SDK (open source), # and from ASPN recipe #146306. import cookielib import getpass import logging import md5 import mimetypes import optparse import os import re import socket import subprocess import sys import urllib import urllib2 import urlparse try: import readline except ImportError: pass # The logging verbosity: # 0: Errors only. # 1: Status messages. # 2: Info logs. # 3: Debug logs. verbosity = 1 # Max size of patch or base file. MAX_UPLOAD_SIZE = 900 * 1024 def GetEmail(prompt): """Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt. """ last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") last_email = "" if os.path.exists(last_email_file_name): try: last_email_file = open(last_email_file_name, "r") last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email except IOError, e: pass email = raw_input(prompt + ": ").strip() if email: try: last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() except IOError, e: pass else: email = last_email return email def StatusUpdate(msg): """Print a status message to stdout. If 'verbosity' is greater than 0, print the message. Args: msg: The string to print. """ if verbosity > 0: print msg def ErrorExit(msg): """Print an error message to stderr and exit.""" print >>sys.stderr, msg sys.exit(1) class ClientLoginError(urllib2.HTTPError): """Raised to indicate there was an error authenticating with ClientLogin.""" def __init__(self, url, code, msg, headers, args): urllib2.HTTPError.__init__(self, url, code, msg, headers, None) self.args = args self.reason = args["Error"] class AbstractRpcServer(object): """Provides a common interface for a simple RPC server.""" def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False): """Creates a new HttpRpcServer. Args: host: The host to send requests to. auth_function: A function that takes no arguments and returns an (email, password) tuple when called. Will be called if authentication is required. host_override: The host header to send to the server (defaults to host). extra_headers: A dict of extra headers to append to every request. save_cookies: If True, save the authentication cookies to local disk. If False, use an in-memory cookiejar instead. Subclasses must implement this functionality. Defaults to False. """ self.host = host self.host_override = host_override self.auth_function = auth_function self.authenticated = False self.extra_headers = extra_headers self.save_cookies = save_cookies self.opener = self._GetOpener() if self.host_override: logging.info("Server: %s; Host: %s", self.host, self.host_override) else: logging.info("Server: %s", self.host) def _GetOpener(self): """Returns an OpenerDirector for making HTTP requests. Returns: A urllib2.OpenerDirector object. """ raise NotImplementedError() def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug("Creating request for: '%s' with payload:\n%s", url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) for key, value in self.extra_headers.iteritems(): req.add_header(key, value) return req def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin. """ account_type = "GOOGLE" if self.host.endswith(".google.com"): # Needed for use inside Google. account_type = "HOSTED" req = self._CreateRequest( url="https://www.google.com/accounts/ClientLogin", data=urllib.urlencode({ "Email": email, "Passwd": password, "service": "ah", "source": "rietveld-codereview-upload", "accountType": account_type, }), ) try: response = self.opener.open(req) response_body = response.read() response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] except urllib2.HTTPError, e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) else: raise def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. """ # This is a dummy value to allow us to identify when we're successful. continue_location = "http://localhost/" args = {"continue": continue_location, "auth": auth_token} req = self._CreateRequest("http://%s/_ah/login?%s" % (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) except urllib2.HTTPError, e: response = e if (response.code != 302 or response.info()["location"] != continue_location): raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) self.authenticated = True def _Authenticate(self): """Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response and directs us to authenticate ourselves with ClientLogin. """ for i in range(3): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) except ClientLoginError, e: if e.reason == "BadAuthentication": print >>sys.stderr, "Invalid username or password." continue if e.reason == "CaptchaRequired": print >>sys.stderr, ( "Please go to\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n" "and verify you are a human. Then try again.") break if e.reason == "NotVerified": print >>sys.stderr, "Account not verified." break if e.reason == "TermsNotAgreed": print >>sys.stderr, "User has not agreed to TOS." break if e.reason == "AccountDeleted": print >>sys.stderr, "The user account has been deleted." break if e.reason == "AccountDisabled": print >>sys.stderr, "The user account has been disabled." break if e.reason == "ServiceDisabled": print >>sys.stderr, ("The user's access to the service has been " "disabled.") break if e.reason == "ServiceUnavailable": print >>sys.stderr, "The service is not available; try again later." break raise self._GetAuthCookie(auth_token) return def Send(self, request_path, payload=None, content_type="application/octet-stream", timeout=None, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests on OS X, the timeout doesn't work right.) kwargs: Any keyword arguments are converted into query string parameters. Returns: The response body, as a string. """ # TODO: Don't require authentication. Let the server say # whether it is necessary. if not self.authenticated: self._Authenticate() old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 args = dict(kwargs) url = "http://%s%s" % (self.host, request_path) if args: url += "?" + urllib.urlencode(args) req = self._CreateRequest(url=url, data=payload) req.add_header("Content-Type", content_type) try: f = self.opener.open(req) response = f.read() f.close() return response except urllib2.HTTPError, e: if tries > 3: raise elif e.code == 401: self._Authenticate() ## elif e.code >= 500 and e.code < 600: ## # Server Error - try again. ## continue else: raise finally: socket.setdefaulttimeout(old_timeout) class HttpRpcServer(AbstractRpcServer): """Provides a simplified RPC-style interface for HTTP requests.""" def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save() def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(urllib2.HTTPErrorProcessor()) if self.save_cookies: self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies") self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) if os.path.exists(self.cookie_file): try: self.cookie_jar.load() self.authenticated = True StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file) except (cookielib.LoadError, IOError): # Failed to load cookies - just ignore them. pass else: # Create an empty cookie file with mode 600 fd = os.open(self.cookie_file, os.O_CREAT, 0600) os.close(fd) # Always chmod the cookie file os.chmod(self.cookie_file, 0600) else: # Don't save cookies across runs of update.py. self.cookie_jar = cookielib.CookieJar() opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) return opener parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]") parser.add_option("-y", "--assume_yes", action="store_true", dest="assume_yes", default=False, help="Assume that the answer to yes/no questions is 'yes'.") # Logging group = parser.add_option_group("Logging options") group.add_option("-q", "--quiet", action="store_const", const=0, dest="verbose", help="Print errors only.") group.add_option("-v", "--verbose", action="store_const", const=2, dest="verbose", default=1, help="Print info level logs (default).") group.add_option("--noisy", action="store_const", const=3, dest="verbose", help="Print all logs.") # Review server group = parser.add_option_group("Review server options") group.add_option("-s", "--server", action="store", dest="server", default="codereview.appspot.com", metavar="SERVER", help=("The server to upload to. The format is host[:port]. " "Defaults to 'codereview.appspot.com'.")) group.add_option("-e", "--email", action="store", dest="email", metavar="EMAIL", default=None, help="The username to use. Will prompt if omitted.") group.add_option("-H", "--host", action="store", dest="host", metavar="HOST", default=None, help="Overrides the Host header sent with all RPCs.") group.add_option("--no_cookies", action="store_false", dest="save_cookies", default=True, help="Do not save authentication cookies to local disk.") # Issue group = parser.add_option_group("Issue options") group.add_option("-d", "--description", action="store", dest="description", metavar="DESCRIPTION", default=None, help="Optional description when creating an issue.") group.add_option("-f", "--description_file", action="store", dest="description_file", metavar="DESCRIPTION_FILE", default=None, help="Optional path of a file that contains " "the description when creating an issue.") group.add_option("-r", "--reviewers", action="store", dest="reviewers", metavar="REVIEWERS", default=None, help="Add reviewers (comma separated email addresses).") group.add_option("--cc", action="store", dest="cc", metavar="CC", default=None, help="Add CC (comma separated email addresses).") # Upload options group = parser.add_option_group("Patch options") group.add_option("-m", "--message", action="store", dest="message", metavar="MESSAGE", default=None, help="A message to identify the patch. " "Will prompt if omitted.") group.add_option("-i", "--issue", type="int", action="store", metavar="ISSUE", default=None, help="Issue number to which to add. Defaults to new issue.") group.add_option("--download_base", action="store_true", dest="download_base", default=False, help="Base files will be downloaded by the server " "(side-by-side diffs may not work on files with CRs).") group.add_option("--rev", action="store", dest="revision", metavar="REV", default=None, help="Branch/tree/revision to diff against (used by DVCS).") group.add_option("--send_mail", action="store_true", dest="send_mail", default=False, help="Send notification email to reviewers.") def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" email = options.email if email is None: email = GetEmail("Email (login for uploading to %s)" % options.server) password = getpass.getpass("Password for %s: " % email) return (email, password) # If this is the dev_appserver, use fake authentication. host = (options.host or options.server).lower() if host == "localhost" or host.startswith("localhost:"): email = options.email if email is None: email = "test@example.com" logging.info("Using debug user %s. Override with --email" % email) server = rpc_server_class( options.server, lambda: (email, "password"), host_override=options.host, extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, save_cookies=options.save_cookies) # Don't try to talk to ClientLogin. server.authenticated = True return server return rpc_server_class(options.server, GetUserCredentials, host_override=options.host, save_cookies=options.save_cookies) def EncodeMultipartFormData(fields, files): """Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' lines = [] for (key, value) in fields: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') lines.append(value) for (key, filename, value) in files: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) lines.append('Content-Type: %s' % GetContentType(filename)) lines.append('') lines.append(value) lines.append('--' + BOUNDARY + '--') lines.append('') body = CRLF.join(lines) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def GetContentType(filename): """Helper to guess the content-type from the filename.""" return mimetypes.guess_type(filename)[0] or 'application/octet-stream' # Use a shell for subcommands on Windows to get a PATH search. use_shell = sys.platform.startswith("win") def RunShellWithReturnCode(command, print_output=False, universal_newlines=True): """Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, return code) """ logging.info("Running %s", command) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=use_shell, universal_newlines=universal_newlines) if print_output: output_array = [] while True: line = p.stdout.readline() if not line: break print line.strip("\n") output_array.append(line) output = "".join(output_array) else: output = p.stdout.read() p.wait() errout = p.stderr.read() if print_output and errout: print >>sys.stderr, errout p.stdout.close() p.stderr.close() return output, p.returncode def RunShell(command, silent_ok=False, universal_newlines=True, print_output=False): data, retcode = RunShellWithReturnCode(command, print_output, universal_newlines) if retcode: ErrorExit("Got error status from %s:\n%s" % (command, data)) if not silent_ok and not data: ErrorExit("No output from %s" % command) return data class VersionControlSystem(object): """Abstract base class providing an interface to the VCS.""" def __init__(self, options): """Constructor. Args: options: Command line options. """ self.options = options def GenerateDiff(self, args): """Return the current diff as a string. Args: args: Extra arguments to pass to the diff command. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" unknown_files = self.GetUnknownFiles() if unknown_files: print "The following files are not added to version control:" for line in unknown_files: print line prompt = "Are you sure to continue?(y/N) " answer = raw_input(prompt).strip() if answer != "y": ErrorExit("User aborted") def GetBaseFile(self, filename): """Get the content of the upstream version of a file. Returns: A tuple (base_content, new_content, is_binary, status) base_content: The contents of the base file. new_content: For text files, this is empty. For binary files, this is the contents of the new file, since the diff output won't contain information to reconstruct the current file. is_binary: True iff the file is binary. status: The status of the file. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(True): if line.startswith('Index:') or line.startswith('Property changes on:'): unused, filename = line.split(':', 1) # On Windows if a file has property changes its filename uses '\' # instead of '/'. filename = filename.strip().replace('\\', '/') files[filename] = self.GetBaseFile(filename) return files def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well).""" def UploadFile(filename, file_id, content, is_binary, status, is_base): """Uploads a file to the server.""" file_too_large = False if is_base: type = "base" else: type = "current" if len(content) > MAX_UPLOAD_SIZE: print ("Not uploading the %s file for %s because it's too large." % (type, filename)) file_too_large = True content = "" checksum = md5.new(content).hexdigest() if options.verbose > 0 and not file_too_large: print "Uploading %s file for %s" % (type, filename) url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) form_fields = [("filename", filename), ("status", status), ("checksum", checksum), ("is_binary", str(is_binary)), ("is_current", str(not is_base)), ] if file_too_large: form_fields.append(("file_too_large", "1")) if options.email: form_fields.append(("user", options.email)) ctype, body = EncodeMultipartFormData(form_fields, [("data", filename, content)]) response_body = rpc_server.Send(url, body, content_type=ctype) if not response_body.startswith("OK"): StatusUpdate(" --> %s" % response_body) sys.exit(1) patches = dict() [patches.setdefault(v, k) for k, v in patch_list] for filename in patches.keys(): base_content, new_content, is_binary, status = files[filename] file_id_str = patches.get(filename) if file_id_str.find("nobase") != -1: base_content = None file_id_str = file_id_str[file_id_str.rfind("_") + 1:] file_id = int(file_id_str) if base_content != None: UploadFile(filename, file_id, base_content, is_binary, status, True) if new_content != None: UploadFile(filename, file_id, new_content, is_binary, status, False) def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/") class SubversionVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Subversion.""" def __init__(self, options): super(SubversionVCS, self).__init__(options) if self.options.revision: match = re.match(r"(\d+)(:(\d+))?", self.options.revision) if not match: ErrorExit("Invalid Subversion revision %s." % self.options.revision) self.rev_start = match.group(1) self.rev_end = match.group(3) else: self.rev_start = self.rev_end = None # Cache output from "svn list -r REVNO dirname". # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev). self.svnls_cache = {} # SVN base URL is required to fetch files deleted in an older revision. # Result is cached to not guess it over and over again in GetBaseFile(). required = self.options.download_base or self.options.revision is not None self.svn_base = self._GuessBase(required) def GuessBase(self, required): """Wrapper for _GuessBase.""" return self.svn_base def _GuessBase(self, required): """Returns the SVN base URL. Args: required: If true, exits if the url can't be guessed, otherwise None is returned. """ info = RunShell(["svn", "info"]) for line in info.splitlines(): words = line.split() if len(words) == 2 and words[0] == "URL:": url = words[1] scheme, netloc, path, params, query, fragment = urlparse.urlparse(url) username, netloc = urllib.splituser(netloc) if username: logging.info("Removed username from base URL") if netloc.endswith("svn.python.org"): if netloc == "svn.python.org": if path.startswith("/projects/"): path = path[9:] elif netloc != "pythondev@svn.python.org": ErrorExit("Unrecognized Python URL: %s" % url) base = "http://svn.python.org/view/*checkout*%s/" % path logging.info("Guessed Python base = %s", base) elif netloc.endswith("svn.collab.net"): if path.startswith("/repos/"): path = path[6:] base = "http://svn.collab.net/viewvc/*checkout*%s/" % path logging.info("Guessed CollabNet base = %s", base) elif netloc.endswith(".googlecode.com"): path = path + "/" base = urlparse.urlunparse(("http", netloc, path, params, query, fragment)) logging.info("Guessed Google Code base = %s", base) else: path = path + "/" base = urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) logging.info("Guessed base = %s", base) return base if required: ErrorExit("Can't find URL in output from svn info") return None def GenerateDiff(self, args): cmd = ["svn", "diff"] if self.options.revision: cmd += ["-r", self.options.revision] cmd.extend(args) data = RunShell(cmd) count = 0 for line in data.splitlines(): if line.startswith("Index:") or line.startswith("Property changes on:"): count += 1 logging.info(line) if not count: ErrorExit("No valid patches found in output from svn diff") return data def _CollapseKeywords(self, content, keyword_str): """Collapses SVN keywords.""" # svn cat translates keywords but svn diff doesn't. As a result of this # behavior patching.PatchChunks() fails with a chunk mismatch error. # This part was originally written by the Review Board development team # who had the same problem (http://reviews.review-board.org/r/276/). # Mapping of keywords to known aliases svn_keywords = { # Standard keywords 'Date': ['Date', 'LastChangedDate'], 'Revision': ['Revision', 'LastChangedRevision', 'Rev'], 'Author': ['Author', 'LastChangedBy'], 'HeadURL': ['HeadURL', 'URL'], 'Id': ['Id'], # Aliases 'LastChangedDate': ['LastChangedDate', 'Date'], 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'], 'LastChangedBy': ['LastChangedBy', 'Author'], 'URL': ['URL', 'HeadURL'], } def repl(m): if m.group(2): return "$%s::%s$" % (m.group(1), " " * len(m.group(3))) return "$%s$" % m.group(1) keywords = [keyword for name in keyword_str.split(" ") for keyword in svn_keywords.get(name, [])] return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content) def GetUnknownFiles(self): status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True) unknown_files = [] for line in status.split("\n"): if line and line[0] == "?": unknown_files.append(line) return unknown_files def ReadFile(self, filename): """Returns the contents of a file.""" file = open(filename, 'rb') result = "" try: result = file.read() finally: file.close() return result def GetStatus(self, filename): """Returns the status of a file.""" if not self.options.revision: status = RunShell(["svn", "status", "--ignore-externals", filename]) if not status: ErrorExit("svn status returned no output for %s" % filename) status_lines = status.splitlines() # If file is in a cl, the output will begin with # "\n--- Changelist 'cl_name':\n". See # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt if (len(status_lines) == 3 and not status_lines[0] and status_lines[1].startswith("--- Changelist")): status = status_lines[2] else: status = status_lines[0] # If we have a revision to diff against we need to run "svn list" # for the old and the new revision and compare the results to get # the correct status for a file. else: dirname, relfilename = os.path.split(filename) if dirname not in self.svnls_cache: cmd = ["svn", "list", "-r", self.rev_start, dirname or "."] out, returncode = RunShellWithReturnCode(cmd) if returncode: ErrorExit("Failed to get status for %s." % filename) old_files = out.splitlines() args = ["svn", "list"] if self.rev_end: args += ["-r", self.rev_end] cmd = args + [dirname or "."] out, returncode = RunShellWithReturnCode(cmd) if returncode: ErrorExit("Failed to run command %s" % cmd) self.svnls_cache[dirname] = (old_files, out.splitlines()) old_files, new_files = self.svnls_cache[dirname] if relfilename in old_files and relfilename not in new_files: status = "D " elif relfilename in old_files and relfilename in new_files: status = "M " else: status = "A " return status def GetBaseFile(self, filename): status = self.GetStatus(filename) base_content = None new_content = None # If a file is copied its status will be "A +", which signifies # "addition-with-history". See "svn st" for more information. We need to # upload the original file or else diff parsing will fail if the file was # edited. if status[0] == "A" and status[3] != "+": # We'll need to upload the new content if we're adding a binary file # since diff's output won't contain it. mimetype = RunShell(["svn", "propget", "svn:mime-type", filename], silent_ok=True) base_content = "" is_binary = mimetype and not mimetype.startswith("text/") if is_binary and self.IsImage(filename): new_content = self.ReadFile(filename) elif (status[0] in ("M", "D", "R") or (status[0] == "A" and status[3] == "+") or # Copied file. (status[0] == " " and status[1] == "M")): # Property change. args = [] if self.options.revision: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) else: # Don't change filename, it's needed later. url = filename args += ["-r", "BASE"] cmd = ["svn"] + args + ["propget", "svn:mime-type", url] mimetype, returncode = RunShellWithReturnCode(cmd) if returncode: # File does not exist in the requested revision. # Reset mimetype, it contains an error message. mimetype = "" get_base = False is_binary = mimetype and not mimetype.startswith("text/") if status[0] == " ": # Empty base content just to force an upload. base_content = "" elif is_binary: if self.IsImage(filename): get_base = True if status[0] == "M": if not self.rev_end: new_content = self.ReadFile(filename) else: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end) new_content = RunShell(["svn", "cat", url], universal_newlines=True, silent_ok=True) else: base_content = "" else: get_base = True if get_base: if is_binary: universal_newlines = False else: universal_newlines = True if self.rev_start: # "svn cat -r REV delete_file.txt" doesn't work. cat requires # the full URL with "@REV" appended instead of using "-r" option. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) base_content = RunShell(["svn", "cat", url], universal_newlines=universal_newlines, silent_ok=True) else: base_content = RunShell(["svn", "cat", filename], universal_newlines=universal_newlines, silent_ok=True) if not is_binary: args = [] if self.rev_start: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) else: url = filename args += ["-r", "BASE"] cmd = ["svn"] + args + ["propget", "svn:keywords", url] keywords, returncode = RunShellWithReturnCode(cmd) if keywords and not returncode: base_content = self._CollapseKeywords(base_content, keywords) else: StatusUpdate("svn status returned unexpected output: %s" % status) sys.exit(1) return base_content, new_content, is_binary, status[0:5] class GitVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Git.""" def __init__(self, options): super(GitVCS, self).__init__(options) # Map of filename -> hash of base file. self.base_hashes = {} def GenerateDiff(self, extra_args): # This is more complicated than svn's GenerateDiff because we must convert # the diff output to include an svn-style "Index:" line as well as record # the hashes of the base files, so we can upload them along with our diff. if self.options.revision: extra_args = [self.options.revision] + extra_args gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args) svndiff = [] filecount = 0 filename = None for line in gitdiff.splitlines(): match = re.match(r"diff --git a/(.*) b/.*$", line) if match: filecount += 1 filename = match.group(1) svndiff.append("Index: %s\n" % filename) else: # The "index" line in a git diff looks like this (long hashes elided): # index 82c0d44..b2cee3f 100755 # We want to save the left hash, as that identifies the base file. match = re.match(r"index (\w+)\.\.", line) if match: self.base_hashes[filename] = match.group(1) svndiff.append(line + "\n") if not filecount: ErrorExit("No valid patches found in output from git diff") return "".join(svndiff) def GetUnknownFiles(self): status = RunShell(["git", "ls-files", "--exclude-standard", "--others"], silent_ok=True) return status.splitlines() def GetBaseFile(self, filename): hash = self.base_hashes[filename] base_content = None new_content = None is_binary = False if hash == "0" * 40: # All-zero hash indicates no base file. status = "A" base_content = "" else: status = "M" base_content, returncode = RunShellWithReturnCode(["git", "show", hash]) if returncode: ErrorExit("Got error status from 'git show %s'" % hash) return (base_content, new_content, is_binary, status) class MercurialVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Mercurial.""" def __init__(self, options, repo_dir): super(MercurialVCS, self).__init__(options) # Absolute path to repository (we can be in a subdir) self.repo_dir = os.path.normpath(repo_dir) # Compute the subdir cwd = os.path.normpath(os.getcwd()) assert cwd.startswith(self.repo_dir) self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/") if self.options.revision: self.base_rev = self.options.revision else: self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip() def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), filename return filename[len(self.subdir):].lstrip(r"\/") def GenerateDiff(self, extra_args): # If no file specified, restrict to the current subdir extra_args = extra_args or ["."] cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args data = RunShell(cmd, silent_ok=True) svndiff = [] filecount = 0 for line in data.splitlines(): m = re.match("diff --git a/(\S+) b/(\S+)", line) if m: # Modify line to make it look like as it comes from svn diff. # With this modification no changes on the server side are required # to make upload.py work with Mercurial repos. # NOTE: for proper handling of moved/copied files, we have to use # the second filename. filename = m.group(2) svndiff.append("Index: %s" % filename) svndiff.append("=" * 67) filecount += 1 logging.info(line) else: svndiff.append(line) if not filecount: ErrorExit("No valid patches found in output from hg diff") return "\n".join(svndiff) + "\n" def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" args = [] status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], silent_ok=True) unknown_files = [] for line in status.splitlines(): st, fn = line.split(" ", 1) if st == "?": unknown_files.append(fn) return unknown_files def GetBaseFile(self, filename): # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self._GetRelPath(filename) # "hg status -C" returns two lines for moved/copied files, one otherwise out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath]) out = out.splitlines() # HACK: strip error message about missing file/directory if it isn't in # the working copy if out[0].startswith('%s: ' % relpath): out = out[1:] if len(out) > 1: # Moved/copied => considered as modified, use old filename to # retrieve base contents oldrelpath = out[1].strip() status = "M" else: status, _ = out[0].split(' ', 1) if status != "A": base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], silent_ok=True) is_binary = "\0" in base_content # Mercurial's heuristic if status != "R": new_content = open(relpath, "rb").read() is_binary = is_binary or "\0" in new_content if is_binary and base_content: # Fetch again without converting newlines base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath], silent_ok=True, universal_newlines=False) if not is_binary or not self.IsImage(relpath): new_content = None return base_content, new_content, is_binary, status # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync. def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. """ patches = [] filename = None diff = [] for line in data.splitlines(True): new_filename = None if line.startswith('Index:'): unused, new_filename = line.split(':', 1) new_filename = new_filename.strip() elif line.startswith('Property changes on:'): unused, temp_filename = line.split(':', 1) # When a file is modified, paths use '/' between directories, however # when a property is modified '\' is used on Windows. Make them the same # otherwise the file shows up twice. temp_filename = temp_filename.strip().replace('\\', '/') if temp_filename != filename: # File has property changes but no modifications, create a new diff. new_filename = temp_filename if new_filename: if filename and diff: patches.append((filename, ''.join(diff))) filename = new_filename diff = [line] continue if diff is not None: diff.append(line) if filename and diff: patches.append((filename, ''.join(diff))) return patches def UploadSeparatePatches(issue, rpc_server, patchset, data, options): """Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. """ patches = SplitPatch(data) rv = [] for patch in patches: if len(patch[1]) > MAX_UPLOAD_SIZE: print ("Not uploading the patch for " + patch[0] + " because the file is too large.") continue form_fields = [("filename", patch[0])] if not options.download_base: form_fields.append(("content_upload", "1")) files = [("data", "data.diff", patch[1])] ctype, body = EncodeMultipartFormData(form_fields, files) url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) print "Uploading patch for " + patch[0] response_body = rpc_server.Send(url, body, content_type=ctype) lines = response_body.splitlines() if not lines or lines[0] != "OK": StatusUpdate(" --> %s" % response_body) sys.exit(1) rv.append([lines[1], patch[0]]) return rv def GuessVCS(options): """Helper to guess the version control system. This examines the current directory, guesses which VersionControlSystem we're using, and returns an instance of the appropriate class. Exit with an error if we can't figure it out. Returns: A VersionControlSystem instance. Exits if the VCS can't be guessed. """ # Mercurial has a command to get the base directory of a repository # Try running it, but don't die if we don't have hg installed. # NOTE: we try Mercurial first as it can sit on top of an SVN working copy. try: out, returncode = RunShellWithReturnCode(["hg", "root"]) if returncode == 0: return MercurialVCS(options, out.strip()) except OSError, (errno, message): if errno != 2: # ENOENT -- they don't have hg installed. raise # Subversion has a .svn in all working directories. if os.path.isdir('.svn'): logging.info("Guessed VCS = Subversion") return SubversionVCS(options) # Git has a command to test if you're in a git tree. # Try running it, but don't die if we don't have git installed. try: out, returncode = RunShellWithReturnCode(["git", "rev-parse", "--is-inside-work-tree"]) if returncode == 0: return GitVCS(options) except OSError, (errno, message): if errno != 2: # ENOENT -- they don't have git installed. raise ErrorExit(("Could not guess version control system. " "Are you in a working copy directory?")) def RealMain(argv, data=None): """The real main function. Args: argv: Command line arguments. data: Diff contents. If None (default) the diff is generated by the VersionControlSystem implementation returned by GuessVCS(). Returns: A 2-tuple (issue id, patchset id). The patchset id is None if the base files are not uploaded by this script (applies only to SVN checkouts). """ logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:" "%(lineno)s %(message)s ")) os.environ['LC_ALL'] = 'C' options, args = parser.parse_args(argv[1:]) global verbosity verbosity = options.verbose if verbosity >= 3: logging.getLogger().setLevel(logging.DEBUG) elif verbosity >= 2: logging.getLogger().setLevel(logging.INFO) vcs = GuessVCS(options) if isinstance(vcs, SubversionVCS): # base field is only allowed for Subversion. # Note: Fetching base files may become deprecated in future releases. base = vcs.GuessBase(options.download_base) else: base = None if not base and options.download_base: options.download_base = True logging.info("Enabled upload of base file") if not options.assume_yes: vcs.CheckForUnknownFiles() if data is None: data = vcs.GenerateDiff(args) files = vcs.GetBaseFiles(data) if verbosity >= 1: print "Upload server:", options.server, "(change with -s/--server)" if options.issue: prompt = "Message describing this patch set: " else: prompt = "New issue subject: " message = options.message or raw_input(prompt).strip() if not message: ErrorExit("A non-empty message is required") rpc_server = GetRpcServer(options) form_fields = [("subject", message)] if base: form_fields.append(("base", base)) if options.issue: form_fields.append(("issue", str(options.issue))) if options.email: form_fields.append(("user", options.email)) if options.reviewers: for reviewer in options.reviewers.split(','): if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1: ErrorExit("Invalid email address: %s" % reviewer) form_fields.append(("reviewers", options.reviewers)) if options.cc: for cc in options.cc.split(','): if "@" in cc and not cc.split("@")[1].count(".") == 1: ErrorExit("Invalid email address: %s" % cc) form_fields.append(("cc", options.cc)) description = options.description if options.description_file: if options.description: ErrorExit("Can't specify description and description_file") file = open(options.description_file, 'r') description = file.read() file.close() if description: form_fields.append(("description", description)) # Send a hash of all the base file so the server can determine if a copy # already exists in an earlier patchset. base_hashes = "" for file, info in files.iteritems(): if not info[0] is None: checksum = md5.new(info[0]).hexdigest() if base_hashes: base_hashes += "|" base_hashes += checksum + ":" + file form_fields.append(("base_hashes", base_hashes)) # If we're uploading base files, don't send the email before the uploads, so # that it contains the file status. if options.send_mail and options.download_base: form_fields.append(("send_mail", "1")) if not options.download_base: form_fields.append(("content_upload", "1")) if len(data) > MAX_UPLOAD_SIZE: print "Patch is large, so uploading file patches separately." uploaded_diff_file = [] form_fields.append(("separate_patches", "1")) else: uploaded_diff_file = [("data", "data.diff", data)] ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file) response_body = rpc_server.Send("/upload", body, content_type=ctype) patchset = None if not options.download_base or not uploaded_diff_file: lines = response_body.splitlines() if len(lines) >= 2: msg = lines[0] patchset = lines[1].strip() patches = [x.split(" ", 1) for x in lines[2:]] else: msg = response_body else: msg = response_body StatusUpdate(msg) if not response_body.startswith("Issue created.") and \ not response_body.startswith("Issue updated."): sys.exit(0) issue = msg[msg.rfind("/")+1:] if not uploaded_diff_file: result = UploadSeparatePatches(issue, rpc_server, patchset, data, options) if not options.download_base: patches = result if not options.download_base: vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files) if options.send_mail: rpc_server.Send("/" + issue + "/mail", payload="") return issue, patchset def main(): try: RealMain(sys.argv) except KeyboardInterrupt: print StatusUpdate("Interrupted.") sys.exit(1) if __name__ == "__main__": main()
gpl-3.0
hotsyk/declaration-widgets
setup.py
1
1627
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read().replace('.. :changelog:', '') requirements = [ # TODO: put package requirements here ] test_requirements = [ # TODO: put package test requirements here ] setup( name='declaration-widgets', version='0.1.0', description="Python Boilerplate contains all the boilerplate you need to create a Python package.", long_description=readme + '\n\n' + history, author="Volodymyr Hotsyk", author_email='gotsyk@gmail.com', url='https://github.com/hotsyk/declaration-widgets', packages=[ 'declaration-widgets', ], package_dir={'declaration-widgets': 'declaration-widgets'}, include_package_data=True, install_requires=requirements, license="BSD", zip_safe=False, keywords='declaration-widgets', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], test_suite='tests', tests_require=test_requirements )
bsd-3-clause
JingheZ/shogun
examples/undocumented/python_modular/classifier_svmlight_linear_term_modular.py
17
2004
#!/usr/bin/env python import numpy traindna=['CGCACGTACGTAGCTCGAT', 'CGACGTAGTCGTAGTCGTA', 'CGACGGGGGGGGGGTCGTA', 'CGACCTAGTCGTAGTCGTA', 'CGACCACAGTTATATAGTA', 'CGACGTAGTCGTAGTCGTA', 'CGACGTAGTTTTTTTCGTA', 'CGACGTAGTCGTAGCCCCA', 'CAAAAAAAAAAAAAAAATA', 'CGACGGGGGGGGGGGCGTA'] label_traindna=numpy.array(5*[-1.0] + 5*[1.0]) testdna=['AGCACGTACGTAGCTCGAT', 'AGACGTAGTCGTAGTCGTA', 'CAACGGGGGGGGGGTCGTA', 'CGACCTAGTCGTAGTCGTA', 'CGAACACAGTTATATAGTA', 'CGACCTAGTCGTAGTCGTA', 'CGACGTGGGGTTTTTCGTA', 'CGACGTAGTCCCAGCCCCA', 'CAAAAAAAAAAAACCAATA', 'CGACGGCCGGGGGGGCGTA'] label_test_dna=numpy.array(5*[-1.0] + 5*[1.0]) parameter_list = [[traindna,testdna,label_traindna,3,10,1e-5,1],[traindna,testdna,label_traindna,3,10,1e-5,1]] def classifier_svmlight_linear_term_modular (fm_train_dna=traindna,fm_test_dna=testdna, \ label_train_dna=label_traindna,degree=3, \ C=10,epsilon=1e-5,num_threads=1): from modshogun import StringCharFeatures, BinaryLabels, DNA from modshogun import WeightedDegreeStringKernel from modshogun import SVMLight feats_train=StringCharFeatures(DNA) feats_train.set_features(fm_train_dna) feats_test=StringCharFeatures(DNA) feats_test.set_features(fm_test_dna) kernel=WeightedDegreeStringKernel(feats_train, feats_train, degree) labels=BinaryLabels(label_train_dna) svm=SVMLight(C, kernel, labels) svm.set_qpsize(3) svm.set_linear_term(-numpy.array([1,2,3,4,5,6,7,8,7,6], dtype=numpy.double)); svm.set_epsilon(epsilon) svm.parallel.set_num_threads(num_threads) svm.train() kernel.init(feats_train, feats_test) out = svm.apply().get_labels() return out,kernel if __name__=='__main__': print('SVMLight') classifier_svmlight_linear_term_modular(*parameter_list[0])
gpl-3.0
psoetens/pcl-svn
cmake/merge_cmake_install.py
9
1093
#!/usr/bin/env python # file: merge_cmake_install.py import sys, math import fnmatch import os import shutil if len(sys.argv) != 2: # stop the program and print an error message sys.exit("Must provide a cmake binary folder") base_folder = sys.argv[1] string_to_remove_debug = "IF(\"${CMAKE_INSTALL_CONFIG_NAME}\" MATCHES \"^([Dd][Ee][Bb][Uu][Gg])$\")" string_to_remove_release = "IF(\"${CMAKE_INSTALL_CONFIG_NAME}\" MATCHES \"^([Rr][Ee][Ll][Ee][Aa][Ss][Ee])$\")" matches = [] for root, dirnames, filenames in os.walk(base_folder): for filename in fnmatch.filter(filenames, 'cmake_install.cmake'): matches.append(os.path.join(root, filename)) for one_match in matches: #print one_match, "\n" shutil.move( one_match, one_match+"~" ) destination= open( one_match, "w" ) source= open( one_match+"~", "r" ) for line in source: if string_to_remove_debug in line: destination.write( "\n" ) elif string_to_remove_release in line: destination.write( "\n" ) else: destination.write( line ) source.close() destination.close()
bsd-3-clause
mrquim/mrquimrepo
repo/script.module.trakt/lib/trakt/interfaces/__init__.py
4
1977
from __future__ import absolute_import, division, print_function from trakt.interfaces import auth from trakt.interfaces import calendars from trakt.interfaces import movies from trakt.interfaces import oauth from trakt.interfaces import scrobble from trakt.interfaces import search from trakt.interfaces import shows from trakt.interfaces import sync from trakt.interfaces import users INTERFACES = [ # / auth.AuthInterface, oauth.OAuthInterface, oauth.DeviceOAuthInterface, oauth.PinOAuthInterface, scrobble.ScrobbleInterface, search.SearchInterface, # /calendars/ calendars.AllCalendarsInterface, calendars.MyCalendarsInterface, # /sync/ sync.SyncInterface, sync.SyncCollectionInterface, sync.SyncHistoryInterface, sync.SyncPlaybackInterface, sync.SyncRatingsInterface, sync.SyncWatchedInterface, sync.SyncWatchlistInterface, # /shows/ shows.ShowsInterface, # /movies/ movies.MoviesInterface, # /users/ users.UsersInterface, users.UsersSettingsInterface, # /users/lists/ users.UsersListsInterface, users.UsersListInterface ] def get_interfaces(): for interface in INTERFACES: if not interface.path: continue path = interface.path.strip('/') if path: path = path.split('/') else: path = [] yield path, interface def construct_map(client, d=None, interfaces=None): if d is None: d = {} if interfaces is None: interfaces = get_interfaces() for path, interface in interfaces: if len(path) == 0: continue key = path.pop(0) if len(path) == 0: d[key] = interface(client) continue value = d.get(key, {}) if type(value) is not dict: value = {None: value} construct_map(client, value, [(path, interface)]) d[key] = value return d
gpl-2.0
j-griffith/cinder
cinder/tests/unit/group/test_groups_manager_replication.py
4
5560
# Copyright (C) 2017 Dell Inc. or its subsidiaries. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import ddt import mock from oslo_config import cfg from oslo_utils import importutils from cinder import context from cinder import exception from cinder import objects from cinder.objects import fields from cinder import quota from cinder import test from cinder.tests.unit import fake_constants as fake from cinder.tests.unit import utils as tests_utils from cinder.volume import api as volume_api from cinder.volume import configuration as conf from cinder.volume import driver from cinder.volume import utils as volutils GROUP_QUOTAS = quota.GROUP_QUOTAS CONF = cfg.CONF @ddt.ddt class GroupManagerTestCase(test.TestCase): def setUp(self): super(GroupManagerTestCase, self).setUp() self.volume = importutils.import_object(CONF.volume_manager) self.configuration = mock.Mock(conf.Configuration) self.context = context.get_admin_context() self.context.user_id = fake.USER_ID self.project_id = fake.PROJECT3_ID self.context.project_id = self.project_id self.volume.driver.set_initialized() self.volume.stats = {'allocated_capacity_gb': 0, 'pools': {}} self.volume_api = volume_api.API() @mock.patch.object(GROUP_QUOTAS, "reserve", return_value=["RESERVATION"]) @mock.patch.object(GROUP_QUOTAS, "commit") @mock.patch.object(GROUP_QUOTAS, "rollback") @mock.patch.object(driver.VolumeDriver, "delete_group", return_value=({'status': ( fields.GroupStatus.DELETED)}, [])) @mock.patch.object(driver.VolumeDriver, "enable_replication", return_value=(None, [])) @mock.patch.object(driver.VolumeDriver, "disable_replication", return_value=(None, [])) @mock.patch.object(driver.VolumeDriver, "failover_replication", return_value=(None, [])) def test_replication_group(self, fake_failover_rep, fake_disable_rep, fake_enable_rep, fake_delete_grp, fake_rollback, fake_commit, fake_reserve): """Test enable, disable, and failover replication for group.""" def fake_driver_create_grp(context, group): """Make sure that the pool is part of the host.""" self.assertIn('host', group) host = group.host pool = volutils.extract_host(host, level='pool') self.assertEqual('fakepool', pool) return {'status': fields.GroupStatus.AVAILABLE, 'replication_status': fields.ReplicationStatus.DISABLING} self.mock_object(self.volume.driver, 'create_group', fake_driver_create_grp) group = tests_utils.create_group( self.context, availability_zone=CONF.storage_availability_zone, volume_type_ids=[fake.VOLUME_TYPE_ID], host='fakehost@fakedrv#fakepool', group_type_id=fake.GROUP_TYPE_ID) group = objects.Group.get_by_id(self.context, group.id) self.volume.create_group(self.context, group) self.assertEqual( group.id, objects.Group.get_by_id(context.get_admin_context(), group.id).id) self.volume.disable_replication(self.context, group) group = objects.Group.get_by_id( context.get_admin_context(), group.id) self.assertEqual(fields.ReplicationStatus.DISABLED, group.replication_status) group.replication_status = fields.ReplicationStatus.ENABLING group.save() self.volume.enable_replication(self.context, group) group = objects.Group.get_by_id( context.get_admin_context(), group.id) self.assertEqual(fields.ReplicationStatus.ENABLED, group.replication_status) group.replication_status = fields.ReplicationStatus.FAILING_OVER group.save() self.volume.failover_replication(self.context, group) group = objects.Group.get_by_id( context.get_admin_context(), group.id) self.assertEqual(fields.ReplicationStatus.FAILED_OVER, group.replication_status) targets = self.volume.list_replication_targets(self.context, group) self.assertIn('replication_targets', targets) self.volume.delete_group(self.context, group) grp = objects.Group.get_by_id( context.get_admin_context(read_deleted='yes'), group.id) self.assertEqual(fields.GroupStatus.DELETED, grp.status) self.assertRaises(exception.NotFound, objects.Group.get_by_id, self.context, group.id)
apache-2.0
mancoast/CPythonPyc_test
cpython/278_test_future4.py
136
1516
from __future__ import unicode_literals import unittest from test import test_support class TestFuture(unittest.TestCase): def assertType(self, obj, typ): self.assertTrue(type(obj) is typ, "type(%r) is %r, not %r" % (obj, type(obj), typ)) def test_unicode_strings(self): self.assertType("", unicode) self.assertType('', unicode) self.assertType(r"", unicode) self.assertType(r'', unicode) self.assertType(""" """, unicode) self.assertType(''' ''', unicode) self.assertType(r""" """, unicode) self.assertType(r''' ''', unicode) self.assertType(u"", unicode) self.assertType(u'', unicode) self.assertType(ur"", unicode) self.assertType(ur'', unicode) self.assertType(u""" """, unicode) self.assertType(u''' ''', unicode) self.assertType(ur""" """, unicode) self.assertType(ur''' ''', unicode) self.assertType(b"", str) self.assertType(b'', str) self.assertType(br"", str) self.assertType(br'', str) self.assertType(b""" """, str) self.assertType(b''' ''', str) self.assertType(br""" """, str) self.assertType(br''' ''', str) self.assertType('' '', unicode) self.assertType('' u'', unicode) self.assertType(u'' '', unicode) self.assertType(u'' u'', unicode) def test_main(): test_support.run_unittest(TestFuture) if __name__ == "__main__": test_main()
gpl-3.0
Matt-Deacalion/django
tests/conditional_processing/tests.py
322
9157
# -*- coding:utf-8 -*- from __future__ import unicode_literals from datetime import datetime from django.test import SimpleTestCase, override_settings FULL_RESPONSE = 'Test conditional get response' LAST_MODIFIED = datetime(2007, 10, 21, 23, 21, 47) LAST_MODIFIED_STR = 'Sun, 21 Oct 2007 23:21:47 GMT' LAST_MODIFIED_NEWER_STR = 'Mon, 18 Oct 2010 16:56:23 GMT' LAST_MODIFIED_INVALID_STR = 'Mon, 32 Oct 2010 16:56:23 GMT' EXPIRED_LAST_MODIFIED_STR = 'Sat, 20 Oct 2007 23:21:47 GMT' ETAG = 'b4246ffc4f62314ca13147c9d4f76974' EXPIRED_ETAG = '7fae4cd4b0f81e7d2914700043aa8ed6' @override_settings(ROOT_URLCONF='conditional_processing.urls') class ConditionalGet(SimpleTestCase): def assertFullResponse(self, response, check_last_modified=True, check_etag=True): self.assertEqual(response.status_code, 200) self.assertEqual(response.content, FULL_RESPONSE.encode()) if check_last_modified: self.assertEqual(response['Last-Modified'], LAST_MODIFIED_STR) if check_etag: self.assertEqual(response['ETag'], '"%s"' % ETAG) def assertNotModified(self, response): self.assertEqual(response.status_code, 304) self.assertEqual(response.content, b'') def test_without_conditions(self): response = self.client.get('/condition/') self.assertFullResponse(response) def test_if_modified_since(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR response = self.client.get('/condition/') self.assertNotModified(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_NEWER_STR response = self.client.get('/condition/') self.assertNotModified(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_INVALID_STR response = self.client.get('/condition/') self.assertFullResponse(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR response = self.client.get('/condition/') self.assertFullResponse(response) def test_if_unmodified_since(self): self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_STR response = self.client.get('/condition/') self.assertFullResponse(response) self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_NEWER_STR response = self.client.get('/condition/') self.assertFullResponse(response) self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_INVALID_STR response = self.client.get('/condition/') self.assertFullResponse(response) self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR response = self.client.get('/condition/') self.assertEqual(response.status_code, 412) def test_if_none_match(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/') self.assertNotModified(response) self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.get('/condition/') self.assertFullResponse(response) # Several etags in If-None-Match is a bit exotic but why not? self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s", "%s"' % (ETAG, EXPIRED_ETAG) response = self.client.get('/condition/') self.assertNotModified(response) def test_if_match(self): self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % ETAG response = self.client.put('/condition/etag/') self.assertEqual(response.status_code, 200) self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.put('/condition/etag/') self.assertEqual(response.status_code, 412) def test_both_headers(self): # see http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.4 self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/') self.assertNotModified(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/') self.assertFullResponse(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.get('/condition/') self.assertFullResponse(response) self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.get('/condition/') self.assertFullResponse(response) def test_both_headers_2(self): self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_STR self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/') self.assertFullResponse(response) self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.get('/condition/') self.assertEqual(response.status_code, 412) self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_STR self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.get('/condition/') self.assertEqual(response.status_code, 412) self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR self.client.defaults['HTTP_IF_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/') self.assertEqual(response.status_code, 412) def test_single_condition_1(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR response = self.client.get('/condition/last_modified/') self.assertNotModified(response) response = self.client.get('/condition/etag/') self.assertFullResponse(response, check_last_modified=False) def test_single_condition_2(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/etag/') self.assertNotModified(response) response = self.client.get('/condition/last_modified/') self.assertFullResponse(response, check_etag=False) def test_single_condition_3(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR response = self.client.get('/condition/last_modified/') self.assertFullResponse(response, check_etag=False) def test_single_condition_4(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % EXPIRED_ETAG response = self.client.get('/condition/etag/') self.assertFullResponse(response, check_last_modified=False) def test_single_condition_5(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR response = self.client.get('/condition/last_modified2/') self.assertNotModified(response) response = self.client.get('/condition/etag2/') self.assertFullResponse(response, check_last_modified=False) def test_single_condition_6(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = '"%s"' % ETAG response = self.client.get('/condition/etag2/') self.assertNotModified(response) response = self.client.get('/condition/last_modified2/') self.assertFullResponse(response, check_etag=False) def test_single_condition_7(self): self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR response = self.client.get('/condition/last_modified/') self.assertEqual(response.status_code, 412) response = self.client.get('/condition/etag/') self.assertFullResponse(response, check_last_modified=False) def test_single_condition_8(self): self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = LAST_MODIFIED_STR response = self.client.get('/condition/last_modified/') self.assertFullResponse(response, check_etag=False) def test_single_condition_9(self): self.client.defaults['HTTP_IF_UNMODIFIED_SINCE'] = EXPIRED_LAST_MODIFIED_STR response = self.client.get('/condition/last_modified2/') self.assertEqual(response.status_code, 412) response = self.client.get('/condition/etag2/') self.assertFullResponse(response, check_last_modified=False) def test_single_condition_head(self): self.client.defaults['HTTP_IF_MODIFIED_SINCE'] = LAST_MODIFIED_STR response = self.client.head('/condition/') self.assertNotModified(response) def test_invalid_etag(self): self.client.defaults['HTTP_IF_NONE_MATCH'] = r'"\"' response = self.client.get('/condition/etag/') self.assertFullResponse(response, check_last_modified=False)
bsd-3-clause
ducthien1490/youtube-dl
youtube_dl/extractor/googleplus.py
129
2568
# coding: utf-8 from __future__ import unicode_literals import re import codecs from .common import InfoExtractor from ..utils import unified_strdate class GooglePlusIE(InfoExtractor): IE_DESC = 'Google Plus' _VALID_URL = r'https://plus\.google\.com/(?:[^/]+/)*?posts/(?P<id>\w+)' IE_NAME = 'plus.google' _TEST = { 'url': 'https://plus.google.com/u/0/108897254135232129896/posts/ZButuJc6CtH', 'info_dict': { 'id': 'ZButuJc6CtH', 'ext': 'flv', 'title': '嘆きの天使 降臨', 'upload_date': '20120613', 'uploader': '井上ヨシマサ', } } def _real_extract(self, url): video_id = self._match_id(url) # Step 1, Retrieve post webpage to extract further information webpage = self._download_webpage(url, video_id, 'Downloading entry webpage') title = self._og_search_description(webpage).splitlines()[0] upload_date = unified_strdate(self._html_search_regex( r'''(?x)<a.+?class="o-U-s\s[^"]+"\s+style="display:\s*none"\s*> ([0-9]{4}-[0-9]{2}-[0-9]{2})</a>''', webpage, 'upload date', fatal=False, flags=re.VERBOSE)) uploader = self._html_search_regex( r'rel="author".*?>(.*?)</a>', webpage, 'uploader', fatal=False) # Step 2, Simulate clicking the image box to launch video DOMAIN = 'https://plus.google.com/' video_page = self._search_regex( r'<a href="((?:%s)?photos/.*?)"' % re.escape(DOMAIN), webpage, 'video page URL') if not video_page.startswith(DOMAIN): video_page = DOMAIN + video_page webpage = self._download_webpage(video_page, video_id, 'Downloading video page') def unicode_escape(s): decoder = codecs.getdecoder('unicode_escape') return re.sub( r'\\u[0-9a-fA-F]{4,}', lambda m: decoder(m.group(0))[0], s) # Extract video links all sizes formats = [{ 'url': unicode_escape(video_url), 'ext': 'flv', 'width': int(width), 'height': int(height), } for width, height, video_url in re.findall( r'\d+,(\d+),(\d+),"(https?://redirector\.googlevideo\.com.*?)"', webpage)] self._sort_formats(formats) return { 'id': video_id, 'title': title, 'uploader': uploader, 'upload_date': upload_date, 'formats': formats, }
unlicense
LinuxChristian/home-assistant
homeassistant/components/velux.py
10
1826
""" Connects to VELUX KLF 200 interface. For more details about this component, please refer to the documentation at https://home-assistant.io/components/velux/ """ import logging import asyncio import voluptuous as vol from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv from homeassistant.const import (CONF_HOST, CONF_PASSWORD) DOMAIN = "velux" DATA_VELUX = "data_velux" SUPPORTED_DOMAINS = ['scene'] _LOGGER = logging.getLogger(__name__) REQUIREMENTS = ['pyvlx==0.1.3'] CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, }) }, extra=vol.ALLOW_EXTRA) @asyncio.coroutine def async_setup(hass, config): """Set up the velux component.""" from pyvlx import PyVLXException try: hass.data[DATA_VELUX] = VeluxModule(hass, config) yield from hass.data[DATA_VELUX].async_start() except PyVLXException as ex: _LOGGER.exception("Can't connect to velux interface: %s", ex) return False for component in SUPPORTED_DOMAINS: hass.async_add_job( discovery.async_load_platform(hass, component, DOMAIN, {}, config)) return True class VeluxModule: """Abstraction for velux component.""" def __init__(self, hass, config): """Initialize for velux component.""" from pyvlx import PyVLX self.initialized = False host = config[DOMAIN].get(CONF_HOST) password = config[DOMAIN].get(CONF_PASSWORD) self.pyvlx = PyVLX( host=host, password=password) self.hass = hass @asyncio.coroutine def async_start(self): """Start velux component.""" yield from self.pyvlx.load_scenes() self.initialized = True
apache-2.0
moutai/scikit-learn
sklearn/datasets/tests/test_mldata.py
384
5221
"""Test functionality of mldata fetching utilities.""" import os import shutil import tempfile import scipy as sp from sklearn import datasets from sklearn.datasets import mldata_filename, fetch_mldata from sklearn.utils.testing import assert_in from sklearn.utils.testing import assert_not_in from sklearn.utils.testing import mock_mldata_urlopen from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import with_setup from sklearn.utils.testing import assert_array_equal tmpdir = None def setup_tmpdata(): # create temporary dir global tmpdir tmpdir = tempfile.mkdtemp() os.makedirs(os.path.join(tmpdir, 'mldata')) def teardown_tmpdata(): # remove temporary dir if tmpdir is not None: shutil.rmtree(tmpdir) def test_mldata_filename(): cases = [('datasets-UCI iris', 'datasets-uci-iris'), ('news20.binary', 'news20binary'), ('book-crossing-ratings-1.0', 'book-crossing-ratings-10'), ('Nile Water Level', 'nile-water-level'), ('MNIST (original)', 'mnist-original')] for name, desired in cases: assert_equal(mldata_filename(name), desired) @with_setup(setup_tmpdata, teardown_tmpdata) def test_download(): """Test that fetch_mldata is able to download and cache a data set.""" _urlopen_ref = datasets.mldata.urlopen datasets.mldata.urlopen = mock_mldata_urlopen({ 'mock': { 'label': sp.ones((150,)), 'data': sp.ones((150, 4)), }, }) try: mock = fetch_mldata('mock', data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "target", "data"]: assert_in(n, mock) assert_equal(mock.target.shape, (150,)) assert_equal(mock.data.shape, (150, 4)) assert_raises(datasets.mldata.HTTPError, fetch_mldata, 'not_existing_name') finally: datasets.mldata.urlopen = _urlopen_ref @with_setup(setup_tmpdata, teardown_tmpdata) def test_fetch_one_column(): _urlopen_ref = datasets.mldata.urlopen try: dataname = 'onecol' # create fake data set in cache x = sp.arange(6).reshape(2, 3) datasets.mldata.urlopen = mock_mldata_urlopen({dataname: {'x': x}}) dset = fetch_mldata(dataname, data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "data"]: assert_in(n, dset) assert_not_in("target", dset) assert_equal(dset.data.shape, (2, 3)) assert_array_equal(dset.data, x) # transposing the data array dset = fetch_mldata(dataname, transpose_data=False, data_home=tmpdir) assert_equal(dset.data.shape, (3, 2)) finally: datasets.mldata.urlopen = _urlopen_ref @with_setup(setup_tmpdata, teardown_tmpdata) def test_fetch_multiple_column(): _urlopen_ref = datasets.mldata.urlopen try: # create fake data set in cache x = sp.arange(6).reshape(2, 3) y = sp.array([1, -1]) z = sp.arange(12).reshape(4, 3) # by default dataname = 'threecol-default' datasets.mldata.urlopen = mock_mldata_urlopen({ dataname: ( { 'label': y, 'data': x, 'z': z, }, ['z', 'data', 'label'], ), }) dset = fetch_mldata(dataname, data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "target", "data", "z"]: assert_in(n, dset) assert_not_in("x", dset) assert_not_in("y", dset) assert_array_equal(dset.data, x) assert_array_equal(dset.target, y) assert_array_equal(dset.z, z.T) # by order dataname = 'threecol-order' datasets.mldata.urlopen = mock_mldata_urlopen({ dataname: ({'y': y, 'x': x, 'z': z}, ['y', 'x', 'z']), }) dset = fetch_mldata(dataname, data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "target", "data", "z"]: assert_in(n, dset) assert_not_in("x", dset) assert_not_in("y", dset) assert_array_equal(dset.data, x) assert_array_equal(dset.target, y) assert_array_equal(dset.z, z.T) # by number dataname = 'threecol-number' datasets.mldata.urlopen = mock_mldata_urlopen({ dataname: ({'y': y, 'x': x, 'z': z}, ['z', 'x', 'y']), }) dset = fetch_mldata(dataname, target_name=2, data_name=0, data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "target", "data", "x"]: assert_in(n, dset) assert_not_in("y", dset) assert_not_in("z", dset) assert_array_equal(dset.data, z) assert_array_equal(dset.target, y) # by name dset = fetch_mldata(dataname, target_name='y', data_name='z', data_home=tmpdir) for n in ["COL_NAMES", "DESCR", "target", "data", "x"]: assert_in(n, dset) assert_not_in("y", dset) assert_not_in("z", dset) finally: datasets.mldata.urlopen = _urlopen_ref
bsd-3-clause
82d28a/laikaboss
laika.py
4
16971
#!/usr/bin/env python # Copyright 2015 Lockheed Martin Corporation # # 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 import sys, traceback import os import multiprocessing from optparse import OptionParser import logging, time from laikaboss.objectmodel import ExternalVars, ScanResult from laikaboss.constants import level_minimal, level_metadata, level_full from laikaboss.dispatch import Dispatch, close_modules from laikaboss import config from laikaboss.util import init_yara, init_logging, log_result from laikaboss.clientLib import getJSON, getRootObject, get_scanObjectUID from distutils.util import strtobool import zlib import json # Variable to store configs from file configs = {} # Defaults for all available configurations # To be used if not specified on command line or config file default_configs = { 'num_procs' : '8', 'max_bytes' : '10485760', 'max_files' : '0', 'progress_bar' : 'false', 'save_path' : '', 'scan_modules' : None, 'source' : 'CLI', 'ext_metadata' : {}, 'log_result' : 'false', 'log_json' : '', 'ephID' : '', 'dev_config_path' : 'etc/framework/laikaboss.conf', 'sys_config_path' : '/etc/laikaboss/laikaboss.conf' } def warning(*objs): print("WARNING: ", *objs, file=sys.stderr) def error(*objs): print("ERROR: ", *objs, file=sys.stderr) def getConfig(option): value = '' if option in configs: value = configs[option] else: value = default_configs[option] return value def main(): # Define default configuration location parser = OptionParser(usage="usage: %prog [options] /path/to/file") parser.add_option("-d", "--debug", action="store_true", dest="debug", help="enable debug messages to the console.") parser.add_option("-c", "--config-path", action="store", type="string", dest="config_path", help="path to configuration for laikaboss framework.") parser.add_option("-o", "--out-path", action="store", type="string", dest="save_path", help="Write all results to the specified path") parser.add_option("-s", "--source", action="store", type="string", dest="source", help="Set the source (may affect dispatching) [default:laika]") parser.add_option("-p", "--num_procs", action="store", type="int", dest="num_procs", default=8, help="Specify the number of CPU's to use for a recursive scan. [default:8]") parser.add_option("-l", "--log", action="store_true", dest="log_result", help="enable logging to syslog") parser.add_option("-j", "--log-json", action="store", type="string", dest="log_json", help="enable logging JSON results to file") parser.add_option("-m", "--module", action="store", type="string", dest="scan_modules", help="Specify individual module(s) to run and their arguments. If multiple, must be a space-separated list.") parser.add_option("--parent", action="store", type="string", dest="parent", default="", help="Define the parent of the root object") parser.add_option("-e", "--ephID", action="store", type="string", dest="ephID", default="", help="Specify an ephemeralID to send with the object") parser.add_option("--metadata", action="store", dest="ext_metadata", help="Define metadata to add to the scan or specify a file containing the metadata.") parser.add_option("--size-limit", action="store", type="int", default=10, dest="sizeLimit", help="Specify a size limit in MB (default: 10)") parser.add_option("--file-limit", action="store", type="int", default=0, dest="fileLimit", help="Specify a limited number of files to scan (default: off)") parser.add_option("--progress", action="store_true", dest="progress", default=False, help="enable the progress bar") (options, args) = parser.parse_args() logger = logging.getLogger() if options.debug: # stdout is added by default, we'll capture this object here #lhStdout = logger.handlers[0] fileHandler = logging.FileHandler('laika-debug.log', 'w') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') fileHandler.setFormatter(formatter) logger.addHandler(fileHandler) # remove stdout from handlers so that debug info is only written to the file #logger.removeHandler(lhStdout) logging.basicConfig(level=logging.DEBUG) logger.setLevel(logging.DEBUG) global EXT_METADATA if options.ext_metadata: if os.path.exists(options.ext_metadata): with open(options.ext_metadata) as metafile: EXT_METADATA = json.loads(metafile.read()) else: EXT_METADATA = json.loads(options.ext_metadata) else: EXT_METADATA = getConfig("ext_metadata") global EPHID if options.ephID: EPHID = options.ephID else: EPHID = getConfig("ephID") global SCAN_MODULES if options.scan_modules: SCAN_MODULES = options.scan_modules.split() else: SCAN_MODULES = None logging.debug("SCAN_MODULES: %s" % (SCAN_MODULES)) global PROGRESS_BAR if options.progress: PROGRESS_BAR = 1 else: PROGRESS_BAR = strtobool(getConfig('progress_bar')) logging.debug("PROGRESS_BAR: %s" % (PROGRESS_BAR)) global LOG_RESULT if options.log_result: LOG_RESULT = 1 else: LOG_RESULT = strtobool(getConfig('log_result')) logging.debug("LOG_RESULT: %s" % (LOG_RESULT)) global LOG_JSON if options.log_json: LOG_JSON = options.log_json else: LOG_JSON = getConfig('log_json') global NUM_PROCS if options.num_procs: NUM_PROCS = options.num_procs else: NUM_PROCS = int(getConfig('num_procs')) logging.debug("NUM_PROCS: %s" % (NUM_PROCS)) global MAX_BYTES if options.sizeLimit: MAX_BYTES = options.sizeLimit * 1024 * 1024 else: MAX_BYTES = int(getConfig('max_bytes')) logging.debug("MAX_BYTES: %s" % (MAX_BYTES)) global MAX_FILES if options.fileLimit: MAX_FILES = options.fileLimit else: MAX_FILES = int(getConfig('max_files')) logging.debug("MAX_FILES: %s" % (MAX_FILES)) global SOURCE if options.source: SOURCE = options.source else: SOURCE = getConfig('source') global SAVE_PATH if options.save_path: SAVE_PATH = options.save_path else: SAVE_PATH = getConfig('save_path') global CONFIG_PATH # Highest priority configuration is via argument if options.config_path: CONFIG_PATH = options.config_path logging.debug("using alternative config path: %s" % options.config_path) if not os.path.exists(options.config_path): error("the provided config path is not valid, exiting") return 1 # Next, check to see if we're in the top level source directory (dev environment) elif os.path.exists(default_configs['dev_config_path']): CONFIG_PATH = default_configs['dev_config_path'] # Next, check for an installed copy of the default configuration elif os.path.exists(default_configs['sys_config_path']): CONFIG_PATH = default_configs['sys_config_path'] # Exit else: error('A valid framework configuration was not found in either of the following locations:\ \n%s\n%s' % (default_configs['dev_config_path'],default_configs['sys_config_path'])) return 1 # Check for stdin in no arguments were provided if len(args) == 0: DATA_PATH = [] if not sys.stdin.isatty(): while True: f = sys.stdin.readline().strip() if not f: break else: if not os.path.isfile(f): error("One of the specified files does not exist: %s" % (f)) return 1 if os.path.isdir(f): error("One of the files you specified is actually a directory: %s" % (f)) return 1 DATA_PATH.append(f) if not DATA_PATH: error("You must provide files via stdin when no arguments are provided") return 1 logging.debug("Loaded %s files from stdin" % (len(DATA_PATH))) elif len(args) == 1: if os.path.isdir(args[0]): DATA_PATH = args[0] elif os.path.isfile(args[0]): DATA_PATH = [args[0]] else: error("File or directory does not exist: %s" % (args[0])) return 1 else: for f in args: if not os.path.isfile(f): error("One of the specified files does not exist: %s" % (f)) return 1 if os.path.isdir(f): error("One of the files you specified is actually a directory: %s" % (f)) return 1 DATA_PATH = args tasks = multiprocessing.JoinableQueue() results = multiprocessing.Queue() fileList = [] if type(DATA_PATH) is str: for root, dirs, files in os.walk(DATA_PATH): files = [f for f in files if not f[0] == '.'] dirs[:] = [d for d in dirs if not d[0] == '.'] for fname in files: fullpath = os.path.join(root, fname) if not os.path.islink(fullpath) and os.path.isfile(fullpath): fileList.append(fullpath) else: fileList = DATA_PATH if MAX_FILES: fileList = fileList[:MAX_FILES] num_jobs = len(fileList) logging.debug("Loaded %s files for scanning" % (num_jobs)) # Start consumers # If there's less files to process than processes, reduce the number of processes if num_jobs < NUM_PROCS: NUM_PROCS = num_jobs logging.debug("Starting %s processes" % (NUM_PROCS)) consumers = [ Consumer(tasks, results) for i in xrange(NUM_PROCS) ] try: for w in consumers: w.start() # Enqueue jobs for fname in fileList: tasks.put(fname) # Add a poison pill for each consumer for i in xrange(NUM_PROCS): tasks.put(None) if PROGRESS_BAR: monitor = QueueMonitor(tasks, num_jobs) monitor.start() # Wait for all of the tasks to finish tasks.join() if PROGRESS_BAR: monitor.join() while num_jobs: answer = zlib.decompress(results.get()) print(answer) num_jobs -= 1 except KeyboardInterrupt: error("Cancelled by user.. Shutting down.") for w in consumers: w.terminate() w.join() return None except: raise class QueueMonitor(multiprocessing.Process): def __init__(self, task_queue, task_count): multiprocessing.Process.__init__(self) self.task_queue = task_queue self.task_count = task_count def run(self): try: from progressbar import ProgressBar, Bar, Counter, Timer, ETA, Percentage, RotatingMarker widgets = [Percentage(), Bar(left='[', right=']'), ' Processed: ', Counter(), '/', "%s" % self.task_count, ' total files (', Timer(), ') ', ETA()] pb = ProgressBar(widgets=widgets, maxval=self.task_count).start() while self.task_queue.qsize(): pb.update(self.task_count - self.task_queue.qsize()) time.sleep(0.5) pb.finish() except KeyboardInterrupt: warning("progressbar interrupted by user\n") return 1 except ImportError: warning("progressbar module not available") except: warning("unknown error from progress bar") return 0 class Consumer(multiprocessing.Process): def __init__(self, task_queue, result_queue): self.task_queue = task_queue self.result_queue = result_queue multiprocessing.Process.__init__(self) def run(self): global CONFIG_PATH config.init(path=CONFIG_PATH) init_logging() ret_value = 0 # Loop and accept messages from both channels, acting accordingly while True: next_task = self.task_queue.get() if next_task is None: # Poison pill means shutdown self.task_queue.task_done() logging.debug("%s Got poison pill" % (os.getpid())) break try: with open(next_task) as nextfile: file_buffer = nextfile.read() except IOError: logging.debug("Error opening: %s" % (next_task)) self.task_queue.task_done() self.result_queue.put(answer) continue resultJSON = "" try: # perform the work result = ScanResult() result.source = SOURCE result.startTime = time.time() result.level = level_metadata myexternalVars = ExternalVars(filename=next_task, source=SOURCE, ephID=EPHID, extMetaData=EXT_METADATA) Dispatch(file_buffer, result, 0, externalVars=myexternalVars, extScanModules=SCAN_MODULES) resultJSON = getJSON(result) if SAVE_PATH: rootObject = getRootObject(result) UID_SAVE_PATH = "%s/%s" % (SAVE_PATH, get_scanObjectUID(rootObject)) if not os.path.exists(UID_SAVE_PATH): try: os.makedirs(UID_SAVE_PATH) except (OSError, IOError) as e: error("\nERROR: unable to write to %s...\n" % (UID_SAVE_PATH)) raise for uid, scanObject in result.files.iteritems(): with open("%s/%s" % (UID_SAVE_PATH, uid), "wb") as f: f.write(scanObject.buffer) if scanObject.filename and scanObject.depth != 0: linkPath = "%s/%s" % (UID_SAVE_PATH, scanObject.filename.replace("/","_")) if not os.path.lexists(linkPath): os.symlink("%s" % (uid), linkPath) elif scanObject.filename: filenameParts = scanObject.filename.split("/") os.symlink("%s" % (uid), "%s/%s" % (UID_SAVE_PATH, filenameParts[-1])) with open("%s/%s" % (UID_SAVE_PATH, "result.json"), "wb") as f: f.write(resultJSON) if LOG_RESULT: log_result(result) if LOG_JSON: LOCAL_PATH = LOG_JSON with open(LOCAL_PATH, "ab") as f: f.write(resultJSON + "\n") except: logging.exception("Scan worker died, shutting down") ret_value = 1 break finally: self.task_queue.task_done() self.result_queue.put(zlib.compress(resultJSON)) close_modules() return ret_value if __name__ == "__main__": sys.exit(main())
apache-2.0
toshywoshy/ansible
lib/ansible/utils/encrypt.py
60
7561
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import crypt import multiprocessing import random import string import sys from collections import namedtuple from ansible import constants as C from ansible.errors import AnsibleError, AnsibleAssertionError from ansible.module_utils.six import text_type from ansible.module_utils._text import to_text, to_bytes from ansible.utils.display import Display PASSLIB_AVAILABLE = False try: import passlib import passlib.hash from passlib.utils.handlers import HasRawSalt PASSLIB_AVAILABLE = True except Exception: pass display = Display() __all__ = ['do_encrypt'] _LOCK = multiprocessing.Lock() DEFAULT_PASSWORD_LENGTH = 20 def random_password(length=DEFAULT_PASSWORD_LENGTH, chars=C.DEFAULT_PASSWORD_CHARS): '''Return a random password string of length containing only chars :kwarg length: The number of characters in the new password. Defaults to 20. :kwarg chars: The characters to choose from. The default is all ascii letters, ascii digits, and these symbols ``.,:-_`` ''' if not isinstance(chars, text_type): raise AnsibleAssertionError('%s (%s) is not a text_type' % (chars, type(chars))) random_generator = random.SystemRandom() return u''.join(random_generator.choice(chars) for dummy in range(length)) def random_salt(length=8): """Return a text string suitable for use as a salt for the hash functions we use to encrypt passwords. """ # Note passlib salt values must be pure ascii so we can't let the user # configure this salt_chars = string.ascii_letters + string.digits + u'./' return random_password(length=length, chars=salt_chars) class BaseHash(object): algo = namedtuple('algo', ['crypt_id', 'salt_size', 'implicit_rounds']) algorithms = { 'md5_crypt': algo(crypt_id='1', salt_size=8, implicit_rounds=None), 'bcrypt': algo(crypt_id='2a', salt_size=22, implicit_rounds=None), 'sha256_crypt': algo(crypt_id='5', salt_size=16, implicit_rounds=5000), 'sha512_crypt': algo(crypt_id='6', salt_size=16, implicit_rounds=5000), } def __init__(self, algorithm): self.algorithm = algorithm class CryptHash(BaseHash): def __init__(self, algorithm): super(CryptHash, self).__init__(algorithm) if sys.platform.startswith('darwin'): raise AnsibleError("crypt.crypt not supported on Mac OS X/Darwin, install passlib python module") if algorithm not in self.algorithms: raise AnsibleError("crypt.crypt does not support '%s' algorithm" % self.algorithm) self.algo_data = self.algorithms[algorithm] def hash(self, secret, salt=None, salt_size=None, rounds=None): salt = self._salt(salt, salt_size) rounds = self._rounds(rounds) return self._hash(secret, salt, rounds) def _salt(self, salt, salt_size): salt_size = salt_size or self.algo_data.salt_size return salt or random_salt(salt_size) def _rounds(self, rounds): if rounds == self.algo_data.implicit_rounds: # Passlib does not include the rounds if it is the same as implicit_rounds. # Make crypt lib behave the same, by not explicitly specifying the rounds in that case. return None else: return rounds def _hash(self, secret, salt, rounds): if rounds is None: saltstring = "$%s$%s" % (self.algo_data.crypt_id, salt) else: saltstring = "$%s$rounds=%d$%s" % (self.algo_data.crypt_id, rounds, salt) result = crypt.crypt(secret, saltstring) # crypt.crypt returns None if it cannot parse saltstring # None as result would be interpreted by the some modules (user module) # as no password at all. if not result: raise AnsibleError("crypt.crypt does not support '%s' algorithm" % self.algorithm) return result class PasslibHash(BaseHash): def __init__(self, algorithm): super(PasslibHash, self).__init__(algorithm) if not PASSLIB_AVAILABLE: raise AnsibleError("passlib must be installed to hash with '%s'" % algorithm) try: self.crypt_algo = getattr(passlib.hash, algorithm) except Exception: raise AnsibleError("passlib does not support '%s' algorithm" % algorithm) def hash(self, secret, salt=None, salt_size=None, rounds=None): salt = self._clean_salt(salt) rounds = self._clean_rounds(rounds) return self._hash(secret, salt=salt, salt_size=salt_size, rounds=rounds) def _clean_salt(self, salt): if not salt: return None elif issubclass(self.crypt_algo, HasRawSalt): return to_bytes(salt, encoding='ascii', errors='strict') else: return to_text(salt, encoding='ascii', errors='strict') def _clean_rounds(self, rounds): algo_data = self.algorithms.get(self.algorithm) if rounds: return rounds elif algo_data and algo_data.implicit_rounds: # The default rounds used by passlib depend on the passlib version. # For consistency ensure that passlib behaves the same as crypt in case no rounds were specified. # Thus use the crypt defaults. return algo_data.implicit_rounds else: return None def _hash(self, secret, salt, salt_size, rounds): # Not every hash algorithm supports every parameter. # Thus create the settings dict only with set parameters. settings = {} if salt: settings['salt'] = salt if salt_size: settings['salt_size'] = salt_size if rounds: settings['rounds'] = rounds # starting with passlib 1.7 'using' and 'hash' should be used instead of 'encrypt' if hasattr(self.crypt_algo, 'hash'): result = self.crypt_algo.using(**settings).hash(secret) elif hasattr(self.crypt_algo, 'encrypt'): result = self.crypt_algo.encrypt(secret, **settings) else: raise AnsibleError("installed passlib version %s not supported" % passlib.__version__) # passlib.hash should always return something or raise an exception. # Still ensure that there is always a result. # Otherwise an empty password might be assumed by some modules, like the user module. if not result: raise AnsibleError("failed to hash with algorithm '%s'" % self.algorithm) # Hashes from passlib.hash should be represented as ascii strings of hex # digits so this should not traceback. If it's not representable as such # we need to traceback and then blacklist such algorithms because it may # impact calling code. return to_text(result, errors='strict') def passlib_or_crypt(secret, algorithm, salt=None, salt_size=None, rounds=None): if PASSLIB_AVAILABLE: return PasslibHash(algorithm).hash(secret, salt=salt, salt_size=salt_size, rounds=rounds) else: return CryptHash(algorithm).hash(secret, salt=salt, salt_size=salt_size, rounds=rounds) def do_encrypt(result, encrypt, salt_size=None, salt=None): return passlib_or_crypt(result, encrypt, salt_size=salt_size, salt=salt)
gpl-3.0
mujiansu/arangodb
3rdParty/V8-4.3.61/third_party/python_26/Lib/site-packages/pythonwin/pywin/Demos/objdoc.py
17
1543
# This is a sample file, and shows the basic framework for using an "Object" based # document, rather than a "filename" based document. # This is referenced by the Pythonwin .html documentation. # In the example below, the OpenObject() method is used instead of OpenDocumentFile, # and all the core MFC document open functionality is retained. import win32ui from pywin.mfc import docview class object_template (docview.DocTemplate): def __init__(self): docview.DocTemplate.__init__(self, None, None, None, object_view) def OpenObject(self, object): # Use this instead of OpenDocumentFile. # Look for existing open document for doc in self.GetDocumentList(): print "document is ", doc if doc.object is object: doc.GetFirstView().ActivateFrame() return doc # not found - new one. doc = object_document(self, object) frame = self.CreateNewFrame(doc) doc.OnNewDocument() doc.SetTitle(str(object)) self.InitialUpdateFrame(frame, doc) return doc class object_document (docview.Document): def __init__(self, template, object): docview.Document.__init__(self, template) self.object = object def OnOpenDocument (self, name): raise error, "Should not be called if template strings set up correctly" return 0 class object_view (docview.EditView): def OnInitialUpdate (self): self.ReplaceSel("Object is %s" % `self.GetDocument().object`) def demo (): t = object_template() d = t.OpenObject(win32ui) return (t, d) if __name__=='__main__': import demoutils if demoutils.NeedGoodGUI(): demo()
apache-2.0
boostedtc/arm_boosted-arm-linux-androideabi-4.8
share/gdb/python/gdb/frames.py
126
8031
# Frame-filter commands. # Copyright (C) 2013-2014 Free Software Foundation, Inc. # 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/>. """Internal functions for working with frame-filters.""" import gdb from gdb.FrameIterator import FrameIterator from gdb.FrameDecorator import FrameDecorator import itertools import collections def get_priority(filter_item): """ Internal worker function to return the frame-filter's priority from a frame filter object. This is a fail free function as it is used in sorting and filtering. If a badly implemented frame filter does not implement the priority attribute, return zero (otherwise sorting/filtering will fail and prevent other frame filters from executing). Arguments: filter_item: An object conforming to the frame filter interface. Returns: The priority of the frame filter from the "priority" attribute, or zero. """ # Do not fail here, as the sort will fail. If a filter has not # (incorrectly) set a priority, set it to zero. return getattr(filter_item, "priority", 0) def set_priority(filter_item, priority): """ Internal worker function to set the frame-filter's priority. Arguments: filter_item: An object conforming to the frame filter interface. priority: The priority to assign as an integer. """ filter_item.priority = priority def get_enabled(filter_item): """ Internal worker function to return a filter's enabled state from a frame filter object. This is a fail free function as it is used in sorting and filtering. If a badly implemented frame filter does not implement the enabled attribute, return False (otherwise sorting/filtering will fail and prevent other frame filters from executing). Arguments: filter_item: An object conforming to the frame filter interface. Returns: The enabled state of the frame filter from the "enabled" attribute, or False. """ # If the filter class is badly implemented when called from the # Python filter command, do not cease filter operations, just set # enabled to False. return getattr(filter_item, "enabled", False) def set_enabled(filter_item, state): """ Internal Worker function to set the frame-filter's enabled state. Arguments: filter_item: An object conforming to the frame filter interface. state: True or False, depending on desired state. """ filter_item.enabled = state def return_list(name): """ Internal Worker function to return the frame filter dictionary, depending on the name supplied as an argument. If the name is not "all", "global" or "progspace", it is assumed to name an object-file. Arguments: name: The name of the list, as specified by GDB user commands. Returns: A dictionary object for a single specified dictionary, or a list containing all the items for "all" Raises: gdb.GdbError: A dictionary of that name cannot be found. """ # If all dictionaries are wanted in the case of "all" we # cannot return a combined dictionary as keys() may clash in # between different dictionaries. As we just want all the frame # filters to enable/disable them all, just return the combined # items() as a chained iterator of dictionary values. if name == "all": glob = gdb.frame_filters.values() prog = gdb.current_progspace().frame_filters.values() return_iter = itertools.chain(glob, prog) for objfile in gdb.objfiles(): return_iter = itertools.chain(return_iter, objfile.frame_filters.values()) return return_iter if name == "global": return gdb.frame_filters else: if name == "progspace": cp = gdb.current_progspace() return cp.frame_filters else: for objfile in gdb.objfiles(): if name == objfile.filename: return objfile.frame_filters msg = "Cannot find frame-filter dictionary for '" + name + "'" raise gdb.GdbError(msg) def _sort_list(): """ Internal Worker function to merge all known frame-filter lists, prune any filters with the state set to "disabled", and sort the list on the frame-filter's "priority" attribute. Returns: sorted_list: A sorted, pruned list of frame filters to execute. """ all_filters = return_list("all") sorted_frame_filters = sorted(all_filters, key = get_priority, reverse = True) sorted_frame_filters = filter(get_enabled, sorted_frame_filters) return sorted_frame_filters def execute_frame_filters(frame, frame_low, frame_high): """ Internal function called from GDB that will execute the chain of frame filters. Each filter is executed in priority order. After the execution completes, slice the iterator to frame_low - frame_high range. Arguments: frame: The initial frame. frame_low: The low range of the slice. If this is a negative integer then it indicates a backward slice (ie bt -4) which counts backward from the last frame in the backtrace. frame_high: The high range of the slice. If this is -1 then it indicates all frames until the end of the stack from frame_low. Returns: frame_iterator: The sliced iterator after all frame filters have had a change to execute, or None if no frame filters are registered. """ # Get a sorted list of frame filters. sorted_list = list(_sort_list()) # Check to see if there are any frame-filters. If not, just # return None and let default backtrace printing occur. if len(sorted_list) == 0: return None frame_iterator = FrameIterator(frame) # Apply a basic frame decorator to all gdb.Frames. This unifies # the interface. Python 3.x moved the itertools.imap # functionality to map(), so check if it is available. if hasattr(itertools,"imap"): frame_iterator = itertools.imap(FrameDecorator, frame_iterator) else: frame_iterator = map(FrameDecorator, frame_iterator) for ff in sorted_list: frame_iterator = ff.filter(frame_iterator) # Slicing # Is this a slice from the end of the backtrace, ie bt -2? if frame_low < 0: count = 0 slice_length = abs(frame_low) # We cannot use MAXLEN argument for deque as it is 2.6 onwards # and some GDB versions might be < 2.6. sliced = collections.deque() for frame_item in frame_iterator: if count >= slice_length: sliced.popleft(); count = count + 1 sliced.append(frame_item) return iter(sliced) # -1 for frame_high means until the end of the backtrace. Set to # None if that is the case, to indicate to itertools.islice to # slice to the end of the iterator. if frame_high == -1: frame_high = None else: # As frames start from 0, add one to frame_high so islice # correctly finds the end frame_high = frame_high + 1; sliced = itertools.islice(frame_iterator, frame_low, frame_high) return sliced
gpl-2.0
antoniov/tools
zerobug/setup.py
2
1743
from setuptools import setup setup(name='zerobug', version='1.0.1.1', description='Zeroincombenze continuous testing framework' ' and tools for python and bash programs', long_description=""" This library can run unit test of target package software. Supported languages are *python* (through z0testlib.py) and *bash* (through z0testrc) *zerobug* supports test automation, aggregation of tests into collections and independence of the tests from the reporting framework. The *zerobug* module provides all code that make it easy to support testing both for python programs both for bash scripts. *zerobug* differs from pytest standard library because show execution test with a message like "n/tot message" where *n* is current unit test and *tot* is the total unit test to execute, that is a sort of advancing test progress. *zerobug* is built on follow concepts: * test main - it is a main program to executes all test runners * test runner - it is a program to executes one or more test suites * test suite - it is a collection of test cases * test case -it is a smallest unit test """, classifiers=[ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Programming Language :: Python :: 2.7', 'Intended Audience :: Developers', # 'Topic :: Software Development:: Quality Assurance' ], keywords='unit test', url='http://wiki.zeroincombenze.org/en/Zerobug', author='Antonio Maria Vigliotti', author_email='antoniomaria.vigliotti@gmail.com', license='Affero GPL', packages=['zerobug'], package_data={'zerobug': ['./z0testrc']}, zip_safe=False)
agpl-3.0
bhargav2408/python-for-android
python3-alpha/python3-src/Lib/multiprocessing/connection.py
46
14017
# # A higher level module for using sockets (or Windows named pipes) # # multiprocessing/connection.py # # Copyright (c) 2006-2008, R Oudkerk # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of author nor the names of any contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. # __all__ = [ 'Client', 'Listener', 'Pipe' ] import os import sys import socket import errno import time import tempfile import itertools import _multiprocessing from multiprocessing import current_process, AuthenticationError from multiprocessing.util import get_temp_dir, Finalize, sub_debug, debug from multiprocessing.forking import duplicate, close # # # BUFSIZE = 8192 # A very generous timeout when it comes to local connections... CONNECTION_TIMEOUT = 20. _mmap_counter = itertools.count() default_family = 'AF_INET' families = ['AF_INET'] if hasattr(socket, 'AF_UNIX'): default_family = 'AF_UNIX' families += ['AF_UNIX'] if sys.platform == 'win32': default_family = 'AF_PIPE' families += ['AF_PIPE'] def _init_timeout(timeout=CONNECTION_TIMEOUT): return time.time() + timeout def _check_timeout(t): return time.time() > t # # # def arbitrary_address(family): ''' Return an arbitrary free address for the given family ''' if family == 'AF_INET': return ('localhost', 0) elif family == 'AF_UNIX': return tempfile.mktemp(prefix='listener-', dir=get_temp_dir()) elif family == 'AF_PIPE': return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' % (os.getpid(), next(_mmap_counter))) else: raise ValueError('unrecognized family') def address_type(address): ''' Return the types of the address This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE' ''' if type(address) == tuple: return 'AF_INET' elif type(address) is str and address.startswith('\\\\'): return 'AF_PIPE' elif type(address) is str: return 'AF_UNIX' else: raise ValueError('address type of %r unrecognized' % address) # # Public functions # class Listener(object): ''' Returns a listener object. This is a wrapper for a bound socket which is 'listening' for connections, or for a Windows named pipe. ''' def __init__(self, address=None, family=None, backlog=1, authkey=None): family = family or (address and address_type(address)) \ or default_family address = address or arbitrary_address(family) if family == 'AF_PIPE': self._listener = PipeListener(address, backlog) else: self._listener = SocketListener(address, family, backlog) if authkey is not None and not isinstance(authkey, bytes): raise TypeError('authkey should be a byte string') self._authkey = authkey def accept(self): ''' Accept a connection on the bound socket or named pipe of `self`. Returns a `Connection` object. ''' c = self._listener.accept() if self._authkey: deliver_challenge(c, self._authkey) answer_challenge(c, self._authkey) return c def close(self): ''' Close the bound socket or named pipe of `self`. ''' return self._listener.close() address = property(lambda self: self._listener._address) last_accepted = property(lambda self: self._listener._last_accepted) def Client(address, family=None, authkey=None): ''' Returns a connection to the address of a `Listener` ''' family = family or address_type(address) if family == 'AF_PIPE': c = PipeClient(address) else: c = SocketClient(address) if authkey is not None and not isinstance(authkey, bytes): raise TypeError('authkey should be a byte string') if authkey is not None: answer_challenge(c, authkey) deliver_challenge(c, authkey) return c if sys.platform != 'win32': def Pipe(duplex=True): ''' Returns pair of connection objects at either end of a pipe ''' if duplex: s1, s2 = socket.socketpair() c1 = _multiprocessing.Connection(os.dup(s1.fileno())) c2 = _multiprocessing.Connection(os.dup(s2.fileno())) s1.close() s2.close() else: fd1, fd2 = os.pipe() c1 = _multiprocessing.Connection(fd1, writable=False) c2 = _multiprocessing.Connection(fd2, readable=False) return c1, c2 else: from _multiprocessing import win32 def Pipe(duplex=True): ''' Returns pair of connection objects at either end of a pipe ''' address = arbitrary_address('AF_PIPE') if duplex: openmode = win32.PIPE_ACCESS_DUPLEX access = win32.GENERIC_READ | win32.GENERIC_WRITE obsize, ibsize = BUFSIZE, BUFSIZE else: openmode = win32.PIPE_ACCESS_INBOUND access = win32.GENERIC_WRITE obsize, ibsize = 0, BUFSIZE h1 = win32.CreateNamedPipe( address, openmode, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, 1, obsize, ibsize, win32.NMPWAIT_WAIT_FOREVER, win32.NULL ) h2 = win32.CreateFile( address, access, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL ) win32.SetNamedPipeHandleState( h2, win32.PIPE_READMODE_MESSAGE, None, None ) try: win32.ConnectNamedPipe(h1, win32.NULL) except WindowsError as e: if e.args[0] != win32.ERROR_PIPE_CONNECTED: raise c1 = _multiprocessing.PipeConnection(h1, writable=duplex) c2 = _multiprocessing.PipeConnection(h2, readable=duplex) return c1, c2 # # Definitions for connections based on sockets # class SocketListener(object): ''' Representation of a socket which is bound to an address and listening ''' def __init__(self, address, family, backlog=1): self._socket = socket.socket(getattr(socket, family)) self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._socket.bind(address) self._socket.listen(backlog) self._address = self._socket.getsockname() self._family = family self._last_accepted = None if family == 'AF_UNIX': self._unlink = Finalize( self, os.unlink, args=(address,), exitpriority=0 ) else: self._unlink = None def accept(self): s, self._last_accepted = self._socket.accept() fd = duplicate(s.fileno()) conn = _multiprocessing.Connection(fd) s.close() return conn def close(self): self._socket.close() if self._unlink is not None: self._unlink() def SocketClient(address): ''' Return a connection object connected to the socket given by `address` ''' family = address_type(address) with socket.socket( getattr(socket, family) ) as s: t = _init_timeout() while 1: try: s.connect(address) except socket.error as e: if e.args[0] != errno.ECONNREFUSED or _check_timeout(t): debug('failed to connect to address %s', address) raise time.sleep(0.01) else: break else: raise fd = duplicate(s.fileno()) conn = _multiprocessing.Connection(fd) return conn # # Definitions for connections based on named pipes # if sys.platform == 'win32': class PipeListener(object): ''' Representation of a named pipe ''' def __init__(self, address, backlog=None): self._address = address handle = win32.CreateNamedPipe( address, win32.PIPE_ACCESS_DUPLEX, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, win32.NMPWAIT_WAIT_FOREVER, win32.NULL ) self._handle_queue = [handle] self._last_accepted = None sub_debug('listener created with address=%r', self._address) self.close = Finalize( self, PipeListener._finalize_pipe_listener, args=(self._handle_queue, self._address), exitpriority=0 ) def accept(self): newhandle = win32.CreateNamedPipe( self._address, win32.PIPE_ACCESS_DUPLEX, win32.PIPE_TYPE_MESSAGE | win32.PIPE_READMODE_MESSAGE | win32.PIPE_WAIT, win32.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, win32.NMPWAIT_WAIT_FOREVER, win32.NULL ) self._handle_queue.append(newhandle) handle = self._handle_queue.pop(0) try: win32.ConnectNamedPipe(handle, win32.NULL) except WindowsError as e: if e.args[0] != win32.ERROR_PIPE_CONNECTED: raise return _multiprocessing.PipeConnection(handle) @staticmethod def _finalize_pipe_listener(queue, address): sub_debug('closing listener with address=%r', address) for handle in queue: close(handle) def PipeClient(address): ''' Return a connection object connected to the pipe given by `address` ''' t = _init_timeout() while 1: try: win32.WaitNamedPipe(address, 1000) h = win32.CreateFile( address, win32.GENERIC_READ | win32.GENERIC_WRITE, 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL ) except WindowsError as e: if e.args[0] not in (win32.ERROR_SEM_TIMEOUT, win32.ERROR_PIPE_BUSY) or _check_timeout(t): raise else: break else: raise win32.SetNamedPipeHandleState( h, win32.PIPE_READMODE_MESSAGE, None, None ) return _multiprocessing.PipeConnection(h) # # Authentication stuff # MESSAGE_LENGTH = 20 CHALLENGE = b'#CHALLENGE#' WELCOME = b'#WELCOME#' FAILURE = b'#FAILURE#' def deliver_challenge(connection, authkey): import hmac assert isinstance(authkey, bytes) message = os.urandom(MESSAGE_LENGTH) connection.send_bytes(CHALLENGE + message) digest = hmac.new(authkey, message).digest() response = connection.recv_bytes(256) # reject large message if response == digest: connection.send_bytes(WELCOME) else: connection.send_bytes(FAILURE) raise AuthenticationError('digest received was wrong') def answer_challenge(connection, authkey): import hmac assert isinstance(authkey, bytes) message = connection.recv_bytes(256) # reject large message assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message message = message[len(CHALLENGE):] digest = hmac.new(authkey, message).digest() connection.send_bytes(digest) response = connection.recv_bytes(256) # reject large message if response != WELCOME: raise AuthenticationError('digest sent was rejected') # # Support for using xmlrpclib for serialization # class ConnectionWrapper(object): def __init__(self, conn, dumps, loads): self._conn = conn self._dumps = dumps self._loads = loads for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'): obj = getattr(conn, attr) setattr(self, attr, obj) def send(self, obj): s = self._dumps(obj) self._conn.send_bytes(s) def recv(self): s = self._conn.recv_bytes() return self._loads(s) def _xml_dumps(obj): return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf8') def _xml_loads(s): (obj,), method = xmlrpclib.loads(s.decode('utf8')) return obj class XmlListener(Listener): def accept(self): global xmlrpclib import xmlrpc.client as xmlrpclib obj = Listener.accept(self) return ConnectionWrapper(obj, _xml_dumps, _xml_loads) def XmlClient(*args, **kwds): global xmlrpclib import xmlrpc.client as xmlrpclib return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)
apache-2.0
pedrogazquez/appBares
rango/forms.py
1
3240
from django import forms from django.contrib.auth.models import User from rango.models import Tapa, Bar, UserProfile class BarForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text="Por favor introduzca el nombre del bar") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0) # An inline class to provide additional information on the form. class Meta: # Provide an association between the ModelForm and a model model = Bar # class TapaForm(forms.ModelForm): # nombre = forms.CharField(max_length=128, help_text="Por favor introduzca el nombre de la tapa") # url = forms.URLField(max_length=200, help_text="Por favor introduzca la direccion de la imagen de la tapa") # views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) # def clean(self): # cleaned_data = self.cleaned_data # url = cleaned_data.get('url') # # If url is not empty and doesn't start with 'http://' add 'http://' to the beginning # if url and not url.startswith('http://'): # url = 'http://' + url # cleaned_data['url'] = url # return cleaned_data # class Meta: # # Provide an association between the ModelForm and a model # model = Tapa # # What fields do we want to include in our form? # # This way we don't need every field in the model present. # # Some fields may allow NULL values, so we may not want to include them... # # Here, we are hiding the foreign keys # fields = ('nombre', 'url','views') class TapaForm(forms.ModelForm): nombre = forms.CharField(max_length=128, help_text="Por favor introduzca el nombre de la tapa") url = forms.URLField(max_length=200, help_text="Por favor introduzca la direccion de la imagen de la tapa") views = forms.IntegerField(widget=forms.HiddenInput(), initial=0) class Meta: # Provide an association between the ModelForm and a model model = Tapa # What fields do we want to include in our form? # This way we don't need every field in the model present. # Some fields may allow NULL values, so we may not want to include them... # Here, we are hiding the foreign key. # we can either exclude the category field from the form, exclude = ('bar',) #or specify the fields to include (i.e. not include the category field) fields = ('nombre', 'url','views') class UserForm(forms.ModelForm): username = forms.CharField(help_text="Please enter a username.") email = forms.CharField(help_text="Please enter your email.") password = forms.CharField(widget=forms.PasswordInput(), help_text="Please enter a password.") class Meta: model = User fields = ('username', 'email', 'password') class UserProfileForm(forms.ModelForm): website = forms.URLField(help_text="Please enter your website.", required=False) picture = forms.ImageField(help_text="Select a profile image to upload.", required=False) class Meta: model = UserProfile fields = ('website', 'picture')
gpl-3.0
EntPack/SilentDune-Client
silentdune_client/modules/automation/auto_discovery/updates.py
1
25425
# # Authors: Ma He <mahe.itsec@gmail.com> # Robert Abram <robert.abram@entpack.com> # Copyright (C) 2015-2017 EntPack # see file 'LICENSE' for use and warranty information # # 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 datetime import datetime import fnmatch import glob import logging import os import platform import shlex import socket import subprocess import time try: from urllib import parse except ImportError: # < 3.0 import urlparse as parse import ConfigParser from silentdune_client.modules import QueueTask from silentdune_client.modules.firewall.manager import SilentDuneClientFirewallModule, \ TASK_FIREWALL_INSERT_RULES from silentdune_client.builders import iptables as ipt from silentdune_client.modules.automation.auto_discovery.base_discovery_service import BaseDiscoveryService from silentdune_client.modules.firewall.manager.iptables_utils import create_iptables_egress_ingress_rule, \ create_iptables_egress_rule_dest, create_iptables_ingress_rule_source from silentdune_client.modules.firewall.manager.slots import Slots from silentdune_client.utils.misc import which _logger = logging.getLogger('sd-client') class SystemUpdatesDiscovery(BaseDiscoveryService): """ Auto discover SystemUpdates like apt-get and yum. """ _rebuild_rules_interval = 5 # Rebuild the updates cache rules every 5 days. _slot = Slots.updates _config_section_name = 'auto_discovery' _config_property_name = '_disable_auto_updates' _dist = '' _dist_version = '' _machine = '' _disable_auto_updates_ftp = None _disable_auto_updates_rsync = None _rebuild_rules = True # Rebuild the rules _rebuild_cache = False # Should we rebuild the package manager cache? _cache_last_rebuilt = None # Time stamp last time cache was rebuilt. _hostnames = list() # Previously added hostnames _repo_manager = None _repo_cache_base = '' _repo_config_base = '' _repo_service_base = '' # openSUSE/SLES systems _saved_rules = None def __init__(self, config): super(SystemUpdatesDiscovery, self).__init__(config) self._disable_auto_updates_ftp = True if self.config.get( self._config_section_name, 'disable_auto_updates_ftp').lower() == 'yes' else False def _discover_iptables(self): """ Virtual Override :return: Firewall Rules """ rules = list() # Find the system package manager executable and setup our environment info if not self._repo_manager and not self.discover_pkg_manager(): _logger.error('{0}: unable to continue setting up rules for updates.'.format(self.get_name())) return None # Test to see if DNS lookup is available right now. If not, just return and wait until DNS is working. if not self.resolve_hostname('example.org', 80): return None # Every 5 days rebuild the rules. if self._cache_last_rebuilt: days = int((datetime.now() - self._cache_last_rebuilt).days) if days >= self._rebuild_rules_interval: self._rebuild_rules = True rules.append(self.iptables_updates()) return rules def discover_pkg_manager(self): """ Find the system package manager executable :return: True if found, otherwise False """ self._dist = platform.dist()[0].lower() self._dist_version = platform.dist()[1] self._dist_version = self._dist_version.split('.')[0] self._machine = platform.machine() if self._dist in 'ubuntu debian': self._repo_manager = which('apt-get') # Nothing else to do. elif self._dist in 'centos redhat fedora': self._repo_config_base = '/etc/yum.repos.d/*.repo' self._repo_manager = which('dnf') self._repo_cache_base = '/var/cache/dnf' if not self._repo_manager: self._repo_manager = which('yum') self._repo_cache_base = '/var/cache/yum/{0}/{1}'.format(self._machine, self._dist_version) elif self._dist in 'suse': self._repo_manager = which('zypper') self._repo_config_base = '/etc/zypp/repos.d/*.repo' self._repo_service_base = '/etc/zypp/services.d/*.service' # No metalink cache until suse implements metalinks in zypper else: _logger.error('{0}: unsupported distribution ({1})'.format(self.get_name(), self._dist)) return False if not self._repo_manager: _logger.error('{0}: unable to find package manager executable for {1}'.format(self.get_name(), self._dist)) return False return True def iptables_updates(self): rules = list() if self._dist in 'ubuntu debian': rules.append(self.iptables_updates_apt()) elif self._dist in 'centos redhat fedora': rules.append(self.add_repository_rules()) elif self._dist in 'suse': rules.append(self.add_repository_rules()) return rules def iptables_updates_apt(self): rules = list() if not os.path.exists('/etc/apt/sources.list'): _logger.error('{0}: /etc/apt/sources.list not found.'.format(self.get_name())) return None # Get all nameserver ip address values with open('/etc/apt/sources.list') as handle: for line in handle: if line.startswith('deb '): url = line.split()[1] if url: rules.append(self.add_rule_by_url(url)) return rules def add_repository_rules(self): """ Add repository rules for rpm based systems. """ # If it is not time to rebuild the package manager cache, just return the rules we have. if not self._rebuild_rules: return self._saved_rules self._rebuild_cache = False # reset hostnames list self._hostnames = list() rules = list() base_urls = list() mirror_urls = list() _logger.debug('{0}: adding rules for {1} repositories'.format(self.get_name(), self._dist)) # Loop through all the repo files and gather url information repofiles = glob.glob(self._repo_config_base) # Add in any zypper service files. if self._dist in 'suse': repofiles += glob.glob(self._repo_service_base) for repofile in repofiles: config = ConfigParser.ConfigParser() if config.read(repofile): sections = config.sections() # Loop through sections looking for enabled repositories. for section in sections: if config.has_option(section, 'enabled'): enabled = config.getint(section, 'enabled') else: enabled = 1 if not enabled: continue _logger.debug('{0}: adding urls for section: {1}'.format(self.get_name(), section)) url = None if config.has_option(section, 'metalink'): url = config.get(section, 'metalink') self._rebuild_cache = True if url: mirror_urls.append([section, url]) elif config.has_option(section, 'mirrorlist'): url = config.get(section, 'mirrorlist') self._rebuild_cache = True if url: mirror_urls.append([section, url]) elif config.has_option(section, 'baseurl'): url = config.get(section, 'baseurl') if url: base_urls.append([section, url]) # Handle zypper service files. elif config.has_option(section, 'url'): url = config.get(section, 'url') if url: base_urls.append([section, url]) if not url: _logger.debug('{0}: could not find repo section ({1}) url?'.format(self.get_name(), section)) # Loop through all the urls and add rules for them. for section, url in base_urls: # TODO: Add support for mirrorbrain style mirrorlists. rules.append(self.add_rule_by_url(url)) # If we don't need to rebuild the package manager cache, just return the rules we have. if not self._rebuild_cache: return rules for section, url in mirror_urls: rules.append(self.add_rule_by_url(url)) # Rebuild the package manager cache # Open up all port 80 and port 443 connections so cache rebuild succeeds. all_access = list() all_access.append(create_iptables_egress_ingress_rule( '', 80, 'tcp', self._slot, transport=ipt.TRANSPORT_IPV4)) all_access.append(create_iptables_egress_ingress_rule( '', 80, 'tcp', self._slot, transport=ipt.TRANSPORT_IPV6)) all_access.append(create_iptables_egress_ingress_rule( '', 443, 'tcp', self._slot, transport=ipt.TRANSPORT_IPV4)) all_access.append(create_iptables_egress_ingress_rule( '', 443, 'tcp', self._slot, transport=ipt.TRANSPORT_IPV6)) # our parent will take care of clearing these rules once we return the real rules. self.add_url_rule_to_firewall(all_access) time.sleep(2) # Give the firewall manager time to add the rules. if not self.rebuild_package_manager_cache(): return rules # Check to see if we know where the package manage cache data is. if not self._repo_cache_base: return rules # loop through the mirror list and parse the mirrorlist or metalink file. for section, url in mirror_urls: file, file_type = self.get_cache_file(section) if file: if file_type == 'mirrorlist': urls = self.get_mirrorlist_urls_from_file(file, section) else: urls = self.get_metalink_urls_from_file(file, section) if urls: for url in urls: if url: rules.append(self.add_rule_by_url(url)) self._cache_last_rebuilt = datetime.now() self._saved_rules = rules return rules def get_cache_file(self, section): """ Auto detect the mirror list path, file and type. :param section: config section name :return: file and file type """ if 'yum' in self._repo_manager: cachepath = '{0}/{1}'.format(self._repo_cache_base, section) elif 'dnf' in self._repo_manager: # Get all the files and directories in the cache base dir files = os.listdir(self._repo_cache_base) # Filter out only the directories we are looking for files = fnmatch.filter(files, '{0}-????????????????'.format(section)) # Now figure out which path is the newest one. cachepath = '{0}/{1}/'.format(self._repo_cache_base, max(files, key=os.path.getmtime)) else: return None, '' if not os.path.isdir(cachepath): _logger.error('{0}: calculated cache path is invalid ({1})'.format(self.get_name(), cachepath)) return None, '' # detect url cache file and type if os.path.isfile('{0}/mirrorlist.txt'.format(cachepath)): return '{0}/mirrorlist.txt'.format(cachepath), 'mirrorlist' if os.path.isfile('{0}/mirrorlist'.format(cachepath)): return '{0}/mirrorlist'.format(cachepath), 'mirrorlist' if os.path.isfile('{0}/metalink.xml'.format(cachepath)): return '{0}/metalink.xml'.format(cachepath), 'metalink' _logger.error('{0}: cache file is not found ({1})'.format(self.get_name(), cachepath)) return None, '' def rebuild_package_manager_cache(self): """ Have the package manager clean and rebuild it's cache information :return: True if successful, otherwise False """ if self._dist in 'suse': cmd_clean = '{0} clean'.format(self._repo_manager) cmd_make = '{0} refresh'.format(self._repo_manager) elif self._dist in 'centos redhat fedora': cmd_clean = '{0} clean metadata'.format(self._repo_manager) cmd_make = '{0} makecache fast'.format(self._repo_manager) else: _logger.error('{0}: unsupported package manager, unable to rebuild cache.') return False _logger.debug('{0}: rebuilding {1} package manager cache data'.format(self.get_name(), self._dist)) # Clean package manager cache p = subprocess.Popen(shlex.split(cmd_clean), stdout=subprocess.PIPE) stdoutdata, stderrdata = p.communicate() p.wait() if stderrdata: _logger.error('{0}: cleaning package manager cache failed.'.format(self.get_name())) return False # Rebuild the package manager cache p = subprocess.Popen(shlex.split(cmd_make), stdout=subprocess.PIPE) stdoutdata, stderrdata = p.communicate() p.wait() if stderrdata: _logger.error('{0}: rebuilding package manager cache failed.'.format(self.get_name())) return False return True def add_url_rule_to_firewall(self, rules): """ Add rules allowing access immediately to the firewall. :param rules: rules list """ if not rules: return # Notify the firewall module to reload the rules. task = QueueTask(TASK_FIREWALL_INSERT_RULES, src_module=self._parent.get_name(), dest_module=SilentDuneClientFirewallModule().get_name(), data=rules) self._parent.send_parent_task(task) time.sleep(2) # Give the firewall manager time to add the rule to the kernel def resolve_hostname(self, hostname, port): """ Return a single or multiple IP addresses from the hostname parameter :param hostname: hostname string, IE: www.example.org :param port: :return: list of IP addresses """ ipaddrs = list() if hostname: if port: if 1 < port <= 65536: try: ais = socket.getaddrinfo(hostname, port, 0, 0, socket.IPPROTO_TCP) except: _logger.debug('{0}: error resolving host: {1}:{2}'.format(self.get_name(), hostname, port)) return None for result in ais: ipaddr = result[-1][0] ipaddrs.append(ipaddr) return ipaddrs def add_rule_by_url(self, url): """ :param url: Complete url string :return: urlparse URI """ rules = list() if not url: _logger.debug('{0}: empty url given, unable to add rule'.format(self.get_name())) return None try: uri = parse.urlparse(url) except: _logger.error('{0}: error parsing url ({1})'.format(self.get_name(), url)) return None if not uri.scheme or not uri.hostname or uri.scheme not in ['http', 'https', 'ftp', 'rsync']: return None # If this is an FTP url... if uri.scheme == 'ftp': return self.add_ftp_rule_by_url(uri) port = uri.port if not port: if uri.scheme == 'http': port = 80 elif uri.scheme == 'https': port = 443 elif uri.scheme == 'rsync': port = 873 key = uri.hostname + ':' + str(port) # Avoid duplicate urls. if key not in self._hostnames: self._hostnames.append(key) ipaddrs = self.resolve_hostname(uri.hostname, port) if ipaddrs: for ipaddr in ipaddrs: # _logger.debug('{0}: adding ip: {1} from hostname: {2}'.format( # self.get_name(), uri.scheme + '://' + ipaddr, uri.hostname)) rules.append(create_iptables_egress_ingress_rule( ipaddr, port, 'tcp', self._slot, transport=ipt.TRANSPORT_AUTO)) _logger.debug('{0}: host: {1} ip: {2}:{3}'.format(self.get_name(), uri.hostname, ipaddr, port)) return rules return None def add_ftp_rule_by_url(self, uri): """ Add rules to allow FTP access based on uri value :param uri: urlparse uri value :return: rules """ # Check to make sure we can add ftp rules. if self._disable_auto_updates_ftp: return None rules = list() ipaddrs = self.resolve_hostname(uri.hostname, 21) if ipaddrs: for ipaddr in ipaddrs: _logger.debug('{0}: adding ip: {1} from hostname: {2}'.format( self.get_name(), uri.scheme + '://' + ipaddr, uri.hostname)) # FTP control rules.append(create_iptables_egress_ingress_rule(ipaddr, 21, 'tcp', self._slot, transport=ipt.TRANSPORT_AUTO)) # FTP data transfer rules.append(create_iptables_egress_rule_dest(ipaddr, 20, 'tcp', self._slot, 'ESTABLISHED', transport=ipt.TRANSPORT_AUTO)) rules.append( create_iptables_ingress_rule_source(ipaddr, 20, 'tcp', self._slot, 'ESTABLISHED,RELATED', transport=ipt.TRANSPORT_AUTO)) rules.append( create_iptables_egress_rule_dest(ipaddr, None, 'tcp', self._slot, 'ESTABLISHED,RELATED', transport=ipt.TRANSPORT_AUTO)) rules.append( create_iptables_ingress_rule_source(ipaddr, None, 'tcp', self._slot, 'ESTABLISHED', transport=ipt.TRANSPORT_AUTO)) return rules def get_mirrorlist_urls_from_file(self, file, section): urls = list() if not file or not os.path.isfile(file): _logger.debug('{0}: unable to locate mirrorlist file ({1})'.format(self.get_name(), file)) return urls with open(file) as handle: lines = handle.read().split('\n') if lines: for line in lines: if line.strip(): urls.append(line.strip()) _logger.debug('{0}: retrieving mirrorlist urls for "{1}" succeeded'.format(self.get_name(), section)) return urls def get_metalink_urls_from_file(self, file, section): urls = list() if not file or not os.path.isfile(file): _logger.debug('{0}: unable to locate metalink file ({1})'.format(self.get_name(), file)) return urls with open(file) as handle: lines = handle.read().split('\n') if lines: for line in lines: if line.find('<url protocol=') != -1: url = line.split(' >')[1].split('</url>')[0].strip() if url: urls.append(url) if line.find('xmlns="') != -1: url = line.split('xmlns="')[1].split('"')[0].strip() if url: urls.append(url) if line.find('xmlns:mm0="') != -1: url = line.split('xmlns:mm0="')[1].split('"')[0].strip() if url: urls.append(url) else: _logger.debug('{0}: no data read from metalink file ({1})'.format(self.get_name(), file)) return None _logger.debug('{0}: retrieving metalink urls for "{1}" succeeded'.format(self.get_name(), section)) return urls # def grab_mirror_list_urls(self, mirrorlist, section): # """ # Attempt to download repository mirrorlist data using curl and return the urls. # :param mirrorlist: # :return: url list # """ # urls = list() # # if mirrorlist: # # mirrorlist = mirrorlist.replace('$releasever', self._dist_version) # mirrorlist = mirrorlist.replace('$basearch', self._machine) # mirrorlist = mirrorlist.replace('$infra', 'stock') # # c = pycurl.Curl() # transport = c.IPRESOLVE_V4 # # # Force curl IPv4 DNS lookup, if that fails try IPv6 DNS lookup. # while True: # try: # storage = StringIO() # c = pycurl.Curl() # c.setopt(c.URL, mirrorlist.encode('utf-8')) # c.setopt(c.IPRESOLVE, transport) # c.setopt(c.WRITEFUNCTION, storage.write) # c.perform() # c.close() # content = storage.getvalue() # urllist = content.split('\n') # for url in urllist: # if url.strip(): # urls.append(url.strip()) # break # except pycurl.error as e: # # if transport == c.IPRESOLVE_V4: # transport = c.IPRESOLVE_V6 # continue # # _logger.debug('{0}: {1}: retrieving mirror list failed ({2})'.format(self.get_name(), section, e)) # return None # # _logger.debug('{0}: retrieving mirror list for section "{1}" succeeded'.format(self.get_name(), section)) # return urls # def grab_metalink_urls(self, metalink, section): # """ # Attempt to download repository metalink data using curl and return the urls. # :param metalink: metalink url # :return: url list # """ # # urls = list() # content = None # # if metalink: # metalink = metalink.replace('$releasever', self._dist_version) # metalink = metalink.replace('$basearch', self._machine) # # c = pycurl.Curl() # transport = c.IPRESOLVE_V4 # # # Force curl IPv4 DNS lookup, if that fails try IPv6 DNS lookup. # while True: # try: # storage = StringIO() # c = pycurl.Curl() # c.setopt(c.URL, metalink.encode('utf-8')) # c.setopt(c.IPRESOLVE, transport) # c.setopt(c.WRITEFUNCTION, storage.write) # c.perform() # c.close() # content = storage.getvalue() # break # except pycurl.error as e: # # if transport == c.IPRESOLVE_V4: # transport = c.IPRESOLVE_V6 # continue # # _logger.debug('{0}: retrieving metalink list failed ({1})'.format(self.get_name(), e)) # return None # # if content: # lines = content.split('\n') # for line in lines: # if line.find('<url protocol=') != -1: # url = line.split(' >')[1].split('</url>')[0] # if url: # urls.append(url.strip()) # if line.find('xmlns="') != -1: # url = line.split('xmlns="')[1].split('"')[0] # if url: # urls.append(url.strip()) # if line.find('xmlns:mm0="') != -1: # url = line.split('xmlns:mm0="')[1].split('"')[0] # if url: # urls.append(url.strip()) # # _logger.debug('{0}: retrieving metalink list for section "{1}" succeeded'.format(self.get_name(), section)) # return urls
lgpl-3.0
ar7z1/ansible
lib/ansible/modules/network/ios/ios_static_route.py
58
8881
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = """ --- module: ios_static_route version_added: "2.4" author: "Ricardo Carrillo Cruz (@rcarrillocruz)" short_description: Manage static IP routes on Cisco IOS network devices description: - This module provides declarative management of static IP routes on Cisco IOS network devices. notes: - Tested against IOS 15.6 requirements: - Python >= 3.3 or C(ipaddress) python package options: prefix: description: - Network prefix of the static route. mask: description: - Network prefix mask of the static route. next_hop: description: - Next hop IP of the static route. admin_distance: description: - Admin distance of the static route. aggregate: description: List of static route definitions. state: description: - State of the static route configuration. default: present choices: ['present', 'absent'] extends_documentation_fragment: ios """ EXAMPLES = """ - name: configure static route ios_static_route: prefix: 192.168.2.0 mask: 255.255.255.0 next_hop: 10.0.0.1 - name: remove configuration ios_static_route: prefix: 192.168.2.0 mask: 255.255.255.0 next_hop: 10.0.0.1 state: absent - name: Add static route aggregates ios_static_route: aggregate: - { prefix: 172.16.32.0, mask: 255.255.255.0, next_hop: 10.0.0.8 } - { prefix: 172.16.33.0, mask: 255.255.255.0, next_hop: 10.0.0.8 } - name: Add static route aggregates ios_static_route: aggregate: - { prefix: 172.16.32.0, mask: 255.255.255.0, next_hop: 10.0.0.8 } - { prefix: 172.16.33.0, mask: 255.255.255.0, next_hop: 10.0.0.8 } state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always type: list sample: - ip route 192.168.2.0 255.255.255.0 10.0.0.1 """ from copy import deepcopy import re from ansible.module_utils._text import to_text from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import ConnectionError from ansible.module_utils.network.common.utils import remove_default_spec from ansible.module_utils.network.ios.ios import get_config, load_config, run_commands from ansible.module_utils.network.ios.ios import ios_argument_spec, check_args try: from ipaddress import ip_network HAS_IPADDRESS = True except ImportError: HAS_IPADDRESS = False def map_obj_to_commands(want, have, module): commands = list() for w in want: # Try to match an existing config with the desired config for h in have: for key in ['prefix', 'mask', 'next_hop']: # If any key doesn't match, skip to the next set if w[key] != h[key]: break # If all keys match, don't execute final else else: break # If no matches found, clear `h` else: h = None prefix = w['prefix'] mask = w['mask'] next_hop = w['next_hop'] admin_distance = w.get('admin_distance') if not admin_distance and h: w['admin_distance'] = admin_distance = h['admin_distance'] state = w['state'] del w['state'] if state == 'absent' and w in have: commands.append('no ip route %s %s %s' % (prefix, mask, next_hop)) elif state == 'present' and w not in have: if admin_distance: commands.append('ip route %s %s %s %s' % (prefix, mask, next_hop, admin_distance)) else: commands.append('ip route %s %s %s' % (prefix, mask, next_hop)) return commands def map_config_to_obj(module): obj = [] try: out = run_commands(module, 'show ip static route')[0] match = re.search(r'.*Static local RIB for default\s*(.*)$', out, re.DOTALL) if match and match.group(1): for r in match.group(1).splitlines(): splitted_line = r.split() code = splitted_line[0] if code != 'M': continue cidr = ip_network(to_text(splitted_line[1])) prefix = str(cidr.network_address) mask = str(cidr.netmask) next_hop = splitted_line[4] admin_distance = splitted_line[2][1] obj.append({ 'prefix': prefix, 'mask': mask, 'next_hop': next_hop, 'admin_distance': admin_distance }) except ConnectionError: out = get_config(module, flags='| include ip route') for line in out.splitlines(): splitted_line = line.split() if len(splitted_line) not in (5, 6): continue prefix = splitted_line[2] mask = splitted_line[3] next_hop = splitted_line[4] if len(splitted_line) == 6: admin_distance = splitted_line[5] else: admin_distance = '1' obj.append({ 'prefix': prefix, 'mask': mask, 'next_hop': next_hop, 'admin_distance': admin_distance }) return obj def map_params_to_obj(module, required_together=None): keys = ['prefix', 'mask', 'next_hop', 'admin_distance', 'state'] obj = [] aggregate = module.params.get('aggregate') if aggregate: for item in aggregate: route = item.copy() for key in keys: if route.get(key) is None: route[key] = module.params.get(key) module._check_required_together(required_together, route) obj.append(route) else: module._check_required_together(required_together, module.params) obj.append({ 'prefix': module.params['prefix'].strip(), 'mask': module.params['mask'].strip(), 'next_hop': module.params['next_hop'].strip(), 'admin_distance': module.params.get('admin_distance'), 'state': module.params['state'], }) for route in obj: if route['admin_distance']: route['admin_distance'] = str(route['admin_distance']) return obj def main(): """ main entry point for module execution """ element_spec = dict( prefix=dict(type='str'), mask=dict(type='str'), next_hop=dict(type='str'), admin_distance=dict(type='int'), state=dict(default='present', choices=['present', 'absent']) ) aggregate_spec = deepcopy(element_spec) aggregate_spec['prefix'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(ios_argument_spec) required_one_of = [['aggregate', 'prefix']] required_together = [['prefix', 'mask', 'next_hop']] mutually_exclusive = [['aggregate', 'prefix']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) if not HAS_IPADDRESS: module.fail_json(msg="ipaddress python package is required") warnings = list() check_args(module, warnings) result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module, required_together=required_together) have = map_config_to_obj(module) commands = map_obj_to_commands(want, have, module) result['commands'] = commands if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
sunqb/oa_qian
flask/Lib/site-packages/pip/_vendor/html5lib/treewalkers/pulldom.py
1729
2302
from __future__ import absolute_import, division, unicode_literals from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS from . import _base from ..constants import voidElements class TreeWalker(_base.TreeWalker): def __iter__(self): ignore_until = None previous = None for event in self.tree: if previous is not None and \ (ignore_until is None or previous[1] is ignore_until): if previous[1] is ignore_until: ignore_until = None for token in self.tokens(previous, event): yield token if token["type"] == "EmptyTag": ignore_until = previous[1] previous = event if ignore_until is None or previous[1] is ignore_until: for token in self.tokens(previous, None): yield token elif ignore_until is not None: raise ValueError("Illformed DOM event stream: void element without END_ELEMENT") def tokens(self, event, next): type, node = event if type == START_ELEMENT: name = node.nodeName namespace = node.namespaceURI attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) attrs[(attr.namespaceURI, attr.localName)] = attr.value if name in voidElements: for token in self.emptyTag(namespace, name, attrs, not next or next[1] is not node): yield token else: yield self.startTag(namespace, name, attrs) elif type == END_ELEMENT: name = node.nodeName namespace = node.namespaceURI if name not in voidElements: yield self.endTag(namespace, name) elif type == COMMENT: yield self.comment(node.nodeValue) elif type in (IGNORABLE_WHITESPACE, CHARACTERS): for token in self.text(node.nodeValue): yield token else: yield self.unknown(type)
apache-2.0
google-research/disentanglement_lib
disentanglement_lib/data/ground_truth/cars3d.py
1
4067
# coding=utf-8 # Copyright 2018 The DisentanglementLib 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. """Cars3D data set.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from disentanglement_lib.data.ground_truth import ground_truth_data from disentanglement_lib.data.ground_truth import util import numpy as np import PIL import scipy.io as sio from six.moves import range from sklearn.utils import extmath from tensorflow.compat.v1 import gfile CARS3D_PATH = os.path.join( os.environ.get("DISENTANGLEMENT_LIB_DATA", "."), "cars") class Cars3D(ground_truth_data.GroundTruthData): """Cars3D data set. The data set was first used in the paper "Deep Visual Analogy-Making" (https://papers.nips.cc/paper/5845-deep-visual-analogy-making) and can be downloaded from http://www.scottreed.info/. The images are rescaled to 64x64. The ground-truth factors of variation are: 0 - elevation (4 different values) 1 - azimuth (24 different values) 2 - object type (183 different values) """ def __init__(self): self.factor_sizes = [4, 24, 183] features = extmath.cartesian( [np.array(list(range(i))) for i in self.factor_sizes]) self.latent_factor_indices = [0, 1, 2] self.num_total_factors = features.shape[1] self.index = util.StateSpaceAtomIndex(self.factor_sizes, features) self.state_space = util.SplitDiscreteStateSpace(self.factor_sizes, self.latent_factor_indices) self.data_shape = [64, 64, 3] self.images = self._load_data() @property def num_factors(self): return self.state_space.num_latent_factors @property def factors_num_values(self): return self.factor_sizes @property def observation_shape(self): return self.data_shape def sample_factors(self, num, random_state): """Sample a batch of factors Y.""" return self.state_space.sample_latent_factors(num, random_state) def sample_observations_from_factors(self, factors, random_state): """Sample a batch of observations X given a batch of factors Y.""" all_factors = self.state_space.sample_all_factors(factors, random_state) indices = self.index.features_to_index(all_factors) return self.images[indices].astype(np.float32) def _load_data(self): dataset = np.zeros((24 * 4 * 183, 64, 64, 3)) all_files = [x for x in gfile.ListDirectory(CARS3D_PATH) if ".mat" in x] for i, filename in enumerate(all_files): data_mesh = _load_mesh(filename) factor1 = np.array(list(range(4))) factor2 = np.array(list(range(24))) all_factors = np.transpose([ np.tile(factor1, len(factor2)), np.repeat(factor2, len(factor1)), np.tile(i, len(factor1) * len(factor2)) ]) indexes = self.index.features_to_index(all_factors) dataset[indexes] = data_mesh return dataset def _load_mesh(filename): """Parses a single source file and rescales contained images.""" with gfile.Open(os.path.join(CARS3D_PATH, filename), "rb") as f: mesh = np.einsum("abcde->deabc", sio.loadmat(f)["im"]) flattened_mesh = mesh.reshape((-1,) + mesh.shape[2:]) rescaled_mesh = np.zeros((flattened_mesh.shape[0], 64, 64, 3)) for i in range(flattened_mesh.shape[0]): pic = PIL.Image.fromarray(flattened_mesh[i, :, :, :]) pic.thumbnail((64, 64, 3), PIL.Image.ANTIALIAS) rescaled_mesh[i, :, :, :] = np.array(pic) return rescaled_mesh * 1. / 255
apache-2.0
google/latexify_py
tests/node_visitor_base_test.py
1
2191
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for node_visitor_base.""" import pytest from latexify import node_visitor_base class MockVisitor(node_visitor_base.NodeVisitorBase): """Mock visitor class.""" def __init__(self): # Dummy member to fail visitor invocation. self.visit_Baz = None # pylint: disable=invalid-name def generic_visit(self, node, action): return 'generic_visit: {}, {}'.format(node.__class__.__name__, action) def visit_Foo(self, node, action): # pylint: disable=invalid-name del node return 'visit_Foo: {}'.format(action) def visit_Foo_abc(self, node): # pylint: disable=invalid-name del node return 'visit_Foo_abc' def visit_Foo_xyz(self, node): # pylint: disable=invalid-name del node return 'visit_Foo_xyz' class Foo: pass class Bar: pass class Baz: pass def test_generic_visit(): visitor = MockVisitor() assert visitor.visit(Bar()) == 'generic_visit: Bar, None' assert visitor.visit(Bar(), 'unknown') == 'generic_visit: Bar, unknown' assert visitor.visit(Bar(), '123') == 'generic_visit: Bar, 123' def test_visit_node(): visitor = MockVisitor() assert visitor.visit(Foo()) == 'visit_Foo: None' assert visitor.visit(Foo(), 'unknown') == 'visit_Foo: unknown' assert visitor.visit(Foo(), '123') == 'visit_Foo: 123' def test_visit_node_action(): visitor = MockVisitor() assert visitor.visit(Foo(), 'abc') == 'visit_Foo_abc' assert visitor.visit(Foo(), 'xyz') == 'visit_Foo_xyz' def test_invalid_visit(): visitor = MockVisitor() with pytest.raises(AttributeError, match='visit_Baz is not callable'): visitor.visit(Baz())
apache-2.0
fjxhkj/PTVS
Python/Tests/TestData/WFastCgi/DjangoAppUrlRewrite/DjangoApplication/wsgi.py
56
1185
""" WSGI config for DjangoApplication7 project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DjangoApplication.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
apache-2.0
JudoWill/ResearchNotebooks
GA-PhredProcessing.py
1
1153
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import os, os.path import shutil import glob import sys from subprocess import check_call, check_output os.chdir('/home/will/Dropbox/PhredDirectory/') staden_path = '/home/will/staden-2.0.0b9.x86_64/bin/' sys.path.append('/home/will/PySeqUtils/') # <codecell> from GeneralSeqTools import call_muscle, fasta_reader, fasta_writer # <codecell> #from Bio import SeqIO from Bio.SeqIO.AbiIO import AbiIterator files = glob.glob('../Wigdahl Trace files/2:11:11/*.ab1') seqs = [] for f in files: rec = AbiIterator(open(f, mode = 'rb'), trim = True).next() seqs.append( (rec.id, rec.seq.tostring()) ) # <codecell> !/home/will/staden-2.0.0b9.x86_64/bin/convert_trace --help # <codecell> res = call_muscle(seqs) with open('align_data.fasta', 'w') as handle: fasta_writer(handle, res) # <codecell> from HIVTransTool import process_seqs results = list(process_seqs(seqs[:50], extract_regions = True, known_names = 50)) # <codecell> for row in results: if row['RegionName'] == 'LTR5': print row['Name'], row['QueryNuc'] # <codecell> results[:5] # <codecell>
mit
stackforge/monasca-api
monasca_api/healthcheck/keystone_protocol.py
2
2125
# Copyright 2017 FUJITSU LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from keystonemiddleware import auth_token from oslo_log import log LOG = log.getLogger(__name__) _SKIP_PATH = '/version', '/healthcheck' """Tuple of non-application endpoints""" class SkippingAuthProtocol(auth_token.AuthProtocol): """SkippingAuthProtocol to reach healthcheck endpoint Because healthcheck endpoints exists as endpoint, it is hidden behind keystone filter thus a request needs to authenticated before it is reached. Note: SkippingAuthProtocol is lean customization of :py:class:`keystonemiddleware.auth_token.AuthProtocol` that disables keystone communication if request is meant to reach healthcheck """ def process_request(self, request): path = request.path for p in _SKIP_PATH: if path.endswith(p): LOG.debug( ('Request path is %s and it does not require keystone ' 'communication'), path) return None # return NONE to reach actual logic return super(SkippingAuthProtocol, self).process_request(request) def filter_factory(global_conf, **local_conf): # pragma: no cover """Return factory function for :py:class:`.SkippingAuthProtocol` :param global_conf: global configuration :param local_conf: local configuration :return: factory function :rtype: function """ conf = global_conf.copy() conf.update(local_conf) def auth_filter(app): return SkippingAuthProtocol(app, conf) return auth_filter
apache-2.0
rlanyi/mitro
mitro-core/tools/txnsim.py
25
1305
#!/usr/bin/env python import sys import random import heapq DISTRIBUTION = [ 341, 444, 551, 656, 765, 906, 1130, 1588, 3313, 84399 ] EVENTS_PER_MS = 5754. / 431997259 # do a simulation MAX_TIME = 60 * 60 * 24 * 1000 if __name__ == '__main__': scale_factor = int(sys.argv[1]) exp_lambda = (EVENTS_PER_MS * scale_factor) num_pending_transactions = [] # a new event shows up according to the random variable, and lasts for # some time based on the distribution of percentiles current_time = 0 count = 0 pending_events = [] while current_time < MAX_TIME: count += 1 current_time += random.expovariate(exp_lambda) # new event! heapq.heappush(pending_events, current_time + random.choice(DISTRIBUTION)) while pending_events and (pending_events[0] < current_time): heapq.heappop(pending_events) num_pending_transactions.append(len(pending_events)) print 'total transactions: ', count print 'max pending at any time: ', max(num_pending_transactions) mean = sum(num_pending_transactions) / len(num_pending_transactions) print 'average pending: ', mean print ('stddev pending: ', (sum([(x-mean)**2 for x in num_pending_transactions]) / len(num_pending_transactions))**.5 )
gpl-3.0
teddywing/django-shorturls
src/shorturls/tests/test_views.py
4
2387
from django.conf import settings from django.test import TestCase from shorturls.baseconv import base62 class RedirectViewTestCase(TestCase): urls = 'shorturls.urls' fixtures = ['shorturls-test-data.json'] def setUp(self): self.old_shorten = getattr(settings, 'SHORTEN_MODELS', None) self.old_base = getattr(settings, 'SHORTEN_FULL_BASE_URL', None) settings.SHORTEN_MODELS = { 'A': 'shorturls.animal', 'V': 'shorturls.vegetable', 'M': 'shorturls.mineral', 'bad': 'not.amodel', 'bad2': 'not.even.valid', } settings.SHORTEN_FULL_BASE_URL = 'http://example.com' def tearDown(self): if self.old_shorten is not None: settings.SHORTEN_MODELS = self.old_shorten if self.old_base is not None: settings.SHORTEN_FULL_BASE_URL = self.old_base def test_redirect(self): """ Test the basic operation of a working redirect. """ response = self.client.get('/A%s' % enc(12345)) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], 'http://example.com/animal/12345/') def test_redirect_from_request(self): """ Test a relative redirect when the Sites app isn't installed. """ settings.SHORTEN_FULL_BASE_URL = None response = self.client.get('/A%s' % enc(54321), HTTP_HOST='example.org') self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], 'http://example.org/animal/54321/') def test_redirect_complete_url(self): """ Test a redirect when the object returns a complete URL. """ response = self.client.get('/V%s' % enc(785)) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], 'http://example.net/veggies/785') def test_bad_short_urls(self): self.assertEqual(404, self.client.get('/badabcd').status_code) self.assertEqual(404, self.client.get('/bad2abcd').status_code) self.assertEqual(404, self.client.get('/Vssssss').status_code) def test_model_without_get_absolute_url(self): self.assertEqual(404, self.client.get('/M%s' % enc(10101)).status_code) def enc(id): return base62.from_decimal(id)
bsd-3-clause
isrohutamahopetechnik/MissionPlanner
Lib/site-packages/scipy/ndimage/tests/test_ndimage.py
53
203784
# Copyright (C) 2003-2005 Peter J. Verveer # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import math import numpy import numpy as np from numpy import fft from numpy.testing import assert_, assert_equal, assert_array_equal, \ TestCase, run_module_suite, \ assert_array_almost_equal, assert_almost_equal import scipy.ndimage as ndimage eps = 1e-12 def sumsq(a, b): return math.sqrt(((a - b)**2).sum()) class TestNdimage(TestCase): def setUp(self): # list of numarray data types self.types = [numpy.int8, numpy.uint8, numpy.int16, numpy.uint16, numpy.int32, numpy.uint32, numpy.int64, numpy.uint64, numpy.float32, numpy.float64] # list of boundary modes: self.modes = ['nearest', 'wrap', 'reflect', 'mirror', 'constant'] def test_correlate01(self): "correlation 1" array = numpy.array([1, 2]) weights = numpy.array([2]) expected = [2, 4] output = ndimage.correlate(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, expected) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, expected) def test_correlate02(self): "correlation 2" array = numpy.array([1, 2, 3]) kernel = numpy.array([1]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(array, output) output = ndimage.correlate1d(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve1d(array, kernel) assert_array_almost_equal(array, output) def test_correlate03(self): "correlation 3" array = numpy.array([1]) weights = numpy.array([1, 1]) expected = [2] output = ndimage.correlate(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, expected) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, expected) def test_correlate04(self): "correlation 4" array = numpy.array([1, 2]) tcor = [2, 3] tcov = [3, 4] weights = numpy.array([1, 1]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, tcov) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, tcov) def test_correlate05(self): "correlation 5" array = numpy.array([1, 2, 3]) tcor = [2, 3, 5] tcov = [3, 5, 6] kernel = numpy.array([1, 1]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(tcor, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(tcov, output) output = ndimage.correlate1d(array, kernel) assert_array_almost_equal(tcor, output) output = ndimage.convolve1d(array, kernel) assert_array_almost_equal(tcov, output) def test_correlate06(self): "correlation 6" array = numpy.array([1, 2, 3]) tcor = [9, 14, 17] tcov = [7, 10, 15] weights = numpy.array([1, 2, 3]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, tcov) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, tcov) def test_correlate07(self): "correlation 7" array = numpy.array([1, 2, 3]) expected = [5, 8, 11] weights = numpy.array([1, 2, 1]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, expected) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, expected) def test_correlate08(self): "correlation 8" array = numpy.array([1, 2, 3]) tcor = [1, 2, 5] tcov = [3, 6, 7] weights = numpy.array([1, 2, -1]) output = ndimage.correlate(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve(array, weights) assert_array_almost_equal(output, tcov) output = ndimage.correlate1d(array, weights) assert_array_almost_equal(output, tcor) output = ndimage.convolve1d(array, weights) assert_array_almost_equal(output, tcov) def test_correlate09(self): "correlation 9" array = [] kernel = numpy.array([1, 1]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(array, output) output = ndimage.correlate1d(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve1d(array, kernel) assert_array_almost_equal(array, output) def test_correlate10(self): "correlation 10" array = [[]] kernel = numpy.array([[1, 1]]) output = ndimage.correlate(array, kernel) assert_array_almost_equal(array, output) output = ndimage.convolve(array, kernel) assert_array_almost_equal(array, output) def test_correlate11(self): "correlation 11" array = numpy.array([[1, 2, 3], [4, 5, 6]]) kernel = numpy.array([[1, 1], [1, 1]]) output = ndimage.correlate(array, kernel) assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output) output = ndimage.convolve(array, kernel) assert_array_almost_equal([[12, 16, 18], [18, 22, 24]], output) def test_correlate12(self): "correlation 12" array = numpy.array([[1, 2, 3], [4, 5, 6]]) kernel = numpy.array([[1, 0], [0, 1]]) output = ndimage.correlate(array, kernel) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) output = ndimage.convolve(array, kernel) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) def test_correlate13(self): "correlation 13" kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) for type2 in self.types: output = ndimage.correlate(array, kernel, output=type2) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) assert_equal(output.dtype.type, type2) output = ndimage.convolve(array, kernel, output=type2) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) assert_equal(output.dtype.type, type2) def test_correlate14(self): "correlation 14" kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) for type2 in self.types: output = numpy.zeros(array.shape, type2) ndimage.correlate(array, kernel, output=output) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) assert_equal(output.dtype.type, type2) ndimage.convolve(array, kernel, output=output) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) assert_equal(output.dtype.type, type2) def test_correlate15(self): "correlation 15" kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) output = ndimage.correlate(array, kernel, output=numpy.float32) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) assert_equal(output.dtype.type, numpy.float32) output = ndimage.convolve(array, kernel, output=numpy.float32) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) assert_equal(output.dtype.type, numpy.float32) def test_correlate16(self): "correlation 16" kernel = numpy.array([[0.5, 0 ], [0, 0.5]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) output = ndimage.correlate(array, kernel, output=numpy.float32) assert_array_almost_equal([[1, 1.5, 2.5], [2.5, 3, 4]], output) assert_equal(output.dtype.type, numpy.float32) output = ndimage.convolve(array, kernel, output=numpy.float32) assert_array_almost_equal([[3, 4, 4.5], [4.5, 5.5, 6]], output) assert_equal(output.dtype.type, numpy.float32) def test_correlate17(self): "correlation 17" array = numpy.array([1, 2, 3]) tcor = [3, 5, 6] tcov = [2, 3, 5] kernel = numpy.array([1, 1]) output = ndimage.correlate(array, kernel, origin=-1) assert_array_almost_equal(tcor, output) output = ndimage.convolve(array, kernel, origin=-1) assert_array_almost_equal(tcov, output) output = ndimage.correlate1d(array, kernel, origin=-1) assert_array_almost_equal(tcor, output) output = ndimage.convolve1d(array, kernel, origin=-1) assert_array_almost_equal(tcov, output) def test_correlate18(self): "correlation 18" kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) output = ndimage.correlate(array, kernel, output=numpy.float32, mode='nearest', origin=-1) assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) assert_equal(output.dtype.type, numpy.float32) output = ndimage.convolve(array, kernel, output=numpy.float32, mode='nearest', origin=-1) assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) assert_equal(output.dtype.type, numpy.float32) def test_correlate19(self): "correlation 19" kernel = numpy.array([[1, 0], [0, 1]]) for type1 in self.types: array = numpy.array([[1, 2, 3], [4, 5, 6]], type1) output = ndimage.correlate(array, kernel, output=numpy.float32, mode='nearest', origin=[-1, 0]) assert_array_almost_equal([[5, 6, 8], [8, 9, 11]], output) assert_equal(output.dtype.type, numpy.float32) output = ndimage.convolve(array, kernel, output=numpy.float32, mode='nearest', origin=[-1, 0]) assert_array_almost_equal([[3, 5, 6], [6, 8, 9]], output) assert_equal(output.dtype.type, numpy.float32) def test_correlate20(self): "correlation 20" weights = numpy.array([1, 2, 1]) expected = [[5, 10, 15], [7, 14, 21]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, output=output) assert_array_almost_equal(output, expected) ndimage.convolve1d(array, weights, axis=0, output=output) assert_array_almost_equal(output, expected) def test_correlate21(self): "correlation 21" array = numpy.array([[1, 2, 3], [2, 4, 6]]) expected = [[5, 10, 15], [7, 14, 21]] weights = numpy.array([1, 2, 1]) output = ndimage.correlate1d(array, weights, axis=0) assert_array_almost_equal(output, expected) output = ndimage.convolve1d(array, weights, axis=0) assert_array_almost_equal(output, expected) def test_correlate22(self): "correlation 22" weights = numpy.array([1, 2, 1]) expected = [[6, 12, 18], [6, 12, 18]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, mode='wrap', output=output) assert_array_almost_equal(output, expected) ndimage.convolve1d(array, weights, axis=0, mode='wrap', output=output) assert_array_almost_equal(output, expected) def test_correlate23(self): "correlation 23" weights = numpy.array([1, 2, 1]) expected = [[5, 10, 15], [7, 14, 21]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, mode='nearest', output=output) assert_array_almost_equal(output, expected) ndimage.convolve1d(array, weights, axis=0, mode='nearest', output=output) assert_array_almost_equal(output, expected) def test_correlate24(self): "correlation 24" weights = numpy.array([1, 2, 1]) tcor = [[7, 14, 21], [8, 16, 24]] tcov = [[4, 8, 12], [5, 10, 15]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, mode='nearest', output=output, origin=-1) assert_array_almost_equal(output, tcor) ndimage.convolve1d(array, weights, axis=0, mode='nearest', output=output, origin=-1) assert_array_almost_equal(output, tcov) def test_correlate25(self): "correlation 25" weights = numpy.array([1, 2, 1]) tcor = [[4, 8, 12], [5, 10, 15]] tcov = [[7, 14, 21], [8, 16, 24]] for type1 in self.types: array = numpy.array([[1, 2, 3], [2, 4, 6]], type1) for type2 in self.types: output = numpy.zeros((2, 3), type2) ndimage.correlate1d(array, weights, axis=0, mode='nearest', output=output, origin=1) assert_array_almost_equal(output, tcor) ndimage.convolve1d(array, weights, axis=0, mode='nearest', output=output, origin=1) assert_array_almost_equal(output, tcov) def test_gauss01(self): "gaussian filter 1" input = numpy.array([[1, 2, 3], [2, 4, 6]], numpy.float32) output = ndimage.gaussian_filter(input, 0) assert_array_almost_equal(output, input) def test_gauss02(self): "gaussian filter 2" input = numpy.array([[1, 2, 3], [2, 4, 6]], numpy.float32) output = ndimage.gaussian_filter(input, 1.0) assert_equal(input.dtype, output.dtype) assert_equal(input.shape, output.shape) def test_gauss03(self): "gaussian filter 3 - single precision data" input = numpy.arange(100 * 100).astype(numpy.float32) input.shape = (100, 100) output = ndimage.gaussian_filter(input, [1.0, 1.0]) assert_equal(input.dtype, output.dtype) assert_equal(input.shape, output.shape) # input.sum() is 49995000.0. With single precision floats, we can't # expect more than 8 digits of accuracy, so use decimal=0 in this test. assert_almost_equal(output.sum(dtype='d'), input.sum(dtype='d'), decimal=0) assert_(sumsq(input, output) > 1.0) def test_gauss04(self): "gaussian filter 4" input = numpy.arange(100 * 100).astype(numpy.float32) input.shape = (100, 100) otype = numpy.float64 output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) assert_equal(output.dtype.type, numpy.float64) assert_equal(input.shape, output.shape) assert_(sumsq(input, output) > 1.0) def test_gauss05(self): "gaussian filter 5" input = numpy.arange(100 * 100).astype(numpy.float32) input.shape = (100, 100) otype = numpy.float64 output = ndimage.gaussian_filter(input, [1.0, 1.0], order=1, output=otype) assert_equal(output.dtype.type, numpy.float64) assert_equal(input.shape, output.shape) assert_(sumsq(input, output) > 1.0) def test_gauss06(self): "gaussian filter 6" input = numpy.arange(100 * 100).astype(numpy.float32) input.shape = (100, 100) otype = numpy.float64 output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) output2 = ndimage.gaussian_filter(input, 1.0, output=otype) assert_array_almost_equal(output1, output2) def test_prewitt01(self): "prewitt filter 1" for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 1) output = ndimage.prewitt(array, 0) assert_array_almost_equal(t, output) def test_prewitt02(self): "prewitt filter 2" for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 1) output = numpy.zeros(array.shape, type) ndimage.prewitt(array, 0, output) assert_array_almost_equal(t, output) def test_prewitt03(self): "prewitt filter 3" for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 1) t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 0) output = ndimage.prewitt(array, 1) assert_array_almost_equal(t, output) def test_prewitt04(self): "prewitt filter 4" for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.prewitt(array, -1) output = ndimage.prewitt(array, 1) assert_array_almost_equal(t, output) def test_sobel01(self): "sobel filter 1" for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 1) output = ndimage.sobel(array, 0) assert_array_almost_equal(t, output) def test_sobel02(self): "sobel filter 2" for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 1) output = numpy.zeros(array.shape, type) ndimage.sobel(array, 0, output) assert_array_almost_equal(t, output) def test_sobel03(self): "sobel filter 3" for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 1) t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 0) output = numpy.zeros(array.shape, type) output = ndimage.sobel(array, 1) assert_array_almost_equal(t, output) def test_sobel04(self): "sobel filter 4" for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) t = ndimage.sobel(array, -1) output = ndimage.sobel(array, 1) assert_array_almost_equal(t, output) def test_laplace01(self): "laplace filter 1" for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.correlate1d(array, [1, -2, 1], 0) tmp2 = ndimage.correlate1d(array, [1, -2, 1], 1) output = ndimage.laplace(array) assert_array_almost_equal(tmp1 + tmp2, output) def test_laplace02(self): "laplace filter 2" for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.correlate1d(array, [1, -2, 1], 0) tmp2 = ndimage.correlate1d(array, [1, -2, 1], 1) output = numpy.zeros(array.shape, type) ndimage.laplace(array, output=output) assert_array_almost_equal(tmp1 + tmp2, output) def test_gaussian_laplace01(self): "gaussian laplace filter 1" for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) output = ndimage.gaussian_laplace(array, 1.0) assert_array_almost_equal(tmp1 + tmp2, output) def test_gaussian_laplace02(self): "gaussian laplace filter 2" for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) output = numpy.zeros(array.shape, type) ndimage.gaussian_laplace(array, 1.0, output) assert_array_almost_equal(tmp1 + tmp2, output) def test_generic_laplace01(self): "generic laplace filter 1" def derivative2(input, axis, output, mode, cval, a, b): sigma = [a, b / 2.0] input = numpy.asarray(input) order = [0] * input.ndim order[axis] = 2 return ndimage.gaussian_filter(input, sigma, order, output, mode, cval) for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = numpy.zeros(array.shape, type) tmp = ndimage.generic_laplace(array, derivative2, extra_arguments=(1.0,), extra_keywords={'b': 2.0}) ndimage.gaussian_laplace(array, 1.0, output) assert_array_almost_equal(tmp, output) def test_gaussian_gradient_magnitude01(self): "gaussian gradient magnitude filter 1" for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) output = ndimage.gaussian_gradient_magnitude(array, 1.0) expected = tmp1 * tmp1 + tmp2 * tmp2 numpy.sqrt(expected, expected) assert_array_almost_equal(expected, output) def test_gaussian_gradient_magnitude02(self): "gaussian gradient magnitude filter 2" for type in [numpy.int32, numpy.float32, numpy.float64]: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) * 100 tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) output = numpy.zeros(array.shape, type) ndimage.gaussian_gradient_magnitude(array, 1.0, output) expected = tmp1 * tmp1 + tmp2 * tmp2 numpy.sqrt(expected, expected) assert_array_almost_equal(expected, output) def test_generic_gradient_magnitude01(self): "generic gradient magnitude 1" array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], numpy.float64) def derivative(input, axis, output, mode, cval, a, b): sigma = [a, b / 2.0] input = numpy.asarray(input) order = [0] * input.ndim order[axis] = 1 return ndimage.gaussian_filter(input, sigma, order, output, mode, cval) tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0) tmp2 = ndimage.generic_gradient_magnitude(array, derivative, extra_arguments=(1.0,), extra_keywords={'b': 2.0}) assert_array_almost_equal(tmp1, tmp2) def test_uniform01(self): "uniform filter 1" array = numpy.array([2, 4, 6]) size = 2 output = ndimage.uniform_filter1d(array, size, origin=-1) assert_array_almost_equal([3, 5, 6], output) def test_uniform02(self): "uniform filter 2" array = numpy.array([1, 2, 3]) filter_shape = [0] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal(array, output) def test_uniform03(self): "uniform filter 3" array = numpy.array([1, 2, 3]) filter_shape = [1] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal(array, output) def test_uniform04(self): "uniform filter 4" array = numpy.array([2, 4, 6]) filter_shape = [2] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal([2, 3, 5], output) def test_uniform05(self): "uniform filter 5" array = [] filter_shape = [1] output = ndimage.uniform_filter(array, filter_shape) assert_array_almost_equal([], output) def test_uniform06(self): "uniform filter 6" filter_shape = [2, 2] for type1 in self.types: array = numpy.array([[4, 8, 12], [16, 20, 24]], type1) for type2 in self.types: output = ndimage.uniform_filter(array, filter_shape, output=type2) assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output) assert_equal(output.dtype.type, type2) def test_minimum_filter01(self): "minimum filter 1" array = numpy.array([1, 2, 3, 4, 5]) filter_shape = numpy.array([2]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([1, 1, 2, 3, 4], output) def test_minimum_filter02(self): "minimum filter 2" array = numpy.array([1, 2, 3, 4, 5]) filter_shape = numpy.array([3]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([1, 1, 2, 3, 4], output) def test_minimum_filter03(self): "minimum filter 3" array = numpy.array([3, 2, 5, 1, 4]) filter_shape = numpy.array([2]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([3, 2, 2, 1, 1], output) def test_minimum_filter04(self): "minimum filter 4" array = numpy.array([3, 2, 5, 1, 4]) filter_shape = numpy.array([3]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([2, 2, 1, 1, 1], output) def test_minimum_filter05(self): "minimum filter 5" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) filter_shape = numpy.array([2, 3]) output = ndimage.minimum_filter(array, filter_shape) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 2, 1, 1, 1], [5, 3, 3, 1, 1]], output) def test_minimum_filter06(self): "minimum filter 6" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 1, 1], [1, 1, 1]] output = ndimage.minimum_filter(array, footprint=footprint) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 2, 1, 1, 1], [5, 3, 3, 1, 1]], output) def test_minimum_filter07(self): "minimum filter 7" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.minimum_filter(array, footprint=footprint) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]], output) def test_minimum_filter08(self): "minimum filter 8" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.minimum_filter(array, footprint=footprint, origin=-1) assert_array_almost_equal([[3, 1, 3, 1, 1], [5, 3, 3, 1, 1], [3, 3, 1, 1, 1]], output) def test_minimum_filter09(self): "minimum filter 9" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.minimum_filter(array, footprint=footprint, origin=[-1, 0]) assert_array_almost_equal([[2, 3, 1, 3, 1], [5, 5, 3, 3, 1], [5, 3, 3, 1, 1]], output) def test_maximum_filter01(self): "maximum filter 1" array = numpy.array([1, 2, 3, 4, 5]) filter_shape = numpy.array([2]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([1, 2, 3, 4, 5], output) def test_maximum_filter02(self): "maximum filter 2" array = numpy.array([1, 2, 3, 4, 5]) filter_shape = numpy.array([3]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([2, 3, 4, 5, 5], output) def test_maximum_filter03(self): "maximum filter 3" array = numpy.array([3, 2, 5, 1, 4]) filter_shape = numpy.array([2]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([3, 3, 5, 5, 4], output) def test_maximum_filter04(self): "maximum filter 4" array = numpy.array([3, 2, 5, 1, 4]) filter_shape = numpy.array([3]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([3, 5, 5, 5, 4], output) def test_maximum_filter05(self): "maximum filter 5" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) filter_shape = numpy.array([2, 3]) output = ndimage.maximum_filter(array, filter_shape) assert_array_almost_equal([[3, 5, 5, 5, 4], [7, 9, 9, 9, 5], [8, 9, 9, 9, 7]], output) def test_maximum_filter06(self): "maximum filter 6" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 1, 1], [1, 1, 1]] output = ndimage.maximum_filter(array, footprint=footprint) assert_array_almost_equal([[3, 5, 5, 5, 4], [7, 9, 9, 9, 5], [8, 9, 9, 9, 7]], output) def test_maximum_filter07(self): "maximum filter 7" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.maximum_filter(array, footprint=footprint) assert_array_almost_equal([[3, 5, 5, 5, 4], [7, 7, 9, 9, 5], [7, 9, 8, 9, 7]], output) def test_maximum_filter08(self): "maximum filter 8" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.maximum_filter(array, footprint=footprint, origin=-1) assert_array_almost_equal([[7, 9, 9, 5, 5], [9, 8, 9, 7, 5], [8, 8, 7, 7, 7]], output) def test_maximum_filter09(self): "maximum filter 9" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.maximum_filter(array, footprint=footprint, origin=[-1, 0]) assert_array_almost_equal([[7, 7, 9, 9, 5], [7, 9, 8, 9, 7], [8, 8, 8, 7, 7]], output) def test_rank01(self): "rank filter 1" array = numpy.array([1, 2, 3, 4, 5]) output = ndimage.rank_filter(array, 1, size=2) assert_array_almost_equal(array, output) output = ndimage.percentile_filter(array, 100, size=2) assert_array_almost_equal(array, output) output = ndimage.median_filter(array, 2) assert_array_almost_equal(array, output) def test_rank02(self): "rank filter 2" array = numpy.array([1, 2, 3, 4, 5]) output = ndimage.rank_filter(array, 1, size=[3]) assert_array_almost_equal(array, output) output = ndimage.percentile_filter(array, 50, size=3) assert_array_almost_equal(array, output) output = ndimage.median_filter(array, (3,)) assert_array_almost_equal(array, output) def test_rank03(self): "rank filter 3" array = numpy.array([3, 2, 5, 1, 4]) output = ndimage.rank_filter(array, 1, size=[2]) assert_array_almost_equal([3, 3, 5, 5, 4], output) output = ndimage.percentile_filter(array, 100, size=2) assert_array_almost_equal([3, 3, 5, 5, 4], output) def test_rank04(self): "rank filter 4" array = numpy.array([3, 2, 5, 1, 4]) expected = [3, 3, 2, 4, 4] output = ndimage.rank_filter(array, 1, size=3) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 50, size=3) assert_array_almost_equal(expected, output) output = ndimage.median_filter(array, size=3) assert_array_almost_equal(expected, output) def test_rank05(self): "rank filter 5" array = numpy.array([3, 2, 5, 1, 4]) expected = [3, 3, 2, 4, 4] output = ndimage.rank_filter(array, -2, size=3) assert_array_almost_equal(expected, output) def test_rank06(self): "rank filter 6" array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) expected = [[2, 2, 1, 1, 1], [3, 3, 2, 1, 1], [5, 5, 3, 3, 1]] output = ndimage.rank_filter(array, 1, size=[2, 3]) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 17, size=(2, 3)) assert_array_almost_equal(expected, output) def test_rank07(self): "rank filter 7" array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) expected = [[3, 5, 5, 5, 4], [5, 5, 7, 5, 4], [6, 8, 8, 7, 5]] output = ndimage.rank_filter(array, -2, size=[2, 3]) assert_array_almost_equal(expected, output) def test_rank08(self): "median filter 8" array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]]) expected = [[3, 3, 2, 4, 4], [5, 5, 5, 4, 4], [5, 6, 7, 5, 5]] kernel = numpy.array([2, 3]) output = ndimage.percentile_filter(array, 50.0, size=(2, 3)) assert_array_almost_equal(expected, output) output = ndimage.rank_filter(array, 3, size=(2, 3)) assert_array_almost_equal(expected, output) output = ndimage.median_filter(array, size=(2, 3)) assert_array_almost_equal(expected, output) def test_rank09(self): "rank filter 9" expected = [[3, 3, 2, 4, 4], [3, 5, 2, 5, 1], [5, 5, 8, 3, 5]] footprint = [[1, 0, 1], [0, 1, 0]] for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = ndimage.rank_filter(array, 1, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 35, footprint=footprint) assert_array_almost_equal(expected, output) def test_rank10(self): "rank filter 10" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) expected = [[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]] footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.rank_filter(array, 0, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 0.0, footprint=footprint) assert_array_almost_equal(expected, output) def test_rank11(self): "rank filter 11" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) expected = [[3, 5, 5, 5, 4], [7, 7, 9, 9, 5], [7, 9, 8, 9, 7]] footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.rank_filter(array, -1, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 100.0, footprint=footprint) assert_array_almost_equal(expected, output) def test_rank12(self): "rank filter 12" expected = [[3, 3, 2, 4, 4], [3, 5, 2, 5, 1], [5, 5, 8, 3, 5]] footprint = [[1, 0, 1], [0, 1, 0]] for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = ndimage.rank_filter(array, 1, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.percentile_filter(array, 50.0, footprint=footprint) assert_array_almost_equal(expected, output) output = ndimage.median_filter(array, footprint=footprint) assert_array_almost_equal(expected, output) def test_rank13(self): "rank filter 13" expected = [[5, 2, 5, 1, 1], [5, 8, 3, 5, 5], [6, 6, 5, 5, 5]] footprint = [[1, 0, 1], [0, 1, 0]] for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = ndimage.rank_filter(array, 1, footprint=footprint, origin=-1) assert_array_almost_equal(expected, output) def test_rank14(self): "rank filter 14" expected = [[3, 5, 2, 5, 1], [5, 5, 8, 3, 5], [5, 6, 6, 5, 5]] footprint = [[1, 0, 1], [0, 1, 0]] for type in self.types: array = numpy.array([[3, 2, 5, 1, 4], [5, 8, 3, 7, 1], [5, 6, 9, 3, 5]], type) output = ndimage.rank_filter(array, 1, footprint=footprint, origin=[-1, 0]) assert_array_almost_equal(expected, output) def test_generic_filter1d01(self): "generic 1d filter 1" weights = numpy.array([1.1, 2.2, 3.3]) def _filter_func(input, output, fltr, total): fltr = fltr / total for ii in range(input.shape[0] - 2): output[ii] = input[ii] * fltr[0] output[ii] += input[ii + 1] * fltr[1] output[ii] += input[ii + 2] * fltr[2] for type in self.types: a = numpy.arange(12, dtype=type) a.shape = (3,4) r1 = ndimage.correlate1d(a, weights / weights.sum(), 0, origin=-1) r2 = ndimage.generic_filter1d(a, _filter_func, 3, axis=0, origin=-1, extra_arguments=(weights,), extra_keywords={'total': weights.sum()}) assert_array_almost_equal(r1, r2) def test_generic_filter01(self): "generic filter 1" filter_ = numpy.array([[1.0, 2.0], [3.0, 4.0]]) footprint = numpy.array([[1, 0], [0, 1]]) cf = numpy.array([1., 4.]) def _filter_func(buffer, weights, total=1.0): weights = cf / total return (buffer * weights).sum() for type in self.types: a = numpy.arange(12, dtype=type) a.shape = (3,4) r1 = ndimage.correlate(a, filter_ * footprint) r1 /= 5 r2 = ndimage.generic_filter(a, _filter_func, footprint=footprint, extra_arguments=(cf,), extra_keywords={'total': cf.sum()}) assert_array_almost_equal(r1, r2) def test_extend01(self): "line extension 1" array = numpy.array([1, 2, 3]) weights = numpy.array([1, 0]) expected_values = [[1, 1, 2], [3, 1, 2], [1, 1, 2], [2, 1, 2], [0, 1, 2]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) assert_array_equal(output,expected_value) def test_extend02(self): "line extension 2" array = numpy.array([1, 2, 3]) weights = numpy.array([1, 0, 0, 0, 0, 0, 0, 0]) expected_values = [[1, 1, 1], [3, 1, 2], [3, 3, 2], [1, 2, 3], [0, 0, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend03(self): "line extension 3" array = numpy.array([1, 2, 3]) weights = numpy.array([0, 0, 1]) expected_values = [[2, 3, 3], [2, 3, 1], [2, 3, 3], [2, 3, 2], [2, 3, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend04(self): "line extension 4" array = numpy.array([1, 2, 3]) weights = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) expected_values = [[3, 3, 3], [2, 3, 1], [2, 1, 1], [1, 2, 3], [0, 0, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend05(self): "line extension 5" array = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) weights = numpy.array([[1, 0], [0, 0]]) expected_values = [[[1, 1, 2], [1, 1, 2], [4, 4, 5]], [[9, 7, 8], [3, 1, 2], [6, 4, 5]], [[1, 1, 2], [1, 1, 2], [4, 4, 5]], [[5, 4, 5], [2, 1, 2], [5, 4, 5]], [[0, 0, 0], [0, 1, 2], [0, 4, 5]]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend06(self): "line extension 6" array = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) weights = numpy.array([[0, 0, 0], [0, 0, 0], [0, 0, 1]]) expected_values = [[[5, 6, 6], [8, 9, 9], [8, 9, 9]], [[5, 6, 4], [8, 9, 7], [2, 3, 1]], [[5, 6, 6], [8, 9, 9], [8, 9, 9]], [[5, 6, 5], [8, 9, 8], [5, 6, 5]], [[5, 6, 0], [8, 9, 0], [0, 0, 0]]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend07(self): "line extension 7" array = numpy.array([1, 2, 3]) weights = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) expected_values = [[3, 3, 3], [2, 3, 1], [2, 1, 1], [1, 2, 3], [0, 0, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend08(self): "line extension 8" array = numpy.array([[1], [2], [3]]) weights = numpy.array([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) expected_values = [[[3], [3], [3]], [[2], [3], [1]], [[2], [1], [1]], [[1], [2], [3]], [[0], [0], [0]]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend09(self): "line extension 9" array = numpy.array([1, 2, 3]) weights = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) expected_values = [[3, 3, 3], [2, 3, 1], [2, 1, 1], [1, 2, 3], [0, 0, 0]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_extend10(self): "line extension 10" array = numpy.array([[1], [2], [3]]) weights = numpy.array([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) expected_values = [[[3], [3], [3]], [[2], [3], [1]], [[2], [1], [1]], [[1], [2], [3]], [[0], [0], [0]]] for mode, expected_value in zip(self.modes, expected_values): output = ndimage.correlate(array, weights, mode=mode, cval=0) assert_array_equal(output, expected_value) def test_boundaries(self): "boundary modes" def shift(x): return (x[0] + 0.5,) data = numpy.array([1,2,3,4.]) expected = {'constant': [1.5,2.5,3.5,-1,-1,-1,-1], 'wrap': [1.5,2.5,3.5,1.5,2.5,3.5,1.5], 'mirror' : [1.5,2.5,3.5,3.5,2.5,1.5,1.5], 'nearest' : [1.5,2.5,3.5,4,4,4,4]} for mode in expected.keys(): assert_array_equal(expected[mode], ndimage.geometric_transform(data,shift, cval=-1,mode=mode, output_shape=(7,), order=1)) def test_boundaries2(self): "boundary modes 2" def shift(x): return (x[0] - 0.9,) data = numpy.array([1,2,3,4]) expected = {'constant': [-1,1,2,3], 'wrap': [3,1,2,3], 'mirror' : [2,1,2,3], 'nearest' : [1,1,2,3]} for mode in expected.keys(): assert_array_equal(expected[mode], ndimage.geometric_transform(data,shift, cval=-1,mode=mode, output_shape=(4,))) def test_fourier_gaussian_real01(self): "gaussian fourier filter for real transforms 1" for shape in [(32, 16), (31, 15)]: for type in [numpy.float32, numpy.float64]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1) def test_fourier_gaussian_complex01(self): "gaussian fourier filter for complex transforms 1" for shape in [(32, 16), (31, 15)]: for type in [numpy.complex64, numpy.complex128]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.fft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0) a = fft.ifft(a, shape[1], 1) a = fft.ifft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a.real), 1.0) def test_fourier_uniform_real01(self): "uniform fourier filter for real transforms 1" for shape in [(32, 16), (31, 15)]: for type in [numpy.float32, numpy.float64]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1.0) def test_fourier_uniform_complex01(self): "uniform fourier filter for complex transforms 1" for shape in [(32, 16), (31, 15)]: for type in [numpy.complex64, numpy.complex128]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.fft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0) a = fft.ifft(a, shape[1], 1) a = fft.ifft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a.real), 1.0) def test_fourier_shift_real01(self): "shift filter for real transforms 1" for shape in [(32, 16), (31, 15)]: for dtype in [numpy.float32, numpy.float64]: expected = numpy.arange(shape[0] * shape[1], dtype=dtype) expected.shape = shape a = fft.rfft(expected, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_shift(a, [1, 1], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1]) assert_array_almost_equal(a.imag, numpy.zeros(shape)) def test_fourier_shift_complex01(self): "shift filter for complex transforms 1" for shape in [(32, 16), (31, 15)]: for type in [numpy.complex64, numpy.complex128]: expected = numpy.arange(shape[0] * shape[1], dtype=type) expected.shape = shape a = fft.fft(expected, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_shift(a, [1, 1], -1, 0) a = fft.ifft(a, shape[1], 1) a = fft.ifft(a, shape[0], 0) assert_array_almost_equal(a.real[1:, 1:], expected[:-1, :-1]) assert_array_almost_equal(a.imag, numpy.zeros(shape)) def test_fourier_ellipsoid_real01(self): "ellipsoid fourier filter for real transforms 1" for shape in [(32, 16), (31, 15)]: for type in [numpy.float32, numpy.float64]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.rfft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0) a = fft.ifft(a, shape[1], 1) a = fft.irfft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a), 1.0) def test_fourier_ellipsoid_complex01(self): "ellipsoid fourier filter for complex transforms 1" for shape in [(32, 16), (31, 15)]: for type in [numpy.complex64, numpy.complex128]: a = numpy.zeros(shape, type) a[0, 0] = 1.0 a = fft.fft(a, shape[0], 0) a = fft.fft(a, shape[1], 1) a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0) a = fft.ifft(a, shape[1], 1) a = fft.ifft(a, shape[0], 0) assert_almost_equal(ndimage.sum(a.real), 1.0) def test_spline01(self): "spline filter 1" for type in self.types: data = numpy.ones([], type) for order in range(2, 6): out = ndimage.spline_filter(data, order=order) assert_array_almost_equal(out, 1) def test_spline02(self): "spline filter 2" for type in self.types: data = numpy.array([1]) for order in range(2, 6): out = ndimage.spline_filter(data, order=order) assert_array_almost_equal(out, [1]) def test_spline03(self): "spline filter 3" for type in self.types: data = numpy.ones([], type) for order in range(2, 6): out = ndimage.spline_filter(data, order, output=type) assert_array_almost_equal(out, 1) def test_spline04(self): "spline filter 4" for type in self.types: data = numpy.ones([4], type) for order in range(2, 6): out = ndimage.spline_filter(data, order) assert_array_almost_equal(out, [1, 1, 1, 1]) def test_spline05(self): "spline filter 5" for type in self.types: data = numpy.ones([4, 4], type) for order in range(2, 6): out = ndimage.spline_filter(data, order=order) assert_array_almost_equal(out, [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) def test_geometric_transform01(self): "geometric transform 1" data = numpy.array([1]) def mapping(x): return x for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [1]) def test_geometric_transform02(self): "geometric transform 2" data = numpy.ones([4]) def mapping(x): return x for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [1, 1, 1, 1]) def test_geometric_transform03(self): "geometric transform 3" data = numpy.ones([4]) def mapping(x): return (x[0] - 1,) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [0, 1, 1, 1]) def test_geometric_transform04(self): "geometric transform 4" data = numpy.array([4, 1, 3, 2]) def mapping(x): return (x[0] - 1,) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [0, 4, 1, 3]) def test_geometric_transform05(self): "geometric transform 5" data = numpy.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) def mapping(x): return (x[0], x[1] - 1) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [[0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1]]) def test_geometric_transform06(self): "geometric transform 6" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) def mapping(x): return (x[0], x[1] - 1) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]) def test_geometric_transform07(self): "geometric transform 7" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) def mapping(x): return (x[0] - 1, x[1]) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]) def test_geometric_transform08(self): "geometric transform 8" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) def mapping(x): return (x[0] - 1, x[1] - 1) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, data.shape, order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_geometric_transform10(self): "geometric transform 10" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) def mapping(x): return (x[0] - 1, x[1] - 1) for order in range(0, 6): if (order > 1): filtered = ndimage.spline_filter(data, order=order) else: filtered = data out = ndimage.geometric_transform(filtered, mapping, data.shape, order=order, prefilter=False) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_geometric_transform13(self): "geometric transform 13" data = numpy.ones([2], numpy.float64) def mapping(x): return (x[0] // 2,) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, [4], order=order) assert_array_almost_equal(out, [1, 1, 1, 1]) def test_geometric_transform14(self): "geometric transform 14" data = [1, 5, 2, 6, 3, 7, 4, 4] def mapping(x): return (2 * x[0],) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, [4], order=order) assert_array_almost_equal(out, [1, 2, 3, 4]) def test_geometric_transform15(self): "geometric transform 15" data = [1, 2, 3, 4] def mapping(x): return (x[0] / 2,) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, [8], order=order) assert_array_almost_equal(out[::2], [1, 2, 3, 4]) def test_geometric_transform16(self): "geometric transform 16" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9.0, 10, 11, 12]] def mapping(x): return (x[0], x[1] * 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (3, 2), order=order) assert_array_almost_equal(out, [[1, 3], [5, 7], [9, 11]]) def test_geometric_transform17(self): "geometric transform 17" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] * 2, x[1]) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (1, 4), order=order) assert_array_almost_equal(out, [[1, 2, 3, 4]]) def test_geometric_transform18(self): "geometric transform 18" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] * 2, x[1] * 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (1, 2), order=order) assert_array_almost_equal(out, [[1, 3]]) def test_geometric_transform19(self): "geometric transform 19" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0], x[1] / 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (3, 8), order=order) assert_array_almost_equal(out[..., ::2], data) def test_geometric_transform20(self): "geometric transform 20" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] / 2, x[1]) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (6, 4), order=order) assert_array_almost_equal(out[::2, ...], data) def test_geometric_transform21(self): "geometric transform 21" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (x[0] / 2, x[1] / 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (6, 8), order=order) assert_array_almost_equal(out[::2, ::2], data) def test_geometric_transform22(self): "geometric transform 22" data = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], numpy.float64) def mapping1(x): return (x[0] / 2, x[1] / 2) def mapping2(x): return (x[0] * 2, x[1] * 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping1, (6, 8), order=order) out = ndimage.geometric_transform(out, mapping2, (3, 4), order=order) assert_array_almost_equal(out, data) def test_geometric_transform23(self): "geometric transform 23" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x): return (1, x[0] * 2) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (2,), order=order) out = out.astype(numpy.int32) assert_array_almost_equal(out, [5, 7]) def test_geometric_transform24(self): "geometric transform 24" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] def mapping(x, a, b): return (a, x[0] * b) for order in range(0, 6): out = ndimage.geometric_transform(data, mapping, (2,), order=order, extra_arguments=(1,), extra_keywords={'b': 2}) assert_array_almost_equal(out, [5, 7]) def test_map_coordinates01(self): "map coordinates 1" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) idx = numpy.indices(data.shape) idx -= 1 for order in range(0, 6): out = ndimage.map_coordinates(data, idx, order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_map_coordinates02(self): "map coordinates 2" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) idx = numpy.indices(data.shape, numpy.float64) idx -= 0.5 for order in range(0, 6): out1 = ndimage.shift(data, 0.5, order=order) out2 = ndimage.map_coordinates(data, idx, order=order) assert_array_almost_equal(out1, out2) def test_affine_transform01(self): "affine_transform 1" data = numpy.array([1]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1]], order=order) assert_array_almost_equal(out, [1]) def test_affine_transform02(self): "affine transform 2" data = numpy.ones([4]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1]], order=order) assert_array_almost_equal(out, [1, 1, 1, 1]) def test_affine_transform03(self): "affine transform 3" data = numpy.ones([4]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1]], -1, order=order) assert_array_almost_equal(out, [0, 1, 1, 1]) def test_affine_transform04(self): "affine transform 4" data = numpy.array([4, 1, 3, 2]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1]], -1, order=order) assert_array_almost_equal(out, [0, 4, 1, 3]) def test_affine_transform05(self): "affine transform 5" data = numpy.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 1]], [0, -1], order=order) assert_array_almost_equal(out, [[0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1]]) def test_affine_transform06(self): "affine transform 6" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 1]], [0, -1], order=order) assert_array_almost_equal(out, [[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]) def test_affine_transform07(self): "affine transform 7" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 1]], [-1, 0], order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]) def test_affine_transform08(self): "affine transform 8" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 1]], [-1, -1], order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_affine_transform09(self): "affine transform 9" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): if (order > 1): filtered = ndimage.spline_filter(data, order=order) else: filtered = data out = ndimage.affine_transform(filtered,[[1, 0], [0, 1]], [-1, -1], order=order, prefilter=False) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_affine_transform10(self): "affine transform 10" data = numpy.ones([2], numpy.float64) for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5]], output_shape=(4,), order=order) assert_array_almost_equal(out, [1, 1, 1, 0]) def test_affine_transform11(self): "affine transform 11" data = [1, 5, 2, 6, 3, 7, 4, 4] for order in range(0, 6): out = ndimage.affine_transform(data, [[2]], 0, (4,), order=order) assert_array_almost_equal(out, [1, 2, 3, 4]) def test_affine_transform12(self): "affine transform 12" data = [1, 2, 3, 4] for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5]], 0, (8,), order=order) assert_array_almost_equal(out[::2], [1, 2, 3, 4]) def test_affine_transform13(self): "affine transform 13" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9.0, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0], [0, 2]], 0, (3, 2), order=order) assert_array_almost_equal(out, [[1, 3], [5, 7], [9, 11]]) def test_affine_transform14(self): "affine transform 14" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[2, 0], [0, 1]], 0, (1, 4), order=order) assert_array_almost_equal(out, [[1, 2, 3, 4]]) def test_affine_transform15(self): "affine transform 15" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[2, 0], [0, 2]], 0, (1, 2), order=order) assert_array_almost_equal(out, [[1, 3]]) def test_affine_transform16(self): "affine transform 16" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[1, 0.0], [0, 0.5]], 0, (3, 8), order=order) assert_array_almost_equal(out[..., ::2], data) def test_affine_transform17(self): "affine transform 17" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5, 0], [0, 1]], 0, (6, 4), order=order) assert_array_almost_equal(out[::2, ...], data) def test_affine_transform18(self): "affine transform 18" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5, 0], [0, 0.5]], 0, (6, 8), order=order) assert_array_almost_equal(out[::2, ::2], data) def test_affine_transform19(self): "affine transform 19" data = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], numpy.float64) for order in range(0, 6): out = ndimage.affine_transform(data, [[0.5, 0], [0, 0.5]], 0, (6, 8), order=order) out = ndimage.affine_transform(out, [[2.0, 0], [0, 2.0]], 0, (3, 4), order=order) assert_array_almost_equal(out, data) def test_affine_transform20(self): "affine transform 20" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[0], [2]], 0, (2,), order=order) assert_array_almost_equal(out, [1, 3]) def test_affine_transform21(self): "affine transform 21" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [[2], [0]], 0, (2,), order=order) assert_array_almost_equal(out, [1, 9]) def test_shift01(self): "shift 1" data = numpy.array([1]) for order in range(0, 6): out = ndimage.shift(data, [1], order=order) assert_array_almost_equal(out, [0]) def test_shift02(self): "shift 2" data = numpy.ones([4]) for order in range(0, 6): out = ndimage.shift(data, [1], order=order) assert_array_almost_equal(out, [0, 1, 1, 1]) def test_shift03(self): "shift 3" data = numpy.ones([4]) for order in range(0, 6): out = ndimage.shift(data, -1, order=order) assert_array_almost_equal(out, [1, 1, 1, 0]) def test_shift04(self): "shift 4" data = numpy.array([4, 1, 3, 2]) for order in range(0, 6): out = ndimage.shift(data, 1, order=order) assert_array_almost_equal(out, [0, 4, 1, 3]) def test_shift05(self): "shift 5" data = numpy.array([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) for order in range(0, 6): out = ndimage.shift(data, [0, 1], order=order) assert_array_almost_equal(out, [[0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1]]) def test_shift06(self): "shift 6" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.shift(data, [0, 1], order=order) assert_array_almost_equal(out, [[0, 4, 1, 3], [0, 7, 6, 8], [0, 3, 5, 3]]) def test_shift07(self): "shift 7" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.shift(data, [1, 0], order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [4, 1, 3, 2], [7, 6, 8, 5]]) def test_shift08(self): "shift 8" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): out = ndimage.shift(data, [1, 1], order=order) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_shift09(self): "shift 9" data = numpy.array([[4, 1, 3, 2], [7, 6, 8, 5], [3, 5, 3, 6]]) for order in range(0, 6): if (order > 1): filtered = ndimage.spline_filter(data, order=order) else: filtered = data out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False) assert_array_almost_equal(out, [[0, 0, 0, 0], [0, 4, 1, 3], [0, 7, 6, 8]]) def test_zoom1(self): "zoom 1" for order in range(0,6): for z in [2,[2,2]]: arr = numpy.array(range(25)).reshape((5,5)).astype(float) arr = ndimage.zoom(arr, z, order=order) assert_equal(arr.shape,(10,10)) assert_(numpy.all(arr[-1,:] != 0)) assert_(numpy.all(arr[-1,:] >= (20 - eps))) assert_(numpy.all(arr[0,:] <= (5 + eps))) assert_(numpy.all(arr >= (0 - eps))) assert_(numpy.all(arr <= (24 + eps))) def test_zoom2(self): "zoom 2" arr = numpy.arange(12).reshape((3,4)) out = ndimage.zoom(ndimage.zoom(arr,2),0.5) assert_array_equal(out,arr) def test_zoom_affine01(self): "zoom by affine transformation 1" data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] for order in range(0, 6): out = ndimage.affine_transform(data, [0.5, 0.5], 0, (6, 8), order=order) assert_array_almost_equal(out[::2, ::2], data) def test_rotate01(self): "rotate 1" data = numpy.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 0) assert_array_almost_equal(out, data) def test_rotate02(self): "rotate 2" data = numpy.array([[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]], dtype=numpy.float64) expected = numpy.array([[0, 0, 0], [0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90) assert_array_almost_equal(out, expected) def test_rotate03(self): "rotate 3" data = numpy.array([[0, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0]], dtype=numpy.float64) expected = numpy.array([[0, 0, 0], [0, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90) assert_array_almost_equal(out, expected) def test_rotate04(self): "rotate 4" data = numpy.array([[0, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0]], dtype=numpy.float64) expected = numpy.array([[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90, reshape=False) assert_array_almost_equal(out, expected) def test_rotate05(self): "rotate 5" data = numpy.empty((4,3,3)) for i in range(3): data[:,:,i] = numpy.array([[0,0,0], [0,1,0], [0,1,0], [0,0,0]], dtype=numpy.float64) expected = numpy.array([[0,0,0,0], [0,1,1,0], [0,0,0,0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90) for i in range(3): assert_array_almost_equal(out[:,:,i], expected) def test_rotate06(self): "rotate 6" data = numpy.empty((3,4,3)) for i in range(3): data[:,:,i] = numpy.array([[0,0,0,0], [0,1,1,0], [0,0,0,0]], dtype=numpy.float64) expected = numpy.array([[0,0,0], [0,1,0], [0,1,0], [0,0,0]], dtype=numpy.float64) for order in range(0, 6): out = ndimage.rotate(data, 90) for i in range(3): assert_array_almost_equal(out[:,:,i], expected) def test_rotate07(self): "rotate 7" data = numpy.array([[[0, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0]]] * 2, dtype=numpy.float64) data = data.transpose() expected = numpy.array([[[0, 0, 0], [0, 1, 0], [0, 1, 0], [0, 0, 0], [0, 0, 0]]] * 2, dtype=numpy.float64) expected = expected.transpose([2,1,0]) for order in range(0, 6): out = ndimage.rotate(data, 90, axes=(0, 1)) assert_array_almost_equal(out, expected) def test_rotate08(self): "rotate 8" data = numpy.array([[[0, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0]]] * 2, dtype=numpy.float64) data = data.transpose() expected = numpy.array([[[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]] * 2, dtype=numpy.float64) expected = expected.transpose() for order in range(0, 6): out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False) assert_array_almost_equal(out, expected) def test_watershed_ift01(self): "watershed_ift 1" data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[ -1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0]], numpy.int8) out = ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]]) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift02(self): "watershed_ift 2" data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[ -1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0]], numpy.int8) out = ndimage.watershed_ift(data, markers) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, -1, 1, 1, 1, -1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, -1, 1, 1, 1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift03(self): "watershed_ift 3" data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 2, 0, 3, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, -1]], numpy.int8) out = ndimage.watershed_ift(data, markers) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, -1, 2, -1, 3, -1, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, -1, 2, -1, 3, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift04(self): "watershed_ift 4" data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 2, 0, 3, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, -1]], numpy.int8) out = ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]]) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, 2, 2, 3, 3, 3, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift05(self): "watershed_ift 5" data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 3, 0, 2, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, -1]], numpy.int8) out = ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]]) expected = [[-1, -1, -1, -1, -1, -1, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, 3, 3, 2, 2, 2, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift06(self): "watershed_ift 6" data = numpy.array([[0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[ -1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0]], numpy.int8) out = ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]]) expected = [[-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_watershed_ift07(self): "watershed_ift 7" shape = (7, 6) data = numpy.zeros(shape, dtype=numpy.uint8) data = data.transpose() data[...] = numpy.array([[0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], numpy.uint8) markers = numpy.array([[-1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0]], numpy.int8) out = numpy.zeros(shape, dtype = numpy.int16) out = out.transpose() ndimage.watershed_ift(data, markers, structure=[[1,1,1], [1,1,1], [1,1,1]], output=out) expected = [[-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, 1, 1, 1, 1, 1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] assert_array_almost_equal(out, expected) def test_distance_transform_bf01(self): "brute force distance transform 1" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'euclidean', return_indices=True) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 2, 4, 2, 1, 0, 0], [0, 0, 1, 4, 8, 4, 1, 0, 0], [0, 0, 1, 2, 4, 2, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out * out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 1, 2, 2, 2, 2], [3, 3, 3, 2, 1, 2, 3, 3, 3], [4, 4, 4, 4, 6, 4, 4, 4, 4], [5, 5, 6, 6, 7, 6, 6, 5, 5], [6, 6, 6, 7, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 1, 2, 4, 6, 7, 7, 8], [0, 1, 1, 1, 6, 7, 7, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(ft, expected) def test_distance_transform_bf02(self): "brute force distance transform 2" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'cityblock', return_indices=True) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 2, 2, 2, 1, 0, 0], [0, 0, 1, 2, 3, 2, 1, 0, 0], [0, 0, 1, 2, 2, 2, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 1, 2, 2, 2, 2], [3, 3, 3, 3, 1, 3, 3, 3, 3], [4, 4, 4, 4, 7, 4, 4, 4, 4], [5, 5, 6, 7, 7, 7, 6, 5, 5], [6, 6, 6, 7, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 1, 1, 4, 7, 7, 7, 8], [0, 1, 1, 1, 4, 7, 7, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(expected, ft) def test_distance_transform_bf03(self): "brute force distance transform 3" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'chessboard', return_indices=True) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 2, 1, 1, 0, 0], [0, 0, 1, 2, 2, 2, 1, 0, 0], [0, 0, 1, 1, 2, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 1, 2, 2, 2, 2], [3, 3, 4, 2, 2, 2, 4, 3, 3], [4, 4, 5, 6, 6, 6, 5, 4, 4], [5, 5, 6, 6, 7, 6, 6, 5, 5], [6, 6, 6, 7, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 5, 6, 6, 7, 8], [0, 1, 1, 2, 6, 6, 7, 7, 8], [0, 1, 1, 2, 6, 7, 7, 7, 8], [0, 1, 2, 2, 6, 6, 7, 7, 8], [0, 1, 2, 4, 5, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(ft, expected) def test_distance_transform_bf04(self): "brute force distance transform 4" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) tdt, tft = ndimage.distance_transform_bf(data, return_indices=1) dts = [] fts = [] dt = numpy.zeros(data.shape, dtype=numpy.float64) ndimage.distance_transform_bf(data, distances=dt) dts.append(dt) ft = ndimage.distance_transform_bf(data, return_distances=False, return_indices=1) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_bf(data, return_distances=False, return_indices=True, indices=ft) fts.append(ft) dt, ft = ndimage.distance_transform_bf(data, return_indices=1) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.float64) ft = ndimage.distance_transform_bf(data, distances=dt, return_indices=True) dts.append(dt) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) dt = ndimage.distance_transform_bf(data, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.float64) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_bf(data, distances=dt, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) for dt in dts: assert_array_almost_equal(tdt, dt) for ft in fts: assert_array_almost_equal(tft, ft) def test_distance_transform_bf05(self): "brute force distance transform 5" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'euclidean', return_indices=True, sampling=[2, 2]) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 4, 4, 4, 0, 0, 0], [0, 0, 4, 8, 16, 8, 4, 0, 0], [0, 0, 4, 16, 32, 16, 4, 0, 0], [0, 0, 4, 8, 16, 8, 4, 0, 0], [0, 0, 0, 4, 4, 4, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out * out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 1, 2, 2, 2, 2], [3, 3, 3, 2, 1, 2, 3, 3, 3], [4, 4, 4, 4, 6, 4, 4, 4, 4], [5, 5, 6, 6, 7, 6, 6, 5, 5], [6, 6, 6, 7, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 1, 2, 4, 6, 7, 7, 8], [0, 1, 1, 1, 6, 7, 7, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(ft, expected) def test_distance_transform_bf06(self): "brute force distance transform 6" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_bf(data, 'euclidean', return_indices=True, sampling=[2, 1]) expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 4, 1, 0, 0, 0], [0, 0, 1, 4, 8, 4, 1, 0, 0], [0, 0, 1, 4, 9, 4, 1, 0, 0], [0, 0, 1, 4, 8, 4, 1, 0, 0], [0, 0, 0, 1, 4, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] assert_array_almost_equal(out * out, expected) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 2, 3, 3, 3, 3], [4, 4, 4, 4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 6, 5, 5, 5, 5], [6, 6, 6, 6, 7, 6, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 6, 6, 6, 7, 8], [0, 1, 1, 1, 6, 7, 7, 7, 8], [0, 1, 1, 1, 7, 7, 7, 7, 8], [0, 1, 1, 1, 6, 7, 7, 7, 8], [0, 1, 2, 2, 4, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8]]] assert_array_almost_equal(ft, expected) def test_distance_transform_cdt01(self): "chamfer type distance transform 1" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_cdt(data, 'cityblock', return_indices=True) bf = ndimage.distance_transform_bf(data, 'cityblock') assert_array_almost_equal(bf, out) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 1, 1, 1, 2, 2, 2], [3, 3, 2, 1, 1, 1, 2, 3, 3], [4, 4, 4, 4, 1, 4, 4, 4, 4], [5, 5, 5, 5, 7, 7, 6, 5, 5], [6, 6, 6, 6, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 1, 1, 4, 7, 7, 7, 8], [0, 1, 1, 1, 4, 5, 6, 7, 8], [0, 1, 2, 2, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8],]] assert_array_almost_equal(ft, expected) def test_distance_transform_cdt02(self): "chamfer type distance transform 2" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_cdt(data, 'chessboard', return_indices=True) bf = ndimage.distance_transform_bf(data, 'chessboard') assert_array_almost_equal(bf, out) expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 1, 1, 1, 2, 2, 2], [3, 3, 2, 2, 1, 2, 2, 3, 3], [4, 4, 3, 2, 2, 2, 3, 4, 4], [5, 5, 4, 6, 7, 6, 4, 5, 5], [6, 6, 6, 6, 7, 7, 6, 6, 6], [7, 7, 7, 7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8, 8, 8, 8]], [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 2, 3, 4, 6, 7, 8], [0, 1, 1, 2, 2, 6, 6, 7, 8], [0, 1, 1, 1, 2, 6, 7, 7, 8], [0, 1, 1, 2, 6, 6, 7, 7, 8], [0, 1, 2, 2, 5, 6, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8],]] assert_array_almost_equal(ft, expected) def test_distance_transform_cdt03(self): "chamfer type distance transform 3" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) tdt, tft = ndimage.distance_transform_cdt(data, return_indices=True) dts = [] fts = [] dt = numpy.zeros(data.shape, dtype = numpy.int32) ndimage.distance_transform_cdt(data, distances = dt) dts.append(dt) ft = ndimage.distance_transform_cdt(data, return_distances=False, return_indices=True) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_cdt(data, return_distances=False, return_indices=True, indices=ft) fts.append(ft) dt, ft = ndimage.distance_transform_cdt(data, return_indices=True) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.int32) ft = ndimage.distance_transform_cdt(data, distances=dt, return_indices = True) dts.append(dt) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) dt = ndimage.distance_transform_cdt(data, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.int32) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_cdt(data, distances=dt, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) for dt in dts: assert_array_almost_equal(tdt, dt) for ft in fts: assert_array_almost_equal(tft, ft) def test_distance_transform_edt01(self): "euclidean distance transform 1" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) out, ft = ndimage.distance_transform_edt(data, return_indices=True) bf = ndimage.distance_transform_bf(data, 'euclidean') assert_array_almost_equal(bf, out) dt = ft - numpy.indices(ft.shape[1:], dtype=ft.dtype) dt = dt.astype(numpy.float64) numpy.multiply(dt, dt, dt) dt = numpy.add.reduce(dt, axis=0) numpy.sqrt(dt, dt) assert_array_almost_equal(bf, dt) def test_distance_transform_edt02(self): "euclidean distance transform 2" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) tdt, tft = ndimage.distance_transform_edt(data, return_indices=True) dts = [] fts = [] dt = numpy.zeros(data.shape, dtype=numpy.float64) ndimage.distance_transform_edt(data, distances=dt) dts.append(dt) ft = ndimage.distance_transform_edt(data, return_distances=0, return_indices=True) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_edt(data, return_distances=False,return_indices=True, indices=ft) fts.append(ft) dt, ft = ndimage.distance_transform_edt(data, return_indices=True) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.float64) ft = ndimage.distance_transform_edt(data, distances=dt, return_indices=True) dts.append(dt) fts.append(ft) ft = numpy.indices(data.shape, dtype=numpy.int32) dt = ndimage.distance_transform_edt(data, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) dt = numpy.zeros(data.shape, dtype=numpy.float64) ft = numpy.indices(data.shape, dtype=numpy.int32) ndimage.distance_transform_edt(data, distances=dt, return_indices=True, indices=ft) dts.append(dt) fts.append(ft) for dt in dts: assert_array_almost_equal(tdt, dt) for ft in fts: assert_array_almost_equal(tft, ft) def test_distance_transform_edt03(self): "euclidean distance transform 3" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 2]) out = ndimage.distance_transform_edt(data, sampling=[2, 2]) assert_array_almost_equal(ref, out) def test_distance_transform_edt4(self): "euclidean distance transform 4" for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], type) ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 1]) out = ndimage.distance_transform_edt(data, sampling=[2, 1]) assert_array_almost_equal(ref, out) def test_generate_structure01(self): "generation of a binary structure 1" struct = ndimage.generate_binary_structure(0, 1) assert_array_almost_equal(struct, 1) def test_generate_structure02(self): "generation of a binary structure 2" struct = ndimage.generate_binary_structure(1, 1) assert_array_almost_equal(struct, [1, 1, 1]) def test_generate_structure03(self): "generation of a binary structure 3" struct = ndimage.generate_binary_structure(2, 1) assert_array_almost_equal(struct, [[0, 1, 0], [1, 1, 1], [0, 1, 0]]) def test_generate_structure04(self): "generation of a binary structure 4" struct = ndimage.generate_binary_structure(2, 2) assert_array_almost_equal(struct, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) def test_iterate_structure01(self): "iterating a structure 1" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] out = ndimage.iterate_structure(struct, 2) assert_array_almost_equal(out, [[0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 0, 1, 0, 0]]) def test_iterate_structure02(self): "iterating a structure 2" struct = [[0, 1], [1, 1], [0, 1]] out = ndimage.iterate_structure(struct, 2) assert_array_almost_equal(out, [[0, 0, 1], [0, 1, 1], [1, 1, 1], [0, 1, 1], [0, 0, 1]]) def test_iterate_structure03(self): "iterating a structure 3" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] out = ndimage.iterate_structure(struct, 2, 1) expected = [[0, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 0, 1, 0, 0]] assert_array_almost_equal(out[0], expected) assert_equal(out[1], [2, 2]) def test_binary_erosion01(self): "binary erosion 1" for type in self.types: data = numpy.ones([], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, 1) def test_binary_erosion02(self): "binary erosion 2" for type in self.types: data = numpy.ones([], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, 1) def test_binary_erosion03(self): "binary erosion 3" for type in self.types: data = numpy.ones([1], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [0]) def test_binary_erosion04(self): "binary erosion 4" for type in self.types: data = numpy.ones([1], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [1]) def test_binary_erosion05(self): "binary erosion 5" for type in self.types: data = numpy.ones([3], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [0, 1, 0]) def test_binary_erosion06(self): "binary erosion 6" for type in self.types: data = numpy.ones([3], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [1, 1, 1]) def test_binary_erosion07(self): "binary erosion 7" for type in self.types: data = numpy.ones([5], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [0, 1, 1, 1, 0]) def test_binary_erosion08(self): "binary erosion 8" for type in self.types: data = numpy.ones([5], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [1, 1, 1, 1, 1]) def test_binary_erosion09(self): "binary erosion 9" for type in self.types: data = numpy.ones([5], type) data[2] = 0 out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [0, 0, 0, 0, 0]) def test_binary_erosion10(self): "binary erosion 10" for type in self.types: data = numpy.ones([5], type) data[2] = 0 out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [1, 0, 0, 0, 1]) def test_binary_erosion11(self): "binary erosion 11" for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 0, 1] out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, [1, 0, 1, 0, 1]) def test_binary_erosion12(self): "binary erosion 12" for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 0, 1] out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1) assert_array_almost_equal(out, [0, 1, 0, 1, 1]) def test_binary_erosion13(self): "binary erosion 13" for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 0, 1] out = ndimage.binary_erosion(data, struct, border_value=1, origin=1) assert_array_almost_equal(out, [1, 1, 0, 1, 0]) def test_binary_erosion14(self): "binary erosion 14" for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 1] out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, [1, 1, 0, 0, 1]) def test_binary_erosion15(self): "binary erosion 15" for type in self.types: data = numpy.ones([5], type) data[2] = 0 struct = [1, 1] out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1) assert_array_almost_equal(out, [1, 0, 0, 1, 1]) def test_binary_erosion16(self): "binary erosion 16" for type in self.types: data = numpy.ones([1, 1], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [[1]]) def test_binary_erosion17(self): "binary erosion 17" for type in self.types: data = numpy.ones([1, 1], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [[0]]) def test_binary_erosion18(self): "binary erosion 18" for type in self.types: data = numpy.ones([1, 3], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [[0, 0, 0]]) def test_binary_erosion19(self): "binary erosion 19" for type in self.types: data = numpy.ones([1, 3], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [[1, 1, 1]]) def test_binary_erosion20(self): "binary erosion 20" for type in self.types: data = numpy.ones([3, 3], type) out = ndimage.binary_erosion(data) assert_array_almost_equal(out, [[0, 0, 0], [0, 1, 0], [0, 0, 0]]) def test_binary_erosion21(self): "binary erosion 21" for type in self.types: data = numpy.ones([3, 3], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) def test_binary_erosion22(self): "binary erosion 22" expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, border_value=1) assert_array_almost_equal(out, expected) def test_binary_erosion23(self): "binary erosion 23" struct = ndimage.generate_binary_structure(2, 2) expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, expected) def test_binary_erosion24(self): "binary erosion 24" struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, expected) def test_binary_erosion25(self): "binary erosion 25" struct = [[0, 1, 0], [1, 0, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, struct, border_value=1) assert_array_almost_equal(out, expected) def test_binary_erosion26(self): "binary erosion 26" struct = [[0, 1, 0], [1, 0, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_erosion(data, struct, border_value=1, origin=(-1, -1)) assert_array_almost_equal(out, expected) def test_binary_erosion27(self): "binary erosion 27" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, iterations=2) assert_array_almost_equal(out, expected) def test_binary_erosion28(self): "binary erosion 28" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_erosion(data, struct, border_value=1, iterations=2, output=out) assert_array_almost_equal(out, expected) def test_binary_erosion29(self): "binary erosion 29" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, iterations=3) assert_array_almost_equal(out, expected) def test_binary_erosion30(self): "binary erosion 30" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_erosion(data, struct, border_value=1, iterations=3, output=out) assert_array_almost_equal(out, expected) def test_binary_erosion31(self): "binary erosion 31" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 1]] data = numpy.array([[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_erosion(data, struct, border_value=1, iterations=1, output=out, origin=(-1, -1)) assert_array_almost_equal(out, expected) def test_binary_erosion32(self): "binary erosion 32" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, iterations=2) assert_array_almost_equal(out, expected) def test_binary_erosion33(self): "binary erosion 33" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] mask = [[1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]] data = numpy.array([[0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 1, 0, 0, 1], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, mask=mask, iterations=-1) assert_array_almost_equal(out, expected) def test_binary_erosion34(self): "binary erosion 34" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] mask = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_erosion(data, struct, border_value=1, mask=mask) assert_array_almost_equal(out, expected) def test_binary_erosion35(self): "binary erosion 35" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] mask = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0]], bool) tmp = [[0, 0, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 1]] expected = numpy.logical_and(tmp, mask) tmp = numpy.logical_and(data, numpy.logical_not(mask)) expected = numpy.logical_or(expected, tmp) out = numpy.zeros(data.shape, bool) ndimage.binary_erosion(data, struct, border_value=1, iterations=1, output=out, origin=(-1, -1), mask=mask) assert_array_almost_equal(out, expected) def test_binary_erosion36(self): "binary erosion 36" struct = [[0, 1, 0], [1, 0, 1], [0, 1, 0]] mask = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] tmp = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]]) expected = numpy.logical_and(tmp, mask) tmp = numpy.logical_and(data, numpy.logical_not(mask)) expected = numpy.logical_or(expected, tmp) out = ndimage.binary_erosion(data, struct, mask=mask, border_value=1, origin=(-1, -1)) assert_array_almost_equal(out, expected) def test_binary_dilation01(self): "binary dilation 1" for type in self.types: data = numpy.ones([], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, 1) def test_binary_dilation02(self): "binary dilation 2" for type in self.types: data = numpy.zeros([], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, 0) def test_binary_dilation03(self): "binary dilation 3" for type in self.types: data = numpy.ones([1], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1]) def test_binary_dilation04(self): "binary dilation 4" for type in self.types: data = numpy.zeros([1], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [0]) def test_binary_dilation05(self): "binary dilation 5" for type in self.types: data = numpy.ones([3], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1, 1, 1]) def test_binary_dilation06(self): "binary dilation 6" for type in self.types: data = numpy.zeros([3], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [0, 0, 0]) def test_binary_dilation07(self): "binary dilation 7" struct = ndimage.generate_binary_structure(1, 1) for type in self.types: data = numpy.zeros([3], type) data[1] = 1 out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1, 1, 1]) def test_binary_dilation08(self): "binary dilation 8" for type in self.types: data = numpy.zeros([5], type) data[1] = 1 data[3] = 1 out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1, 1, 1, 1, 1]) def test_binary_dilation09(self): "binary dilation 9" for type in self.types: data = numpy.zeros([5], type) data[1] = 1 out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [1, 1, 1, 0, 0]) def test_binary_dilation10(self): "binary dilation 10" for type in self.types: data = numpy.zeros([5], type) data[1] = 1 out = ndimage.binary_dilation(data, origin=-1) assert_array_almost_equal(out, [0, 1, 1, 1, 0]) def test_binary_dilation11(self): "binary dilation 11" for type in self.types: data = numpy.zeros([5], type) data[1] = 1 out = ndimage.binary_dilation(data, origin=1) assert_array_almost_equal(out, [1, 1, 0, 0, 0]) def test_binary_dilation12(self): "binary dilation 12" for type in self.types: data = numpy.zeros([5], type) data[1] = 1 struct = [1, 0, 1] out = ndimage.binary_dilation(data, struct) assert_array_almost_equal(out, [1, 0, 1, 0, 0]) def test_binary_dilation13(self): "binary dilation 13" for type in self.types: data = numpy.zeros([5], type) data[1] = 1 struct = [1, 0, 1] out = ndimage.binary_dilation(data, struct, border_value=1) assert_array_almost_equal(out, [1, 0, 1, 0, 1]) def test_binary_dilation14(self): "binary dilation 14" for type in self.types: data = numpy.zeros([5], type) data[1] = 1 struct = [1, 0, 1] out = ndimage.binary_dilation(data, struct, origin=-1) assert_array_almost_equal(out, [0, 1, 0, 1, 0]) def test_binary_dilation15(self): "binary dilation 15" for type in self.types: data = numpy.zeros([5], type) data[1] = 1 struct = [1, 0, 1] out = ndimage.binary_dilation(data, struct, origin=-1, border_value=1) assert_array_almost_equal(out, [1, 1, 0, 1, 0]) def test_binary_dilation16(self): "binary dilation 16" for type in self.types: data = numpy.ones([1, 1], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[1]]) def test_binary_dilation17(self): "binary dilation 17" for type in self.types: data = numpy.zeros([1, 1], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[0]]) def test_binary_dilation18(self): "binary dilation 18" for type in self.types: data = numpy.ones([1, 3], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[1, 1, 1]]) def test_binary_dilation19(self): "binary dilation 19" for type in self.types: data = numpy.ones([3, 3], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) def test_binary_dilation20(self): "binary dilation 20" for type in self.types: data = numpy.zeros([3, 3], type) data[1, 1] = 1 out = ndimage.binary_dilation(data) assert_array_almost_equal(out, [[0, 1, 0], [1, 1, 1], [0, 1, 0]]) def test_binary_dilation21(self): "binary dilation 21" struct = ndimage.generate_binary_structure(2, 2) for type in self.types: data = numpy.zeros([3, 3], type) data[1, 1] = 1 out = ndimage.binary_dilation(data, struct) assert_array_almost_equal(out, [[1, 1, 1], [1, 1, 1], [1, 1, 1]]) def test_binary_dilation22(self): "binary dilation 22" expected = [[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data) assert_array_almost_equal(out, expected) def test_binary_dilation23(self): "binary dilation 23" expected = [[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 1], [1, 1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 0, 0, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, border_value=1) assert_array_almost_equal(out, expected) def test_binary_dilation24(self): "binary dilation 24" expected = [[1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 1, 0, 0], [0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, origin=(1, 1)) assert_array_almost_equal(out, expected) def test_binary_dilation25(self): "binary dilation 25" expected = [[1, 1, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, origin=(1, 1), border_value=1) assert_array_almost_equal(out, expected) def test_binary_dilation26(self): "binary dilation 26" struct = ndimage.generate_binary_structure(2, 2) expected = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, struct) assert_array_almost_equal(out, expected) def test_binary_dilation27(self): "binary dilation 27" struct = [[0, 1], [1, 1]] expected = [[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, struct) assert_array_almost_equal(out, expected) def test_binary_dilation28(self): "binary dilation 28" expected = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 1], [1, 1, 1, 1]] for type in self.types: data = numpy.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, border_value=1) assert_array_almost_equal(out, expected) def test_binary_dilation29(self): "binary dilation 29" struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]], bool) out = ndimage.binary_dilation(data, struct, iterations=2) assert_array_almost_equal(out, expected) def test_binary_dilation30(self): "binary dilation 30" struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_dilation(data, struct, iterations=2, output=out) assert_array_almost_equal(out, expected) def test_binary_dilation31(self): "binary dilation 31" struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]], bool) out = ndimage.binary_dilation(data, struct, iterations=3) assert_array_almost_equal(out, expected) def test_binary_dilation32(self): "binary dilation 32" struct = [[0, 1], [1, 1]] expected = [[0, 0, 0, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [0, 0, 0, 0, 0]] data = numpy.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]], bool) out = numpy.zeros(data.shape, bool) ndimage.binary_dilation(data, struct, iterations=3, output=out) assert_array_almost_equal(out, expected) def test_binary_dilation33(self): "binary dilation 33" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) mask = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_dilation(data, struct, iterations=-1, mask=mask, border_value=0) assert_array_almost_equal(out, expected) def test_binary_dilation34(self): "binary dilation 34" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] mask = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.zeros(mask.shape, bool) out = ndimage.binary_dilation(data, struct, iterations=-1, mask=mask, border_value=1) assert_array_almost_equal(out, expected) def test_binary_dilation35(self): "binary dilation 35" tmp = [[1, 1, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 1, 0, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]] data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]) mask = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] expected = numpy.logical_and(tmp, mask) tmp = numpy.logical_and(data, numpy.logical_not(mask)) expected = numpy.logical_or(expected, tmp) for type in self.types: data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_dilation(data, mask=mask, origin=(1, 1), border_value=1) assert_array_almost_equal(out, expected) def test_binary_propagation01(self): "binary propagation 1" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) mask = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_propagation(data, struct, mask=mask, border_value=0) assert_array_almost_equal(out, expected) def test_binary_propagation02(self): "binary propagation 2" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] mask = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.zeros(mask.shape, bool) out = ndimage.binary_propagation(data, struct, mask=mask, border_value=1) assert_array_almost_equal(out, expected) def test_binary_opening01(self): "binary opening 1" expected = [[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_opening(data) assert_array_almost_equal(out, expected) def test_binary_opening02(self): "binary opening 2" struct = ndimage.generate_binary_structure(2, 2) expected = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_opening(data, struct) assert_array_almost_equal(out, expected) def test_binary_closing01(self): "binary closing 1" expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_closing(data) assert_array_almost_equal(out, expected) def test_binary_closing02(self): "binary closing 2" struct = ndimage.generate_binary_structure(2, 2) expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_closing(data, struct) assert_array_almost_equal(out, expected) def test_binary_fill_holes01(self): "binary fill holes 1" expected = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_fill_holes(data) assert_array_almost_equal(out, expected) def test_binary_fill_holes02(self): "binary fill holes 2" expected = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_fill_holes(data) assert_array_almost_equal(out, expected) def test_binary_fill_holes03(self): "binary fill holes 3" expected = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 1, 1, 1], [0, 1, 1, 1, 0, 1, 1, 1], [0, 1, 1, 1, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0]], bool) data = numpy.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0]], bool) out = ndimage.binary_fill_holes(data) assert_array_almost_equal(out, expected) def test_grey_erosion01(self): "grey erosion 1" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] output = ndimage.grey_erosion(array, footprint=footprint) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]], output) def test_grey_erosion02(self): "grey erosion 2" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] output = ndimage.grey_erosion(array, footprint=footprint, structure=structure) assert_array_almost_equal([[2, 2, 1, 1, 1], [2, 3, 1, 3, 1], [5, 5, 3, 3, 1]], output) def test_grey_erosion03(self): "grey erosion 3" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[1, 1, 1], [1, 1, 1]] output = ndimage.grey_erosion(array, footprint=footprint, structure=structure) assert_array_almost_equal([[1, 1, 0, 0, 0], [1, 2, 0, 2, 0], [4, 4, 2, 2, 0]], output) def test_grey_dilation01(self): "grey dilation 1" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[0, 1, 1], [1, 0, 1]] output = ndimage.grey_dilation(array, footprint=footprint) assert_array_almost_equal([[7, 7, 9, 9, 5], [7, 9, 8, 9, 7], [8, 8, 8, 7, 7]], output) def test_grey_dilation02(self): "grey dilation 2" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[0, 1, 1], [1, 0, 1]] structure = [[0, 0, 0], [0, 0, 0]] output = ndimage.grey_dilation(array, footprint=footprint, structure=structure) assert_array_almost_equal([[7, 7, 9, 9, 5], [7, 9, 8, 9, 7], [8, 8, 8, 7, 7]], output) def test_grey_dilation03(self): "grey dilation 3" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[0, 1, 1], [1, 0, 1]] structure = [[1, 1, 1], [1, 1, 1]] output = ndimage.grey_dilation(array, footprint=footprint, structure=structure) assert_array_almost_equal([[8, 8, 10, 10, 6], [8, 10, 9, 10, 8], [9, 9, 9, 8, 8]], output) def test_grey_opening01(self): "grey opening 1" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] tmp = ndimage.grey_erosion(array, footprint=footprint) expected = ndimage.grey_dilation(tmp, footprint=footprint) output = ndimage.grey_opening(array, footprint=footprint) assert_array_almost_equal(expected, output) def test_grey_opening02(self): "grey opening 2" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = ndimage.grey_dilation(tmp, footprint=footprint, structure=structure) output = ndimage.grey_opening(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_grey_closing01(self): "grey closing 1" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] tmp = ndimage.grey_dilation(array, footprint=footprint) expected = ndimage.grey_erosion(tmp, footprint=footprint) output = ndimage.grey_closing(array, footprint=footprint) assert_array_almost_equal(expected, output) def test_grey_closing02(self): "grey closing 2" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_dilation(array, footprint=footprint, structure=structure) expected = ndimage.grey_erosion(tmp, footprint=footprint, structure=structure) output = ndimage.grey_closing(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_morphological_gradient01(self): "morphological gradient 1" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp1 = ndimage.grey_dilation(array, footprint=footprint, structure=structure) tmp2 = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = tmp1 - tmp2 output = numpy.zeros(array.shape, array.dtype) ndimage.morphological_gradient(array, footprint=footprint, structure=structure, output=output) assert_array_almost_equal(expected, output) def test_morphological_gradient02(self): "morphological gradient 2" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp1 = ndimage.grey_dilation(array, footprint=footprint, structure=structure) tmp2 = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = tmp1 - tmp2 output =ndimage.morphological_gradient(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_morphological_laplace01(self): "morphological laplace 1" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp1 = ndimage.grey_dilation(array, footprint=footprint, structure=structure) tmp2 = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = tmp1 + tmp2 - 2 * array output = numpy.zeros(array.shape, array.dtype) ndimage.morphological_laplace(array, footprint=footprint, structure=structure, output=output) assert_array_almost_equal(expected, output) def test_morphological_laplace02(self): "morphological laplace 2" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp1 = ndimage.grey_dilation(array, footprint=footprint, structure=structure) tmp2 = ndimage.grey_erosion(array, footprint=footprint, structure=structure) expected = tmp1 + tmp2 - 2 * array output = ndimage.morphological_laplace(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_white_tophat01(self): "white tophat 1" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_opening(array, footprint=footprint, structure=structure) expected = array - tmp output = numpy.zeros(array.shape, array.dtype) ndimage.white_tophat(array, footprint=footprint, structure=structure, output=output) assert_array_almost_equal(expected, output) def test_white_tophat02(self): "white tophat 2" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_opening(array, footprint=footprint, structure=structure) expected = array - tmp output = ndimage.white_tophat(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_black_tophat01(self): "black tophat 1" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_closing(array, footprint=footprint, structure=structure) expected = tmp - array output = numpy.zeros(array.shape, array.dtype) ndimage.black_tophat(array, footprint=footprint, structure=structure, output=output) assert_array_almost_equal(expected, output) def test_black_tophat02(self): "black tophat 2" array = numpy.array([[3, 2, 5, 1, 4], [7, 6, 9, 3, 5], [5, 8, 3, 7, 1]]) footprint = [[1, 0, 1], [1, 1, 0]] structure = [[0, 0, 0], [0, 0, 0]] tmp = ndimage.grey_closing(array, footprint=footprint, structure=structure) expected = tmp - array output = ndimage.black_tophat(array, footprint=footprint, structure=structure) assert_array_almost_equal(expected, output) def test_hit_or_miss01(self): "binary hit-or-miss transform 1" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 0, 1, 1], [0, 0, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0]], type) out = numpy.zeros(data.shape, bool) ndimage.binary_hit_or_miss(data, struct, output=out) assert_array_almost_equal(expected, out) def test_hit_or_miss02(self): "binary hit-or-miss transform 2" struct = [[0, 1, 0], [1, 1, 1], [0, 1, 0]] expected = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 1, 1, 1, 0], [1, 1, 1, 0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_hit_or_miss(data, struct) assert_array_almost_equal(expected, out) def test_hit_or_miss03(self): "binary hit-or-miss transform 3" struct1 = [[0, 0, 0], [1, 1, 1], [0, 0, 0]] struct2 = [[1, 1, 1], [0, 0, 0], [1, 1, 1]] expected = [[0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] for type in self.types: data = numpy.array([[0, 1, 0, 0, 1, 1, 1, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 1, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0]], type) out = ndimage.binary_hit_or_miss(data, struct1, struct2) assert_array_almost_equal(expected, out) #class NDImageTestResult(unittest.TestResult): # separator1 = '=' * 70 + '\n' # separator2 = '-' * 70 + '\n' # # def __init__(self, stream, verbose): # unittest.TestResult.__init__(self) # self.stream = stream # self.verbose = verbose # # def getDescription(self, test): # return test.shortDescription() or str(test) # # def startTest(self, test): # unittest.TestResult.startTest(self, test) # if self.verbose: # self.stream.write(self.getDescription(test)) # self.stream.write(" ... ") # # def addSuccess(self, test): # unittest.TestResult.addSuccess(self, test) # if self.verbose: # self.stream.write("ok\n") # # def addError(self, test, err): # unittest.TestResult.addError(self, test, err) # if self.verbose: # self.stream.write("ERROR\n") # # def addFailure(self, test, err): # unittest.TestResult.addFailure(self, test, err) # if self.verbose: # self.stream.write("FAIL\n") # # def printErrors(self): # self.printErrorList('ERROR', self.errors) # self.printErrorList('FAIL', self.failures) # # def printErrorList(self, flavour, errors): # for test, err in errors: # self.stream.write(self.separator1) # description = self.getDescription(test) # self.stream.write("%s: %s\n" % (flavour, description)) # self.stream.write(self.separator2) # self.stream.write(err) # #def test(): # if '-v' in sys.argv[1:]: # verbose = 1 # else: # verbose = 0 # suite = unittest.TestSuite() # suite.addTest(unittest.makeSuite(NDImageTest)) # result = NDImageTestResult(sys.stdout, verbose) # suite(result) # result.printErrors() # return len(result.failures), result.testsRun if __name__ == "__main__": run_module_suite()
gpl-3.0
intel-hpdd/intel-manager-for-lustre
chroma_core/services/job_scheduler/job_scheduler_client.py
1
10557
# Copyright (c) 2020 DDN. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. """ The service `job_scheduler` handles both RPCs (JobSchedulerRpc) and a queue (NotificationQueue). The RPCs are used for explicit requests to modify the system or run a particular task, while the queue is used for updates received from agent reports. Access to both of these, along with some additional non-remote functionality is wrapped in JobSchedulerClient. """ from django import db from chroma_core.services import log_register from chroma_core.services.rpc import ServiceRpcInterface from chroma_core.models import ManagedHost, Command log = log_register(__name__) class JobSchedulerRpc(ServiceRpcInterface): methods = [ "set_state", "run_jobs", "cancel_job", "create_host_ssh", "test_host_contact", "create_filesystem", "create_ostpool", "create_task", "remove_task", "update_ostpool", "delete_ostpool", "create_client_mount", "create_copytool", "register_copytool", "unregister_copytool", "update_nids", "trigger_plugin_update", "update_lnet_configuration", "create_host", "create_targets", "available_transitions", "available_jobs", "get_locks", "update_corosync_configuration", "get_transition_consequences", "configure_stratagem", "update_stratagem", "run_stratagem", ] class JobSchedulerClient(object): """Because there are some tasks which are the domain of the job scheduler but do not need to be run in the context of the service, the RPCs and queue operations are accompanied in this class by some operations that run locally. The local operations are read-only operations such as querying what operations are possible for a particular object. """ @classmethod def command_run_jobs(cls, job_dicts, message): """Create and run some Jobs, within a single Command. :param job_dicts: List of 1 or more dicts like {'class_name': 'MyJobClass', 'args': {<dict of arguments to Job constructor>}} :param message: User-visible string describing the operation, e.g. "Detecting filesystems" :return: The ID of a new Command """ return JobSchedulerRpc().run_jobs(job_dicts, message) @classmethod def command_set_state(cls, object_ids, message, run=True): """Modify the system in whatever way is necessary to reach the state specified in `object_ids`. Creates Jobs under a single Command. May create no Jobs if the system is already in the state, or already scheduled to be in that state. If the system is already scheduled to be in that state, then the returned Command will be connected to the existing Jobs which take the system to the desired state. :param cls: :param object_ids: List of three-tuples (natural_key, object_id, new_state) :param message: User-visible string describing the operation, e.g. "Starting filesystem X" :param run: Test only. Schedule jobs without starting them. :return: The ID of a new Command """ return JobSchedulerRpc().set_state(object_ids, message, run) @classmethod def available_transitions(cls, object_list): """Return the transitions available for each object in list See the Job Scheduler method of the same name for details. """ return JobSchedulerRpc().available_transitions(object_list) @classmethod def available_jobs(cls, object_list): """Query which jobs (other than changes to state) can be run on this object. See the Job Scheduler method of the same name for details. """ return JobSchedulerRpc().available_jobs(object_list) @classmethod def get_transition_consequences(cls, stateful_object, new_state): """Query what the side effects of a state transition are. Effectively does a dry run of scheduling jobs for the transition. The return format is like this: :: { 'transition_job': <job dict>, 'dependency_jobs': [<list of job dicts>] } # where each job dict is like { 'class': '<job class name>', 'requires_confirmation': <boolean, whether to prompt for confirmation>, 'confirmation_prompt': <string, confirmation prompt>, 'description': <string, description of the job>, 'stateful_object_id': <ID of the object modified by this job>, 'stateful_object_content_type_id': <Content type ID of the object modified by this job> } :param stateful_object: A StatefulObject instance :param new_state: Hypothetical new value of the 'state' attribute """ return JobSchedulerRpc().get_transition_consequences( stateful_object.__class__.__name__, stateful_object.id, new_state ) @classmethod def cancel_job(cls, job_id): """Attempt to cancel a job which is already scheduled (and possibly running) :param job_id: ID of a Job object """ JobSchedulerRpc().cancel_job(job_id) @classmethod def create_host_ssh(cls, address, server_profile, root_pw, pkey, pkey_pw): """ Create a host which will be set up using SSH :param address: SSH address :return: (<ManagedHost instance>, <Command instance>) """ host_id, command_id = JobSchedulerRpc().create_host_ssh(address, server_profile, root_pw, pkey, pkey_pw) return (ManagedHost.objects.get(pk=host_id), Command.objects.get(pk=command_id)) @classmethod def test_host_contact(cls, address, root_pw=None, pkey=None, pkey_pw=None): command_id = JobSchedulerRpc().test_host_contact(address, root_pw, pkey, pkey_pw) return Command.objects.get(pk=command_id) @classmethod def update_corosync_configuration(cls, corosync_configuration_id, mcast_port, network_interface_ids): command_id = JobSchedulerRpc().update_corosync_configuration( corosync_configuration_id, mcast_port, network_interface_ids ) return Command.objects.get(pk=command_id) @classmethod def create_filesystem(cls, fs_data): return JobSchedulerRpc().create_filesystem(fs_data) @classmethod def create_ostpool(cls, pool_data): return JobSchedulerRpc().create_ostpool(pool_data) @classmethod def update_ostpool(cls, pool_data): return JobSchedulerRpc().update_ostpool(pool_data) @classmethod def delete_ostpool(cls, pool): return JobSchedulerRpc().delete_ostpool(pool) @classmethod def create_task(cls, task_data): return JobSchedulerRpc().create_task(task_data) @classmethod def remove_task(cls, task_id): return JobSchedulerRpc().create_task(task_id) @classmethod def update_nids(cls, nid_data): return JobSchedulerRpc().update_nids(nid_data) @classmethod def trigger_plugin_update(cls, include_host_ids, exclude_host_ids, plugin_names): """ Cause the plugins on the hosts passed to send an update irrespective of whether any changes have occurred. :param include_host_ids: List of host ids to include in the trigger update. :param exclude_host_ids: List of host ids to exclude from the include list (makes for usage easy) :param plugin_names: list of plugins to trigger update on - empty list means all. :return: command id that caused updates to be sent. """ assert isinstance(include_host_ids, list) assert isinstance(exclude_host_ids, list) assert isinstance(plugin_names, list) return JobSchedulerRpc().trigger_plugin_update(include_host_ids, exclude_host_ids, plugin_names) @classmethod def update_lnet_configuration(cls, lnet_configuration_list): return JobSchedulerRpc().update_lnet_configuration(lnet_configuration_list) @classmethod def create_host(cls, fqdn, nodename, address, server_profile_id): # The address of a host isn't something we can learn from it (the # address is specifically how the host is to be reached from the manager # for outbound connections, not just its FQDN). If during creation we know # the address, then great, accept it. Else default to FQDN, it's a reasonable guess. if address is None: address = fqdn host_id, command_id = JobSchedulerRpc().create_host(fqdn, nodename, address, server_profile_id) return (ManagedHost.objects.get(pk=host_id), Command.objects.get(pk=command_id)) @classmethod def create_targets(cls, targets_data): from chroma_core.models import ManagedTarget, Command target_ids, command_id = JobSchedulerRpc().create_targets(targets_data) return (list(ManagedTarget.objects.filter(id__in=target_ids)), Command.objects.get(pk=command_id)) @classmethod def create_client_mount(cls, host, filesystem_name, mountpoint): from chroma_core.models import LustreClientMount client_mount_id = JobSchedulerRpc().create_client_mount(host.id, filesystem_name, mountpoint) return LustreClientMount.objects.get(id=client_mount_id) @classmethod def create_copytool(cls, copytool_data): from chroma_core.models import Copytool copytool_id = JobSchedulerRpc().create_copytool(copytool_data) return Copytool.objects.get(id=copytool_id) @classmethod def register_copytool(cls, copytool_id, uuid): JobSchedulerRpc().register_copytool(copytool_id, uuid) @classmethod def unregister_copytool(cls, copytool_id): JobSchedulerRpc().unregister_copytool(copytool_id) @classmethod def get_locks(cls): return JobSchedulerRpc().get_locks() @classmethod def configure_stratagem(cls, stratagem_data): return JobSchedulerRpc().configure_stratagem(stratagem_data) @classmethod def update_stratagem(cls, stratagem_data): return JobSchedulerRpc().update_stratagem(stratagem_data) @classmethod def run_stratagem(cls, mdts, fs_id, stratagem_data): return JobSchedulerRpc().run_stratagem(mdts, fs_id, stratagem_data)
mit
diox/zamboni
mkt/tvplace/tests/test_views.py
5
4750
import json from django.core.urlresolvers import reverse from nose.tools import eq_, ok_ import mkt from mkt.api.tests import BaseAPI from mkt.api.tests.test_oauth import RestOAuth from mkt.site.fixtures import fixture from mkt.site.tests import ESTestCase, app_factory from mkt.tvplace.serializers import (TVAppSerializer, TVWebsiteSerializer) from mkt.webapps.models import Webapp from mkt.websites.models import Website from mkt.websites.utils import website_factory TVPLACE_APP_EXCLUDED_FIELDS = ( 'absolute_url', 'app_type', 'banner_message', 'banner_regions', 'created', 'default_locale', 'device_types', 'feature_compatibility', 'is_offline', 'is_packaged', 'payment_account', 'payment_required', 'premium_type', 'price', 'price_locale', 'regions', 'resource_uri', 'supported_locales', 'upsell', 'upsold', 'versions') TVPLACE_WEBSITE_EXCLUDED_FIELDS = ('title', 'mobile_url') def assert_tvplace_app(data): for field in TVPLACE_APP_EXCLUDED_FIELDS: ok_(field not in data, field) for field in TVAppSerializer.Meta.fields: ok_(field in data, field) def assert_tvplace_website(data): for field in TVPLACE_WEBSITE_EXCLUDED_FIELDS: ok_(field not in data, field) for field in TVWebsiteSerializer.Meta.fields: ok_(field in data, field) class TestAppDetail(BaseAPI): fixtures = fixture('webapp_337141') def setUp(self): super(TestAppDetail, self).setUp() Webapp.objects.get(pk=337141).addondevicetype_set.create( device_type=5) self.url = reverse('tv-app-detail', kwargs={'pk': 337141}) def test_get(self): res = self.client.get(self.url) data = json.loads(res.content) eq_(data['id'], 337141) def test_get_slug(self): Webapp.objects.get(pk=337141).update(app_slug='foo') res = self.client.get(reverse('tv-app-detail', kwargs={'pk': 'foo'})) data = json.loads(res.content) eq_(data['id'], 337141) class TestMultiSearchView(RestOAuth, ESTestCase): def tearDown(self): Webapp.get_indexer().unindexer(_all=True) Website.get_indexer().unindexer(_all=True) super(TestMultiSearchView, self).tearDown() def test_get_multi(self): website = website_factory() website.update(last_updated=self.days_ago(42)) app = app_factory(version_kw={'reviewed': self.days_ago(1)}) website_factory(devices=[mkt.DEVICE_DESKTOP.id, mkt.DEVICE_GAIA.id]) app.addondevicetype_set.create(device_type=mkt.DEVICE_TV.id) self.reindex(Webapp) self.reindex(Website) url = reverse('tv-multi-search-api') res = self.client.get(url) objects = res.json['objects'] eq_(len(objects), 2) eq_(objects[0]['doc_type'], 'webapp') assert_tvplace_app(objects[0]) eq_(objects[0]['id'], app.pk) eq_(objects[1]['doc_type'], 'website') assert_tvplace_website(objects[1]) eq_(objects[1]['id'], website.pk) def test_search_ordering_relevancy(self): website1 = website_factory( name='Blah', description='Blah', devices=[mkt.DEVICE_TV.id]) website2 = website_factory(name='Blah', devices=[mkt.DEVICE_TV.id], tv_featured=1) website3 = website_factory(name='Blah', devices=[mkt.DEVICE_TV.id]) self.reindex(Website) self.reindex(Webapp) url = reverse('tv-multi-search-api') res = self.client.get(url, {'q': 'blah'}) objects = res.json['objects'] eq_(len(objects), 3) eq_(objects[0]['id'], website2.pk) eq_(objects[1]['id'], website1.pk) eq_(objects[2]['id'], website3.pk) def test_search_ordering(self): website1 = website_factory(name='A', devices=[mkt.DEVICE_TV.id]) website1.update(last_updated=self.days_ago(1)) website2 = website_factory(name='B', devices=[mkt.DEVICE_TV.id], tv_featured=1) website3 = website_factory(name='C', devices=[mkt.DEVICE_TV.id], tv_featured=2) website4 = website_factory(name='D', devices=[mkt.DEVICE_TV.id]) website4.update(last_updated=self.days_ago(2)) self.reindex(Website) self.reindex(Webapp) url = reverse('tv-multi-search-api') res = self.client.get(url) objects = res.json['objects'] eq_(len(objects), 4) eq_(objects[0]['id'], website3.pk) eq_(objects[1]['id'], website2.pk) eq_(objects[2]['id'], website1.pk) eq_(objects[3]['id'], website4.pk)
bsd-3-clause
sfam/home-assistant
homeassistant/components/media_player/cast.py
3
8953
""" homeassistant.components.media_player.chromecast ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides functionality to interact with Cast devices on the network. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.cast/ """ # pylint: disable=import-error import logging from homeassistant.const import ( STATE_PLAYING, STATE_PAUSED, STATE_IDLE, STATE_OFF, STATE_UNKNOWN, CONF_HOST) from homeassistant.components.media_player import ( MediaPlayerDevice, SUPPORT_PAUSE, SUPPORT_VOLUME_SET, SUPPORT_VOLUME_MUTE, SUPPORT_TURN_ON, SUPPORT_TURN_OFF, SUPPORT_YOUTUBE, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_NEXT_TRACK, MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO) REQUIREMENTS = ['pychromecast==0.6.14'] CONF_IGNORE_CEC = 'ignore_cec' CAST_SPLASH = 'https://home-assistant.io/images/cast/splash.png' SUPPORT_CAST = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE | \ SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PREVIOUS_TRACK | \ SUPPORT_NEXT_TRACK | SUPPORT_YOUTUBE | SUPPORT_PLAY_MEDIA KNOWN_HOSTS = [] # pylint: disable=invalid-name cast = None # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): """ Sets up the cast platform. """ global cast import pychromecast cast = pychromecast logger = logging.getLogger(__name__) # import CEC IGNORE attributes ignore_cec = config.get(CONF_IGNORE_CEC, []) if isinstance(ignore_cec, list): cast.IGNORE_CEC += ignore_cec else: logger.error('Chromecast conig, %s must be a list.', CONF_IGNORE_CEC) hosts = [] if discovery_info and discovery_info[0] not in KNOWN_HOSTS: hosts = [discovery_info[0]] elif CONF_HOST in config: hosts = [config[CONF_HOST]] else: hosts = (host_port[0] for host_port in cast.discover_chromecasts() if host_port[0] not in KNOWN_HOSTS) casts = [] for host in hosts: try: casts.append(CastDevice(host)) except cast.ChromecastConnectionError: pass else: KNOWN_HOSTS.append(host) add_devices(casts) class CastDevice(MediaPlayerDevice): """ Represents a Cast device on the network. """ # pylint: disable=abstract-method # pylint: disable=too-many-public-methods def __init__(self, host): import pychromecast.controllers.youtube as youtube self.cast = cast.Chromecast(host) self.youtube = youtube.YouTubeController() self.cast.register_handler(self.youtube) self.cast.socket_client.receiver_controller.register_status_listener( self) self.cast.socket_client.media_controller.register_status_listener(self) self.cast_status = self.cast.status self.media_status = self.cast.media_controller.status # Entity properties and methods @property def should_poll(self): return False @property def name(self): """ Returns the name of the device. """ return self.cast.device.friendly_name # MediaPlayerDevice properties and methods @property def state(self): """ State of the player. """ if self.media_status is None: return STATE_UNKNOWN elif self.media_status.player_is_playing: return STATE_PLAYING elif self.media_status.player_is_paused: return STATE_PAUSED elif self.media_status.player_is_idle: return STATE_IDLE elif self.cast.is_idle: return STATE_OFF else: return STATE_UNKNOWN @property def volume_level(self): """ Volume level of the media player (0..1). """ return self.cast_status.volume_level if self.cast_status else None @property def is_volume_muted(self): """ Boolean if volume is currently muted. """ return self.cast_status.volume_muted if self.cast_status else None @property def media_content_id(self): """ Content ID of current playing media. """ return self.media_status.content_id if self.media_status else None @property def media_content_type(self): """ Content type of current playing media. """ if self.media_status is None: return None elif self.media_status.media_is_tvshow: return MEDIA_TYPE_TVSHOW elif self.media_status.media_is_movie: return MEDIA_TYPE_VIDEO elif self.media_status.media_is_musictrack: return MEDIA_TYPE_MUSIC return None @property def media_duration(self): """ Duration of current playing media in seconds. """ return self.media_status.duration if self.media_status else None @property def media_image_url(self): """ Image url of current playing media. """ if self.media_status is None: return None images = self.media_status.images return images[0].url if images else None @property def media_title(self): """ Title of current playing media. """ return self.media_status.title if self.media_status else None @property def media_artist(self): """ Artist of current playing media. (Music track only) """ return self.media_status.artist if self.media_status else None @property def media_album(self): """ Album of current playing media. (Music track only) """ return self.media_status.album_name if self.media_status else None @property def media_album_artist(self): """ Album arist of current playing media. (Music track only) """ return self.media_status.album_artist if self.media_status else None @property def media_track(self): """ Track number of current playing media. (Music track only) """ return self.media_status.track if self.media_status else None @property def media_series_title(self): """ Series title of current playing media. (TV Show only)""" return self.media_status.series_title if self.media_status else None @property def media_season(self): """ Season of current playing media. (TV Show only) """ return self.media_status.season if self.media_status else None @property def media_episode(self): """ Episode of current playing media. (TV Show only) """ return self.media_status.episode if self.media_status else None @property def app_id(self): """ ID of the current running app. """ return self.cast.app_id @property def app_name(self): """ Name of the current running app. """ return self.cast.app_display_name @property def supported_media_commands(self): """ Flags of media commands that are supported. """ return SUPPORT_CAST def turn_on(self): """ Turns on the ChromeCast. """ # The only way we can turn the Chromecast is on is by launching an app if not self.cast.status or not self.cast.status.is_active_input: if self.cast.app_id: self.cast.quit_app() self.cast.play_media( CAST_SPLASH, cast.STREAM_TYPE_BUFFERED) def turn_off(self): """ Turns Chromecast off. """ self.cast.quit_app() def mute_volume(self, mute): """ mute the volume. """ self.cast.set_volume_muted(mute) def set_volume_level(self, volume): """ set volume level, range 0..1. """ self.cast.set_volume(volume) def media_play(self): """ Send play commmand. """ self.cast.media_controller.play() def media_pause(self): """ Send pause command. """ self.cast.media_controller.pause() def media_previous_track(self): """ Send previous track command. """ self.cast.media_controller.rewind() def media_next_track(self): """ Send next track command. """ self.cast.media_controller.skip() def media_seek(self, position): """ Seek the media to a specific location. """ self.cast.media_controller.seek(position) def play_media(self, media_type, media_id): """ Plays media from a URL """ self.cast.media_controller.play_media(media_id, media_type) def play_youtube(self, media_id): """ Plays a YouTube media. """ self.youtube.play_video(media_id) # implementation of chromecast status_listener methods def new_cast_status(self, status): """ Called when a new cast status is received. """ self.cast_status = status self.update_ha_state() def new_media_status(self, status): """ Called when a new media status is received. """ self.media_status = status self.update_ha_state()
mit
axinging/chromium-crosswalk
build/android/asan_symbolize.py
19
3445
#!/usr/bin/env python # # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import optparse import os import re import sys from pylib import constants from pylib.constants import host_paths # Uses symbol.py from third_party/android_platform, not python's. with host_paths.SysPath( host_paths.ANDROID_PLATFORM_DEVELOPMENT_SCRIPTS_PATH, position=0): import symbol _RE_ASAN = re.compile(r'(.*?)(#\S*?)\s+(\S*?)\s+\((.*?)\+(.*?)\)') def _ParseAsanLogLine(line): m = re.match(_RE_ASAN, line) if not m: return None return { 'prefix': m.group(1), 'library': m.group(4), 'pos': m.group(2), 'rel_address': '%08x' % int(m.group(5), 16), } def _FindASanLibraries(): asan_lib_dir = os.path.join(host_paths.DIR_SOURCE_ROOT, 'third_party', 'llvm-build', 'Release+Asserts', 'lib') asan_libs = [] for src_dir, _, files in os.walk(asan_lib_dir): asan_libs += [os.path.relpath(os.path.join(src_dir, f)) for f in files if f.endswith('.so')] return asan_libs def _TranslateLibPath(library, asan_libs): for asan_lib in asan_libs: if os.path.basename(library) == os.path.basename(asan_lib): return '/' + asan_lib # pylint: disable=no-member return symbol.TranslateLibPath(library) def _Symbolize(asan_input): asan_libs = _FindASanLibraries() libraries = collections.defaultdict(list) asan_lines = [] for asan_log_line in [a.rstrip() for a in asan_input]: m = _ParseAsanLogLine(asan_log_line) if m: libraries[m['library']].append(m) asan_lines.append({'raw_log': asan_log_line, 'parsed': m}) all_symbols = collections.defaultdict(dict) for library, items in libraries.iteritems(): libname = _TranslateLibPath(library, asan_libs) lib_relative_addrs = set([i['rel_address'] for i in items]) # pylint: disable=no-member info_dict = symbol.SymbolInformationForSet(libname, lib_relative_addrs, True) if info_dict: all_symbols[library]['symbols'] = info_dict for asan_log_line in asan_lines: m = asan_log_line['parsed'] if not m: print asan_log_line['raw_log'] continue if (m['library'] in all_symbols and m['rel_address'] in all_symbols[m['library']]['symbols']): s = all_symbols[m['library']]['symbols'][m['rel_address']][0] print '%s%s %s %s' % (m['prefix'], m['pos'], s[0], s[1]) else: print asan_log_line['raw_log'] def main(): parser = optparse.OptionParser() parser.add_option('-l', '--logcat', help='File containing adb logcat output with ASan stacks. ' 'Use stdin if not specified.') parser.add_option('--output-directory', help='Path to the root build directory.') options, _ = parser.parse_args() if options.output_directory: constants.SetOutputDirectory(options.output_directory) # Do an up-front test that the output directory is known. constants.CheckOutputDirectory() if options.logcat: asan_input = file(options.logcat, 'r') else: asan_input = sys.stdin _Symbolize(asan_input.readlines()) if __name__ == "__main__": sys.exit(main())
bsd-3-clause
andrewleech/SickRage
sickbeard/notifiers/synologynotifier.py
3
2926
# coding=utf-8 # Author: Nyaran <nyayukko@gmail.com> # # This file is part of SickRage. # # SickRage 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. # # SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function, unicode_literals import os import subprocess import sickbeard from sickbeard import logger from sickbeard import common from sickrage.helper.encoding import ek from sickrage.helper.exceptions import ex class Notifier(object): def notify_snatch(self, ep_name): if sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONSNATCH: self._send_synologyNotifier(ep_name, common.notifyStrings[common.NOTIFY_SNATCH]) def notify_download(self, ep_name): if sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONDOWNLOAD: self._send_synologyNotifier(ep_name, common.notifyStrings[common.NOTIFY_DOWNLOAD]) def notify_subtitle_download(self, ep_name, lang): if sickbeard.SYNOLOGYNOTIFIER_NOTIFY_ONSUBTITLEDOWNLOAD: self._send_synologyNotifier(ep_name + ": " + lang, common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD]) def notify_git_update(self, new_version="??"): if sickbeard.USE_SYNOLOGYNOTIFIER: update_text = common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] title = common.notifyStrings[common.NOTIFY_GIT_UPDATE] self._send_synologyNotifier(update_text + new_version, title) def notify_login(self, ipaddress=""): if sickbeard.USE_SYNOLOGYNOTIFIER: update_text = common.notifyStrings[common.NOTIFY_LOGIN_TEXT] title = common.notifyStrings[common.NOTIFY_LOGIN] self._send_synologyNotifier(update_text.format(ipaddress), title) def _send_synologyNotifier(self, message, title): synodsmnotify_cmd = ["/usr/syno/bin/synodsmnotify", "@administrators", title, message] logger.log("Executing command " + str(synodsmnotify_cmd)) logger.log("Absolute path to command: " + ek(os.path.abspath, synodsmnotify_cmd[0]), logger.DEBUG) try: p = subprocess.Popen(synodsmnotify_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=sickbeard.PROG_DIR) out, err = p.communicate() # @UnusedVariable logger.log("Script result: " + str(out), logger.DEBUG) except OSError as e: logger.log("Unable to run synodsmnotify: " + ex(e))
gpl-3.0
RouxRC/weboob
modules/lacentrale/test.py
7
1102
# -*- coding: utf-8 -*- # Copyright(C) 2014 Vicnet # # This file is part of weboob. # # weboob 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. # # weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>. from weboob.tools.test import BackendTest class LaCentraleTest(BackendTest): MODULE = 'lacentrale' def test_lacentrale(self): products = list(self.backend.search_products('1000€,pro')) self.assertTrue(len(products) > 0) product = products[0] prices = list(self.backend.iter_prices(product)) self.assertTrue(len(prices) > 0)
agpl-3.0
yusofm/scrapy
scrapy/http/request/form.py
23
6564
""" This module implements the FormRequest class which is a more convenient class (than Request) to generate Requests based on form data. See documentation in docs/topics/request-response.rst """ from six.moves.urllib.parse import urljoin, urlencode import lxml.html from parsel.selector import create_root_node import six from scrapy.http.request import Request from scrapy.utils.python import to_bytes, is_listlike class FormRequest(Request): def __init__(self, *args, **kwargs): formdata = kwargs.pop('formdata', None) if formdata and kwargs.get('method') is None: kwargs['method'] = 'POST' super(FormRequest, self).__init__(*args, **kwargs) if formdata: items = formdata.items() if isinstance(formdata, dict) else formdata querystr = _urlencode(items, self.encoding) if self.method == 'POST': self.headers.setdefault(b'Content-Type', b'application/x-www-form-urlencoded') self._set_body(querystr) else: self._set_url(self.url + ('&' if '?' in self.url else '?') + querystr) @classmethod def from_response(cls, response, formname=None, formid=None, formnumber=0, formdata=None, clickdata=None, dont_click=False, formxpath=None, **kwargs): kwargs.setdefault('encoding', response.encoding) form = _get_form(response, formname, formid, formnumber, formxpath) formdata = _get_inputs(form, formdata, dont_click, clickdata, response) url = _get_form_url(form, kwargs.pop('url', None)) method = kwargs.pop('method', form.method) return cls(url=url, method=method, formdata=formdata, **kwargs) def _get_form_url(form, url): if url is None: return form.action or form.base_url return urljoin(form.base_url, url) def _urlencode(seq, enc): values = [(to_bytes(k, enc), to_bytes(v, enc)) for k, vs in seq for v in (vs if is_listlike(vs) else [vs])] return urlencode(values, doseq=1) def _get_form(response, formname, formid, formnumber, formxpath): """Find the form element """ text = response.body_as_unicode() root = create_root_node(text, lxml.html.HTMLParser, base_url=response.url) forms = root.xpath('//form') if not forms: raise ValueError("No <form> element found in %s" % response) if formname is not None: f = root.xpath('//form[@name="%s"]' % formname) if f: return f[0] if formid is not None: f = root.xpath('//form[@id="%s"]' % formid) if f: return f[0] # Get form element from xpath, if not found, go up if formxpath is not None: nodes = root.xpath(formxpath) if nodes: el = nodes[0] while True: if el.tag == 'form': return el el = el.getparent() if el is None: break raise ValueError('No <form> element found with %s' % formxpath) # If we get here, it means that either formname was None # or invalid if formnumber is not None: try: form = forms[formnumber] except IndexError: raise IndexError("Form number %d not found in %s" % (formnumber, response)) else: return form def _get_inputs(form, formdata, dont_click, clickdata, response): try: formdata = dict(formdata or ()) except (ValueError, TypeError): raise ValueError('formdata should be a dict or iterable of tuples') inputs = form.xpath('descendant::textarea' '|descendant::select' '|descendant::input[@type!="submit" and @type!="image" and @type!="reset"' 'and ((@type!="checkbox" and @type!="radio") or @checked)]') values = [(k, u'' if v is None else v) for k, v in (_value(e) for e in inputs) if k and k not in formdata] if not dont_click: clickable = _get_clickable(clickdata, form) if clickable and clickable[0] not in formdata and not clickable[0] is None: values.append(clickable) values.extend(formdata.items()) return values def _value(ele): n = ele.name v = ele.value if ele.tag == 'select': return _select_value(ele, n, v) return n, v def _select_value(ele, n, v): multiple = ele.multiple if v is None and not multiple: # Match browser behaviour on simple select tag without options selected # And for select tags wihout options o = ele.value_options return (n, o[0]) if o else (None, None) elif v is not None and multiple: # This is a workround to bug in lxml fixed 2.3.1 # fix https://github.com/lxml/lxml/commit/57f49eed82068a20da3db8f1b18ae00c1bab8b12#L1L1139 selected_options = ele.xpath('.//option[@selected]') v = [(o.get('value') or o.text or u'').strip() for o in selected_options] return n, v def _get_clickable(clickdata, form): """ Returns the clickable element specified in clickdata, if the latter is given. If not, it returns the first clickable element found """ clickables = [el for el in form.xpath('.//input[@type="submit"]')] if not clickables: return # If we don't have clickdata, we just use the first clickable element if clickdata is None: el = clickables[0] return (el.name, el.value) # If clickdata is given, we compare it to the clickable elements to find a # match. We first look to see if the number is specified in clickdata, # because that uniquely identifies the element nr = clickdata.get('nr', None) if nr is not None: try: el = list(form.inputs)[nr] except IndexError: pass else: return (el.name, el.value) # We didn't find it, so now we build an XPath expression out of the other # arguments, because they can be used as such xpath = u'.//*' + \ u''.join(u'[@%s="%s"]' % c for c in six.iteritems(clickdata)) el = form.xpath(xpath) if len(el) == 1: return (el[0].name, el[0].value) elif len(el) > 1: raise ValueError("Multiple elements found (%r) matching the criteria " "in clickdata: %r" % (el, clickdata)) else: raise ValueError('No clickable element matching clickdata: %r' % (clickdata,))
bsd-3-clause
cloudbase/neutron
neutron/agent/common/ovs_lib.py
2
26628
# Copyright 2011 VMware, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import collections import itertools import operator import time import uuid from neutron_lib import exceptions from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils import six import tenacity from neutron._i18n import _, _LE, _LI, _LW from neutron.agent.common import utils from neutron.agent.linux import ip_lib from neutron.agent.ovsdb import api as ovsdb from neutron.conf.agent import ovs_conf from neutron.plugins.common import constants as p_const from neutron.plugins.ml2.drivers.openvswitch.agent.common \ import constants UINT64_BITMASK = (1 << 64) - 1 # Special return value for an invalid OVS ofport INVALID_OFPORT = -1 UNASSIGNED_OFPORT = [] # OVS bridge fail modes FAILMODE_SECURE = 'secure' FAILMODE_STANDALONE = 'standalone' ovs_conf.register_ovs_agent_opts() LOG = logging.getLogger(__name__) OVS_DEFAULT_CAPS = { 'datapath_types': [], 'iface_types': [], } def _ofport_result_pending(result): """Return True if ovs-vsctl indicates the result is still pending.""" # ovs-vsctl can return '[]' for an ofport that has not yet been assigned try: int(result) return False except (ValueError, TypeError): return True def _ofport_retry(fn): """Decorator for retrying when OVS has yet to assign an ofport. The instance's vsctl_timeout is used as the max waiting time. This relies on the fact that instance methods receive self as the first argument. """ @six.wraps(fn) def wrapped(*args, **kwargs): self = args[0] new_fn = tenacity.retry( reraise=True, retry=tenacity.retry_if_result(_ofport_result_pending), wait=tenacity.wait_exponential(multiplier=0.01, max=1), stop=tenacity.stop_after_delay( self.vsctl_timeout))(fn) return new_fn(*args, **kwargs) return wrapped class VifPort(object): def __init__(self, port_name, ofport, vif_id, vif_mac, switch): self.port_name = port_name self.ofport = ofport self.vif_id = vif_id self.vif_mac = vif_mac self.switch = switch def __str__(self): return ("iface-id=%s, vif_mac=%s, port_name=%s, ofport=%s, " "bridge_name=%s") % ( self.vif_id, self.vif_mac, self.port_name, self.ofport, self.switch.br_name) class BaseOVS(object): def __init__(self): self.vsctl_timeout = cfg.CONF.ovs_vsctl_timeout self.ovsdb = ovsdb.API.get(self) def add_bridge(self, bridge_name, datapath_type=constants.OVS_DATAPATH_SYSTEM): self.ovsdb.add_br(bridge_name, datapath_type).execute() return OVSBridge(bridge_name) def delete_bridge(self, bridge_name): self.ovsdb.del_br(bridge_name).execute() def bridge_exists(self, bridge_name): return self.ovsdb.br_exists(bridge_name).execute() def port_exists(self, port_name): cmd = self.ovsdb.db_get('Port', port_name, 'name') return bool(cmd.execute(check_error=False, log_errors=False)) def get_bridge_for_iface(self, iface): return self.ovsdb.iface_to_br(iface).execute() def get_bridges(self): return self.ovsdb.list_br().execute(check_error=True) def get_bridge_external_bridge_id(self, bridge): return self.ovsdb.br_get_external_id(bridge, 'bridge-id').execute() def set_db_attribute(self, table_name, record, column, value, check_error=False, log_errors=True): self.ovsdb.db_set(table_name, record, (column, value)).execute( check_error=check_error, log_errors=log_errors) def clear_db_attribute(self, table_name, record, column): self.ovsdb.db_clear(table_name, record, column).execute() def db_get_val(self, table, record, column, check_error=False, log_errors=True): return self.ovsdb.db_get(table, record, column).execute( check_error=check_error, log_errors=log_errors) @property def config(self): """A dict containing the only row from the root Open_vSwitch table This row contains several columns describing the Open vSwitch install and the system on which it is installed. Useful keys include: datapath_types: a list of supported datapath types iface_types: a list of supported interface types ovs_version: the OVS version """ return self.ovsdb.db_list("Open_vSwitch").execute()[0] @property def capabilities(self): _cfg = self.config return {k: _cfg.get(k, OVS_DEFAULT_CAPS[k]) for k in OVS_DEFAULT_CAPS} class OVSBridge(BaseOVS): def __init__(self, br_name, datapath_type=constants.OVS_DATAPATH_SYSTEM): super(OVSBridge, self).__init__() self.br_name = br_name self.datapath_type = datapath_type self._default_cookie = generate_random_cookie() @property def default_cookie(self): return self._default_cookie def set_agent_uuid_stamp(self, val): self._default_cookie = val def set_controller(self, controllers): self.ovsdb.set_controller(self.br_name, controllers).execute(check_error=True) def del_controller(self): self.ovsdb.del_controller(self.br_name).execute(check_error=True) def get_controller(self): return self.ovsdb.get_controller(self.br_name).execute( check_error=True) def _set_bridge_fail_mode(self, mode): self.ovsdb.set_fail_mode(self.br_name, mode).execute(check_error=True) def set_secure_mode(self): self._set_bridge_fail_mode(FAILMODE_SECURE) def set_standalone_mode(self): self._set_bridge_fail_mode(FAILMODE_STANDALONE) def set_protocols(self, protocols): self.set_db_attribute('Bridge', self.br_name, 'protocols', protocols, check_error=True) def create(self, secure_mode=False): with self.ovsdb.transaction() as txn: txn.add( self.ovsdb.add_br(self.br_name, datapath_type=self.datapath_type)) if secure_mode: txn.add(self.ovsdb.set_fail_mode(self.br_name, FAILMODE_SECURE)) def destroy(self): self.delete_bridge(self.br_name) def add_port(self, port_name, *interface_attr_tuples): with self.ovsdb.transaction() as txn: txn.add(self.ovsdb.add_port(self.br_name, port_name)) if interface_attr_tuples: txn.add(self.ovsdb.db_set('Interface', port_name, *interface_attr_tuples)) return self.get_port_ofport(port_name) def replace_port(self, port_name, *interface_attr_tuples): """Replace existing port or create it, and configure port interface.""" # NOTE(xiaohhui): If del_port is inside the transaction, there will # only be one command for replace_port. This will cause the new port # not be found by system, which will lead to Bug #1519926. self.ovsdb.del_port(port_name).execute() with self.ovsdb.transaction() as txn: txn.add(self.ovsdb.add_port(self.br_name, port_name, may_exist=False)) if interface_attr_tuples: txn.add(self.ovsdb.db_set('Interface', port_name, *interface_attr_tuples)) def delete_port(self, port_name): self.ovsdb.del_port(port_name, self.br_name).execute() def run_ofctl(self, cmd, args, process_input=None): full_args = ["ovs-ofctl", cmd, self.br_name] + args # TODO(kevinbenton): This error handling is really brittle and only # detects one specific type of failure. The callers of this need to # be refactored to expect errors so we can re-raise and they can # take appropriate action based on the type of error. for i in range(1, 11): try: return utils.execute(full_args, run_as_root=True, process_input=process_input) except Exception as e: if "failed to connect to socket" in str(e): LOG.debug("Failed to connect to OVS. Retrying " "in 1 second. Attempt: %s/10", i) time.sleep(1) continue LOG.error(_LE("Unable to execute %(cmd)s. Exception: " "%(exception)s"), {'cmd': full_args, 'exception': e}) break def count_flows(self): flow_list = self.run_ofctl("dump-flows", []).split("\n")[1:] return len(flow_list) - 1 def remove_all_flows(self): self.run_ofctl("del-flows", []) @_ofport_retry def _get_port_ofport(self, port_name): return self.db_get_val("Interface", port_name, "ofport") def get_port_ofport(self, port_name): """Get the port's assigned ofport, retrying if not yet assigned.""" ofport = INVALID_OFPORT try: ofport = self._get_port_ofport(port_name) except tenacity.RetryError: LOG.exception(_LE("Timed out retrieving ofport on port %s."), port_name) return ofport def get_datapath_id(self): return self.db_get_val('Bridge', self.br_name, 'datapath_id') def do_action_flows(self, action, kwargs_list): if action != 'del': for kw in kwargs_list: if 'cookie' not in kw: kw['cookie'] = self._default_cookie flow_strs = [_build_flow_expr_str(kw, action) for kw in kwargs_list] self.run_ofctl('%s-flows' % action, ['-'], '\n'.join(flow_strs)) def add_flow(self, **kwargs): self.do_action_flows('add', [kwargs]) def mod_flow(self, **kwargs): self.do_action_flows('mod', [kwargs]) def delete_flows(self, **kwargs): self.do_action_flows('del', [kwargs]) def dump_flows_for_table(self, table): return self.dump_flows_for(table=table) def dump_flows_for(self, **kwargs): retval = None if "cookie" in kwargs: kwargs["cookie"] = check_cookie_mask(str(kwargs["cookie"])) flow_str = ",".join("=".join([key, str(val)]) for key, val in kwargs.items()) flows = self.run_ofctl("dump-flows", [flow_str]) if flows: retval = '\n'.join(item for item in flows.splitlines() if 'NXST' not in item) return retval def dump_all_flows(self): return [f for f in self.run_ofctl("dump-flows", []).splitlines() if 'NXST' not in f] def deferred(self, **kwargs): return DeferredOVSBridge(self, **kwargs) def add_tunnel_port(self, port_name, remote_ip, local_ip, tunnel_type=p_const.TYPE_GRE, vxlan_udp_port=p_const.VXLAN_UDP_PORT, dont_fragment=True, tunnel_csum=False): attrs = [('type', tunnel_type)] # TODO(twilson) This is an OrderedDict solely to make a test happy options = collections.OrderedDict() vxlan_uses_custom_udp_port = ( tunnel_type == p_const.TYPE_VXLAN and vxlan_udp_port != p_const.VXLAN_UDP_PORT ) if vxlan_uses_custom_udp_port: options['dst_port'] = vxlan_udp_port options['df_default'] = str(dont_fragment).lower() options['remote_ip'] = remote_ip options['local_ip'] = local_ip options['in_key'] = 'flow' options['out_key'] = 'flow' if tunnel_csum: options['csum'] = str(tunnel_csum).lower() attrs.append(('options', options)) return self.add_port(port_name, *attrs) def add_patch_port(self, local_name, remote_name): attrs = [('type', 'patch'), ('options', {'peer': remote_name})] return self.add_port(local_name, *attrs) def get_iface_name_list(self): # get the interface name list for this bridge return self.ovsdb.list_ifaces(self.br_name).execute(check_error=True) def get_port_name_list(self): # get the port name list for this bridge return self.ovsdb.list_ports(self.br_name).execute(check_error=True) def get_port_stats(self, port_name): return self.db_get_val("Interface", port_name, "statistics") def get_xapi_iface_id(self, xs_vif_uuid): args = ["xe", "vif-param-get", "param-name=other-config", "param-key=nicira-iface-id", "uuid=%s" % xs_vif_uuid] try: return utils.execute(args, run_as_root=True).strip() except Exception as e: with excutils.save_and_reraise_exception(): LOG.error(_LE("Unable to execute %(cmd)s. " "Exception: %(exception)s"), {'cmd': args, 'exception': e}) def get_ports_attributes(self, table, columns=None, ports=None, check_error=True, log_errors=True, if_exists=False): port_names = ports or self.get_port_name_list() if not port_names: return [] return (self.ovsdb.db_list(table, port_names, columns=columns, if_exists=if_exists). execute(check_error=check_error, log_errors=log_errors)) # returns a VIF object for each VIF port def get_vif_ports(self, ofport_filter=None): edge_ports = [] port_info = self.get_ports_attributes( 'Interface', columns=['name', 'external_ids', 'ofport'], if_exists=True) for port in port_info: name = port['name'] external_ids = port['external_ids'] ofport = port['ofport'] if ofport_filter and ofport in ofport_filter: continue if "iface-id" in external_ids and "attached-mac" in external_ids: p = VifPort(name, ofport, external_ids["iface-id"], external_ids["attached-mac"], self) edge_ports.append(p) elif ("xs-vif-uuid" in external_ids and "attached-mac" in external_ids): # if this is a xenserver and iface-id is not automatically # synced to OVS from XAPI, we grab it from XAPI directly iface_id = self.get_xapi_iface_id(external_ids["xs-vif-uuid"]) p = VifPort(name, ofport, iface_id, external_ids["attached-mac"], self) edge_ports.append(p) return edge_ports def get_vif_port_to_ofport_map(self): results = self.get_ports_attributes( 'Interface', columns=['name', 'external_ids', 'ofport'], if_exists=True) port_map = {} for r in results: # fall back to basic interface name key = self.portid_from_external_ids(r['external_ids']) or r['name'] try: port_map[key] = int(r['ofport']) except TypeError: # port doesn't yet have an ofport entry so we ignore it pass return port_map def get_vif_port_set(self): edge_ports = set() results = self.get_ports_attributes( 'Interface', columns=['name', 'external_ids', 'ofport'], if_exists=True) for result in results: if result['ofport'] == UNASSIGNED_OFPORT: LOG.warning(_LW("Found not yet ready openvswitch port: %s"), result['name']) elif result['ofport'] == INVALID_OFPORT: LOG.warning(_LW("Found failed openvswitch port: %s"), result['name']) elif 'attached-mac' in result['external_ids']: port_id = self.portid_from_external_ids(result['external_ids']) if port_id: edge_ports.add(port_id) return edge_ports def portid_from_external_ids(self, external_ids): if 'iface-id' in external_ids: return external_ids['iface-id'] if 'xs-vif-uuid' in external_ids: iface_id = self.get_xapi_iface_id( external_ids['xs-vif-uuid']) return iface_id def get_port_tag_dict(self): """Get a dict of port names and associated vlan tags. e.g. the returned dict is of the following form:: {u'int-br-eth2': [], u'patch-tun': [], u'qr-76d9e6b6-21': 1, u'tapce5318ff-78': 1, u'tape1400310-e6': 1} The TAG ID is only available in the "Port" table and is not available in the "Interface" table queried by the get_vif_port_set() method. """ results = self.get_ports_attributes( 'Port', columns=['name', 'tag'], if_exists=True) return {p['name']: p['tag'] for p in results} def get_vifs_by_ids(self, port_ids): interface_info = self.get_ports_attributes( "Interface", columns=["name", "external_ids", "ofport"], if_exists=True) by_id = {x['external_ids'].get('iface-id'): x for x in interface_info} result = {} for port_id in port_ids: result[port_id] = None if port_id not in by_id: LOG.info(_LI("Port %(port_id)s not present in bridge " "%(br_name)s"), {'port_id': port_id, 'br_name': self.br_name}) continue pinfo = by_id[port_id] if not self._check_ofport(port_id, pinfo): continue mac = pinfo['external_ids'].get('attached-mac') result[port_id] = VifPort(pinfo['name'], pinfo['ofport'], port_id, mac, self) return result @staticmethod def _check_ofport(port_id, port_info): if port_info['ofport'] in [UNASSIGNED_OFPORT, INVALID_OFPORT]: LOG.warning(_LW("ofport: %(ofport)s for VIF: %(vif)s " "is not a positive integer"), {'ofport': port_info['ofport'], 'vif': port_id}) return False return True def get_vif_port_by_id(self, port_id): ports = self.ovsdb.db_find( 'Interface', ('external_ids', '=', {'iface-id': port_id}), ('external_ids', '!=', {'attached-mac': ''}), columns=['external_ids', 'name', 'ofport']).execute() for port in ports: if self.br_name != self.get_bridge_for_iface(port['name']): continue if not self._check_ofport(port_id, port): continue mac = port['external_ids'].get('attached-mac') return VifPort(port['name'], port['ofport'], port_id, mac, self) LOG.info(_LI("Port %(port_id)s not present in bridge %(br_name)s"), {'port_id': port_id, 'br_name': self.br_name}) def delete_ports(self, all_ports=False): if all_ports: port_names = self.get_port_name_list() else: port_names = (port.port_name for port in self.get_vif_ports()) for port_name in port_names: self.delete_port(port_name) def get_local_port_mac(self): """Retrieve the mac of the bridge's local port.""" address = ip_lib.IPDevice(self.br_name).link.address if address: return address else: msg = _('Unable to determine mac address for %s') % self.br_name raise Exception(msg) def set_controllers_connection_mode(self, connection_mode): """Set bridge controllers connection mode. :param connection_mode: "out-of-band" or "in-band" """ attr = [('connection_mode', connection_mode)] controllers = self.db_get_val('Bridge', self.br_name, 'controller') controllers = [controllers] if isinstance( controllers, uuid.UUID) else controllers with self.ovsdb.transaction(check_error=True) as txn: for controller_uuid in controllers: txn.add(self.ovsdb.db_set('Controller', controller_uuid, *attr)) def _set_egress_bw_limit_for_port(self, port_name, max_kbps, max_burst_kbps): with self.ovsdb.transaction(check_error=True) as txn: txn.add(self.ovsdb.db_set('Interface', port_name, ('ingress_policing_rate', max_kbps))) txn.add(self.ovsdb.db_set('Interface', port_name, ('ingress_policing_burst', max_burst_kbps))) def create_egress_bw_limit_for_port(self, port_name, max_kbps, max_burst_kbps): self._set_egress_bw_limit_for_port( port_name, max_kbps, max_burst_kbps) def get_egress_bw_limit_for_port(self, port_name): max_kbps = self.db_get_val('Interface', port_name, 'ingress_policing_rate') max_burst_kbps = self.db_get_val('Interface', port_name, 'ingress_policing_burst') max_kbps = max_kbps or None max_burst_kbps = max_burst_kbps or None return max_kbps, max_burst_kbps def delete_egress_bw_limit_for_port(self, port_name): self._set_egress_bw_limit_for_port( port_name, 0, 0) def __enter__(self): self.create() return self def __exit__(self, exc_type, exc_value, exc_tb): self.destroy() class DeferredOVSBridge(object): '''Deferred OVSBridge. This class wraps add_flow, mod_flow and delete_flows calls to an OVSBridge and defers their application until apply_flows call in order to perform bulk calls. It wraps also ALLOWED_PASSTHROUGHS calls to avoid mixing OVSBridge and DeferredOVSBridge uses. This class can be used as a context, in such case apply_flows is called on __exit__ except if an exception is raised. This class is not thread-safe, that's why for every use a new instance must be implemented. ''' ALLOWED_PASSTHROUGHS = 'add_port', 'add_tunnel_port', 'delete_port' def __init__(self, br, full_ordered=False, order=('add', 'mod', 'del')): '''Constructor. :param br: wrapped bridge :param full_ordered: Optional, disable flow reordering (slower) :param order: Optional, define in which order flow are applied ''' self.br = br self.full_ordered = full_ordered self.order = order if not self.full_ordered: self.weights = dict((y, x) for x, y in enumerate(self.order)) self.action_flow_tuples = [] def __getattr__(self, name): if name in self.ALLOWED_PASSTHROUGHS: return getattr(self.br, name) raise AttributeError(name) def add_flow(self, **kwargs): self.action_flow_tuples.append(('add', kwargs)) def mod_flow(self, **kwargs): self.action_flow_tuples.append(('mod', kwargs)) def delete_flows(self, **kwargs): self.action_flow_tuples.append(('del', kwargs)) def apply_flows(self): action_flow_tuples = self.action_flow_tuples self.action_flow_tuples = [] if not action_flow_tuples: return if not self.full_ordered: action_flow_tuples.sort(key=lambda af: self.weights[af[0]]) grouped = itertools.groupby(action_flow_tuples, key=operator.itemgetter(0)) itemgetter_1 = operator.itemgetter(1) for action, action_flow_list in grouped: flows = list(map(itemgetter_1, action_flow_list)) self.br.do_action_flows(action, flows) def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: self.apply_flows() else: LOG.exception(_LE("OVS flows could not be applied on bridge %s"), self.br.br_name) def _build_flow_expr_str(flow_dict, cmd): flow_expr_arr = [] actions = None if cmd == 'add': flow_expr_arr.append("hard_timeout=%s" % flow_dict.pop('hard_timeout', '0')) flow_expr_arr.append("idle_timeout=%s" % flow_dict.pop('idle_timeout', '0')) flow_expr_arr.append("priority=%s" % flow_dict.pop('priority', '1')) elif 'priority' in flow_dict: msg = _("Cannot match priority on flow deletion or modification") raise exceptions.InvalidInput(error_message=msg) if cmd != 'del': if "actions" not in flow_dict: msg = _("Must specify one or more actions on flow addition" " or modification") raise exceptions.InvalidInput(error_message=msg) actions = "actions=%s" % flow_dict.pop('actions') for key, value in six.iteritems(flow_dict): if key == 'proto': flow_expr_arr.append(value) else: flow_expr_arr.append("%s=%s" % (key, str(value))) if actions: flow_expr_arr.append(actions) return ','.join(flow_expr_arr) def generate_random_cookie(): return uuid.uuid4().int & UINT64_BITMASK def check_cookie_mask(cookie): if '/' not in cookie: return cookie + '/-1' else: return cookie
apache-2.0
Tejeshwarabm/Westwood
src/tap-bridge/bindings/modulegen__gcc_ILP32.py
19
283308
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.tap_bridge', 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') ## data-rate.h (module 'network'): ns3::DataRate [class] module.add_class('DataRate', import_from_module='ns.network') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', 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-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## 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') ## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper [class] module.add_class('TapBridgeHelper') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## 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::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::FdReader', 'ns3::empty', 'ns3::DefaultDeleter<ns3::FdReader>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::SystemThread', 'ns3::empty', 'ns3::DefaultDeleter<ns3::SystemThread>'], 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')) ## system-thread.h (module 'core'): ns3::SystemThread [class] module.add_class('SystemThread', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## data-rate.h (module 'network'): ns3::DataRateChecker [class] module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## data-rate.h (module 'network'): ns3::DataRateValue [class] module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## 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> >']) ## unix-fd-reader.h (module 'core'): ns3::FdReader [class] module.add_class('FdReader', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## net-device.h (module 'network'): ns3::NetDeviceQueue [class] module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface [class] module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object']) ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## net-device.h (module 'network'): ns3::QueueItem [class] module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) ## net-device.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration] module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network') ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge [class] module.add_class('TapBridge', parent=root_module['ns3::NetDevice']) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::Mode [enumeration] module.add_enum('Mode', ['ILLEGAL', 'CONFIGURE_LOCAL', 'USE_LOCAL', 'USE_BRIDGE'], outer_class=root_module['ns3::TapBridge']) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridgeFdReader [class] module.add_class('TapBridgeFdReader', parent=root_module['ns3::FdReader']) ## 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']) ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&') def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) 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_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TapBridgeHelper_methods(root_module, root_module['ns3::TapBridgeHelper']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_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__Ns3FdReader_Ns3Empty_Ns3DefaultDeleter__lt__ns3FdReader__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) register_Ns3SimpleRefCount__Ns3SystemThread_Ns3Empty_Ns3DefaultDeleter__lt__ns3SystemThread__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3SystemThread_methods(root_module, root_module['ns3::SystemThread']) 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_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker']) register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue']) register_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3FdReader_methods(root_module, root_module['ns3::FdReader']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue']) register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem']) register_Ns3TapBridge_methods(root_module, root_module['ns3::TapBridge']) register_Ns3TapBridgeFdReader_methods(root_module, root_module['ns3::TapBridgeFdReader']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') return def register_Ns3DataRate_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('>=') ## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRate const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor] cls.add_constructor([param('uint64_t', 'bps')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor] cls.add_constructor([param('std::string', 'rate')]) ## data-rate.h (module 'network'): ns3::Time ns3::DataRate::CalculateBitsTxTime(uint32_t bits) const [member function] cls.add_method('CalculateBitsTxTime', 'ns3::Time', [param('uint32_t', 'bits')], is_const=True) ## data-rate.h (module 'network'): ns3::Time ns3::DataRate::CalculateBytesTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateBytesTxTime', 'ns3::Time', [param('uint32_t', 'bytes')], is_const=True) ## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateTxTime', 'double', [param('uint32_t', 'bytes')], deprecated=True, is_const=True) ## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function] cls.add_method('GetBitRate', 'uint64_t', [], is_const=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_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', [], deprecated=True, is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 21 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_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_Ns3TapBridgeHelper_methods(root_module, cls): ## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper::TapBridgeHelper(ns3::TapBridgeHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::TapBridgeHelper const &', 'arg0')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper::TapBridgeHelper() [constructor] cls.add_constructor([]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::TapBridgeHelper::TapBridgeHelper(ns3::Ipv4Address gateway) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'gateway')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::NetDevice> nd) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::NetDevice >', 'nd')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(std::string nodeName, ns3::Ptr<ns3::NetDevice> nd) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('std::string', 'nodeName'), param('ns3::Ptr< ns3::NetDevice >', 'nd')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(ns3::Ptr<ns3::Node> node, std::string ndName) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('ns3::Ptr< ns3::Node >', 'node'), param('std::string', 'ndName')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(std::string nodeName, std::string ndName) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('std::string', 'nodeName'), param('std::string', 'ndName')]) ## tap-bridge-helper.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridgeHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::NetDevice> nd, ns3::AttributeValue const & bridgeType) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::NetDevice >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('ns3::AttributeValue const &', 'bridgeType')]) ## tap-bridge-helper.h (module 'tap-bridge'): void ns3::TapBridgeHelper::SetAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [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'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## 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, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [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'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')], deprecated=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function] cls.add_method('GetSize', 'std::size_t', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function] cls.add_method('SetSize', 'ns3::TypeId', [param('std::size_t', 'size')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t uid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'uid')]) 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) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable] cls.add_instance_attribute('callback', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): bool ns3::Object::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3FdReader_Ns3Empty_Ns3DefaultDeleter__lt__ns3FdReader__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::SimpleRefCount(ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::FdReader, ns3::empty, ns3::DefaultDeleter< ns3::FdReader > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::FdReader, ns3::empty, ns3::DefaultDeleter<ns3::FdReader> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3SystemThread_Ns3Empty_Ns3DefaultDeleter__lt__ns3SystemThread__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::SimpleRefCount(ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::SystemThread, ns3::empty, ns3::DefaultDeleter< ns3::SystemThread > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::SystemThread, ns3::empty, ns3::DefaultDeleter<ns3::SystemThread> >::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_Ns3SystemThread_methods(root_module, cls): ## system-thread.h (module 'core'): ns3::SystemThread::SystemThread(ns3::SystemThread const & arg0) [copy constructor] cls.add_constructor([param('ns3::SystemThread const &', 'arg0')]) ## system-thread.h (module 'core'): ns3::SystemThread::SystemThread(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [constructor] cls.add_constructor([param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## system-thread.h (module 'core'): static bool ns3::SystemThread::Equals(pthread_t id) [member function] cls.add_method('Equals', 'bool', [param('pthread_t', 'id')], is_static=True) ## system-thread.h (module 'core'): void ns3::SystemThread::Join() [member function] cls.add_method('Join', 'void', []) ## system-thread.h (module 'core'): static pthread_t ns3::SystemThread::Self() [member function] cls.add_method('Self', 'pthread_t', [], is_static=True) ## system-thread.h (module 'core'): void ns3::SystemThread::Start() [member function] cls.add_method('Start', 'void', []) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3DataRateChecker_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')]) return def register_Ns3DataRateValue_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor] cls.add_constructor([param('ns3::DataRate const &', 'value')]) ## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): bool ns3::DataRateValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function] cls.add_method('Get', 'ns3::DataRate', [], is_const=True) ## data-rate.h (module 'network'): std::string ns3::DataRateValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function] cls.add_method('Set', 'void', [param('ns3::DataRate const &', 'value')]) return def register_Ns3EmptyAttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::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_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::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_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_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_Ns3FdReader_methods(root_module, cls): ## unix-fd-reader.h (module 'core'): ns3::FdReader::FdReader(ns3::FdReader const & arg0) [copy constructor] cls.add_constructor([param('ns3::FdReader const &', 'arg0')]) ## unix-fd-reader.h (module 'core'): ns3::FdReader::FdReader() [constructor] cls.add_constructor([]) ## unix-fd-reader.h (module 'core'): void ns3::FdReader::Start(int fd, ns3::Callback<void, unsigned char*, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> readCallback) [member function] cls.add_method('Start', 'void', [param('int', 'fd'), param('ns3::Callback< void, unsigned char *, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'readCallback')]) ## unix-fd-reader.h (module 'core'): void ns3::FdReader::Stop() [member function] cls.add_method('Stop', 'void', []) ## unix-fd-reader.h (module 'core'): ns3::FdReader::Data ns3::FdReader::DoRead() [member function] cls.add_method('DoRead', 'ns3::FdReader::Data', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NetDeviceQueue_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::Ptr<ns3::QueueLimits> ns3::NetDeviceQueue::GetQueueLimits() [member function] cls.add_method('GetQueueLimits', 'ns3::Ptr< ns3::QueueLimits >', []) ## net-device.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function] cls.add_method('IsStopped', 'bool', [], is_const=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyQueuedBytes(uint32_t bytes) [member function] cls.add_method('NotifyQueuedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyTransmittedBytes(uint32_t bytes) [member function] cls.add_method('NotifyTransmittedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::ResetQueueLimits() [member function] cls.add_method('ResetQueueLimits', 'void', []) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetQueueLimits(ns3::Ptr<ns3::QueueLimits> ql) [member function] cls.add_method('SetQueueLimits', 'void', [param('ns3::Ptr< ns3::QueueLimits >', 'ql')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetWakeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function] cls.add_method('Wake', 'void', [], is_virtual=True) return def register_Ns3NetDeviceQueueInterface_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::CreateTxQueues() [member function] cls.add_method('CreateTxQueues', 'void', []) ## net-device.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function] cls.add_method('GetNTxQueues', 'uint8_t', [], is_const=True) ## net-device.h (module 'network'): ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function] cls.add_method('GetSelectQueueCallback', 'ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(uint8_t i) const [member function] cls.add_method('GetTxQueue', 'ns3::Ptr< ns3::NetDeviceQueue >', [param('uint8_t', 'i')], is_const=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetSelectQueueCallback', 'void', [param('ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function] cls.add_method('SetTxQueuesN', 'void', [param('uint8_t', 'numTxQueues')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): ns3::Time ns3::Node::GetLocalTime() const [member function] cls.add_method('GetLocalTime', 'ns3::Time', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) ## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function] cls.add_method('ToString', 'std::string', [], is_const=True) return def register_Ns3QueueItem_methods(root_module, cls): cls.add_output_stream_operator() ## net-device.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')]) ## net-device.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## net-device.h (module 'network'): uint32_t ns3::QueueItem::GetPacketSize() const [member function] cls.add_method('GetPacketSize', 'uint32_t', [], is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function] cls.add_method('GetUint8Value', 'bool', [param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')], is_const=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) return def register_Ns3TapBridge_methods(root_module, cls): ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::TapBridge(ns3::TapBridge const & arg0) [copy constructor] cls.add_constructor([param('ns3::TapBridge const &', 'arg0')]) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::TapBridge() [constructor] cls.add_constructor([]) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Ptr<ns3::NetDevice> ns3::TapBridge::GetBridgedNetDevice() [member function] cls.add_method('GetBridgedNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Ptr<ns3::Channel> ns3::TapBridge::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): uint32_t ns3::TapBridge::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridge::Mode ns3::TapBridge::GetMode() [member function] cls.add_method('GetMode', 'ns3::TapBridge::Mode', []) ## tap-bridge.h (module 'tap-bridge'): uint16_t ns3::TapBridge::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Address ns3::TapBridge::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): ns3::Ptr<ns3::Node> ns3::TapBridge::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): static ns3::TypeId ns3::TapBridge::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetBridgedNetDevice(ns3::Ptr<ns3::NetDevice> bridgedDevice) [member function] cls.add_method('SetBridgedNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'bridgedDevice')]) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetMode(ns3::TapBridge::Mode mode) [member function] cls.add_method('SetMode', 'void', [param('ns3::TapBridge::Mode', 'mode')]) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::Start(ns3::Time tStart) [member function] cls.add_method('Start', 'void', [param('ns3::Time', 'tStart')]) ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::Stop(ns3::Time tStop) [member function] cls.add_method('Stop', 'void', [param('ns3::Time', 'tStop')]) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::DiscardFromBridgedDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Address const & src) [member function] cls.add_method('DiscardFromBridgedDevice', 'bool', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'src')], visibility='protected') ## tap-bridge.h (module 'tap-bridge'): void ns3::TapBridge::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## tap-bridge.h (module 'tap-bridge'): bool ns3::TapBridge::ReceiveFromBridgedDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Address const & src, ns3::Address const & dst, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('ReceiveFromBridgedDevice', 'bool', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'src'), param('ns3::Address const &', 'dst'), param('ns3::NetDevice::PacketType', 'packetType')], visibility='protected') return def register_Ns3TapBridgeFdReader_methods(root_module, cls): ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridgeFdReader::TapBridgeFdReader() [constructor] cls.add_constructor([]) ## tap-bridge.h (module 'tap-bridge'): ns3::TapBridgeFdReader::TapBridgeFdReader(ns3::TapBridgeFdReader const & arg0) [copy constructor] cls.add_constructor([param('ns3::TapBridgeFdReader const &', 'arg0')]) ## tap-bridge.h (module 'tap-bridge'): ns3::FdReader::Data ns3::TapBridgeFdReader::DoRead() [member function] cls.add_method('DoRead', 'ns3::FdReader::Data', [], visibility='private', is_virtual=True) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
gpl-2.0
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.0/Lib/plat-irix5/TERMIOS.py
4
10049
# Generated by h2py from /usr/include/sys/termios.h # Included from sys/ttydev.h B0 = 0 B50 = 0000001 B75 = 0000002 B110 = 0000003 B134 = 0000004 B150 = 0000005 B200 = 0000006 B300 = 0000007 B600 = 0000010 B1200 = 0000011 B1800 = 0000012 B2400 = 0000013 B4800 = 0000014 B9600 = 0000015 B19200 = 0000016 EXTA = 0000016 B38400 = 0000017 EXTB = 0000017 # Included from sys/types.h # Included from sgidefs.h _MIPS_ISA_MIPS1 = 1 _MIPS_ISA_MIPS2 = 2 _MIPS_ISA_MIPS3 = 3 _MIPS_ISA_MIPS4 = 4 _MIPS_SIM_ABI32 = 1 _MIPS_SIM_NABI32 = 2 _MIPS_SIM_ABI64 = 3 P_MYID = (-1) P_MYHOSTID = (-1) # Included from sys/bsd_types.h # Included from sys/mkdev.h ONBITSMAJOR = 7 ONBITSMINOR = 8 OMAXMAJ = 0x7f OMAXMIN = 0xff NBITSMAJOR = 14 NBITSMINOR = 18 MAXMAJ = 0x1ff MAXMIN = 0x3ffff OLDDEV = 0 NEWDEV = 1 MKDEV_VER = NEWDEV def major(dev): return __major(MKDEV_VER, dev) def minor(dev): return __minor(MKDEV_VER, dev) # Included from sys/select.h FD_SETSIZE = 1024 NBBY = 8 _POSIX_VDISABLE = 0 def CTRL(c): return ((c)&037) IBSHIFT = 16 NCC = 8 NCCS = 23 VINTR = 0 VQUIT = 1 VERASE = 2 VKILL = 3 VEOF = 4 VEOL = 5 VEOL2 = 6 VMIN = 4 VTIME = 5 VSWTCH = 7 VSTART = 8 VSTOP = 9 VSUSP = 10 VDSUSP = 11 VREPRINT = 12 VDISCARD = 13 VWERASE = 14 VLNEXT = 15 VRPRNT = VREPRINT VFLUSHO = VDISCARD VCEOF = NCC VCEOL = (NCC + 1) CNUL = 0 CDEL = 0377 CESC = ord('\\') CINTR = 0177 CQUIT = 034 CERASE = CTRL(ord('H')) CKILL = CTRL(ord('U')) CEOL = 0 CEOL2 = 0 CEOF = CTRL(ord('d')) CEOT = CEOF CSTART = CTRL(ord('q')) CSTOP = CTRL(ord('s')) CSWTCH = CTRL(ord('z')) CNSWTCH = 0 CSUSP = CSWTCH CLNEXT = CTRL(ord('v')) CWERASE = CTRL(ord('w')) CFLUSHO = CTRL(ord('o')) CFLUSH = CFLUSHO CRPRNT = CTRL(ord('r')) CDSUSP = CTRL(ord('y')) CBRK = 0377 IGNBRK = 0000001 BRKINT = 0000002 IGNPAR = 0000004 PARMRK = 0000010 INPCK = 0000020 ISTRIP = 0000040 INLCR = 0000100 IGNCR = 0000200 ICRNL = 0000400 IUCLC = 0001000 IXON = 0002000 IXANY = 0004000 IXOFF = 0010000 IMAXBEL = 0020000 IBLKMD = 0040000 OPOST = 0000001 OLCUC = 0000002 ONLCR = 0000004 OCRNL = 0000010 ONOCR = 0000020 ONLRET = 0000040 OFILL = 0000100 OFDEL = 0000200 NLDLY = 0000400 NL0 = 0 NL1 = 0000400 CRDLY = 0003000 CR0 = 0 CR1 = 0001000 CR2 = 0002000 CR3 = 0003000 TABDLY = 0014000 TAB0 = 0 TAB1 = 0004000 TAB2 = 0010000 TAB3 = 0014000 XTABS = 0014000 BSDLY = 0020000 BS0 = 0 BS1 = 0020000 VTDLY = 0040000 VT0 = 0 VT1 = 0040000 FFDLY = 0100000 FF0 = 0 FF1 = 0100000 PAGEOUT = 0200000 WRAP = 0400000 CBAUD = 000000017 CSIZE = 000000060 CS5 = 0 CS6 = 000000020 CS7 = 000000040 CS8 = 000000060 CSTOPB = 000000100 CREAD = 000000200 PARENB = 000000400 PARODD = 000001000 HUPCL = 000002000 CLOCAL = 000004000 RCV1EN = 000010000 XMT1EN = 000020000 LOBLK = 000040000 XCLUDE = 000100000 CIBAUD = 003600000 PAREXT = 004000000 CNEW_RTSCTS = 010000000 ISIG = 0000001 ICANON = 0000002 XCASE = 0000004 ECHO = 0000010 ECHOE = 0000020 ECHOK = 0000040 ECHONL = 0000100 NOFLSH = 0000200 IEXTEN = 0000400 ITOSTOP = 0100000 TOSTOP = ITOSTOP ECHOCTL = 0001000 ECHOPRT = 0002000 ECHOKE = 0004000 DEFECHO = 0010000 FLUSHO = 0020000 PENDIN = 0040000 TIOC = (ord('T')<<8) TCGETA = (TIOC|1) TCSETA = (TIOC|2) TCSETAW = (TIOC|3) TCSETAF = (TIOC|4) TCSBRK = (TIOC|5) TCXONC = (TIOC|6) TCFLSH = (TIOC|7) # Included from sys/ioctl.h IOCTYPE = 0xff00 LIOC = (ord('l')<<8) LIOCGETP = (LIOC|1) LIOCSETP = (LIOC|2) LIOCGETS = (LIOC|5) LIOCSETS = (LIOC|6) DIOC = (ord('d')<<8) DIOCGETC = (DIOC|1) DIOCGETB = (DIOC|2) DIOCSETE = (DIOC|3) # Included from sys/ioccom.h IOCPARM_MASK = 0xff IOC_VOID = 0x20000000 IOC_OUT = 0x40000000 IOC_IN = 0x80000000 IOC_INOUT = (IOC_IN|IOC_OUT) # Included from net/soioctl.h # Included from sys/termio.h # Included from sys/termios.h _POSIX_VDISABLE = 0 def CTRL(c): return ((c)&037) IBSHIFT = 16 NCC = 8 NCCS = 23 VINTR = 0 VQUIT = 1 VERASE = 2 VKILL = 3 VEOF = 4 VEOL = 5 VEOL2 = 6 VMIN = 4 VTIME = 5 VSWTCH = 7 VSTART = 8 VSTOP = 9 VSUSP = 10 VDSUSP = 11 VREPRINT = 12 VDISCARD = 13 VWERASE = 14 VLNEXT = 15 VRPRNT = VREPRINT VFLUSHO = VDISCARD VCEOF = NCC VCEOL = (NCC + 1) CNUL = 0 CDEL = 0377 CESC = ord('\\') CINTR = 0177 CQUIT = 034 CERASE = CTRL(ord('H')) CKILL = CTRL(ord('U')) CEOL = 0 CEOL2 = 0 CEOF = CTRL(ord('d')) CEOT = CEOF CSTART = CTRL(ord('q')) CSTOP = CTRL(ord('s')) CSWTCH = CTRL(ord('z')) CNSWTCH = 0 CSUSP = CSWTCH CLNEXT = CTRL(ord('v')) CWERASE = CTRL(ord('w')) CFLUSHO = CTRL(ord('o')) CFLUSH = CFLUSHO CRPRNT = CTRL(ord('r')) CDSUSP = CTRL(ord('y')) CBRK = 0377 IGNBRK = 0000001 BRKINT = 0000002 IGNPAR = 0000004 PARMRK = 0000010 INPCK = 0000020 ISTRIP = 0000040 INLCR = 0000100 IGNCR = 0000200 ICRNL = 0000400 IUCLC = 0001000 IXON = 0002000 IXANY = 0004000 IXOFF = 0010000 IMAXBEL = 0020000 IBLKMD = 0040000 OPOST = 0000001 OLCUC = 0000002 ONLCR = 0000004 OCRNL = 0000010 ONOCR = 0000020 ONLRET = 0000040 OFILL = 0000100 OFDEL = 0000200 NLDLY = 0000400 NL0 = 0 NL1 = 0000400 CRDLY = 0003000 CR0 = 0 CR1 = 0001000 CR2 = 0002000 CR3 = 0003000 TABDLY = 0014000 TAB0 = 0 TAB1 = 0004000 TAB2 = 0010000 TAB3 = 0014000 XTABS = 0014000 BSDLY = 0020000 BS0 = 0 BS1 = 0020000 VTDLY = 0040000 VT0 = 0 VT1 = 0040000 FFDLY = 0100000 FF0 = 0 FF1 = 0100000 PAGEOUT = 0200000 WRAP = 0400000 CBAUD = 000000017 CSIZE = 000000060 CS5 = 0 CS6 = 000000020 CS7 = 000000040 CS8 = 000000060 CSTOPB = 000000100 CREAD = 000000200 PARENB = 000000400 PARODD = 000001000 HUPCL = 000002000 CLOCAL = 000004000 RCV1EN = 000010000 XMT1EN = 000020000 LOBLK = 000040000 XCLUDE = 000100000 CIBAUD = 003600000 PAREXT = 004000000 CNEW_RTSCTS = 010000000 ISIG = 0000001 ICANON = 0000002 XCASE = 0000004 ECHO = 0000010 ECHOE = 0000020 ECHOK = 0000040 ECHONL = 0000100 NOFLSH = 0000200 IEXTEN = 0000400 ITOSTOP = 0100000 TOSTOP = ITOSTOP ECHOCTL = 0001000 ECHOPRT = 0002000 ECHOKE = 0004000 DEFECHO = 0010000 FLUSHO = 0020000 PENDIN = 0040000 TIOC = (ord('T')<<8) TCGETA = (TIOC|1) TCSETA = (TIOC|2) TCSETAW = (TIOC|3) TCSETAF = (TIOC|4) TCSBRK = (TIOC|5) TCXONC = (TIOC|6) TCFLSH = (TIOC|7) LDISC0 = 0 LDISC1 = 1 NTTYDISC = LDISC1 TIOCFLUSH = (TIOC|12) TCSETLABEL = (TIOC|31) TCDSET = (TIOC|32) TCBLKMD = (TIOC|33) TIOCPKT = (TIOC|112) TIOCPKT_DATA = 0x00 TIOCPKT_FLUSHREAD = 0x01 TIOCPKT_FLUSHWRITE = 0x02 TIOCPKT_NOSTOP = 0x10 TIOCPKT_DOSTOP = 0x20 TIOCPKT_IOCTL = 0x40 TIOCNOTTY = (TIOC|113) TIOCSTI = (TIOC|114) TFIOC = (ord('F')<<8) oFIONREAD = (TFIOC|127) TO_STOP = LOBLK IOCTYPE = 0xff00 TCGETS = (TIOC|13) TCSETS = (TIOC|14) TCSETSW = (TIOC|15) TCSETSF = (TIOC|16) TCSANOW = ((ord('T')<<8)|14) TCSADRAIN = ((ord('T')<<8)|15) TCSAFLUSH = ((ord('T')<<8)|16) TCIFLUSH = 0 TCOFLUSH = 1 TCIOFLUSH = 2 TCOOFF = 0 TCOON = 1 TCIOFF = 2 TCION = 3 tIOC = (ord('t')<<8) TIOCGETD = (tIOC|0) TIOCSETD = (tIOC|1) TIOCHPCL = (tIOC|2) TIOCGETP = (tIOC|8) TIOCSETP = (tIOC|9) TIOCSETN = (tIOC|10) TIOCEXCL = (tIOC|13) TIOCNXCL = (tIOC|14) TIOCSETC = (tIOC|17) TIOCGETC = (tIOC|18) TIOCLBIS = (tIOC|127) TIOCLBIC = (tIOC|126) TIOCLSET = (tIOC|125) TIOCLGET = (tIOC|124) TIOCSBRK = (tIOC|123) TIOCCBRK = (tIOC|122) TIOCSDTR = (tIOC|121) TIOCCDTR = (tIOC|120) TIOCSLTC = (tIOC|117) TIOCGLTC = (tIOC|116) TIOCOUTQ = (tIOC|115) TIOCSTOP = (tIOC|111) TIOCSTART = (tIOC|110) TIOCGSID = (tIOC|22) TIOCSSID = (tIOC|24) TIOCMSET = (tIOC|26) TIOCMBIS = (tIOC|27) TIOCMBIC = (tIOC|28) TIOCMGET = (tIOC|29) TIOCM_LE = 0001 TIOCM_DTR = 0002 TIOCM_RTS = 0004 TIOCM_ST = 0010 TIOCM_SR = 0020 TIOCM_CTS = 0040 TIOCM_CAR = 0100 TIOCM_CD = TIOCM_CAR TIOCM_RNG = 0200 TIOCM_RI = TIOCM_RNG TIOCM_DSR = 0400 TIOCREMOTE = (tIOC|30) TIOCSIGNAL = (tIOC|31) ISPTM = ((ord('P')<<8)|1) UNLKPT = ((ord('P')<<8)|2) SVR4SOPEN = ((ord('P')<<8)|100) LDIOC = (ord('D')<<8) LDOPEN = (LDIOC|0) LDCLOSE = (LDIOC|1) LDCHG = (LDIOC|2) LDGETT = (LDIOC|8) LDSETT = (LDIOC|9) LDSMAP = (LDIOC|10) LDGMAP = (LDIOC|11) LDNMAP = (LDIOC|12) DIOC = (ord('d')<<8) DIOCGETP = (DIOC|8) DIOCSETP = (DIOC|9) FIORDCHK = ((ord('f')<<8)|3) CLNEXT = CTRL(ord('v')) CWERASE = CTRL(ord('w')) CFLUSHO = CTRL(ord('o')) CFLUSH = CFLUSHO CRPRNT = CTRL(ord('r')) CDSUSP = CTRL(ord('y')) SSPEED = B9600 TERM_NONE = 0 TERM_TEC = 1 TERM_V61 = 2 TERM_V10 = 3 TERM_TEX = 4 TERM_D40 = 5 TERM_H45 = 6 TERM_D42 = 7 TM_NONE = 0000 TM_SNL = 0001 TM_ANL = 0002 TM_LCF = 0004 TM_CECHO = 0010 TM_CINVIS = 0020 TM_SET = 0200 LDISC0 = 0 LDISC1 = 1 NTTYDISC = LDISC1 TIOCFLUSH = (TIOC|12) TCSETLABEL = (TIOC|31) TCDSET = (TIOC|32) TCBLKMD = (TIOC|33) TIOCPKT = (TIOC|112) TIOCPKT_DATA = 0x00 TIOCPKT_FLUSHREAD = 0x01 TIOCPKT_FLUSHWRITE = 0x02 TIOCPKT_NOSTOP = 0x10 TIOCPKT_DOSTOP = 0x20 TIOCPKT_IOCTL = 0x40 TIOCNOTTY = (TIOC|113) TIOCSTI = (TIOC|114) TFIOC = (ord('F')<<8) oFIONREAD = (TFIOC|127) TO_STOP = LOBLK IOCTYPE = 0xff00 TCGETS = (TIOC|13) TCSETS = (TIOC|14) TCSETSW = (TIOC|15) TCSETSF = (TIOC|16) TCSANOW = ((ord('T')<<8)|14) TCSADRAIN = ((ord('T')<<8)|15) TCSAFLUSH = ((ord('T')<<8)|16) TCIFLUSH = 0 TCOFLUSH = 1 TCIOFLUSH = 2 TCOOFF = 0 TCOON = 1 TCIOFF = 2 TCION = 3 tIOC = (ord('t')<<8) TIOCGETD = (tIOC|0) TIOCSETD = (tIOC|1) TIOCHPCL = (tIOC|2) TIOCGETP = (tIOC|8) TIOCSETP = (tIOC|9) TIOCSETN = (tIOC|10) TIOCEXCL = (tIOC|13) TIOCNXCL = (tIOC|14) TIOCSETC = (tIOC|17) TIOCGETC = (tIOC|18) TIOCLBIS = (tIOC|127) TIOCLBIC = (tIOC|126) TIOCLSET = (tIOC|125) TIOCLGET = (tIOC|124) TIOCSBRK = (tIOC|123) TIOCCBRK = (tIOC|122) TIOCSDTR = (tIOC|121) TIOCCDTR = (tIOC|120) TIOCSLTC = (tIOC|117) TIOCGLTC = (tIOC|116) TIOCOUTQ = (tIOC|115) TIOCSTOP = (tIOC|111) TIOCSTART = (tIOC|110) TIOCGSID = (tIOC|22) TIOCSSID = (tIOC|24) TIOCMSET = (tIOC|26) TIOCMBIS = (tIOC|27) TIOCMBIC = (tIOC|28) TIOCMGET = (tIOC|29) TIOCM_LE = 0001 TIOCM_DTR = 0002 TIOCM_RTS = 0004 TIOCM_ST = 0010 TIOCM_SR = 0020 TIOCM_CTS = 0040 TIOCM_CAR = 0100 TIOCM_CD = TIOCM_CAR TIOCM_RNG = 0200 TIOCM_RI = TIOCM_RNG TIOCM_DSR = 0400 TIOCREMOTE = (tIOC|30) TIOCSIGNAL = (tIOC|31) ISPTM = ((ord('P')<<8)|1) UNLKPT = ((ord('P')<<8)|2) SVR4SOPEN = ((ord('P')<<8)|100) LDIOC = (ord('D')<<8) LDOPEN = (LDIOC|0) LDCLOSE = (LDIOC|1) LDCHG = (LDIOC|2) LDGETT = (LDIOC|8) LDSETT = (LDIOC|9) LDSMAP = (LDIOC|10) LDGMAP = (LDIOC|11) LDNMAP = (LDIOC|12) DIOC = (ord('d')<<8) DIOCGETP = (DIOC|8) DIOCSETP = (DIOC|9) FIORDCHK = ((ord('f')<<8)|3)
mit
smalyshev/pywikibot-core
tests/tests_tests.py
4
1398
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the tests package.""" # # (C) Pywikibot team, 2014 # # Distributed under the terms of the MIT license. from __future__ import absolute_import, unicode_literals __version__ = '$Id$' import pywikibot from tests.aspects import unittest, TestCase from tests.utils import allowed_failure class HttpServerProblemTestCase(TestCase): """Test HTTP status 502 causes this test class to be skipped.""" sites = { '502': { 'hostname': 'http://httpbin.org/status/502', } } def test_502(self): """Test a HTTP 502 response using http://httpbin.org/status/502.""" self.fail('The test framework should skip this test.') pass class TestPageAssert(TestCase): """Test page assertion methods.""" family = 'wikipedia' code = 'en' dry = True @allowed_failure def test_assertPageTitlesEqual(self): """Test assertPageTitlesEqual shows the second page title and '...'.""" pages = [pywikibot.Page(self.site, 'Foo'), pywikibot.Page(self.site, 'Bar'), pywikibot.Page(self.site, 'Baz')] self.assertPageTitlesEqual(pages, ['Foo'], self.site) if __name__ == "__main__": try: unittest.main() except SystemExit: pass
mit
mogoweb/webkit_for_android5.1
v8/test/test262/testcfg.py
2
5147
# Copyright 2011 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import test import os from os.path import join, exists import urllib import hashlib import tarfile TEST_262_ARCHIVE_REVISION = '3a890174343c' # This is the r309 revision. TEST_262_ARCHIVE_MD5 = 'be5d4cfbe69cef70430907b8f3a92b50' TEST_262_URL = 'http://hg.ecmascript.org/tests/test262/archive/%s.tar.bz2' TEST_262_HARNESS = ['sta.js'] class Test262TestCase(test.TestCase): def __init__(self, filename, path, context, root, mode, framework): super(Test262TestCase, self).__init__(context, path, mode) self.filename = filename self.framework = framework self.root = root def IsNegative(self): return '@negative' in self.GetSource() def GetLabel(self): return "%s test262 %s" % (self.mode, self.GetName()) def IsFailureOutput(self, output): if output.exit_code != 0: return True return 'FAILED!' in output.stdout def GetCommand(self): result = self.context.GetVmCommand(self, self.mode) result += self.framework result.append(self.filename) return result def GetName(self): return self.path[-1] def GetSource(self): return open(self.filename).read() class Test262TestConfiguration(test.TestConfiguration): def __init__(self, context, root): super(Test262TestConfiguration, self).__init__(context, root) def ListTests(self, current_path, path, mode, variant_flags): testroot = join(self.root, 'data', 'test', 'suite') harness = [join(self.root, 'data', 'test', 'harness', f) for f in TEST_262_HARNESS] harness += [join(self.root, 'harness-adapt.js')] tests = [] for root, dirs, files in os.walk(testroot): for dotted in [x for x in dirs if x.startswith('.')]: dirs.remove(dotted) dirs.sort() root_path = root[len(self.root):].split(os.path.sep) root_path = current_path + [x for x in root_path if x] files.sort() for file in files: if file.endswith('.js'): test_path = ['test262', file[:-3]] if self.Contains(path, test_path): test = Test262TestCase(join(root, file), test_path, self.context, self.root, mode, harness) tests.append(test) return tests def DownloadData(self): revision = TEST_262_ARCHIVE_REVISION archive_url = TEST_262_URL % revision archive_name = join(self.root, 'test262-%s.tar.bz2' % revision) directory_name = join(self.root, "test262-%s" % revision) if not exists(directory_name) or not exists(archive_name): if not exists(archive_name): print "Downloading test data from %s ..." % archive_url urllib.urlretrieve(archive_url, archive_name) if not exists(directory_name): print "Extracting test262-%s.tar.bz2 ..." % revision md5 = hashlib.md5() with open(archive_name,'rb') as f: for chunk in iter(lambda: f.read(8192), ''): md5.update(chunk) if md5.hexdigest() != TEST_262_ARCHIVE_MD5: raise Exception("Hash mismatch of test data file") archive = tarfile.open(archive_name, 'r:bz2') archive.extractall(join(self.root)) if not exists(join(self.root, 'data')): os.symlink(directory_name, join(self.root, 'data')) def GetBuildRequirements(self): return ['d8'] def GetTestStatus(self, sections, defs): status_file = join(self.root, 'test262.status') if exists(status_file): test.ReadConfigurationInto(status_file, sections, defs) def GetConfiguration(context, root): return Test262TestConfiguration(context, root)
apache-2.0
Lawrence-Liu/scikit-learn
sklearn/cluster/setup.py
263
1449
# Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # License: BSD 3 clause import os from os.path import join import numpy from sklearn._build_utils import get_blas_info def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration cblas_libs, blas_info = get_blas_info() libraries = [] if os.name == 'posix': cblas_libs.append('m') libraries.append('m') config = Configuration('cluster', parent_package, top_path) config.add_extension('_dbscan_inner', sources=['_dbscan_inner.cpp'], include_dirs=[numpy.get_include()], language="c++") config.add_extension('_hierarchical', sources=['_hierarchical.cpp'], language="c++", include_dirs=[numpy.get_include()], libraries=libraries) config.add_extension( '_k_means', libraries=cblas_libs, sources=['_k_means.c'], include_dirs=[join('..', 'src', 'cblas'), numpy.get_include(), blas_info.pop('include_dirs', [])], extra_compile_args=blas_info.pop('extra_compile_args', []), **blas_info ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
bsd-3-clause
askeing/servo
tests/wpt/web-platform-tests/service-workers/service-worker/navigation-preload/resources/redirect-scope.py
46
1342
def main(request, response): if "base" in request.GET: return [("Content-Type", "text/html")], "OK" type = request.GET.first("type") if type == "normal": response.status = 302 response.headers.append("Location", "redirect-redirected.html") response.headers.append("Custom-Header", "hello") return "" if type == "no-location": response.status = 302 response.headers.append("Custom-Header", "hello") return "" if type == "no-location-with-body": response.status = 302 response.headers.append("Content-Type", "text/html") response.headers.append("Custom-Header", "hello") return "<body>BODY</body>" if type == "redirect-to-scope": response.status = 302 response.headers.append("Location", "redirect-scope.py?type=redirect-to-scope2") return "" if type == "redirect-to-scope2": response.status = 302 response.headers.append("Location", "redirect-scope.py?type=redirect-to-scope3") return "" if type == "redirect-to-scope3": response.status = 302 response.headers.append("Location", "redirect-redirected.html") response.headers.append("Custom-Header", "hello") return ""
mpl-2.0
ltilve/chromium
tools/telemetry/telemetry/core/browser_options_unittest.py
20
4731
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import os import unittest from telemetry.core import browser_options class BrowserOptionsTest(unittest.TestCase): def testDefaults(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() parser.add_option('-x', action='store', default=3) parser.parse_args(['--browser', 'any']) self.assertEquals(options.x, 3) # pylint: disable=E1101 def testDefaultsPlusOverride(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() parser.add_option('-x', action='store', default=3) parser.parse_args(['--browser', 'any', '-x', 10]) self.assertEquals(options.x, 10) # pylint: disable=E1101 def testDefaultsDontClobberPresetValue(self): options = browser_options.BrowserFinderOptions() setattr(options, 'x', 7) parser = options.CreateParser() parser.add_option('-x', action='store', default=3) parser.parse_args(['--browser', 'any']) self.assertEquals(options.x, 7) # pylint: disable=E1101 def testCount0(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() parser.add_option('-x', action='count', dest='v') parser.parse_args(['--browser', 'any']) self.assertEquals(options.v, None) # pylint: disable=E1101 def testCount2(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() parser.add_option('-x', action='count', dest='v') parser.parse_args(['--browser', 'any', '-xx']) self.assertEquals(options.v, 2) # pylint: disable=E1101 def testOptparseMutabilityWhenSpecified(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() parser.add_option('-x', dest='verbosity', action='store_true') options_ret, _ = parser.parse_args(['--browser', 'any', '-x']) self.assertEquals(options_ret, options) self.assertTrue(options.verbosity) def testOptparseMutabilityWhenNotSpecified(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() parser.add_option('-x', dest='verbosity', action='store_true') options_ret, _ = parser.parse_args(['--browser', 'any']) self.assertEquals(options_ret, options) self.assertFalse(options.verbosity) def testProfileDirDefault(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() parser.parse_args(['--browser', 'any']) self.assertEquals(options.browser_options.profile_dir, None) def testProfileDir(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() # Need to use a directory that exists. current_dir = os.path.dirname(__file__) parser.parse_args(['--browser', 'any', '--profile-dir', current_dir]) self.assertEquals(options.browser_options.profile_dir, current_dir) def testExtraBrowserArgs(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() parser.parse_args(['--extra-browser-args=--foo --bar']) self.assertEquals(options.browser_options.extra_browser_args, set(['--foo', '--bar'])) def testUseDevToolsActivePort(self): options = browser_options.BrowserFinderOptions() parser = options.CreateParser() parser.parse_args(['--use-devtools-active-port']) self.assertEquals(options.browser_options.use_devtools_active_port, True) def testMergeDefaultValues(self): options = browser_options.BrowserFinderOptions() options.already_true = True options.already_false = False options.override_to_true = False options.override_to_false = True parser = optparse.OptionParser() parser.add_option('--already_true', action='store_true') parser.add_option('--already_false', action='store_true') parser.add_option('--unset', action='store_true') parser.add_option('--default_true', action='store_true', default=True) parser.add_option('--default_false', action='store_true', default=False) parser.add_option('--override_to_true', action='store_true', default=False) parser.add_option('--override_to_false', action='store_true', default=True) options.MergeDefaultValues(parser.get_default_values()) self.assertTrue(options.already_true) self.assertFalse(options.already_false) self.assertTrue(options.unset is None) self.assertTrue(options.default_true) self.assertFalse(options.default_false) self.assertFalse(options.override_to_true) self.assertTrue(options.override_to_false)
bsd-3-clause
frodrigo/osmose-backend
analysers/analyser_osmosis_highway_vs_building.py
4
16195
#!/usr/bin/env python #-*- coding: utf-8 -*- ########################################################################### ## ## ## Copyrights Etienne Chové <chove@crans.org> 2010 ## ## Frédéric Rodrigo <****@free.fr> 2011 ## ## ## ## 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 modules.OsmoseTranslation import T_ from .Analyser_Osmosis import Analyser_Osmosis sql00 = """ CREATE TEMP TABLE {0}highway AS SELECT id, linestring, ST_Transform(linestring, {1}) AS linestring_proj, nodes, tags->'highway' AS highway, coalesce(tags->'level', '0') AS level, CASE WHEN tags?'layer' THEN tags->'layer' WHEN tags->'tunnel' != 'no' THEN 'tunnel' WHEN tags->'bridge' != 'no' THEN 'bridge' ELSE '0' END AS layer, tags ?| ARRAY['ford', 'flood_prone'] AS onwater FROM {0}ways AS ways WHERE tags != ''::hstore AND (( tags?'highway' AND tags->'highway' NOT IN ('planned', 'proposed', 'construction', 'rest_area', 'razed', 'no', 'services', 'elevator') ) OR ( tags?'railway' AND tags->'railway' IN ('rail', 'tram') )) AND (NOT tags?'area' OR tags->'area' = 'no') AND NOT tags?'area:highway' AND array_length(nodes, 1) <= 100 AND -- Large ways have too big bbox ST_NPoints(linestring) > 1 """ sql01 = """ CREATE INDEX idx_{0}highway_linestring ON {0}highway USING gist(linestring); """ sql02 = """ CREATE TEMP TABLE tree AS SELECT id, geom FROM nodes WHERE tags != ''::hstore AND tags?'natural' AND tags->'natural' = 'tree' AND (NOT tags?'level' OR tags->'level' = '0') AND (NOT tags?'layer' OR tags->'layer' = '0') """ sql03 = """ CREATE INDEX idx_tree_geom ON tree USING gist(geom) """ sql04 = """ CREATE TEMP TABLE power AS SELECT id, geom FROM nodes WHERE tags != ''::hstore AND tags?'power' AND tags->'power' IN ('tower', 'pole', 'portal') """ sql05 = """ CREATE INDEX idx_power_geom ON power USING gist(geom) """ sql06 = """ CREATE TEMP TABLE {0}water AS SELECT id, tags->'waterway' AS waterway, nodes, CASE WHEN tags?'layer' THEN tags->'layer' WHEN tags->'tunnel' != 'no' THEN 'tunnel' WHEN tags->'bridge' != 'no' THEN 'bridge' ELSE '0' END AS layer, linestring AS linestring FROM {0}ways AS ways WHERE tags != ''::hstore AND ( tags?'waterway' AND tags->'waterway' IN ('stream', 'ditch', 'river', 'drain', 'canal', 'riverbank') OR ( tags?'natural' AND tags->'natural' = 'water' ) ) AND ST_NPoints(linestring) > 1 """ sql07 = """ CREATE INDEX idx_{0}water_linestring ON {0}water USING gist(linestring) """ sql10 = """ SELECT building.id, highway.id, ST_AsText(way_locate(building.linestring)) FROM {0}buildings AS building JOIN {1}highway AS highway ON highway.highway NOT IN ('footway', 'path', 'steps', 'elevator', 'corridor') AND highway.level = '0' AND highway.layer = '0' AND ST_Crosses(building.polygon_proj, highway.linestring_proj) AND ST_Dimension(ST_Intersection(building.polygon_proj, highway.linestring_proj)) >= 1 -- The cross is more than a point WHERE building.wall AND NOT building.layer """ sql20 = """ SELECT tree.id, building.id, ST_AsText(tree.geom) FROM {0}tree AS tree JOIN {1}buildings AS building ON tree.geom && building.linestring AND ST_Intersects(tree.geom, ST_MakePolygon(building.linestring)) AND NOT building.relation AND building.wall AND NOT building.layer """ sql21 = """ SELECT power.id, building.id, ST_AsText(power.geom) FROM {0}power AS power JOIN {1}buildings AS building ON power.geom && building.linestring AND ST_Intersects(power.geom, ST_MakePolygon(building.linestring)) AND NOT building.relation AND building.wall AND NOT building.layer """ sql30 = """ SELECT tree.id, highway.id, ST_AsText(tree.geom) FROM {0}tree AS tree JOIN {1}highway AS highway ON highway.level = '0' AND highway.layer = '0' AND highway.highway NOT IN ('footway', 'path', 'track') AND tree.geom && highway.linestring AND ST_Intersects(ST_Buffer(tree.geom::geography, 0.25)::geometry, highway.linestring) """ sql31 = """ SELECT power.id, highway.id, ST_AsText(power.geom) FROM {0}power AS power JOIN {1}highway AS highway ON highway.level = '0' AND highway.layer = '0' AND power.geom && highway.linestring AND ST_Intersects(ST_Buffer(power.geom::geography, 0.25)::geometry, highway.linestring) """ sql40 = """ SELECT highway.id, water.id, ST_AsText(ST_Centroid(ST_Intersection(highway.linestring, water.linestring))), CASE WHEN water.waterway IN ('river', 'canal') THEN 5 ELSE 4 END FROM {0}highway AS highway JOIN {1}water AS water ON ST_Crosses(highway.linestring, water.linestring) LEFT JOIN nodes ON nodes.geom && highway.linestring AND nodes.geom && water.linestring AND ST_Intersects(nodes.geom, ST_Intersection(highway.linestring, water.linestring)) WHERE highway.level = '0' AND highway.layer = water.layer AND NOT highway.onwater AND (nodes.id IS NULL OR NOT nodes.tags?'ford') GROUP BY highway.id, water.id, highway.linestring, water.linestring, water.waterway """ sql50 = """ CREATE TEMP TABLE {0}{1}inter AS SELECT ih1.id AS id1, ih2.id AS id2, ih2.level = ih1.level AS level, ih2.layer = ih1.layer AS layer, ST_Dimension(ST_Intersection(ih2.linestring, ih1.linestring)) = 0 AS corsses, ST_Dimension(ST_Intersection(ih2.linestring, ih1.linestring)) = 1 AS overlaps_, ST_Intersection(ih2.linestring, ih1.linestring) AS intersection FROM {0}highway AS ih1 JOIN {1}highway AS ih2 ON ih1.highway IS NOT NULL AND ih2.highway IS NOT NULL AND ({2} OR ih2.id > ih1.id) AND ( ( NOT ih2.nodes && ih1.nodes AND ST_Crosses(ih2.linestring, ih1.linestring) ) OR ST_Overlaps(ih2.linestring, ih1.linestring) ) """ sql51 = """ SELECT id1, id2, CASE ST_Dimension(geom) WHEN 0 THEN ST_AsText(geom) WHEN 1 THEN ST_ASText(way_locate(geom)) END, CASE WHEN corsses THEN 8 WHEN overlaps_ THEN 9 END AS class FROM ( SELECT DISTINCT ON(id1, id2) id1, id2, (ST_DUMP(intersection)).geom AS geom, corsses, overlaps_ FROM {0}{1}inter WHERE level AND layer ORDER BY id1, id2, ST_Dimension((ST_DUMP(intersection)).geom) DESC ) AS t """ sql60 = """ CREATE TEMP TABLE {0}{1}winter AS SELECT ih1.id AS id1, ih2.id AS id2, ih2.layer = ih1.layer AS layer, ST_Dimension(ST_Intersection(ih2.linestring, ih1.linestring)) = 0 AS corsses, ST_Dimension(ST_Intersection(ih2.linestring, ih1.linestring)) = 1 AS overlaps_, ST_Intersection(ih2.linestring, ih1.linestring) AS intersection FROM {0}water AS ih1 JOIN {1}water AS ih2 ON ih1.waterway IN ('stream', 'ditch', 'river', 'drain', 'canal') AND ih2.waterway IN ('stream', 'ditch', 'river', 'drain', 'canal') AND ({2} OR ih2.id > ih1.id) AND ( ( NOT ih2.nodes && ih1.nodes AND ST_Crosses(ih2.linestring, ih1.linestring) ) OR ST_Overlaps(ih2.linestring, ih1.linestring) ) """ sql61 = """ SELECT id1, id2, CASE ST_Dimension(geom) WHEN 0 THEN ST_AsText(geom) WHEN 1 THEN ST_ASText(way_locate(geom)) END, CASE WHEN corsses THEN 10 WHEN overlaps_ THEN 11 END AS class FROM ( SELECT DISTINCT ON(id1, id2) id1, id2, (ST_DUMP(intersection)).geom AS geom, corsses, overlaps_ FROM {0}{1}winter WHERE layer ORDER BY id1, id2, ST_Dimension((ST_DUMP(intersection)).geom) DESC ) AS t """ class Analyser_Osmosis_Highway_VS_Building(Analyser_Osmosis): requires_tables_full = ['buildings'] requires_tables_diff = ['buildings', 'touched_buildings'] def __init__(self, config, logger = None): Analyser_Osmosis.__init__(self, config, logger) doc = dict( detail = T_( '''Two features overlap with no shared node to indicate a physical connection or tagging to indicate a vertical separation.'''), fix = T_( '''Move a feature if it's in the wrong place. Connect the features if appropriate or update the tags if not.'''), trap = T_( '''A feature may be missing a tag e.g. `tunnel=*`, `bridge=*`, `covered=*` or consider `layer=*` on the buidling where a road or railway enters a structure. Warning, information sources can be contradictory in time or with spatial offset.'''), example = T_( '''![](https://wiki.openstreetmap.org/w/images/d/dc/Osmose-eg-error-1070.png) Intersection lane / building.''')) self.classs_change[1] = self.def_class(item = 1070, level = 2, tags = ['highway', 'building', 'geom', 'fix:imagery'], title = T_(u'Highway intersecting building'), **doc) self.classs_change[2] = self.def_class(item = 1070, level = 2, tags = ['tree', 'building', 'geom', 'fix:imagery'], title = T_(u'Tree intersecting building'), **doc) self.classs_change[3] = self.def_class(item = 1070, level = 2, tags = ['highway', 'tree', 'geom', 'fix:imagery'], title = T_(u'Tree and highway too close'), **doc) self.classs_change[4] = self.def_class(item = 1070, level = 3, tags = ['highway', 'waterway', 'geom', 'fix:imagery'], title = T_(u'Highway intersecting small water piece'), **doc) self.classs_change[5] = self.def_class(item = 1070, level = 2, tags = ['highway', 'waterway', 'geom', 'fix:imagery'], title = T_(u'Highway intersecting large water piece'), **doc) self.classs_change[6] = self.def_class(item = 1070, level = 2, tags = ['power', 'building', 'geom', 'fix:imagery'], title = T_(u'Power object intersecting building'), **doc) self.classs_change[7] = self.def_class(item = 1070, level = 2, tags = ['highway', 'power', 'geom', 'fix:imagery'], title = T_(u'Power object and highway too close'), **doc) self.classs_change[8] = self.def_class(item = 1070, level = 2, tags = ['highway', 'geom', 'fix:imagery'], title = T_(u'Highway intersecting highway'), **doc) self.classs_change[9] = self.def_class(item = 1070, level = 2, tags = ['highway', 'geom', 'fix:imagery'], title = T_(u'Highway overlaps'), **doc) self.classs_change[10] = self.def_class(item = 1070, level = 3, tags = ['waterway', 'geom', 'fix:imagery'], title = T_(u'Waterway intersecting waterway'), **doc) self.classs_change[11] = self.def_class(item = 1070, level = 3, tags = ['waterway', 'geom', 'fix:imagery'], title = T_(u'Waterway overlaps'), **doc) self.callback10 = lambda res: {"class":1, "data":[self.way_full, self.way_full, self.positionAsText]} self.callback20 = lambda res: {"class":2, "data":[self.node_full, self.way_full, self.positionAsText]} self.callback21 = lambda res: {"class":6, "data":[self.node_full, self.way_full, self.positionAsText]} self.callback30 = lambda res: {"class":3, "data":[self.node_full, self.way_full, self.positionAsText]} self.callback31 = lambda res: {"class":7, "data":[self.node_full, self.way_full, self.positionAsText]} self.callback40 = lambda res: {"class":res[3], "data":[self.way_full, self.way_full, self.positionAsText]} self.callback50 = lambda res: {"class":res[3], "data":[self.way_full, self.way_full, self.positionAsText] } self.callback60 = lambda res: {"class":res[3], "data":[self.way_full, self.way_full, self.positionAsText] } def analyser_osmosis_full(self): self.run(sql00.format("", self.config.options.get("proj"))) self.run(sql01.format("")) self.run(sql02) self.run(sql03) self.run(sql04) self.run(sql05) self.run(sql06.format("")) self.run(sql07.format("")) self.run(sql10.format("", ""), self.callback10) self.run(sql20.format("", ""), self.callback20) self.run(sql21.format("", ""), self.callback21) self.run(sql30.format("", ""), self.callback30) self.run(sql31.format("", ""), self.callback31) self.run(sql40.format("", ""), self.callback40) self.run(sql50.format("", "", "false")) self.run(sql51.format("", ""), self.callback50) self.run(sql60.format("", "", "false")) self.run(sql61.format("", ""), self.callback60) def analyser_osmosis_diff(self): self.run(sql00.format("", self.config.options.get("proj"))) self.run(sql01.format("")) self.run(sql02) self.run(sql03) self.run(sql04) self.run(sql05) self.run(sql06.format("")) self.run(sql07.format("")) self.create_view_touched("highway", "W") self.create_view_touched("tree", "N") self.create_view_touched("power", "N") self.create_view_touched("water", "N") self.create_view_not_touched("highway", "W") self.create_view_not_touched("tree", "N") self.create_view_not_touched("power", "N") self.create_view_not_touched("water", "W") self.run(sql10.format("touched_", "not_touched_"), self.callback10) self.run(sql10.format("", "touched_"), self.callback10) self.run(sql20.format("touched_", ""), self.callback20) self.run(sql20.format("not_touched_", "touched_"), self.callback20) self.run(sql21.format("touched_", ""), self.callback21) self.run(sql21.format("not_touched_", "touched_"), self.callback21) self.run(sql30.format("touched_", ""), self.callback30) self.run(sql30.format("not_touched_", "touched_"), self.callback30) self.run(sql31.format("touched_", ""), self.callback31) self.run(sql31.format("not_touched_", "touched_"), self.callback31) self.run(sql40.format("touched_", "not_touched_"), self.callback40) self.run(sql40.format("", "touched_"), self.callback40) self.run(sql50.format("not_touched_", "touched_", "true")) self.run(sql51.format("not_touched_", "touched_"), self.callback50) self.run(sql50.format("touched_", "not_touched_", "true")) self.run(sql51.format("touched_", "not_touched_"), self.callback50) self.run(sql50.format("touched_", "touched_", "false")) self.run(sql51.format("touched_", "touched_"), self.callback50) self.run(sql60.format("not_touched_", "touched_", "true")) self.run(sql61.format("not_touched_", "touched_"), self.callback60) self.run(sql60.format("touched_", "not_touched_", "true")) self.run(sql61.format("touched_", "not_touched_"), self.callback60) self.run(sql60.format("touched_", "touched_", "false")) self.run(sql61.format("touched_", "touched_"), self.callback60)
gpl-3.0
ryoqun/mitmproxy
libmproxy/console/help.py
4
3649
from __future__ import absolute_import import urwid from . import common, signals from .. import filt, version footer = [ ("heading", 'mitmproxy v%s ' % version.VERSION), ('heading_key', "q"), ":back ", ] class HelpView(urwid.ListBox): def __init__(self, help_context): self.help_context = help_context or [] urwid.ListBox.__init__( self, self.helptext() ) def helptext(self): text = [] text.append(urwid.Text([("head", "This view:\n")])) text.extend(self.help_context) text.append(urwid.Text([("head", "\n\nMovement:\n")])) keys = [ ("j, k", "down, up"), ("h, l", "left, right (in some contexts)"), ("g, G", "go to end, beginning"), ("space", "page down"), ("pg up/down", "page up/down"), ("arrows", "up, down, left, right"), ] text.extend( common.format_keyvals( keys, key="key", val="text", indent=4)) text.append(urwid.Text([("head", "\n\nGlobal keys:\n")])) keys = [ ("c", "client replay"), ("i", "set interception pattern"), ("o", "options"), ("q", "quit / return to previous page"), ("Q", "quit without confirm prompt"), ("S", "server replay"), ] text.extend( common.format_keyvals(keys, key="key", val="text", indent=4) ) text.append(urwid.Text([("head", "\n\nFilter expressions:\n")])) f = [] for i in filt.filt_unary: f.append( ("~%s" % i.code, i.help) ) for i in filt.filt_rex: f.append( ("~%s regex" % i.code, i.help) ) for i in filt.filt_int: f.append( ("~%s int" % i.code, i.help) ) f.sort() f.extend( [ ("!", "unary not"), ("&", "and"), ("|", "or"), ("(...)", "grouping"), ] ) text.extend(common.format_keyvals(f, key="key", val="text", indent=4)) text.append( urwid.Text( [ "\n", ("text", " Regexes are Python-style.\n"), ("text", " Regexes can be specified as quoted strings.\n"), ("text", " Header matching (~h, ~hq, ~hs) is against a string of the form \"name: value\".\n"), ("text", " Expressions with no operators are regex matches against URL.\n"), ("text", " Default binary operator is &.\n"), ("head", "\n Examples:\n"), ] ) ) examples = [ ("google\.com", "Url containing \"google.com"), ("~q ~b test", "Requests where body contains \"test\""), ("!(~q & ~t \"text/html\")", "Anything but requests with a text/html content type."), ] text.extend( common.format_keyvals(examples, key="key", val="text", indent=4) ) return text def keypress(self, size, key): key = common.shortcuts(key) if key == "q": signals.pop_view_state.send(self) return None elif key == "?": key = None elif key == "G": self.set_focus(0) elif key == "g": self.set_focus(len(self.body.contents)) return urwid.ListBox.keypress(self, size, key)
mit
mF2C/COMPSs
utils/storage/redisPSCO/COMPSs-Redis-bundle/python/storage/storage_object.py
2
2629
#!/usr/bin/python # # Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es) # # 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. # '''Redis Storage Object implementation for the PyCOMPSs Python Binding ''' import uuid import storage.api __name__ = "redispycompss" class storage_object(object): '''Storage Object ''' def __init__(self): '''Constructor method ''' # Id will be None until persisted self.pycompss_psco_identifier = None self.pycompss_mark_as_unmodified() def makePersistent(self, identifier = None): '''Stores the object in the Redis database ''' storage.api.makePersistent(self, identifier) def make_persistent(self, identifier = None): '''Support for underscore notation ''' self.makePersistent(identifier) def deletePersistent(self): '''Deletes the object from the Redis database ''' storage.api.deletePersistent(self) def delete_persistent(self): '''Support for underscore notation ''' self.deletePersistent() def getID(self): '''Gets the ID of the object ''' return self.pycompss_psco_identifier def pycompss_is_modified(self): '''Check if the object was modified ''' return self._pycompss_modified def pycompss_set_mod_flag(self, val): '''Set modification flag to given value ''' super(storage_object, self).__setattr__('_pycompss_modified', val) def pycompss_mark_as_unmodified(self): '''Mark the object as unmodified ''' self.pycompss_set_mod_flag(False) def pycompss_mark_as_modified(self): '''Mark the object as modified ''' self.pycompss_set_mod_flag(True) def __setattr__(self, name, value): '''Custom setattr which marks the object as modified and calls the actual setattr ''' self.pycompss_set_mod_flag(True) super(storage_object, self).__setattr__(name, value) '''Add support for camelCase ''' StorageObject = storage_object
apache-2.0
fsmMLK/inkscapeMadeEasy
examples/iME_Draw_lineStyle_and_markers.py
1
4006
#!/usr/bin/python import inkex import inkscapeMadeEasy_Base as inkBase import inkscapeMadeEasy_Draw as inkDraw import math class myExtension(inkBase.inkscapeMadeEasy): def __init__(self): inkex.Effect.__init__(self) self.OptionParser.add_option("--myColorPicker", action="store", type="string", dest="lineColorPickerVar", default='0') self.OptionParser.add_option("--myColorOption", action="store", type="string", dest="lineColorOptionVar", default='0') def effect(self): # sets the position to the viewport center, round to next 10. position=[self.view_center[0],self.view_center[1]] position[0]=int(math.ceil(position[0] / 10.0)) * 10 position[1]=int(math.ceil(position[1] / 10.0)) * 10 # creates a dot marker, with red stroke color and gray (40%) filling color myDotMarker = inkDraw.marker.createDotMarker(self, nameID='myDot' , RenameMode=1, # overwrite an eventual markers with the same name scale=0.2, strokeColor=inkDraw.color.defined('red'), fillColor=inkDraw.color.gray(0.4)) # parses the input options to get the color of the line lineColor = inkDraw.color.parseColorPicker(self.options.lineColorOptionVar, self.options.lineColorPickerVar) # create a new line style with a 2.0 pt line and the marker just defined at both ends myLineStyleDot = inkDraw.lineStyle.set(lineWidth=2.0, lineColor=lineColor, fillColor=inkDraw.color.defined('blue'), lineJoin='round', lineCap='round', markerStart=myDotMarker, markerMid=myDotMarker, markerEnd=myDotMarker, strokeDashArray=None) #root_layer = self.current_layer root_layer = self.document.getroot() # draws a line using the new line style. (see inkscapeMadeEasy_Draw.line class for further info on this function inkDraw.line.relCoords(root_layer,coordsList= [[0,100],[100,0]],offset=position,lineStyle=myLineStyleDot) # -- Creates a second line style with ellipsis and # creates a ellipsis marker with default values infMarkerStart,infMarkerEnd = inkDraw.marker.createElipsisMarker(self, nameID='myEllipsis' , RenameMode=1) # overwrite an eventual markers with the same name # create a new line style myStyleInf = inkDraw.lineStyle.set(lineWidth=1.0, lineColor=lineColor, fillColor=None, lineJoin='round', lineCap='round', markerStart=infMarkerStart, markerMid=None, markerEnd=infMarkerEnd, strokeDashArray=None) # draws a line using the new line style. (see inkscapeMadeEasy_Draw.line class for further info on this function inkDraw.line.relCoords(root_layer,coordsList= [[0,100],[100,0]],offset=[position[0]+300,position[1]],lineStyle=myStyleInf) if __name__ == '__main__': x = myExtension() x.affect()
gpl-3.0
sysbot/CouchPotatoServer
libs/enzyme/mpeg.py
180
30553
# -*- coding: utf-8 -*- # enzyme - Video metadata parser # Copyright 2011-2012 Antoine Bertin <diaoulael@gmail.com> # Copyright 2003-2006 Thomas Schueppel <stain@acm.org> # Copyright 2003-2006 Dirk Meyer <dischi@freevo.org> # # This file is part of enzyme. # # enzyme 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. # # enzyme 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 enzyme. If not, see <http://www.gnu.org/licenses/>. __all__ = ['Parser'] import os import struct import logging import stat from exceptions import ParseError import core # get logging object log = logging.getLogger(__name__) ##------------------------------------------------------------------------ ## START_CODE ## ## Start Codes, with 'slice' occupying 0x01..0xAF ##------------------------------------------------------------------------ START_CODE = { 0x00 : 'picture_start_code', 0xB0 : 'reserved', 0xB1 : 'reserved', 0xB2 : 'user_data_start_code', 0xB3 : 'sequence_header_code', 0xB4 : 'sequence_error_code', 0xB5 : 'extension_start_code', 0xB6 : 'reserved', 0xB7 : 'sequence end', 0xB8 : 'group of pictures', } for i in range(0x01, 0xAF): START_CODE[i] = 'slice_start_code' ##------------------------------------------------------------------------ ## START CODES ##------------------------------------------------------------------------ PICTURE = 0x00 USERDATA = 0xB2 SEQ_HEAD = 0xB3 SEQ_ERR = 0xB4 EXT_START = 0xB5 SEQ_END = 0xB7 GOP = 0xB8 SEQ_START_CODE = 0xB3 PACK_PKT = 0xBA SYS_PKT = 0xBB PADDING_PKT = 0xBE AUDIO_PKT = 0xC0 VIDEO_PKT = 0xE0 PRIVATE_STREAM1 = 0xBD PRIVATE_STREAM2 = 0xBf TS_PACKET_LENGTH = 188 TS_SYNC = 0x47 ##------------------------------------------------------------------------ ## FRAME_RATE ## ## A lookup table of all the standard frame rates. Some rates adhere to ## a particular profile that ensures compatibility with VLSI capabilities ## of the early to mid 1990s. ## ## CPB ## Constrained Parameters Bitstreams, an MPEG-1 set of sampling and ## bitstream parameters designed to normalize decoder computational ## complexity, buffer size, and memory bandwidth while still addressing ## the widest possible range of applications. ## ## Main Level ## MPEG-2 Video Main Profile and Main Level is analogous to MPEG-1's ## CPB, with sampling limits at CCIR 601 parameters (720x480x30 Hz or ## 720x576x24 Hz). ## ##------------------------------------------------------------------------ FRAME_RATE = [ 0, 24000.0 / 1001, ## 3-2 pulldown NTSC (CPB/Main Level) 24, ## Film (CPB/Main Level) 25, ## PAL/SECAM or 625/60 video 30000.0 / 1001, ## NTSC (CPB/Main Level) 30, ## drop-frame NTSC or component 525/60 (CPB/Main Level) 50, ## double-rate PAL 60000.0 / 1001, ## double-rate NTSC 60, ## double-rate, drop-frame NTSC/component 525/60 video ] ##------------------------------------------------------------------------ ## ASPECT_RATIO -- INCOMPLETE? ## ## This lookup table maps the header aspect ratio index to a float value. ## These are just the defined ratios for CPB I believe. As I understand ## it, a stream that doesn't adhere to one of these aspect ratios is ## technically considered non-compliant. ##------------------------------------------------------------------------ ASPECT_RATIO = (None, # Forbidden 1.0, # 1/1 (VGA) 4.0 / 3, # 4/3 (TV) 16.0 / 9, # 16/9 (Widescreen) 2.21 # (Cinema) ) class MPEG(core.AVContainer): """ Parser for various MPEG files. This includes MPEG-1 and MPEG-2 program streams, elementary streams and transport streams. The reported length differs from the length reported by most video players but the provides length here is correct. An MPEG file has no additional metadata like title, etc; only codecs, length and resolution is reported back. """ def __init__(self, file): core.AVContainer.__init__(self) self.sequence_header_offset = 0 self.mpeg_version = 2 # detect TS (fast scan) if not self.isTS(file): # detect system mpeg (many infos) if not self.isMPEG(file): # detect PES if not self.isPES(file): # Maybe it's MPEG-ES if self.isES(file): # If isES() succeeds, we needn't do anything further. return if file.name.lower().endswith('mpeg') or \ file.name.lower().endswith('mpg'): # This has to be an mpeg file. It could be a bad # recording from an ivtv based hardware encoder with # same bytes missing at the beginning. # Do some more digging... if not self.isMPEG(file, force=True) or \ not self.video or not self.audio: # does not look like an mpeg at all raise ParseError() else: # no mpeg at all raise ParseError() self.mime = 'video/mpeg' if not self.video: self.video.append(core.VideoStream()) if self.sequence_header_offset <= 0: return self.progressive(file) for vi in self.video: vi.width, vi.height = self.dxy(file) vi.fps, vi.aspect = self.framerate_aspect(file) vi.bitrate = self.bitrate(file) if self.length: vi.length = self.length if not self.type: self.type = 'MPEG Video' # set fourcc codec for video and audio vc, ac = 'MP2V', 'MP2A' if self.mpeg_version == 1: vc, ac = 'MPEG', 0x0050 for v in self.video: v.codec = vc for a in self.audio: if not a.codec: a.codec = ac def dxy(self, file): """ get width and height of the video """ file.seek(self.sequence_header_offset + 4, 0) v = file.read(4) x = struct.unpack('>H', v[:2])[0] >> 4 y = struct.unpack('>H', v[1:3])[0] & 0x0FFF return (x, y) def framerate_aspect(self, file): """ read framerate and aspect ratio """ file.seek(self.sequence_header_offset + 7, 0) v = struct.unpack('>B', file.read(1))[0] try: fps = FRAME_RATE[v & 0xf] except IndexError: fps = None if v >> 4 < len(ASPECT_RATIO): aspect = ASPECT_RATIO[v >> 4] else: aspect = None return (fps, aspect) def progressive(self, file): """ Try to find out with brute force if the mpeg is interlaced or not. Search for the Sequence_Extension in the extension header (01B5) """ file.seek(0) buffer = '' count = 0 while 1: if len(buffer) < 1000: count += 1 if count > 1000: break buffer += file.read(1024) if len(buffer) < 1000: break pos = buffer.find('\x00\x00\x01\xb5') if pos == -1 or len(buffer) - pos < 5: buffer = buffer[-10:] continue ext = (ord(buffer[pos + 4]) >> 4) if ext == 8: pass elif ext == 1: if (ord(buffer[pos + 5]) >> 3) & 1: self._set('progressive', True) else: self._set('interlaced', True) return True else: log.debug(u'ext: %r' % ext) buffer = buffer[pos + 4:] return False ##------------------------------------------------------------------------ ## bitrate() ## ## From the MPEG-2.2 spec: ## ## bit_rate -- This is a 30-bit integer. The lower 18 bits of the ## integer are in bit_rate_value and the upper 12 bits are in ## bit_rate_extension. The 30-bit integer specifies the bitrate of the ## bitstream measured in units of 400 bits/second, rounded upwards. ## The value zero is forbidden. ## ## So ignoring all the variable bitrate stuff for now, this 30 bit integer ## multiplied times 400 bits/sec should give the rate in bits/sec. ## ## TODO: Variable bitrates? I need one that implements this. ## ## Continued from the MPEG-2.2 spec: ## ## If the bitstream is a constant bitrate stream, the bitrate specified ## is the actual rate of operation of the VBV specified in annex C. If ## the bitstream is a variable bitrate stream, the STD specifications in ## ISO/IEC 13818-1 supersede the VBV, and the bitrate specified here is ## used to dimension the transport stream STD (2.4.2 in ITU-T Rec. xxx | ## ISO/IEC 13818-1), or the program stream STD (2.4.5 in ITU-T Rec. xxx | ## ISO/IEC 13818-1). ## ## If the bitstream is not a constant rate bitstream the vbv_delay ## field shall have the value FFFF in hexadecimal. ## ## Given the value encoded in the bitrate field, the bitstream shall be ## generated so that the video encoding and the worst case multiplex ## jitter do not cause STD buffer overflow or underflow. ## ## ##------------------------------------------------------------------------ ## Some parts in the code are based on mpgtx (mpgtx.sf.net) def bitrate(self, file): """ read the bitrate (most of the time broken) """ file.seek(self.sequence_header_offset + 8, 0) t, b = struct.unpack('>HB', file.read(3)) vrate = t << 2 | b >> 6 return vrate * 400 def ReadSCRMpeg2(self, buffer): """ read SCR (timestamp) for MPEG2 at the buffer beginning (6 Bytes) """ if len(buffer) < 6: return None highbit = (ord(buffer[0]) & 0x20) >> 5 low4Bytes = ((long(ord(buffer[0])) & 0x18) >> 3) << 30 low4Bytes |= (ord(buffer[0]) & 0x03) << 28 low4Bytes |= ord(buffer[1]) << 20 low4Bytes |= (ord(buffer[2]) & 0xF8) << 12 low4Bytes |= (ord(buffer[2]) & 0x03) << 13 low4Bytes |= ord(buffer[3]) << 5 low4Bytes |= (ord(buffer[4])) >> 3 sys_clock_ref = (ord(buffer[4]) & 0x3) << 7 sys_clock_ref |= (ord(buffer[5]) >> 1) return (long(highbit * (1 << 16) * (1 << 16)) + low4Bytes) / 90000 def ReadSCRMpeg1(self, buffer): """ read SCR (timestamp) for MPEG1 at the buffer beginning (5 Bytes) """ if len(buffer) < 5: return None highbit = (ord(buffer[0]) >> 3) & 0x01 low4Bytes = ((long(ord(buffer[0])) >> 1) & 0x03) << 30 low4Bytes |= ord(buffer[1]) << 22; low4Bytes |= (ord(buffer[2]) >> 1) << 15; low4Bytes |= ord(buffer[3]) << 7; low4Bytes |= ord(buffer[4]) >> 1; return (long(highbit) * (1 << 16) * (1 << 16) + low4Bytes) / 90000; def ReadPTS(self, buffer): """ read PTS (PES timestamp) at the buffer beginning (5 Bytes) """ high = ((ord(buffer[0]) & 0xF) >> 1) med = (ord(buffer[1]) << 7) + (ord(buffer[2]) >> 1) low = (ord(buffer[3]) << 7) + (ord(buffer[4]) >> 1) return ((long(high) << 30) + (med << 15) + low) / 90000 def ReadHeader(self, buffer, offset): """ Handle MPEG header in buffer on position offset Return None on error, new offset or 0 if the new offset can't be scanned """ if buffer[offset:offset + 3] != '\x00\x00\x01': return None id = ord(buffer[offset + 3]) if id == PADDING_PKT: return offset + (ord(buffer[offset + 4]) << 8) + \ ord(buffer[offset + 5]) + 6 if id == PACK_PKT: if ord(buffer[offset + 4]) & 0xF0 == 0x20: self.type = 'MPEG-1 Video' self.get_time = self.ReadSCRMpeg1 self.mpeg_version = 1 return offset + 12 elif (ord(buffer[offset + 4]) & 0xC0) == 0x40: self.type = 'MPEG-2 Video' self.get_time = self.ReadSCRMpeg2 return offset + (ord(buffer[offset + 13]) & 0x07) + 14 else: # I have no idea what just happened, but for some DVB # recordings done with mencoder this points to a # PACK_PKT describing something odd. Returning 0 here # (let's hope there are no extensions in the header) # fixes it. return 0 if 0xC0 <= id <= 0xDF: # code for audio stream for a in self.audio: if a.id == id: break else: self.audio.append(core.AudioStream()) self.audio[-1]._set('id', id) return 0 if 0xE0 <= id <= 0xEF: # code for video stream for v in self.video: if v.id == id: break else: self.video.append(core.VideoStream()) self.video[-1]._set('id', id) return 0 if id == SEQ_HEAD: # sequence header, remember that position for later use self.sequence_header_offset = offset return 0 if id in [PRIVATE_STREAM1, PRIVATE_STREAM2]: # private stream. we don't know, but maybe we can guess later add = ord(buffer[offset + 8]) # if (ord(buffer[offset+6]) & 4) or 1: # id = ord(buffer[offset+10+add]) if buffer[offset + 11 + add:offset + 15 + add].find('\x0b\x77') != -1: # AC3 stream for a in self.audio: if a.id == id: break else: self.audio.append(core.AudioStream()) self.audio[-1]._set('id', id) self.audio[-1].codec = 0x2000 # AC3 return 0 if id == SYS_PKT: return 0 if id == EXT_START: return 0 return 0 # Normal MPEG (VCD, SVCD) ======================================== def isMPEG(self, file, force=False): """ This MPEG starts with a sequence of 0x00 followed by a PACK Header http://dvd.sourceforge.net/dvdinfo/packhdr.html """ file.seek(0, 0) buffer = file.read(10000) offset = 0 # seek until the 0 byte stop while offset < len(buffer) - 100 and buffer[offset] == '\0': offset += 1 offset -= 2 # test for mpeg header 0x00 0x00 0x01 header = '\x00\x00\x01%s' % chr(PACK_PKT) if offset < 0 or not buffer[offset:offset + 4] == header: if not force: return 0 # brute force and try to find the pack header in the first # 10000 bytes somehow offset = buffer.find(header) if offset < 0: return 0 # scan the 100000 bytes of data buffer += file.read(100000) # scan first header, to get basic info about # how to read a timestamp self.ReadHeader(buffer, offset) # store first timestamp self.start = self.get_time(buffer[offset + 4:]) while len(buffer) > offset + 1000 and \ buffer[offset:offset + 3] == '\x00\x00\x01': # read the mpeg header new_offset = self.ReadHeader(buffer, offset) # header scanning detected error, this is no mpeg if new_offset == None: return 0 if new_offset: # we have a new offset offset = new_offset # skip padding 0 before a new header while len(buffer) > offset + 10 and \ not ord(buffer[offset + 2]): offset += 1 else: # seek to new header by brute force offset += buffer[offset + 4:].find('\x00\x00\x01') + 4 # fill in values for support functions: self.__seek_size__ = 1000000 self.__sample_size__ = 10000 self.__search__ = self._find_timer_ self.filename = file.name # get length of the file self.length = self.get_length() return 1 def _find_timer_(self, buffer): """ Return position of timer in buffer or None if not found. This function is valid for 'normal' mpeg files """ pos = buffer.find('\x00\x00\x01%s' % chr(PACK_PKT)) if pos == -1: return None return pos + 4 # PES ============================================================ def ReadPESHeader(self, offset, buffer, id=0): """ Parse a PES header. Since it starts with 0x00 0x00 0x01 like 'normal' mpegs, this function will return (0, None) when it is no PES header or (packet length, timestamp position (maybe None)) http://dvd.sourceforge.net/dvdinfo/pes-hdr.html """ if not buffer[0:3] == '\x00\x00\x01': return 0, None packet_length = (ord(buffer[4]) << 8) + ord(buffer[5]) + 6 align = ord(buffer[6]) & 4 header_length = ord(buffer[8]) # PES ID (starting with 001) if ord(buffer[3]) & 0xE0 == 0xC0: id = id or ord(buffer[3]) & 0x1F for a in self.audio: if a.id == id: break else: self.audio.append(core.AudioStream()) self.audio[-1]._set('id', id) elif ord(buffer[3]) & 0xF0 == 0xE0: id = id or ord(buffer[3]) & 0xF for v in self.video: if v.id == id: break else: self.video.append(core.VideoStream()) self.video[-1]._set('id', id) # new mpeg starting if buffer[header_length + 9:header_length + 13] == \ '\x00\x00\x01\xB3' and not self.sequence_header_offset: # yes, remember offset for later use self.sequence_header_offset = offset + header_length + 9 elif ord(buffer[3]) == 189 or ord(buffer[3]) == 191: # private stream. we don't know, but maybe we can guess later id = id or ord(buffer[3]) & 0xF if align and \ buffer[header_length + 9:header_length + 11] == '\x0b\x77': # AC3 stream for a in self.audio: if a.id == id: break else: self.audio.append(core.AudioStream()) self.audio[-1]._set('id', id) self.audio[-1].codec = 0x2000 # AC3 else: # unknown content pass ptsdts = ord(buffer[7]) >> 6 if ptsdts and ptsdts == ord(buffer[9]) >> 4: if ord(buffer[9]) >> 4 != ptsdts: log.warning(u'WARNING: bad PTS/DTS, please contact us') return packet_length, None # timestamp = self.ReadPTS(buffer[9:14]) high = ((ord(buffer[9]) & 0xF) >> 1) med = (ord(buffer[10]) << 7) + (ord(buffer[11]) >> 1) low = (ord(buffer[12]) << 7) + (ord(buffer[13]) >> 1) return packet_length, 9 return packet_length, None def isPES(self, file): log.info(u'trying mpeg-pes scan') file.seek(0, 0) buffer = file.read(3) # header (also valid for all mpegs) if not buffer == '\x00\x00\x01': return 0 self.sequence_header_offset = 0 buffer += file.read(10000) offset = 0 while offset + 1000 < len(buffer): pos, timestamp = self.ReadPESHeader(offset, buffer[offset:]) if not pos: return 0 if timestamp != None and not hasattr(self, 'start'): self.get_time = self.ReadPTS bpos = buffer[offset + timestamp:offset + timestamp + 5] self.start = self.get_time(bpos) if self.sequence_header_offset and hasattr(self, 'start'): # we have all informations we need break offset += pos if offset + 1000 < len(buffer) and len(buffer) < 1000000 or 1: # looks like a pes, read more buffer += file.read(10000) if not self.video and not self.audio: # no video and no audio? return 0 self.type = 'MPEG-PES' # fill in values for support functions: self.__seek_size__ = 10000000 # 10 MB self.__sample_size__ = 500000 # 500 k scanning self.__search__ = self._find_timer_PES_ self.filename = file.name # get length of the file self.length = self.get_length() return 1 def _find_timer_PES_(self, buffer): """ Return position of timer in buffer or -1 if not found. This function is valid for PES files """ pos = buffer.find('\x00\x00\x01') offset = 0 if pos == -1 or offset + 1000 >= len(buffer): return None retpos = -1 ackcount = 0 while offset + 1000 < len(buffer): pos, timestamp = self.ReadPESHeader(offset, buffer[offset:]) if timestamp != None and retpos == -1: retpos = offset + timestamp if pos == 0: # Oops, that was a mpeg header, no PES header offset += buffer[offset:].find('\x00\x00\x01') retpos = -1 ackcount = 0 else: offset += pos if retpos != -1: ackcount += 1 if ackcount > 10: # looks ok to me return retpos return None # Elementary Stream =============================================== def isES(self, file): file.seek(0, 0) try: header = struct.unpack('>LL', file.read(8)) except (struct.error, IOError): return False if header[0] != 0x1B3: return False # Is an mpeg video elementary stream self.mime = 'video/mpeg' video = core.VideoStream() video.width = header[1] >> 20 video.height = (header[1] >> 8) & 0xfff if header[1] & 0xf < len(FRAME_RATE): video.fps = FRAME_RATE[header[1] & 0xf] if (header[1] >> 4) & 0xf < len(ASPECT_RATIO): # FIXME: Empirically the aspect looks like PAR rather than DAR video.aspect = ASPECT_RATIO[(header[1] >> 4) & 0xf] self.video.append(video) return True # Transport Stream =============================================== def isTS(self, file): file.seek(0, 0) buffer = file.read(TS_PACKET_LENGTH * 2) c = 0 while c + TS_PACKET_LENGTH < len(buffer): if ord(buffer[c]) == ord(buffer[c + TS_PACKET_LENGTH]) == TS_SYNC: break c += 1 else: return 0 buffer += file.read(10000) self.type = 'MPEG-TS' while c + TS_PACKET_LENGTH < len(buffer): start = ord(buffer[c + 1]) & 0x40 # maybe load more into the buffer if c + 2 * TS_PACKET_LENGTH > len(buffer) and c < 500000: buffer += file.read(10000) # wait until the ts payload contains a payload header if not start: c += TS_PACKET_LENGTH continue tsid = ((ord(buffer[c + 1]) & 0x3F) << 8) + ord(buffer[c + 2]) adapt = (ord(buffer[c + 3]) & 0x30) >> 4 offset = 4 if adapt & 0x02: # meta info present, skip it for now adapt_len = ord(buffer[c + offset]) offset += adapt_len + 1 if not ord(buffer[c + 1]) & 0x40: # no new pes or psi in stream payload starting pass elif adapt & 0x01: # PES timestamp = self.ReadPESHeader(c + offset, buffer[c + offset:], tsid)[1] if timestamp != None: if not hasattr(self, 'start'): self.get_time = self.ReadPTS timestamp = c + offset + timestamp self.start = self.get_time(buffer[timestamp:timestamp + 5]) elif not hasattr(self, 'audio_ok'): timestamp = c + offset + timestamp start = self.get_time(buffer[timestamp:timestamp + 5]) if start is not None and self.start is not None and \ abs(start - self.start) < 10: # looks ok self.audio_ok = True else: # timestamp broken del self.start log.warning(u'Timestamp error, correcting') if hasattr(self, 'start') and self.start and \ self.sequence_header_offset and self.video and self.audio: break c += TS_PACKET_LENGTH if not self.sequence_header_offset: return 0 # fill in values for support functions: self.__seek_size__ = 10000000 # 10 MB self.__sample_size__ = 100000 # 100 k scanning self.__search__ = self._find_timer_TS_ self.filename = file.name # get length of the file self.length = self.get_length() return 1 def _find_timer_TS_(self, buffer): c = 0 while c + TS_PACKET_LENGTH < len(buffer): if ord(buffer[c]) == ord(buffer[c + TS_PACKET_LENGTH]) == TS_SYNC: break c += 1 else: return None while c + TS_PACKET_LENGTH < len(buffer): start = ord(buffer[c + 1]) & 0x40 if not start: c += TS_PACKET_LENGTH continue tsid = ((ord(buffer[c + 1]) & 0x3F) << 8) + ord(buffer[c + 2]) adapt = (ord(buffer[c + 3]) & 0x30) >> 4 offset = 4 if adapt & 0x02: # meta info present, skip it for now offset += ord(buffer[c + offset]) + 1 if adapt & 0x01: timestamp = self.ReadPESHeader(c + offset, buffer[c + offset:], tsid)[1] if timestamp is None: # this should not happen log.error(u'bad TS') return None return c + offset + timestamp c += TS_PACKET_LENGTH return None # Support functions ============================================== def get_endpos(self): """ get the last timestamp of the mpeg, return -1 if this is not possible """ if not hasattr(self, 'filename') or not hasattr(self, 'start'): return None length = os.stat(self.filename)[stat.ST_SIZE] if length < self.__sample_size__: return file = open(self.filename) file.seek(length - self.__sample_size__) buffer = file.read(self.__sample_size__) end = None while 1: pos = self.__search__(buffer) if pos == None: break end = self.get_time(buffer[pos:]) or end buffer = buffer[pos + 100:] file.close() return end def get_length(self): """ get the length in seconds, return -1 if this is not possible """ end = self.get_endpos() if end == None or self.start == None: return None if self.start > end: return int(((long(1) << 33) - 1) / 90000) - self.start + end return end - self.start def seek(self, end_time): """ Return the byte position in the file where the time position is 'pos' seconds. Return 0 if this is not possible """ if not hasattr(self, 'filename') or not hasattr(self, 'start'): return 0 file = open(self.filename) seek_to = 0 while 1: file.seek(self.__seek_size__, 1) buffer = file.read(self.__sample_size__) if len(buffer) < 10000: break pos = self.__search__(buffer) if pos != None: # found something nt = self.get_time(buffer[pos:]) if nt is not None and nt >= end_time: # too much, break break # that wasn't enough seek_to = file.tell() file.close() return seek_to def __scan__(self): """ scan file for timestamps (may take a long time) """ if not hasattr(self, 'filename') or not hasattr(self, 'start'): return 0 file = open(self.filename) log.debug(u'scanning file...') while 1: file.seek(self.__seek_size__ * 10, 1) buffer = file.read(self.__sample_size__) if len(buffer) < 10000: break pos = self.__search__(buffer) if pos == None: continue log.debug(u'buffer position: %r' % self.get_time(buffer[pos:])) file.close() log.debug(u'done scanning file') Parser = MPEG
gpl-3.0
wetek-enigma/enigma2
lib/python/Screens/ButtonSetup.py
1
29746
from GlobalActions import globalActionMap from Components.ActionMap import ActionMap, HelpableActionMap from Components.Button import Button from Components.ChoiceList import ChoiceList, ChoiceEntryComponent from Components.SystemInfo import SystemInfo from Components.config import config, ConfigSubsection, ConfigText, ConfigYesNo from Components.PluginComponent import plugins from Screens.ChoiceBox import ChoiceBox from Screens.Screen import Screen from Screens.MessageBox import MessageBox from Plugins.Plugin import PluginDescriptor from Tools.BoundFunction import boundFunction from ServiceReference import ServiceReference from enigma import eServiceReference, eActionMap from Components.Label import Label import os def getButtonSetupKeys(): return [(_("Red"), "red", ""), (_("Red long"), "red_long", ""), (_("Green"), "green", ""), (_("Green long"), "green_long", ""), (_("Yellow"), "yellow", ""), (_("Yellow long"), "yellow_long", ""), (_("Blue"), "blue", ""), (_("Blue long"), "blue_long", ""), (_("Info (EPG)"), "info", "Infobar/InfoPressed/1"), (_("Info (EPG) Long"), "info_long", "Infobar/showEventInfoPlugins/1"), (_("Epg/Guide"), "epg", "Infobar/EPGPressed/1"), (_("Epg/Guide long"), "epg_long", "Infobar/showEventGuidePlugins/1"), (_("Left"), "cross_left", ""), (_("Right"), "cross_right", ""), (_("Up"), "cross_up", ""), (_("Down"), "cross_down", ""), (_("PageUp"), "pageup", ""), (_("PageUp long"), "pageup_long", ""), (_("PageDown"), "pagedown", ""), (_("PageDown long"), "pagedown_long", ""), (_("Channel up"), "channelup", ""), (_("Channel down"), "channeldown", ""), (_("TV"), "showTv", ""), (_("Radio"), "radio", ""), (_("Radio long"), "radio_long", ""), (_("Rec"), "rec", ""), (_("Rec long"), "rec_long", ""), (_("Teletext"), "text", ""), (_("Help"), "displayHelp", ""), (_("Help long"), "displayHelp_long", ""), (_("Subtitle"), "subtitle", ""), (_("Subtitle long"), "subtitle_long", ""), (_("Menu"), "mainMenu", ""), (_("List/Fav"), "list", ""), (_("List/Fav long"), "list_long", ""), (_("PVR"), "pvr", ""), (_("PVR long"), "pvr_long", ""), (_("Favorites"), "favorites", ""), (_("Favorites long"), "favorites_long", ""), (_("File"), "file", ""), (_("File long"), "file_long", ""), (_("OK long"), "ok_long", ""), (_("Media"), "media", ""), (_("Media long"), "media_long", ""), (_("Open"), "open", ""), (_("Open long"), "open_long", ""), (_("Www"), "www", ""), (_("Www long"), "www_long", ""), (_("Directory"), "directory", ""), (_("Directory long"), "directory_long", ""), (_("Back/Recall"), "back", ""), (_("Back/Recall") + " " + _("long"), "back_long", ""), (_("Home"), "home", ""), (_("End"), "end", ""), (_("Next"), "next", ""), (_("Previous"), "previous", ""), (_("Audio"), "audio", ""), (_("Play"), "play", ""), (_("Playpause"), "playpause", ""), (_("Stop"), "stop", ""), (_("Pause"), "pause", ""), (_("Rewind"), "rewind", ""), (_("Fastforward"), "fastforward", ""), (_("Skip back"), "skip_back", ""), (_("Skip forward"), "skip_forward", ""), (_("activatePiP"), "activatePiP", ""), (_("Timer"), "timer", ""), (_("Playlist"), "playlist", ""), (_("Playlist long"), "playlist_long", ""), (_("Timeshift"), "timeshift", ""), (_("Homepage"), "homep", ""), (_("Homepage long"), "homep_long", ""), (_("Search/WEB"), "search", ""), (_("Search/WEB long"), "search_long", ""), (_("Slow"), "slow", ""), (_("Mark/Portal/Playlist"), "mark", ""), (_("Sleep"), "sleep", ""), (_("Sleep long"), "sleep_long", ""), (_("Power"), "power", ""), (_("Power long"), "power_long", ""), (_("HDMIin"), "HDMIin", "Infobar/HDMIIn"), (_("HDMIin") + " " + _("long"), "HDMIin_long", (SystemInfo["LcdLiveTV"] and "Infobar/ToggleLCDLiveTV") or ""), (_("Context"), "contextMenu", "Infobar/showExtensionSelection"), (_("Context long"), "context_long", ""), (_("SAT"), "sat", "Infobar/openSatellites"), (_("SAT long"), "sat_long", ""), (_("Prov"), "prov", ""), (_("Prov long"), "prov_long", ""), (_("F1/LAN"), "f1", ""), (_("F1/LAN long"), "f1_long", ""), (_("F2"), "f2", ""), (_("F2 long"), "f2_long", ""), (_("F3"), "f3", ""), (_("F3 long"), "f3_long", ""), (_("F4"), "f4", ""), (_("F4 long"), "f4_long", ""),] config.misc.ButtonSetup = ConfigSubsection() config.misc.ButtonSetup.additional_keys = ConfigYesNo(default=True) for x in getButtonSetupKeys(): exec "config.misc.ButtonSetup." + x[1] + " = ConfigText(default='" + x[2] + "')" def getButtonSetupFunctions(): ButtonSetupFunctions = [] twinPlugins = [] twinPaths = {} pluginlist = plugins.getPlugins(PluginDescriptor.WHERE_EVENTINFO) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path and 'selectedevent' not in plugin.__call__.func_code.co_varnames: if twinPaths.has_key(plugin.path[24:]): twinPaths[plugin.path[24:]] += 1 else: twinPaths[plugin.path[24:]] = 1 ButtonSetupFunctions.append((plugin.name, plugin.path[24:] + "/" + str(twinPaths[plugin.path[24:]]) , "EPG")) twinPlugins.append(plugin.name) pluginlist = plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU, PluginDescriptor.WHERE_EVENTINFO]) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path: if twinPaths.has_key(plugin.path[24:]): twinPaths[plugin.path[24:]] += 1 else: twinPaths[plugin.path[24:]] = 1 ButtonSetupFunctions.append((plugin.name, plugin.path[24:] + "/" + str(twinPaths[plugin.path[24:]]) , "Plugins")) twinPlugins.append(plugin.name) ButtonSetupFunctions.append((_("Show graphical multi EPG"), "Infobar/openGraphEPG", "EPG")) ButtonSetupFunctions.append((_("Main menu"), "Infobar/mainMenu", "InfoBar")) ButtonSetupFunctions.append((_("Show help"), "Infobar/showHelp", "InfoBar")) ButtonSetupFunctions.append((_("Show extension selection"), "Infobar/showExtensionSelection", "InfoBar")) ButtonSetupFunctions.append((_("Zap down"), "Infobar/zapDown", "InfoBar")) ButtonSetupFunctions.append((_("Zap up"), "Infobar/zapUp", "InfoBar")) ButtonSetupFunctions.append((_("Volume down"), "Infobar/volumeDown", "InfoBar")) ButtonSetupFunctions.append((_("Volume up"), "Infobar/volumeUp", "InfoBar")) ButtonSetupFunctions.append((_("Show Infobar"), "Infobar/toggleShow", "InfoBar")) ButtonSetupFunctions.append((_("Show service list"), "Infobar/openServiceList", "InfoBar")) ButtonSetupFunctions.append((_("Show favourites list"), "Infobar/openBouquets", "InfoBar")) ButtonSetupFunctions.append((_("Show satellites list"), "Infobar/openSatellites", "InfoBar")) ButtonSetupFunctions.append((_("History back"), "Infobar/historyBack", "InfoBar")) ButtonSetupFunctions.append((_("History next"), "Infobar/historyNext", "InfoBar")) ButtonSetupFunctions.append((_("Show eventinfo plugins"), "Infobar/showEventInfoPlugins", "EPG")) ButtonSetupFunctions.append((_("Show event details"), "Infobar/openEventView", "EPG")) ButtonSetupFunctions.append((_("Show single service EPG"), "Infobar/openSingleServiceEPG", "EPG")) ButtonSetupFunctions.append((_("Show multi channel EPG"), "Infobar/openMultiServiceEPG", "EPG")) ButtonSetupFunctions.append((_("Show Audioselection"), "Infobar/audioSelection", "InfoBar")) ButtonSetupFunctions.append((_("Enable digital downmix"), "Infobar/audioDownmixOn", "InfoBar")) ButtonSetupFunctions.append((_("Disable digital downmix"), "Infobar/audioDownmixOff", "InfoBar")) ButtonSetupFunctions.append((_("Switch to radio mode"), "Infobar/showRadio", "InfoBar")) ButtonSetupFunctions.append((_("Switch to TV mode"), "Infobar/showTv", "InfoBar")) ButtonSetupFunctions.append((_("Show servicelist or movies"), "Infobar/showServiceListOrMovies", "InfoBar")) ButtonSetupFunctions.append((_("Show movies"), "Infobar/showMovies", "InfoBar")) ButtonSetupFunctions.append((_("Instant record"), "Infobar/instantRecord", "InfoBar")) ButtonSetupFunctions.append((_("Start instant recording"), "Infobar/startInstantRecording", "InfoBar")) ButtonSetupFunctions.append((_("Activate timeshift End"), "Infobar/activateTimeshiftEnd", "InfoBar")) ButtonSetupFunctions.append((_("Activate timeshift end and pause"), "Infobar/activateTimeshiftEndAndPause", "InfoBar")) ButtonSetupFunctions.append((_("Start timeshift"), "Infobar/startTimeshift", "InfoBar")) ButtonSetupFunctions.append((_("Stop timeshift"), "Infobar/stopTimeshift", "InfoBar")) ButtonSetupFunctions.append((_("Start teletext"), "Infobar/startTeletext", "InfoBar")) ButtonSetupFunctions.append((_("Show subservice selection"), "Infobar/subserviceSelection", "InfoBar")) ButtonSetupFunctions.append((_("Show subtitle selection"), "Infobar/subtitleSelection", "InfoBar")) ButtonSetupFunctions.append((_("Show subtitle quick menu"), "Infobar/subtitleQuickMenu", "InfoBar")) ButtonSetupFunctions.append((_("Letterbox zoom"), "Infobar/vmodeSelection", "InfoBar")) if SystemInfo["PIPAvailable"]: ButtonSetupFunctions.append((_("Show PIP"), "Infobar/showPiP", "InfoBar")) ButtonSetupFunctions.append((_("Swap PIP"), "Infobar/swapPiP", "InfoBar")) ButtonSetupFunctions.append((_("Move PIP"), "Infobar/movePiP", "InfoBar")) ButtonSetupFunctions.append((_("Toggle PIPzap"), "Infobar/togglePipzap", "InfoBar")) ButtonSetupFunctions.append((_("Activate HbbTV (Redbutton)"), "Infobar/activateRedButton", "InfoBar")) ButtonSetupFunctions.append((_("Toggle HDMI-In full screen"), "Infobar/HDMIInFull", "InfoBar")) ButtonSetupFunctions.append((_("Toggle HDMI-In PiP"), "Infobar/HDMIInPiP", "InfoBar")) if SystemInfo["LcdLiveTV"]: ButtonSetupFunctions.append((_("Toggle LCD LiveTV"), "Infobar/ToggleLCDLiveTV", "InfoBar")) ButtonSetupFunctions.append((_("Hotkey Setup"), "Module/Screens.ButtonSetup/ButtonSetup", "Setup")) ButtonSetupFunctions.append((_("Software update"), "Module/Screens.SoftwareUpdate/UpdatePlugin", "Setup")) ButtonSetupFunctions.append((_("CI (Common Interface) Setup"), "Module/Screens.Ci/CiSelection", "Setup")) ButtonSetupFunctions.append((_("Tuner Configuration"), "Module/Screens.Satconfig/NimSelection", "Scanning")) ButtonSetupFunctions.append((_("Manual Scan"), "Module/Screens.ScanSetup/ScanSetup", "Scanning")) ButtonSetupFunctions.append((_("Automatic Scan"), "Module/Screens.ScanSetup/ScanSimple", "Scanning")) for plugin in plugins.getPluginsForMenu("scan"): ButtonSetupFunctions.append((plugin[0], "MenuPlugin/scan/" + plugin[2], "Scanning")) ButtonSetupFunctions.append((_("Network setup"), "Module/Screens.NetworkSetup/NetworkAdapterSelection", "Setup")) ButtonSetupFunctions.append((_("Network menu"), "Infobar/showNetworkMounts", "Setup")) ButtonSetupFunctions.append((_("Plugin Browser"), "Module/Screens.PluginBrowser/PluginBrowser", "Setup")) ButtonSetupFunctions.append((_("Channel Info"), "Module/Screens.ServiceInfo/ServiceInfo", "Setup")) ButtonSetupFunctions.append((_("SkinSelector"), "Module/Screens.SkinSelector/SkinSelector", "Setup")) ButtonSetupFunctions.append((_("LCD SkinSelector"), "Module/Screens.SkinSelector/LcdSkinSelector", "Setup")) ButtonSetupFunctions.append((_("Timer"), "Module/Screens.TimerEdit/TimerEditList", "Setup")) ButtonSetupFunctions.append((_("Open AutoTimer"), "Infobar/showAutoTimerList", "Setup")) for plugin in plugins.getPluginsForMenu("system"): if plugin[2]: ButtonSetupFunctions.append((plugin[0], "MenuPlugin/system/" + plugin[2], "Setup")) ButtonSetupFunctions.append((_("Standby"), "Module/Screens.Standby/Standby", "Power")) ButtonSetupFunctions.append((_("Restart"), "Module/Screens.Standby/TryQuitMainloop/2", "Power")) ButtonSetupFunctions.append((_("Restart enigma"), "Module/Screens.Standby/TryQuitMainloop/3", "Power")) ButtonSetupFunctions.append((_("Deep standby"), "Module/Screens.Standby/TryQuitMainloop/1", "Power")) ButtonSetupFunctions.append((_("SleepTimer"), "Module/Screens.SleepTimerEdit/SleepTimerEdit", "Power")) ButtonSetupFunctions.append((_("PowerTimer"), "Module/Screens.PowerTimerEdit/PowerTimerEditList", "Power")) ButtonSetupFunctions.append((_("Usage Setup"), "Setup/usage", "Setup")) ButtonSetupFunctions.append((_("User interface settings"), "Setup/userinterface", "Setup")) ButtonSetupFunctions.append((_("Recording Setup"), "Setup/recording", "Setup")) ButtonSetupFunctions.append((_("Harddisk Setup"), "Setup/harddisk", "Setup")) ButtonSetupFunctions.append((_("Subtitles Settings"), "Setup/subtitlesetup", "Setup")) ButtonSetupFunctions.append((_("Language"), "Module/Screens.LanguageSelection/LanguageSelection", "Setup")) ButtonSetupFunctions.append((_("OscamInfo Mainmenu"), "Module/Screens.OScamInfo/OscamInfoMenu", "Plugins")) ButtonSetupFunctions.append((_("CCcamInfo Mainmenu"), "Module/Screens.CCcamInfo/CCcamInfoMain", "Plugins")) ButtonSetupFunctions.append((_("Movieplayer"), "Module/Screens.MovieSelection/MovieSelection", "Plugins")) if os.path.isdir("/etc/ppanels"): for x in [x for x in os.listdir("/etc/ppanels") if x.endswith(".xml")]: x = x[:-4] ButtonSetupFunctions.append((_("PPanel") + " " + x, "PPanel/" + x, "PPanels")) if os.path.isdir("/usr/script"): for x in [x for x in os.listdir("/usr/script") if x.endswith(".sh")]: x = x[:-3] ButtonSetupFunctions.append((_("Shellscript") + " " + x, "Shellscript/" + x, "Shellscripts")) if os.path.isfile("/usr/lib/enigma2/python/Plugins/Extensions/Infopanel/ScriptRunner.pyo"): ButtonSetupFunctions.append((_("ScriptRunner"), "ScriptRunner/", "Plugins")) if os.path.isfile("/usr/lib/enigma2/python/Plugins/Extensions/Infopanel/QuickMenu.pyo"): ButtonSetupFunctions.append((_("QuickMenu"), "QuickMenu/", "Plugins")) if os.path.isfile("/usr/lib/enigma2/python/Plugins/Extensions/Kodi/plugin.pyo"): ButtonSetupFunctions.append((_("Kodi MediaCenter"), "Kodi/", "Plugins")) return ButtonSetupFunctions class ButtonSetup(Screen): def __init__(self, session, args=None): Screen.__init__(self, session) self['description'] = Label(_('Click on your remote on the button you want to change')) self.session = session self.setTitle(_("Hotkey Setup")) self["key_red"] = Button(_("Exit")) self.list = [] self.ButtonSetupKeys = getButtonSetupKeys() self.ButtonSetupFunctions = getButtonSetupFunctions() for x in self.ButtonSetupKeys: self.list.append(ChoiceEntryComponent('',(_(x[0]), x[1]))) self["list"] = ChoiceList(list=self.list[:config.misc.ButtonSetup.additional_keys.value and len(self.ButtonSetupKeys) or 10], selection = 0) self["choosen"] = ChoiceList(list=[]) self.getFunctions() self["actions"] = ActionMap(["OkCancelActions"], { "cancel": self.close, }, -1) self["ButtonSetupButtonActions"] = ButtonSetupActionMap(["ButtonSetupActions"], dict((x[1], self.ButtonSetupGlobal) for x in self.ButtonSetupKeys)) self.longkeyPressed = False self.onLayoutFinish.append(self.__layoutFinished) self.onExecBegin.append(self.getFunctions) self.onShown.append(self.disableKeyMap) self.onClose.append(self.enableKeyMap) def __layoutFinished(self): self["choosen"].selectionEnabled(0) def disableKeyMap(self): globalActionMap.setEnabled(False) eActionMap.getInstance().unbindNativeKey("ListboxActions", 0) eActionMap.getInstance().unbindNativeKey("ListboxActions", 1) eActionMap.getInstance().unbindNativeKey("ListboxActions", 4) eActionMap.getInstance().unbindNativeKey("ListboxActions", 5) def enableKeyMap(self): globalActionMap.setEnabled(True) eActionMap.getInstance().bindKey("keymap.xml", "generic", 103, 5, "ListboxActions", "moveUp") eActionMap.getInstance().bindKey("keymap.xml", "generic", 108, 5, "ListboxActions", "moveDown") eActionMap.getInstance().bindKey("keymap.xml", "generic", 105, 5, "ListboxActions", "pageUp") eActionMap.getInstance().bindKey("keymap.xml", "generic", 106, 5, "ListboxActions", "pageDown") def ButtonSetupGlobal(self, key): if self.longkeyPressed: self.longkeyPressed = False else: index = 0 for x in self.list[:config.misc.ButtonSetup.additional_keys.value and len(self.ButtonSetupKeys) or 10]: if key == x[0][1]: self["list"].moveToIndex(index) if key.endswith("_long"): self.longkeyPressed = True break index += 1 self.getFunctions() self.session.open(ButtonSetupSelect, self["list"].l.getCurrentSelection()) def getFunctions(self): key = self["list"].l.getCurrentSelection()[0][1] if key: selected = [] for x in eval("config.misc.ButtonSetup." + key + ".value.split(',')"): function = list(function for function in self.ButtonSetupFunctions if function[1] == x ) if function: selected.append(ChoiceEntryComponent('',((function[0][0]), function[0][1]))) self["choosen"].setList(selected) class ButtonSetupSelect(Screen): def __init__(self, session, key, args=None): Screen.__init__(self, session) self.skinName="ButtonSetupSelect" self['description'] = Label(_('Select the desired function and click on "OK" to assign it. Use "CH+/-" to toggle between the lists. Select an assigned function and click on "OK" to de-assign it. Use "Next/Previous" to change the order of the assigned functions.')) self.session = session self.key = key self.setTitle(_("Hotkey Setup for") + ": " + key[0][0]) self["key_red"] = Button(_("Cancel")) self["key_green"] = Button(_("Save")) self.mode = "list" self.ButtonSetupFunctions = getButtonSetupFunctions() self.config = eval("config.misc.ButtonSetup." + key[0][1]) self.expanded = [] self.selected = [] for x in self.config.value.split(','): function = list(function for function in self.ButtonSetupFunctions if function[1] == x ) if function: self.selected.append(ChoiceEntryComponent('',((function[0][0]), function[0][1]))) self.prevselected = self.selected[:] self["choosen"] = ChoiceList(list=self.selected, selection=0) self["list"] = ChoiceList(list=self.getFunctionList(), selection=0) self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions", "KeyboardInputActions"], { "ok": self.keyOk, "cancel": self.cancel, "red": self.cancel, "green": self.save, "up": self.keyUp, "down": self.keyDown, "left": self.keyLeft, "right": self.keyRight, "pageUp": self.toggleMode, "pageDown": self.toggleMode, "shiftUp": self.moveUp, "shiftDown": self.moveDown, }, -1) self.onShown.append(self.enableKeyMap) self.onClose.append(self.disableKeyMap) self.onLayoutFinish.append(self.__layoutFinished) def __layoutFinished(self): self["choosen"].selectionEnabled(0) def disableKeyMap(self): globalActionMap.setEnabled(False) eActionMap.getInstance().unbindNativeKey("ListboxActions", 0) eActionMap.getInstance().unbindNativeKey("ListboxActions", 1) eActionMap.getInstance().unbindNativeKey("ListboxActions", 4) eActionMap.getInstance().unbindNativeKey("ListboxActions", 5) def enableKeyMap(self): globalActionMap.setEnabled(True) eActionMap.getInstance().bindKey("keymap.xml", "generic", 103, 5, "ListboxActions", "moveUp") eActionMap.getInstance().bindKey("keymap.xml", "generic", 108, 5, "ListboxActions", "moveDown") eActionMap.getInstance().bindKey("keymap.xml", "generic", 105, 5, "ListboxActions", "pageUp") eActionMap.getInstance().bindKey("keymap.xml", "generic", 106, 5, "ListboxActions", "pageDown") def getFunctionList(self): functionslist = [] catagories = {} for function in self.ButtonSetupFunctions: if not catagories.has_key(function[2]): catagories[function[2]] = [] catagories[function[2]].append(function) for catagorie in sorted(list(catagories)): if catagorie in self.expanded: functionslist.append(ChoiceEntryComponent('expanded',((catagorie), "Expander"))) for function in catagories[catagorie]: functionslist.append(ChoiceEntryComponent('verticalline',((function[0]), function[1]))) else: functionslist.append(ChoiceEntryComponent('expandable',((catagorie), "Expander"))) return functionslist def toggleMode(self): if self.mode == "list" and self.selected: self.mode = "choosen" self["choosen"].selectionEnabled(1) self["list"].selectionEnabled(0) elif self.mode == "choosen": self.mode = "list" self["choosen"].selectionEnabled(0) self["list"].selectionEnabled(1) def keyOk(self): if self.mode == "list": currentSelected = self["list"].l.getCurrentSelection() if currentSelected[0][1] == "Expander": if currentSelected[0][0] in self.expanded: self.expanded.remove(currentSelected[0][0]) else: self.expanded.append(currentSelected[0][0]) self["list"].setList(self.getFunctionList()) else: if currentSelected[:2] in self.selected: self.selected.remove(currentSelected[:2]) else: self.selected.append(currentSelected[:2]) elif self.selected: self.selected.remove(self["choosen"].l.getCurrentSelection()) if not self.selected: self.toggleMode() self["choosen"].setList(self.selected) def keyLeft(self): self[self.mode].instance.moveSelection(self[self.mode].instance.pageUp) def keyRight(self): self[self.mode].instance.moveSelection(self[self.mode].instance.pageDown) def keyUp(self): self[self.mode].instance.moveSelection(self[self.mode].instance.moveUp) def keyDown(self): self[self.mode].instance.moveSelection(self[self.mode].instance.moveDown) def moveUp(self): self.moveChoosen(self.keyUp) def moveDown(self): self.moveChoosen(self.keyDown) def moveChoosen(self, direction): if self.mode == "choosen": currentIndex = self["choosen"].getSelectionIndex() swapIndex = (currentIndex + (direction == self.keyDown and 1 or -1)) % len(self["choosen"].list) self["choosen"].list[currentIndex], self["choosen"].list[swapIndex] = self["choosen"].list[swapIndex], self["choosen"].list[currentIndex] self["choosen"].setList(self["choosen"].list) direction() else: return 0 def save(self): configValue = [] for x in self.selected: configValue.append(x[0][1]) self.config.value = ",".join(configValue) self.config.save() self.close() def cancel(self): if self.selected != self.prevselected: self.session.openWithCallback(self.cancelCallback, MessageBox, _("Are you sure to cancel all changes"), default=False) else: self.close() def cancelCallback(self, answer): answer and self.close() class ButtonSetupActionMap(ActionMap): def action(self, contexts, action): if (action in tuple(x[1] for x in getButtonSetupKeys()) and self.actions.has_key(action)): res = self.actions[action](action) if res is not None: return res return 1 else: return ActionMap.action(self, contexts, action) class helpableButtonSetupActionMap(HelpableActionMap): def action(self, contexts, action): if (action in tuple(x[1] for x in getButtonSetupKeys()) and self.actions.has_key(action)): res = self.actions[action](action) if res is not None: return res return 1 else: return ActionMap.action(self, contexts, action) class InfoBarButtonSetup(): def __init__(self): self.ButtonSetupKeys = getButtonSetupKeys() self["ButtonSetupButtonActions"] = helpableButtonSetupActionMap(self, "ButtonSetupActions", dict((x[1],(self.ButtonSetupGlobal, boundFunction(self.getHelpText, x[1]))) for x in self.ButtonSetupKeys), -10) self.longkeyPressed = False self.onExecEnd.append(self.clearLongkeyPressed) def clearLongkeyPressed(self): self.longkeyPressed = False def getKeyFunctions(self, key): if key in ("play", "playpause", "Stop", "stop", "pause", "rewind", "next", "previous", "fastforward", "skip_back", "skip_forward") and (self.__class__.__name__ == "MoviePlayer" or hasattr(self, "timeshiftActivated") and self.timeshiftActivated()): return False selection = eval("config.misc.ButtonSetup." + key + ".value.split(',')") selected = [] for x in selection: if x.startswith("ZapPanic"): selected.append(((_("Panic to") + " " + ServiceReference(eServiceReference(x.split("/", 1)[1]).toString()).getServiceName()), x)) elif x.startswith("Zap"): selected.append(((_("Zap to") + " " + ServiceReference(eServiceReference(x.split("/", 1)[1]).toString()).getServiceName()), x)) else: function = list(function for function in getButtonSetupFunctions() if function[1] == x ) if function: selected.append(function[0]) return selected def getHelpText(self, key): selected = self.getKeyFunctions(key) if not selected: return if len(selected) == 1: return selected[0][0] else: return _("ButtonSetup") + " " + tuple(x[0] for x in self.ButtonSetupKeys if x[1] == key)[0] def ButtonSetupGlobal(self, key): if self.longkeyPressed: self.longkeyPressed = False else: selected = self.getKeyFunctions(key) if not selected: return 0 elif len(selected) == 1: if key.endswith("_long"): self.longkeyPressed = True return self.execButtonSetup(selected[0]) else: key = tuple(x[0] for x in self.ButtonSetupKeys if x[1] == key)[0] self.session.openWithCallback(self.execButtonSetup, ChoiceBox, (_("Hotkey")) + " " + key, selected) def execButtonSetup(self, selected): if selected: selected = selected[1].split("/") if selected[0] == "Plugins": twinPlugins = [] twinPaths = {} pluginlist = plugins.getPlugins(PluginDescriptor.WHERE_EVENTINFO) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path and 'selectedevent' not in plugin.__call__.func_code.co_varnames: if twinPaths.has_key(plugin.path[24:]): twinPaths[plugin.path[24:]] += 1 else: twinPaths[plugin.path[24:]] = 1 if plugin.path[24:] + "/" + str(twinPaths[plugin.path[24:]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) pluginlist = plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU]) pluginlist.sort(key=lambda p: p.name) for plugin in pluginlist: if plugin.name not in twinPlugins and plugin.path: if twinPaths.has_key(plugin.path[24:]): twinPaths[plugin.path[24:]] += 1 else: twinPaths[plugin.path[24:]] = 1 if plugin.path[24:] + "/" + str(twinPaths[plugin.path[24:]]) == "/".join(selected): self.runPlugin(plugin) return twinPlugins.append(plugin.name) elif selected[0] == "MenuPlugin": for plugin in plugins.getPluginsForMenu(selected[1]): if plugin[2] == selected[2]: self.runPlugin(plugin[1]) return elif selected[0] == "Infobar": if hasattr(self, selected[1]): exec "self." + ".".join(selected[1:]) + "()" else: return 0 elif selected[0] == "Module": try: exec "from " + selected[1] + " import *" exec "self.session.open(" + ",".join(selected[2:]) + ")" except: print "[ButtonSetup] error during executing module %s, screen %s" % (selected[1], selected[2]) elif selected[0] == "Setup": exec "from Screens.Setup import *" exec "self.session.open(Setup, \"" + selected[1] + "\")" elif selected[0].startswith("Zap"): if selected[0] == "ZapPanic": self.servicelist.history = [] self.pipShown() and self.showPiP() self.servicelist.servicelist.setCurrent(eServiceReference("/".join(selected[1:]))) self.servicelist.zap(enable_pipzap = True) if hasattr(self, "lastservice"): self.lastservice = eServiceReference("/".join(selected[1:])) self.close() else: self.show() from Screens.MovieSelection import defaultMoviePath moviepath = defaultMoviePath() if moviepath: config.movielist.last_videodir.value = moviepath elif selected[0] == "PPanel": ppanelFileName = '/etc/ppanels/' + selected[1] + ".xml" if os.path.isfile(ppanelFileName) and os.path.isdir('/usr/lib/enigma2/python/Plugins/Extensions/PPanel'): from Plugins.Extensions.PPanel.ppanel import PPanel self.session.open(PPanel, name=selected[1] + ' PPanel', node=None, filename=ppanelFileName, deletenode=None) elif selected[0] == "Shellscript": command = '/usr/script/' + selected[1] + ".sh" if os.path.isfile(command) and os.path.isdir('/usr/lib/enigma2/python/Plugins/Extensions/PPanel'): from Plugins.Extensions.PPanel.ppanel import Execute self.session.open(Execute, selected[1] + " shellscript", None, command) else: from Screens.Console import Console exec "self.session.open(Console,_(selected[1]),[command])" elif selected[0] == "EMC": try: from Plugins.Extensions.EnhancedMovieCenter.plugin import showMoviesNew from Screens.InfoBar import InfoBar open(showMoviesNew(InfoBar.instance)) except Exception as e: print('[EMCPlayer] showMovies exception:\n' + str(e)) elif selected[0] == "ScriptRunner": if os.path.isfile("/usr/lib/enigma2/python/Plugins/Extensions/Infopanel/ScriptRunner.pyo"): from Plugins.Extensions.Infopanel.ScriptRunner import ScriptRunner self.session.open (ScriptRunner) elif selected[0] == "QuickMenu": if os.path.isfile("/usr/lib/enigma2/python/Plugins/Extensions/Infopanel/QuickMenu.pyo"): from Plugins.Extensions.Infopanel.QuickMenu import QuickMenu self.session.open (QuickMenu) elif selected[0] == "Kodi": if os.path.isfile("/usr/lib/enigma2/python/Plugins/Extensions/Kodi/plugin.pyo"): from Plugins.Extensions.Kodi.plugin import KodiMainScreen self.session.open(KodiMainScreen) def showServiceListOrMovies(self): if hasattr(self, "openServiceList"): self.openServiceList() elif hasattr(self, "showMovies"): self.showMovies() def ToggleLCDLiveTV(self): config.lcd.showTv.value = not config.lcd.showTv.value
gpl-2.0
andyzsf/django
django/utils/formats.py
29
8485
from __future__ import absolute_import # Avoid importing `importlib` from this package. import decimal import datetime from importlib import import_module import unicodedata from django.conf import settings from django.utils import dateformat, numberformat, datetime_safe from django.utils.encoding import force_str from django.utils.functional import lazy from django.utils.safestring import mark_safe from django.utils import six from django.utils.translation import get_language, to_locale, check_for_language # format_cache is a mapping from (format_type, lang) to the format string. # By using the cache, it is possible to avoid running get_format_modules # repeatedly. _format_cache = {} _format_modules_cache = {} ISO_INPUT_FORMATS = { 'DATE_INPUT_FORMATS': ('%Y-%m-%d',), 'TIME_INPUT_FORMATS': ('%H:%M:%S', '%H:%M:%S.%f', '%H:%M'), 'DATETIME_INPUT_FORMATS': ( '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d' ), } def reset_format_cache(): """Clear any cached formats. This method is provided primarily for testing purposes, so that the effects of cached formats can be removed. """ global _format_cache, _format_modules_cache _format_cache = {} _format_modules_cache = {} def iter_format_modules(lang, format_module_path=None): """ Does the heavy lifting of finding format modules. """ if not check_for_language(lang): return if format_module_path is None: format_module_path = settings.FORMAT_MODULE_PATH format_locations = [] if format_module_path: if isinstance(format_module_path, six.string_types): format_module_path = [format_module_path] for path in format_module_path: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') locale = to_locale(lang) locales = [locale] if '_' in locale: locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: try: yield import_module('%s.formats' % (location % loc)) except ImportError: pass def get_format_modules(lang=None, reverse=False): """ Returns a list of the format modules found """ if lang is None: lang = get_language() modules = _format_modules_cache.setdefault(lang, list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH))) if reverse: return list(reversed(modules)) return modules def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, returns the format for the current language (locale), defaults to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT' If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ format_type = force_str(format_type) if use_l10n or (use_l10n is None and settings.USE_L10N): if lang is None: lang = get_language() cache_key = (format_type, lang) try: cached = _format_cache[cache_key] if cached is not None: return cached else: # Return the general setting by default return getattr(settings, format_type) except KeyError: for module in get_format_modules(lang): try: val = getattr(module, format_type) for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): if iso_input not in val: if isinstance(val, tuple): val = list(val) val.append(iso_input) _format_cache[cache_key] = val return val except AttributeError: pass _format_cache[cache_key] = None return getattr(settings, format_type) get_format_lazy = lazy(get_format, six.text_type, list, tuple) def date_format(value, format=None, use_l10n=None): """ Formats a datetime.date or datetime.datetime object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n)) def time_format(value, format=None, use_l10n=None): """ Formats a datetime.time object using a localizable format If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n)) def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Formats a numeric value using localization settings If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n or (use_l10n is None and settings.USE_L10N): lang = get_language() else: lang = None return numberformat.format( value, get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n), decimal_pos, get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n), get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n), force_grouping=force_grouping ) def localize(value, use_l10n=None): """ Checks if value is a localizable type (date, number...) and returns it formatted as a string using current locale format. If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ if isinstance(value, bool): return mark_safe(six.text_type(value)) elif isinstance(value, (decimal.Decimal, float) + six.integer_types): return number_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.datetime): return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n) elif isinstance(value, datetime.date): return date_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.time): return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n) else: return value def localize_input(value, default=None): """ Checks if an input value is a localizable type and returns it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, (decimal.Decimal, float) + six.integer_types): return number_format(value) elif isinstance(value, datetime.datetime): value = datetime_safe.new_datetime(value) format = force_str(default or get_format('DATETIME_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.date): value = datetime_safe.new_date(value) format = force_str(default or get_format('DATE_INPUT_FORMATS')[0]) return value.strftime(format) elif isinstance(value, datetime.time): format = force_str(default or get_format('TIME_INPUT_FORMATS')[0]) return value.strftime(format) return value def sanitize_separators(value): """ Sanitizes a value according to the current decimal and thousand separator setting. Used with form field input. """ if settings.USE_L10N and isinstance(value, six.string_types): parts = [] decimal_separator = get_format('DECIMAL_SEPARATOR') if decimal_separator in value: value, decimals = value.split(decimal_separator, 1) parts.append(decimals) if settings.USE_THOUSAND_SEPARATOR: thousand_sep = get_format('THOUSAND_SEPARATOR') if thousand_sep == '.' and value.count('.') == 1 and len(value.split('.')[-1]) != 3: # Special case where we suspect a dot meant decimal separator (see #22171) pass else: for replacement in { thousand_sep, unicodedata.normalize('NFKD', thousand_sep)}: value = value.replace(replacement, '') parts.append(value) value = '.'.join(reversed(parts)) return value
bsd-3-clause
llonchj/sentry
tests/sentry/web/frontend/tests.py
2
7035
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.core.urlresolvers import reverse from exam import fixture from sentry.constants import MEMBER_USER from sentry.models import User from sentry.testutils import TestCase class EnvStatusTest(TestCase): @fixture def path(self): return reverse('sentry-admin-status') def test_requires_auth(self): resp = self.client.get(self.path) self.assertEquals(resp.status_code, 302) def test_renders_template(self): self.login_as(self.user) resp = self.client.get(self.path) self.assertEquals(resp.status_code, 200) self.assertTemplateUsed(resp, 'sentry/admin/status/env.html') class PackageStatusTest(TestCase): @fixture def path(self): return reverse('sentry-admin-packages-status') def test_requires_auth(self): resp = self.client.get(self.path) self.assertEquals(resp.status_code, 302) def test_renders_template(self): self.login_as(self.user) resp = self.client.get(self.path) self.assertEquals(resp.status_code, 200) self.assertTemplateUsed(resp, 'sentry/admin/status/packages.html') class MailStatusTest(TestCase): @fixture def path(self): return reverse('sentry-admin-mail-status') def test_requires_auth(self): resp = self.client.get(self.path) self.assertEquals(resp.status_code, 302) def test_renders_template(self): self.login_as(self.user) resp = self.client.get(self.path) self.assertEquals(resp.status_code, 200) self.assertTemplateUsed(resp, 'sentry/admin/status/mail.html') class OverviewTest(TestCase): @fixture def path(self): return reverse('sentry-admin-overview') def test_requires_auth(self): resp = self.client.get(self.path) self.assertEquals(resp.status_code, 302) def test_renders_template(self): self.login_as(self.user) resp = self.client.get(self.path) self.assertEquals(resp.status_code, 200) self.assertTemplateUsed(resp, 'sentry/admin/stats.html') class ManageUsersTest(TestCase): @fixture def path(self): return reverse('sentry-admin-users') def test_does_render(self): self.login_as(self.user) resp = self.client.get(self.path) assert resp.status_code == 200 self.assertTemplateUsed(resp, 'sentry/admin/users/list.html') class ReplayTest(TestCase): @fixture def path(self): return reverse('sentry-replay', kwargs={ 'organization_slug': self.organization.slug, 'project_id': self.project.slug, 'group_id': self.group.id, 'event_id': self.event.id, }) def test_does_render(self): self.login_as(self.user) resp = self.client.get(self.path) self.assertEquals(resp.status_code, 200) self.assertTemplateUsed(resp, 'sentry/events/replay_request.html') class PermissionBase(TestCase): """ These tests simply ensure permission requirements for various views. """ @fixture def admin(self): user = User(username="admin", email="admin@localhost", is_staff=True, is_superuser=True) user.set_password('admin') user.save() return user @fixture def member(self): user = User(username="member", email="member@localhost") user.set_password('member') user.save() om = self.create_member( organization=self.team.organization, user=user, type=MEMBER_USER, teams=[self.team], ) return user @fixture def nobody(self): user = User(username="nobody", email="nobody@localhost") user.set_password('nobody') user.save() return user @fixture def owner(self): user = User(username="owner", email="owner@localhost") user.set_password('owner') user.save() return user @fixture def organization(self): return self.create_organization(owner=self.owner) @fixture def team(self): return self.create_team(slug='foo', organization=self.organization) @fixture def project(self): project = self.create_project(slug='test') return project def _assertPerm(self, path, template, account=None, want=True): """ Requests ``path`` and asserts that ``template`` is rendered for ``account`` (Anonymous if None) given ``want`` is Trueish. """ if account: self.login_as(getattr(self, account)) else: self.client.logout() resp = self.client.get(path) if want: self.assertEquals(resp.status_code, 200) self.assertTemplateUsed(resp, template) else: self.assertEquals(resp.status_code, 302) self.assertTemplateNotUsed(resp, template) class RemoveProjectTest(PermissionBase): template = 'sentry/projects/remove.html' @fixture def path(self): return reverse('sentry-remove-project', kwargs={'organization_slug': self.organization.slug, 'project_slug': self.project.slug}) def test_admin_cannot_remove_default(self): with self.settings(SENTRY_PROJECT=self.project.id): self._assertPerm(self.path, self.template, self.admin.username, False) def test_owner_cannot_remove_default(self): with self.settings(SENTRY_PROJECT=self.project.id): self._assertPerm(self.path, self.template, self.owner.username, False) def test_anonymous_cannot_remove_default(self): with self.settings(SENTRY_PROJECT=self.project.id): self._assertPerm(self.path, self.template, None, False) def test_user_cannot_remove_default(self): with self.settings(SENTRY_PROJECT=self.project.id): self._assertPerm(self.path, self.template, self.nobody.username, False) def test_member_cannot_remove_default(self): with self.settings(SENTRY_PROJECT=self.project.id): self._assertPerm(self.path, self.template, self.member.username, False) def test_admin_can_load(self): with self.settings(SENTRY_PROJECT=-1): self._assertPerm(self.path, self.template, self.admin.username) def test_owner_can_load(self): with self.settings(SENTRY_PROJECT=-1): self._assertPerm(self.path, self.template, self.owner.username) def test_anonymous_cannot_load(self): with self.settings(SENTRY_PROJECT=-1): self._assertPerm(self.path, self.template, None, False) def test_user_cannot_load(self): with self.settings(SENTRY_PROJECT=-1): self._assertPerm(self.path, self.template, self.nobody.username, False) def test_member_cannot_load(self): with self.settings(SENTRY_PROJECT=-1): self._assertPerm(self.path, self.template, self.member.username, False)
bsd-3-clause
amghost/myblog
node_modules/pygmentize-bundled/vendor/pygments/build-3.3/pygments/formatters/html.py
94
31067
# -*- coding: utf-8 -*- """ pygments.formatters.html ~~~~~~~~~~~~~~~~~~~~~~~~ Formatter for HTML output. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import os import sys import os.path import io from pygments.formatter import Formatter from pygments.token import Token, Text, STANDARD_TYPES from pygments.util import get_bool_opt, get_int_opt, get_list_opt, bytes try: import ctags except ImportError: ctags = None __all__ = ['HtmlFormatter'] _escape_html_table = { ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;', ord('"'): '&quot;', ord("'"): '&#39;', } def escape_html(text, table=_escape_html_table): """Escape &, <, > as well as single and double quotes for HTML.""" return text.translate(table) def get_random_id(): """Return a random id for javascript fields.""" from random import random from time import time try: from hashlib import sha1 as sha except ImportError: import sha sha = sha.new return sha('%s|%s' % (random(), time())).hexdigest() def _get_ttype_class(ttype): fname = STANDARD_TYPES.get(ttype) if fname: return fname aname = '' while fname is None: aname = '-' + ttype[-1] + aname ttype = ttype.parent fname = STANDARD_TYPES.get(ttype) return fname + aname CSSFILE_TEMPLATE = '''\ td.linenos { background-color: #f0f0f0; padding-right: 10px; } span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } pre { line-height: 125%%; } %(styledefs)s ''' DOC_HEADER = '''\ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>%(title)s</title> <meta http-equiv="content-type" content="text/html; charset=%(encoding)s"> <style type="text/css"> ''' + CSSFILE_TEMPLATE + ''' </style> </head> <body> <h2>%(title)s</h2> ''' DOC_HEADER_EXTERNALCSS = '''\ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>%(title)s</title> <meta http-equiv="content-type" content="text/html; charset=%(encoding)s"> <link rel="stylesheet" href="%(cssfile)s" type="text/css"> </head> <body> <h2>%(title)s</h2> ''' DOC_FOOTER = '''\ </body> </html> ''' class HtmlFormatter(Formatter): r""" Format tokens as HTML 4 ``<span>`` tags within a ``<pre>`` tag, wrapped in a ``<div>`` tag. The ``<div>``'s CSS class can be set by the `cssclass` option. If the `linenos` option is set to ``"table"``, the ``<pre>`` is additionally wrapped inside a ``<table>`` which has one row and two cells: one containing the line numbers and one containing the code. Example: .. sourcecode:: html <div class="highlight" > <table><tr> <td class="linenos" title="click to toggle" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"> <pre>1 2</pre> </td> <td class="code"> <pre><span class="Ke">def </span><span class="NaFu">foo</span>(bar): <span class="Ke">pass</span> </pre> </td> </tr></table></div> (whitespace added to improve clarity). Wrapping can be disabled using the `nowrap` option. A list of lines can be specified using the `hl_lines` option to make these lines highlighted (as of Pygments 0.11). With the `full` option, a complete HTML 4 document is output, including the style definitions inside a ``<style>`` tag, or in a separate file if the `cssfile` option is given. When `tagsfile` is set to the path of a ctags index file, it is used to generate hyperlinks from names to their definition. You must enable `anchorlines` and run ctags with the `-n` option for this to work. The `python-ctags` module from PyPI must be installed to use this feature; otherwise a `RuntimeError` will be raised. The `get_style_defs(arg='')` method of a `HtmlFormatter` returns a string containing CSS rules for the CSS classes used by the formatter. The argument `arg` can be used to specify additional CSS selectors that are prepended to the classes. A call `fmter.get_style_defs('td .code')` would result in the following CSS classes: .. sourcecode:: css td .code .kw { font-weight: bold; color: #00FF00 } td .code .cm { color: #999999 } ... If you have Pygments 0.6 or higher, you can also pass a list or tuple to the `get_style_defs()` method to request multiple prefixes for the tokens: .. sourcecode:: python formatter.get_style_defs(['div.syntax pre', 'pre.syntax']) The output would then look like this: .. sourcecode:: css div.syntax pre .kw, pre.syntax .kw { font-weight: bold; color: #00FF00 } div.syntax pre .cm, pre.syntax .cm { color: #999999 } ... Additional options accepted: `nowrap` If set to ``True``, don't wrap the tokens at all, not even inside a ``<pre>`` tag. This disables most other options (default: ``False``). `full` Tells the formatter to output a "full" document, i.e. a complete self-contained document (default: ``False``). `title` If `full` is true, the title that should be used to caption the document (default: ``''``). `style` The style to use, can be a string or a Style subclass (default: ``'default'``). This option has no effect if the `cssfile` and `noclobber_cssfile` option are given and the file specified in `cssfile` exists. `noclasses` If set to true, token ``<span>`` tags will not use CSS classes, but inline styles. This is not recommended for larger pieces of code since it increases output size by quite a bit (default: ``False``). `classprefix` Since the token types use relatively short class names, they may clash with some of your own class names. In this case you can use the `classprefix` option to give a string to prepend to all Pygments-generated CSS class names for token types. Note that this option also affects the output of `get_style_defs()`. `cssclass` CSS class for the wrapping ``<div>`` tag (default: ``'highlight'``). If you set this option, the default selector for `get_style_defs()` will be this class. *New in Pygments 0.9:* If you select the ``'table'`` line numbers, the wrapping table will have a CSS class of this string plus ``'table'``, the default is accordingly ``'highlighttable'``. `cssstyles` Inline CSS styles for the wrapping ``<div>`` tag (default: ``''``). `prestyles` Inline CSS styles for the ``<pre>`` tag (default: ``''``). *New in Pygments 0.11.* `cssfile` If the `full` option is true and this option is given, it must be the name of an external file. If the filename does not include an absolute path, the file's path will be assumed to be relative to the main output file's path, if the latter can be found. The stylesheet is then written to this file instead of the HTML file. *New in Pygments 0.6.* `noclobber_cssfile` If `cssfile` is given and the specified file exists, the css file will not be overwritten. This allows the use of the `full` option in combination with a user specified css file. Default is ``False``. *New in Pygments 1.1.* `linenos` If set to ``'table'``, output line numbers as a table with two cells, one containing the line numbers, the other the whole code. This is copy-and-paste-friendly, but may cause alignment problems with some browsers or fonts. If set to ``'inline'``, the line numbers will be integrated in the ``<pre>`` tag that contains the code (that setting is *new in Pygments 0.8*). For compatibility with Pygments 0.7 and earlier, every true value except ``'inline'`` means the same as ``'table'`` (in particular, that means also ``True``). The default value is ``False``, which means no line numbers at all. **Note:** with the default ("table") line number mechanism, the line numbers and code can have different line heights in Internet Explorer unless you give the enclosing ``<pre>`` tags an explicit ``line-height`` CSS property (you get the default line spacing with ``line-height: 125%``). `hl_lines` Specify a list of lines to be highlighted. *New in Pygments 0.11.* `linenostart` The line number for the first line (default: ``1``). `linenostep` If set to a number n > 1, only every nth line number is printed. `linenospecial` If set to a number n > 0, every nth line number is given the CSS class ``"special"`` (default: ``0``). `nobackground` If set to ``True``, the formatter won't output the background color for the wrapping element (this automatically defaults to ``False`` when there is no wrapping element [eg: no argument for the `get_syntax_defs` method given]) (default: ``False``). *New in Pygments 0.6.* `lineseparator` This string is output between lines of code. It defaults to ``"\n"``, which is enough to break a line inside ``<pre>`` tags, but you can e.g. set it to ``"<br>"`` to get HTML line breaks. *New in Pygments 0.7.* `lineanchors` If set to a nonempty string, e.g. ``foo``, the formatter will wrap each output line in an anchor tag with a ``name`` of ``foo-linenumber``. This allows easy linking to certain lines. *New in Pygments 0.9.* `linespans` If set to a nonempty string, e.g. ``foo``, the formatter will wrap each output line in a span tag with an ``id`` of ``foo-linenumber``. This allows easy access to lines via javascript. *New in Pygments 1.6.* `anchorlinenos` If set to `True`, will wrap line numbers in <a> tags. Used in combination with `linenos` and `lineanchors`. `tagsfile` If set to the path of a ctags file, wrap names in anchor tags that link to their definitions. `lineanchors` should be used, and the tags file should specify line numbers (see the `-n` option to ctags). *New in Pygments 1.6.* `tagurlformat` A string formatting pattern used to generate links to ctags definitions. Available variables are `%(path)s`, `%(fname)s` and `%(fext)s`. Defaults to an empty string, resulting in just `#prefix-number` links. *New in Pygments 1.6.* **Subclassing the HTML formatter** *New in Pygments 0.7.* The HTML formatter is now built in a way that allows easy subclassing, thus customizing the output HTML code. The `format()` method calls `self._format_lines()` which returns a generator that yields tuples of ``(1, line)``, where the ``1`` indicates that the ``line`` is a line of the formatted source code. If the `nowrap` option is set, the generator is the iterated over and the resulting HTML is output. Otherwise, `format()` calls `self.wrap()`, which wraps the generator with other generators. These may add some HTML code to the one generated by `_format_lines()`, either by modifying the lines generated by the latter, then yielding them again with ``(1, line)``, and/or by yielding other HTML code before or after the lines, with ``(0, html)``. The distinction between source lines and other code makes it possible to wrap the generator multiple times. The default `wrap()` implementation adds a ``<div>`` and a ``<pre>`` tag. A custom `HtmlFormatter` subclass could look like this: .. sourcecode:: python class CodeHtmlFormatter(HtmlFormatter): def wrap(self, source, outfile): return self._wrap_code(source) def _wrap_code(self, source): yield 0, '<code>' for i, t in source: if i == 1: # it's a line of formatted code t += '<br>' yield i, t yield 0, '</code>' This results in wrapping the formatted lines with a ``<code>`` tag, where the source lines are broken using ``<br>`` tags. After calling `wrap()`, the `format()` method also adds the "line numbers" and/or "full document" wrappers if the respective options are set. Then, all HTML yielded by the wrapped generator is output. """ name = 'HTML' aliases = ['html'] filenames = ['*.html', '*.htm'] def __init__(self, **options): Formatter.__init__(self, **options) self.title = self._decodeifneeded(self.title) self.nowrap = get_bool_opt(options, 'nowrap', False) self.noclasses = get_bool_opt(options, 'noclasses', False) self.classprefix = options.get('classprefix', '') self.cssclass = self._decodeifneeded(options.get('cssclass', 'highlight')) self.cssstyles = self._decodeifneeded(options.get('cssstyles', '')) self.prestyles = self._decodeifneeded(options.get('prestyles', '')) self.cssfile = self._decodeifneeded(options.get('cssfile', '')) self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile', False) self.tagsfile = self._decodeifneeded(options.get('tagsfile', '')) self.tagurlformat = self._decodeifneeded(options.get('tagurlformat', '')) if self.tagsfile: if not ctags: raise RuntimeError('The "ctags" package must to be installed ' 'to be able to use the "tagsfile" feature.') self._ctags = ctags.CTags(self.tagsfile) linenos = options.get('linenos', False) if linenos == 'inline': self.linenos = 2 elif linenos: # compatibility with <= 0.7 self.linenos = 1 else: self.linenos = 0 self.linenostart = abs(get_int_opt(options, 'linenostart', 1)) self.linenostep = abs(get_int_opt(options, 'linenostep', 1)) self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0)) self.nobackground = get_bool_opt(options, 'nobackground', False) self.lineseparator = options.get('lineseparator', '\n') self.lineanchors = options.get('lineanchors', '') self.linespans = options.get('linespans', '') self.anchorlinenos = options.get('anchorlinenos', False) self.hl_lines = set() for lineno in get_list_opt(options, 'hl_lines', []): try: self.hl_lines.add(int(lineno)) except ValueError: pass self._create_stylesheet() def _get_css_class(self, ttype): """Return the css class of this token type prefixed with the classprefix option.""" ttypeclass = _get_ttype_class(ttype) if ttypeclass: return self.classprefix + ttypeclass return '' def _create_stylesheet(self): t2c = self.ttype2class = {Token: ''} c2s = self.class2style = {} for ttype, ndef in self.style: name = self._get_css_class(ttype) style = '' if ndef['color']: style += 'color: #%s; ' % ndef['color'] if ndef['bold']: style += 'font-weight: bold; ' if ndef['italic']: style += 'font-style: italic; ' if ndef['underline']: style += 'text-decoration: underline; ' if ndef['bgcolor']: style += 'background-color: #%s; ' % ndef['bgcolor'] if ndef['border']: style += 'border: 1px solid #%s; ' % ndef['border'] if style: t2c[ttype] = name # save len(ttype) to enable ordering the styles by # hierarchy (necessary for CSS cascading rules!) c2s[name] = (style[:-2], ttype, len(ttype)) def get_style_defs(self, arg=None): """ Return CSS style definitions for the classes produced by the current highlighting style. ``arg`` can be a string or list of selectors to insert before the token type classes. """ if arg is None: arg = ('cssclass' in self.options and '.'+self.cssclass or '') if isinstance(arg, str): args = [arg] else: args = list(arg) def prefix(cls): if cls: cls = '.' + cls tmp = [] for arg in args: tmp.append((arg and arg + ' ' or '') + cls) return ', '.join(tmp) styles = [(level, ttype, cls, style) for cls, (style, ttype, level) in self.class2style.items() if cls and style] styles.sort() lines = ['%s { %s } /* %s */' % (prefix(cls), style, repr(ttype)[6:]) for (level, ttype, cls, style) in styles] if arg and not self.nobackground and \ self.style.background_color is not None: text_style = '' if Text in self.ttype2class: text_style = ' ' + self.class2style[self.ttype2class[Text]][0] lines.insert(0, '%s { background: %s;%s }' % (prefix(''), self.style.background_color, text_style)) if self.style.highlight_color is not None: lines.insert(0, '%s.hll { background-color: %s }' % (prefix(''), self.style.highlight_color)) return '\n'.join(lines) def _decodeifneeded(self, value): if isinstance(value, bytes): if self.encoding: return value.decode(self.encoding) return value.decode() return value def _wrap_full(self, inner, outfile): if self.cssfile: if os.path.isabs(self.cssfile): # it's an absolute filename cssfilename = self.cssfile else: try: filename = outfile.name if not filename or filename[0] == '<': # pseudo files, e.g. name == '<fdopen>' raise AttributeError cssfilename = os.path.join(os.path.dirname(filename), self.cssfile) except AttributeError: print('Note: Cannot determine output file name, ' \ 'using current directory as base for the CSS file name', file=sys.stderr) cssfilename = self.cssfile # write CSS file only if noclobber_cssfile isn't given as an option. try: if not os.path.exists(cssfilename) or not self.noclobber_cssfile: cf = open(cssfilename, "w") cf.write(CSSFILE_TEMPLATE % {'styledefs': self.get_style_defs('body')}) cf.close() except IOError as err: err.strerror = 'Error writing CSS file: ' + err.strerror raise yield 0, (DOC_HEADER_EXTERNALCSS % dict(title = self.title, cssfile = self.cssfile, encoding = self.encoding)) else: yield 0, (DOC_HEADER % dict(title = self.title, styledefs = self.get_style_defs('body'), encoding = self.encoding)) for t, line in inner: yield t, line yield 0, DOC_FOOTER def _wrap_tablelinenos(self, inner): dummyoutfile = io.StringIO() lncount = 0 for t, line in inner: if t: lncount += 1 dummyoutfile.write(line) fl = self.linenostart mw = len(str(lncount + fl - 1)) sp = self.linenospecial st = self.linenostep la = self.lineanchors aln = self.anchorlinenos nocls = self.noclasses if sp: lines = [] for i in range(fl, fl+lncount): if i % st == 0: if i % sp == 0: if aln: lines.append('<a href="#%s-%d" class="special">%*d</a>' % (la, i, mw, i)) else: lines.append('<span class="special">%*d</span>' % (mw, i)) else: if aln: lines.append('<a href="#%s-%d">%*d</a>' % (la, i, mw, i)) else: lines.append('%*d' % (mw, i)) else: lines.append('') ls = '\n'.join(lines) else: lines = [] for i in range(fl, fl+lncount): if i % st == 0: if aln: lines.append('<a href="#%s-%d">%*d</a>' % (la, i, mw, i)) else: lines.append('%*d' % (mw, i)) else: lines.append('') ls = '\n'.join(lines) # in case you wonder about the seemingly redundant <div> here: since the # content in the other cell also is wrapped in a div, some browsers in # some configurations seem to mess up the formatting... if nocls: yield 0, ('<table class="%stable">' % self.cssclass + '<tr><td><div class="linenodiv" ' 'style="background-color: #f0f0f0; padding-right: 10px">' '<pre style="line-height: 125%">' + ls + '</pre></div></td><td class="code">') else: yield 0, ('<table class="%stable">' % self.cssclass + '<tr><td class="linenos"><div class="linenodiv"><pre>' + ls + '</pre></div></td><td class="code">') yield 0, dummyoutfile.getvalue() yield 0, '</td></tr></table>' def _wrap_inlinelinenos(self, inner): # need a list of lines since we need the width of a single number :( lines = list(inner) sp = self.linenospecial st = self.linenostep num = self.linenostart mw = len(str(len(lines) + num - 1)) if self.noclasses: if sp: for t, line in lines: if num%sp == 0: style = 'background-color: #ffffc0; padding: 0 5px 0 5px' else: style = 'background-color: #f0f0f0; padding: 0 5px 0 5px' yield 1, '<span style="%s">%*s</span> ' % ( style, mw, (num%st and ' ' or num)) + line num += 1 else: for t, line in lines: yield 1, ('<span style="background-color: #f0f0f0; ' 'padding: 0 5px 0 5px">%*s</span> ' % ( mw, (num%st and ' ' or num)) + line) num += 1 elif sp: for t, line in lines: yield 1, '<span class="lineno%s">%*s</span> ' % ( num%sp == 0 and ' special' or '', mw, (num%st and ' ' or num)) + line num += 1 else: for t, line in lines: yield 1, '<span class="lineno">%*s</span> ' % ( mw, (num%st and ' ' or num)) + line num += 1 def _wrap_lineanchors(self, inner): s = self.lineanchors i = self.linenostart - 1 # subtract 1 since we have to increment i # *before* yielding for t, line in inner: if t: i += 1 yield 1, '<a name="%s-%d"></a>' % (s, i) + line else: yield 0, line def _wrap_linespans(self, inner): s = self.linespans i = self.linenostart - 1 for t, line in inner: if t: i += 1 yield 1, '<span id="%s-%d">%s</span>' % (s, i, line) else: yield 0, line def _wrap_div(self, inner): style = [] if (self.noclasses and not self.nobackground and self.style.background_color is not None): style.append('background: %s' % (self.style.background_color,)) if self.cssstyles: style.append(self.cssstyles) style = '; '.join(style) yield 0, ('<div' + (self.cssclass and ' class="%s"' % self.cssclass) + (style and (' style="%s"' % style)) + '>') for tup in inner: yield tup yield 0, '</div>\n' def _wrap_pre(self, inner): style = [] if self.prestyles: style.append(self.prestyles) if self.noclasses: style.append('line-height: 125%') style = '; '.join(style) yield 0, ('<pre' + (style and ' style="%s"' % style) + '>') for tup in inner: yield tup yield 0, '</pre>' def _format_lines(self, tokensource): """ Just format the tokens, without any wrapping tags. Yield individual lines. """ nocls = self.noclasses lsep = self.lineseparator # for <span style=""> lookup only getcls = self.ttype2class.get c2s = self.class2style escape_table = _escape_html_table tagsfile = self.tagsfile lspan = '' line = '' for ttype, value in tokensource: if nocls: cclass = getcls(ttype) while cclass is None: ttype = ttype.parent cclass = getcls(ttype) cspan = cclass and '<span style="%s">' % c2s[cclass][0] or '' else: cls = self._get_css_class(ttype) cspan = cls and '<span class="%s">' % cls or '' parts = value.translate(escape_table).split('\n') if tagsfile and ttype in Token.Name: filename, linenumber = self._lookup_ctag(value) if linenumber: base, filename = os.path.split(filename) if base: base += '/' filename, extension = os.path.splitext(filename) url = self.tagurlformat % {'path': base, 'fname': filename, 'fext': extension} parts[0] = "<a href=\"%s#%s-%d\">%s" % \ (url, self.lineanchors, linenumber, parts[0]) parts[-1] = parts[-1] + "</a>" # for all but the last line for part in parts[:-1]: if line: if lspan != cspan: line += (lspan and '</span>') + cspan + part + \ (cspan and '</span>') + lsep else: # both are the same line += part + (lspan and '</span>') + lsep yield 1, line line = '' elif part: yield 1, cspan + part + (cspan and '</span>') + lsep else: yield 1, lsep # for the last line if line and parts[-1]: if lspan != cspan: line += (lspan and '</span>') + cspan + parts[-1] lspan = cspan else: line += parts[-1] elif parts[-1]: line = cspan + parts[-1] lspan = cspan # else we neither have to open a new span nor set lspan if line: yield 1, line + (lspan and '</span>') + lsep def _lookup_ctag(self, token): entry = ctags.TagEntry() if self._ctags.find(entry, token, 0): return entry['file'], entry['lineNumber'] else: return None, None def _highlight_lines(self, tokensource): """ Highlighted the lines specified in the `hl_lines` option by post-processing the token stream coming from `_format_lines`. """ hls = self.hl_lines for i, (t, value) in enumerate(tokensource): if t != 1: yield t, value if i + 1 in hls: # i + 1 because Python indexes start at 0 if self.noclasses: style = '' if self.style.highlight_color is not None: style = (' style="background-color: %s"' % (self.style.highlight_color,)) yield 1, '<span%s>%s</span>' % (style, value) else: yield 1, '<span class="hll">%s</span>' % value else: yield 1, value def wrap(self, source, outfile): """ Wrap the ``source``, which is a generator yielding individual lines, in custom generators. See docstring for `format`. Can be overridden. """ return self._wrap_div(self._wrap_pre(source)) def format_unencoded(self, tokensource, outfile): """ The formatting process uses several nested generators; which of them are used is determined by the user's options. Each generator should take at least one argument, ``inner``, and wrap the pieces of text generated by this. Always yield 2-tuples: (code, text). If "code" is 1, the text is part of the original tokensource being highlighted, if it's 0, the text is some piece of wrapping. This makes it possible to use several different wrappers that process the original source linewise, e.g. line number generators. """ source = self._format_lines(tokensource) if self.hl_lines: source = self._highlight_lines(source) if not self.nowrap: if self.linenos == 2: source = self._wrap_inlinelinenos(source) if self.lineanchors: source = self._wrap_lineanchors(source) if self.linespans: source = self._wrap_linespans(source) source = self.wrap(source, outfile) if self.linenos == 1: source = self._wrap_tablelinenos(source) if self.full: source = self._wrap_full(source, outfile) for t, piece in source: outfile.write(piece)
mit
bdang2012/taiga-back
taiga/projects/attachments/permissions.py
9
4133
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014 David Barragán <bameda@dbarragan.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from taiga.base.api.permissions import (TaigaResourcePermission, HasProjectPerm, AllowAny, PermissionComponent) class IsAttachmentOwnerPerm(PermissionComponent): def check_permissions(self, request, view, obj=None): if obj and obj.owner and request.user.is_authenticated(): return request.user == obj.owner return False class UserStoryAttachmentPermission(TaigaResourcePermission): retrieve_perms = HasProjectPerm('view_us') | IsAttachmentOwnerPerm() create_perms = HasProjectPerm('modify_us') update_perms = HasProjectPerm('modify_us') | IsAttachmentOwnerPerm() partial_update_perms = HasProjectPerm('modify_us') | IsAttachmentOwnerPerm() destroy_perms = HasProjectPerm('modify_us') | IsAttachmentOwnerPerm() list_perms = AllowAny() class TaskAttachmentPermission(TaigaResourcePermission): retrieve_perms = HasProjectPerm('view_tasks') | IsAttachmentOwnerPerm() create_perms = HasProjectPerm('modify_task') update_perms = HasProjectPerm('modify_task') | IsAttachmentOwnerPerm() partial_update_perms = HasProjectPerm('modify_task') | IsAttachmentOwnerPerm() destroy_perms = HasProjectPerm('modify_task') | IsAttachmentOwnerPerm() list_perms = AllowAny() class IssueAttachmentPermission(TaigaResourcePermission): retrieve_perms = HasProjectPerm('view_issues') | IsAttachmentOwnerPerm() create_perms = HasProjectPerm('modify_issue') update_perms = HasProjectPerm('modify_issue') | IsAttachmentOwnerPerm() partial_update_perms = HasProjectPerm('modify_issue') | IsAttachmentOwnerPerm() destroy_perms = HasProjectPerm('modify_issue') | IsAttachmentOwnerPerm() list_perms = AllowAny() class WikiAttachmentPermission(TaigaResourcePermission): retrieve_perms = HasProjectPerm('view_wiki_pages') | IsAttachmentOwnerPerm() create_perms = HasProjectPerm('modify_wiki_page') update_perms = HasProjectPerm('modify_wiki_page') | IsAttachmentOwnerPerm() partial_update_perms = HasProjectPerm('modify_wiki_page') | IsAttachmentOwnerPerm() destroy_perms = HasProjectPerm('modify_wiki_page') | IsAttachmentOwnerPerm() list_perms = AllowAny() class RawAttachmentPerm(PermissionComponent): def check_permissions(self, request, view, obj=None): is_owner = IsAttachmentOwnerPerm().check_permissions(request, view, obj) if obj.content_type.app_label == "userstories" and obj.content_type.model == "userstory": return UserStoryAttachmentPermission(request, view).check_permissions('retrieve', obj) or is_owner elif obj.content_type.app_label == "tasks" and obj.content_type.model == "task": return TaskAttachmentPermission(request, view).check_permissions('retrieve', obj) or is_owner elif obj.content_type.app_label == "issues" and obj.content_type.model == "issue": return IssueAttachmentPermission(request, view).check_permissions('retrieve', obj) or is_owner elif obj.content_type.app_label == "wiki" and obj.content_type.model == "wikipage": return WikiAttachmentPermission(request, view).check_permissions('retrieve', obj) or is_owner return False class RawAttachmentPermission(TaigaResourcePermission): retrieve_perms = RawAttachmentPerm()
agpl-3.0
bottompawn/kbengine
kbe/res/scripts/common/Lib/unittest/test/test_break.py
81
9812
import gc import io import os import sys import signal import weakref import unittest @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreak(unittest.TestCase): int_handler = None def setUp(self): self._default_handler = signal.getsignal(signal.SIGINT) if self.int_handler is not None: signal.signal(signal.SIGINT, self.int_handler) def tearDown(self): signal.signal(signal.SIGINT, self._default_handler) unittest.signals._results = weakref.WeakKeyDictionary() unittest.signals._interrupt_handler = None def testInstallHandler(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(unittest.signals._interrupt_handler.called) def testRegisterResult(self): result = unittest.TestResult() unittest.registerResult(result) for ref in unittest.signals._results: if ref is result: break elif ref is not result: self.fail("odd object in result set") else: self.fail("result not found") def testInterruptCaught(self): default_handler = signal.getsignal(signal.SIGINT) result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) try: test(result) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(result.breakCaught) def testSecondInterrupt(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") result = unittest.TestResult() unittest.installHandler() unittest.registerResult(result) def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) result.breakCaught = True self.assertTrue(result.shouldStop) os.kill(pid, signal.SIGINT) self.fail("Second KeyboardInterrupt not raised") try: test(result) except KeyboardInterrupt: pass else: self.fail("Second KeyboardInterrupt not raised") self.assertTrue(result.breakCaught) def testTwoResults(self): unittest.installHandler() result = unittest.TestResult() unittest.registerResult(result) new_handler = signal.getsignal(signal.SIGINT) result2 = unittest.TestResult() unittest.registerResult(result2) self.assertEqual(signal.getsignal(signal.SIGINT), new_handler) result3 = unittest.TestResult() def test(result): pid = os.getpid() os.kill(pid, signal.SIGINT) try: test(result) except KeyboardInterrupt: self.fail("KeyboardInterrupt not handled") self.assertTrue(result.shouldStop) self.assertTrue(result2.shouldStop) self.assertFalse(result3.shouldStop) def testHandlerReplacedButCalled(self): # Can't use skipIf decorator because the signal handler may have # been changed after defining this method. if signal.getsignal(signal.SIGINT) == signal.SIG_IGN: self.skipTest("test requires SIGINT to not be ignored") # If our handler has been replaced (is no longer installed) but is # called by the *new* handler, then it isn't safe to delay the # SIGINT and we should immediately delegate to the default handler unittest.installHandler() handler = signal.getsignal(signal.SIGINT) def new_handler(frame, signum): handler(frame, signum) signal.signal(signal.SIGINT, new_handler) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass else: self.fail("replaced but delegated handler doesn't raise interrupt") def testRunner(self): # Creating a TextTestRunner with the appropriate argument should # register the TextTestResult it creates runner = unittest.TextTestRunner(stream=io.StringIO()) result = runner.run(unittest.TestSuite()) self.assertIn(result, unittest.signals._results) def testWeakReferences(self): # Calling registerResult on a result should not keep it alive result = unittest.TestResult() unittest.registerResult(result) ref = weakref.ref(result) del result # For non-reference counting implementations gc.collect();gc.collect() self.assertIsNone(ref()) def testRemoveResult(self): result = unittest.TestResult() unittest.registerResult(result) unittest.installHandler() self.assertTrue(unittest.removeResult(result)) # Should this raise an error instead? self.assertFalse(unittest.removeResult(unittest.TestResult())) try: pid = os.getpid() os.kill(pid, signal.SIGINT) except KeyboardInterrupt: pass self.assertFalse(result.shouldStop) def testMainInstallsHandler(self): failfast = object() test = object() verbosity = object() result = object() default_handler = signal.getsignal(signal.SIGINT) class FakeRunner(object): initArgs = [] runArgs = [] def __init__(self, *args, **kwargs): self.initArgs.append((args, kwargs)) def run(self, test): self.runArgs.append(test) return result class Program(unittest.TestProgram): def __init__(self, catchbreak): self.exit = False self.verbosity = verbosity self.failfast = failfast self.catchbreak = catchbreak self.testRunner = FakeRunner self.test = test self.result = None p = Program(False) p.runTests() self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None, 'verbosity': verbosity, 'failfast': failfast, 'warnings': None})]) self.assertEqual(FakeRunner.runArgs, [test]) self.assertEqual(p.result, result) self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) FakeRunner.initArgs = [] FakeRunner.runArgs = [] p = Program(True) p.runTests() self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None, 'verbosity': verbosity, 'failfast': failfast, 'warnings': None})]) self.assertEqual(FakeRunner.runArgs, [test]) self.assertEqual(p.result, result) self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) def testRemoveHandler(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() unittest.removeHandler() self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) # check that calling removeHandler multiple times has no ill-effect unittest.removeHandler() self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) def testRemoveHandlerAsDecorator(self): default_handler = signal.getsignal(signal.SIGINT) unittest.installHandler() @unittest.removeHandler def test(): self.assertEqual(signal.getsignal(signal.SIGINT), default_handler) test() self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler) @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreakDefaultIntHandler(TestBreak): int_handler = signal.default_int_handler @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreakSignalIgnored(TestBreak): int_handler = signal.SIG_IGN @unittest.skipUnless(hasattr(os, 'kill'), "Test requires os.kill") @unittest.skipIf(sys.platform =="win32", "Test cannot run on Windows") @unittest.skipIf(sys.platform == 'freebsd6', "Test kills regrtest on freebsd6 " "if threads have been used") class TestBreakSignalDefault(TestBreak): int_handler = signal.SIG_DFL if __name__ == "__main__": unittest.main()
lgpl-3.0
googleapis/googleapis-gen
google/ads/googleads/v7/googleads-py/google/ads/googleads/v7/errors/types/feed_attribute_reference_error.py
1
1293
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import proto # type: ignore __protobuf__ = proto.module( package='google.ads.googleads.v7.errors', marshal='google.ads.googleads.v7', manifest={ 'FeedAttributeReferenceErrorEnum', }, ) class FeedAttributeReferenceErrorEnum(proto.Message): r"""Container for enum describing possible feed attribute reference errors. """ class FeedAttributeReferenceError(proto.Enum): r"""Enum describing possible feed attribute reference errors.""" UNSPECIFIED = 0 UNKNOWN = 1 CANNOT_REFERENCE_REMOVED_FEED = 2 INVALID_FEED_NAME = 3 INVALID_FEED_ATTRIBUTE_NAME = 4 __all__ = tuple(sorted(__protobuf__.manifest))
apache-2.0
NielsZeilemaker/incubator-airflow
airflow/operators/oracle_operator.py
46
1893
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from airflow.hooks.oracle_hook import OracleHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class OracleOperator(BaseOperator): """ Executes sql code in a specific Oracle database :param oracle_conn_id: reference to a specific Oracle database :type oracle_conn_id: string :param sql: the sql code to be executed :type sql: Can receive a str representing a sql statement, a list of str (sql statements), or reference to a template file. Template reference are recognized by str ending in '.sql' """ template_fields = ('sql',) template_ext = ('.sql',) ui_color = '#ededed' @apply_defaults def __init__( self, sql, oracle_conn_id='oracle_default', parameters=None, autocommit=False, *args, **kwargs): super(OracleOperator, self).__init__(*args, **kwargs) self.oracle_conn_id = oracle_conn_id self.sql = sql self.autocommit = autocommit self.parameters = parameters def execute(self, context): logging.info('Executing: ' + str(self.sql)) hook = OracleHook(oracle_conn_id=self.oracle_conn_id) hook.run( self.sql, autocommit=self.autocommit, parameters=self.parameters)
apache-2.0
PaulWay/insights-core
insights/parsers/tests/test_lvdisplay.py
3
2739
from insights.tests import context_wrap from insights.parsers.lvdisplay import LvDisplay LV_DISPLAY = """ Adding lvsapp01ap01:0 as an user of lvsapp01ap01_mlog --- Volume group --- VG Name vgp01app Format lvm2 Metadata Areas 4 Metadata Sequence No 56 VG Access read/write VG Status resizable Clustered yes Shared no MAX LV 0 Cur LV 4 Open LV 1 Max PV 0 Cur PV 4 Act PV 4 VG Size 399.98 GiB PE Size 4.00 MiB Total PE 102396 Alloc PE / Size 82435 / 322.01 GiB Free PE / Size 19961 / 77.97 GiB VG UUID JVgCxE-UY84-C0Gk-8Cmn-UGXu-UHo0-9Qa4Re --- Logical volume --- global/lvdisplay_shows_full_device_path not found in config: defaulting to 0 LV Path /dev/vgp01app/lvsapp01ap01-old LV Name lvsapp01ap01-old VG Name vgp01app LV UUID eLjsoG-Gvnh-zEbV-zFwD-HyQT-1zEs-VN4W2D LV Write Access read/write LV Creation host, time lvn-itm-099, 2015-02-24 09:19:54 +0100 LV Status available # open 0 LV Size 64.00 GiB Current LE 16384 Segments 4 Allocation inherit Read ahead sectors auto - currently set to 256 Block device 253:50 --- Logical volume --- global/lvdisplay_shows_full_device_path not found in config: defaulting to 0 LV Path /dev/vgp01app/lvsapp01ap02 LV Name lvsapp01ap02 VG Name vgp01app LV UUID tFGsSW-nimQ-4JUL-4Fw0-IJn0-Jcoo-Szgfgz LV Write Access read/write LV Creation host, time lvn-itm-099, 2015-02-24 15:24:52 +0100 LV Status available # open 0 LV Size 64.00 GiB Current LE 16384 Mirrored volumes 2 Segments 1 Allocation inherit Read ahead sectors auto - currently set to 256 Block device 253:54 """ def test_lvdisplay(): lvs = LvDisplay(context_wrap(LV_DISPLAY)) assert 'vgp01app' == lvs.get('volumes')['Volume group'][0]['VG Name'] assert '399.98 GiB' == lvs.get('volumes')['Volume group'][0]['VG Size'] assert 'vgp01app' == lvs.get('volumes')['Logical volume'][1]['VG Name'] assert 'vgp01app' in lvs.vgs assert lvs.vgs['vgp01app'] == lvs.get('volumes')['Volume group'][0] assert 'lvsapp01ap02' in lvs.lvs assert lvs.lvs['lvsapp01ap02'] == lvs.get('volumes')['Logical volume'][1]
apache-2.0
theimaginaire/dayone
node_modules/node-gyp/gyp/pylib/gyp/generator/eclipse.py
1825
17014
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """GYP backend that generates Eclipse CDT settings files. This backend DOES NOT generate Eclipse CDT projects. Instead, it generates XML files that can be imported into an Eclipse CDT project. The XML file contains a list of include paths and symbols (i.e. defines). Because a full .cproject definition is not created by this generator, it's not possible to properly define the include dirs and symbols for each file individually. Instead, one set of includes/symbols is generated for the entire project. This works fairly well (and is a vast improvement in general), but may still result in a few indexer issues here and there. This generator has no automated tests, so expect it to be broken. """ from xml.sax.saxutils import escape import os.path import subprocess import gyp import gyp.common import gyp.msvs_emulation import shlex import xml.etree.cElementTree as ET generator_wants_static_library_dependencies_adjusted = False generator_default_variables = { } for dirname in ['INTERMEDIATE_DIR', 'PRODUCT_DIR', 'LIB_DIR', 'SHARED_LIB_DIR']: # Some gyp steps fail if these are empty(!), so we convert them to variables generator_default_variables[dirname] = '$' + dirname for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME', 'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT', 'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX', 'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX', 'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX', 'CONFIGURATION_NAME']: generator_default_variables[unused] = '' # Include dirs will occasionally use the SHARED_INTERMEDIATE_DIR variable as # part of the path when dealing with generated headers. This value will be # replaced dynamically for each configuration. generator_default_variables['SHARED_INTERMEDIATE_DIR'] = \ '$SHARED_INTERMEDIATE_DIR' def CalculateVariables(default_variables, params): generator_flags = params.get('generator_flags', {}) for key, val in generator_flags.items(): default_variables.setdefault(key, val) flavor = gyp.common.GetFlavor(params) default_variables.setdefault('OS', flavor) if flavor == 'win': # Copy additional generator configuration data from VS, which is shared # by the Eclipse generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) if generator_flags.get('adjust_static_libraries', False): global generator_wants_static_library_dependencies_adjusted generator_wants_static_library_dependencies_adjusted = True def GetAllIncludeDirectories(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path): """Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options. """ gyp_includes_set = set() compiler_includes_list = [] # Find compiler's default include dirs. if compiler_path: command = shlex.split(compiler_path) command.extend(['-E', '-xc++', '-v', '-']) proc = subprocess.Popen(args=command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.communicate()[1] # Extract the list of include dirs from the output, which has this format: # ... # #include "..." search starts here: # #include <...> search starts here: # /usr/include/c++/4.6 # /usr/local/include # End of search list. # ... in_include_list = False for line in output.splitlines(): if line.startswith('#include'): in_include_list = True continue if line.startswith('End of search list.'): break if in_include_list: include_dir = line.strip() if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) flavor = gyp.common.GetFlavor(params) if flavor == 'win': generator_flags = params.get('generator_flags', {}) for target_name in target_list: target = target_dicts[target_name] if config_name in target['configurations']: config = target['configurations'][config_name] # Look for any include dirs that were explicitly added via cflags. This # may be done in gyp files to force certain includes to come at the end. # TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and # remove this. if flavor == 'win': msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) cflags = msvs_settings.GetCflags(config_name) else: cflags = config['cflags'] for cflag in cflags: if cflag.startswith('-I'): include_dir = cflag[2:] if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) # Find standard gyp include dirs. if config.has_key('include_dirs'): include_dirs = config['include_dirs'] for shared_intermediate_dir in shared_intermediate_dirs: for include_dir in include_dirs: include_dir = include_dir.replace('$SHARED_INTERMEDIATE_DIR', shared_intermediate_dir) if not os.path.isabs(include_dir): base_dir = os.path.dirname(target_name) include_dir = base_dir + '/' + include_dir include_dir = os.path.abspath(include_dir) gyp_includes_set.add(include_dir) # Generate a list that has all the include dirs. all_includes_list = list(gyp_includes_set) all_includes_list.sort() for compiler_include in compiler_includes_list: if not compiler_include in gyp_includes_set: all_includes_list.append(compiler_include) # All done. return all_includes_list def GetCompilerPath(target_list, data, options): """Determine a command that can be used to invoke the compiler. Returns: If this is a gyp project that has explicit make settings, try to determine the compiler from that. Otherwise, see if a compiler was specified via the CC_target environment variable. """ # First, see if the compiler is configured in make's settings. build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings_dict = data[build_file].get('make_global_settings', {}) for key, value in make_global_settings_dict: if key in ['CC', 'CXX']: return os.path.join(options.toplevel_dir, value) # Check to see if the compiler was specified as an environment variable. for key in ['CC_target', 'CC', 'CXX']: compiler = os.environ.get(key) if compiler: return compiler return 'gcc' def GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path): """Calculate the defines for a project. Returns: A dict that includes explict defines declared in gyp files along with all of the default defines that the compiler uses. """ # Get defines declared in the gyp files. all_defines = {} flavor = gyp.common.GetFlavor(params) if flavor == 'win': generator_flags = params.get('generator_flags', {}) for target_name in target_list: target = target_dicts[target_name] if flavor == 'win': msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) extra_defines = msvs_settings.GetComputedDefines(config_name) else: extra_defines = [] if config_name in target['configurations']: config = target['configurations'][config_name] target_defines = config['defines'] else: target_defines = [] for define in target_defines + extra_defines: split_define = define.split('=', 1) if len(split_define) == 1: split_define.append('1') if split_define[0].strip() in all_defines: # Already defined continue all_defines[split_define[0].strip()] = split_define[1].strip() # Get default compiler defines (if possible). if flavor == 'win': return all_defines # Default defines already processed in the loop above. if compiler_path: command = shlex.split(compiler_path) command.extend(['-E', '-dM', '-']) cpp_proc = subprocess.Popen(args=command, cwd='.', stdin=subprocess.PIPE, stdout=subprocess.PIPE) cpp_output = cpp_proc.communicate()[0] cpp_lines = cpp_output.split('\n') for cpp_line in cpp_lines: if not cpp_line.strip(): continue cpp_line_parts = cpp_line.split(' ', 2) key = cpp_line_parts[1] if len(cpp_line_parts) >= 3: val = cpp_line_parts[2] else: val = '1' all_defines[key] = val return all_defines def WriteIncludePaths(out, eclipse_langs, include_dirs): """Write the includes section of a CDT settings export file.""" out.write(' <section name="org.eclipse.cdt.internal.ui.wizards.' \ 'settingswizards.IncludePaths">\n') out.write(' <language name="holder for library settings"></language>\n') for lang in eclipse_langs: out.write(' <language name="%s">\n' % lang) for include_dir in include_dirs: out.write(' <includepath workspace_path="false">%s</includepath>\n' % include_dir) out.write(' </language>\n') out.write(' </section>\n') def WriteMacros(out, eclipse_langs, defines): """Write the macros section of a CDT settings export file.""" out.write(' <section name="org.eclipse.cdt.internal.ui.wizards.' \ 'settingswizards.Macros">\n') out.write(' <language name="holder for library settings"></language>\n') for lang in eclipse_langs: out.write(' <language name="%s">\n' % lang) for key in sorted(defines.iterkeys()): out.write(' <macro><name>%s</name><value>%s</value></macro>\n' % (escape(key), escape(defines[key]))) out.write(' </language>\n') out.write(' </section>\n') def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params['options'] generator_flags = params.get('generator_flags', {}) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.join(generator_flags.get('output_dir', 'out'), config_name) toplevel_build = os.path.join(options.toplevel_dir, build_dir) # Ninja uses out/Debug/gen while make uses out/Debug/obj/gen as the # SHARED_INTERMEDIATE_DIR. Include both possible locations. shared_intermediate_dirs = [os.path.join(toplevel_build, 'obj', 'gen'), os.path.join(toplevel_build, 'gen')] GenerateCdtSettingsFile(target_list, target_dicts, data, params, config_name, os.path.join(toplevel_build, 'eclipse-cdt-settings.xml'), options, shared_intermediate_dirs) GenerateClasspathFile(target_list, target_dicts, options.toplevel_dir, toplevel_build, os.path.join(toplevel_build, 'eclipse-classpath.xml')) def GenerateCdtSettingsFile(target_list, target_dicts, data, params, config_name, out_name, options, shared_intermediate_dirs): gyp.common.EnsureDirExists(out_name) with open(out_name, 'w') as out: out.write('<?xml version="1.0" encoding="UTF-8"?>\n') out.write('<cdtprojectproperties>\n') eclipse_langs = ['C++ Source File', 'C Source File', 'Assembly Source File', 'GNU C++', 'GNU C', 'Assembly'] compiler_path = GetCompilerPath(target_list, data, options) include_dirs = GetAllIncludeDirectories(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path) WriteIncludePaths(out, eclipse_langs, include_dirs) defines = GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path) WriteMacros(out, eclipse_langs, defines) out.write('</cdtprojectproperties>\n') def GenerateClasspathFile(target_list, target_dicts, toplevel_dir, toplevel_build, out_name): '''Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.''' gyp.common.EnsureDirExists(out_name) result = ET.Element('classpath') def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, 'classpathentry') entry_element.set('kind', kind) entry_element.set('path', path) AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER']) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')]) ET.ElementTree(result).write(out_name) def GetJavaJars(target_list, target_dicts, toplevel_dir): '''Generates a sequence of all .jars used as inputs.''' for target_name in target_list: target = target_dicts[target_name] for action in target.get('actions', []): for input_ in action['inputs']: if os.path.splitext(input_)[1] == '.jar' and not input_.startswith('$'): if os.path.isabs(input_): yield input_ else: yield os.path.join(os.path.dirname(target_name), input_) def GetJavaSourceDirs(target_list, target_dicts, toplevel_dir): '''Generates a sequence of all likely java package root directories.''' for target_name in target_list: target = target_dicts[target_name] for action in target.get('actions', []): for input_ in action['inputs']: if (os.path.splitext(input_)[1] == '.java' and not input_.startswith('$')): dir_ = os.path.dirname(os.path.join(os.path.dirname(target_name), input_)) # If there is a parent 'src' or 'java' folder, navigate up to it - # these are canonical package root names in Chromium. This will # break if 'src' or 'java' exists in the package structure. This # could be further improved by inspecting the java file for the # package name if this proves to be too fragile in practice. parent_search = dir_ while os.path.basename(parent_search) not in ['src', 'java']: parent_search, _ = os.path.split(parent_search) if not parent_search or parent_search == toplevel_dir: # Didn't find a known root, just return the original path yield dir_ break else: yield parent_search def GenerateOutput(target_list, target_dicts, data, params): """Generate an XML settings file that can be imported into a CDT project.""" if params['options'].generator_output: raise NotImplementedError("--generator_output not implemented for eclipse") user_config = params.get('generator_flags', {}).get('config', None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['configurations'].keys() for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
mit
examachine/pisi
pisi/exml/xmlfilepiks.py
1
2519
# -*- coding: utf-8 -*- # # Copyright (C) 2005, TUBITAK/UEKAE # # 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. # # Please read the COPYING file. # # Author: Eray Ozkural <eray@pardus.org.tr> """ XmlFile class further abstracts a dom object using the high-level dom functions provided in xmlext module (and sorely lacking in xml.dom :( ) function names are mixedCase for compatibility with minidom, an 'old library' this implementation uses piksemel """ import gettext __trans = gettext.translation('pisi', fallback=True) _ = __trans.ugettext import codecs import exceptions import piksemel as iks import pisi from pisi.file import File from pisi.util import join_path as join class Error(pisi.Error): pass class XmlFile(object): """A class to help reading and writing an XML file""" def __init__(self, tag): self.rootTag = tag def newDocument(self): """clear DOM""" self.doc = iks.newDocument(self.rootTag) def unlink(self): """deallocate DOM structure""" del self.doc def rootNode(self): """returns root document element""" return self.doc def readxmlfile(self, file): raise Exception("not implemented") try: self.doc = iks.parse(file) return self.doc except Exception, e: raise Error(_("File '%s' has invalid XML") % (localpath) ) def readxml(self, uri, tmpDir='/tmp', sha1sum=False, compress=None, sign=None, copylocal = False): uri = File.make_uri(uri) #try: localpath = File.download(uri, tmpDir, sha1sum=sha1sum, compress=compress,sign=sign, copylocal=copylocal) #except IOError, e: # raise Error(_("Cannot read URI %s: %s") % (uri, unicode(e)) ) try: self.doc = iks.parse(localpath) return self.doc except Exception, e: raise Error(_("File '%s' has invalid XML") % (localpath) ) def writexml(self, uri, tmpDir = '/tmp', sha1sum=False, compress=None, sign=None): f = File(uri, File.write, sha1sum=sha1sum, compress=compress, sign=sign) f.write(self.doc.toPrettyString()) f.close() def writexmlfile(self, f): f.write(self.doc.toPrettyString())
gpl-3.0
aperigault/ansible
test/units/modules/network/netscaler/test_netscaler_cs_policy.py
68
12560
# Copyright (c) 2017 Citrix Systems # # 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 units.compat.mock import patch, Mock, MagicMock, call import sys if sys.version_info[:2] != (2, 6): import requests from units.modules.utils import set_module_args from .netscaler_module import TestModule, nitro_base_patcher class TestNetscalerCSPolicyModule(TestModule): @classmethod def setUpClass(cls): class MockException(Exception): pass cls.MockException = MockException m = MagicMock() nssrc_modules_mock = { 'nssrc.com.citrix.netscaler.nitro.resource.config.cs': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.cs.cspolicy': m, } cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock) cls.nitro_base_patcher = nitro_base_patcher @classmethod def tearDownClass(cls): cls.nitro_base_patcher.stop() cls.nitro_specific_patcher.stop() def set_module_state(self, state): set_module_args(dict( nitro_user='user', nitro_pass='pass', nsip='192.0.2.1', state=state, )) def setUp(self): super(TestNetscalerCSPolicyModule, self).setUp() self.nitro_base_patcher.start() self.nitro_specific_patcher.start() def tearDown(self): super(TestNetscalerCSPolicyModule, self).tearDown() self.nitro_base_patcher.stop() self.nitro_specific_patcher.stop() def test_graceful_nitro_api_import_error(self): # Stop nitro api patching to cause ImportError self.set_module_state('present') self.nitro_base_patcher.stop() self.nitro_specific_patcher.stop() from ansible.modules.network.netscaler import netscaler_cs_policy self.module = netscaler_cs_policy result = self.failed() self.assertEqual(result['msg'], 'Could not load nitro python sdk') def test_graceful_nitro_error_on_login(self): self.set_module_state('present') from ansible.modules.network.netscaler import netscaler_cs_policy class MockException(Exception): def __init__(self, *args, **kwargs): self.errorcode = 0 self.message = '' client_mock = Mock() client_mock.login = Mock(side_effect=MockException) m = Mock(return_value=client_mock) with patch('ansible.modules.network.netscaler.netscaler_cs_policy.get_nitro_client', m): with patch('ansible.modules.network.netscaler.netscaler_cs_policy.nitro_exception', MockException): self.module = netscaler_cs_policy result = self.failed() self.assertTrue(result['msg'].startswith('nitro exception'), msg='nitro exception during login not handled properly') def test_graceful_no_connection_error(self): if sys.version_info[:2] == (2, 6): self.skipTest('requests library not available under python2.6') self.set_module_state('present') from ansible.modules.network.netscaler import netscaler_cs_policy client_mock = Mock() attrs = {'login.side_effect': requests.exceptions.ConnectionError} client_mock.configure_mock(**attrs) m = Mock(return_value=client_mock) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', get_nitro_client=m, nitro_exception=self.MockException, ): self.module = netscaler_cs_policy result = self.failed() self.assertTrue(result['msg'].startswith('Connection error'), msg='Connection error was not handled gracefully') def test_graceful_login_error(self): self.set_module_state('present') from ansible.modules.network.netscaler import netscaler_cs_policy if sys.version_info[:2] == (2, 6): self.skipTest('requests library not available under python2.6') class MockException(Exception): pass client_mock = Mock() attrs = {'login.side_effect': requests.exceptions.SSLError} client_mock.configure_mock(**attrs) m = Mock(return_value=client_mock) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', get_nitro_client=m, nitro_exception=MockException, ): self.module = netscaler_cs_policy result = self.failed() self.assertTrue(result['msg'].startswith('SSL Error'), msg='SSL Error was not handled gracefully') def test_create_non_existing_cs_policy(self): self.set_module_state('present') from ansible.modules.network.netscaler import netscaler_cs_policy cs_policy_mock = MagicMock() attrs = { 'diff_object.return_value': {}, } cs_policy_mock.configure_mock(**attrs) m = MagicMock(return_value=cs_policy_mock) policy_exists_mock = Mock(side_effect=[False, True]) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', ConfigProxy=m, policy_exists=policy_exists_mock, nitro_exception=self.MockException, ensure_feature_is_enabled=Mock(), ): self.module = netscaler_cs_policy result = self.exited() cs_policy_mock.assert_has_calls([call.add()]) self.assertTrue(result['changed'], msg='Change not recorded') def test_update_cs_policy_when_cs_policy_differs(self): self.set_module_state('present') from ansible.modules.network.netscaler import netscaler_cs_policy cs_policy_mock = MagicMock() attrs = { 'diff_object.return_value': {}, } cs_policy_mock.configure_mock(**attrs) m = MagicMock(return_value=cs_policy_mock) policy_exists_mock = Mock(side_effect=[True, True]) policy_identical_mock = Mock(side_effect=[False, True]) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', ConfigProxy=m, policy_exists=policy_exists_mock, policy_identical=policy_identical_mock, ensure_feature_is_enabled=Mock(), nitro_exception=self.MockException, ): self.module = netscaler_cs_policy result = self.exited() cs_policy_mock.assert_has_calls([call.update()]) self.assertTrue(result['changed'], msg='Change not recorded') def test_no_change_to_module_when_all_identical(self): self.set_module_state('present') from ansible.modules.network.netscaler import netscaler_cs_policy cs_policy_mock = MagicMock() attrs = { 'diff_object.return_value': {}, } cs_policy_mock.configure_mock(**attrs) m = MagicMock(return_value=cs_policy_mock) policy_exists_mock = Mock(side_effect=[True, True]) policy_identical_mock = Mock(side_effect=[True, True]) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', ConfigProxy=m, policy_exists=policy_exists_mock, policy_identical=policy_identical_mock, ensure_feature_is_enabled=Mock(), nitro_exception=self.MockException, ): self.module = netscaler_cs_policy result = self.exited() self.assertFalse(result['changed'], msg='Erroneous changed status update') def test_absent_operation(self): self.set_module_state('absent') from ansible.modules.network.netscaler import netscaler_cs_policy cs_policy_mock = MagicMock() attrs = { 'diff_object.return_value': {}, } cs_policy_mock.configure_mock(**attrs) m = MagicMock(return_value=cs_policy_mock) policy_exists_mock = Mock(side_effect=[True, False]) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', ConfigProxy=m, policy_exists=policy_exists_mock, nitro_exception=self.MockException, ensure_feature_is_enabled=Mock(), ): self.module = netscaler_cs_policy result = self.exited() cs_policy_mock.assert_has_calls([call.delete()]) self.assertTrue(result['changed'], msg='Changed status not set correctly') def test_absent_operation_no_change(self): self.set_module_state('absent') from ansible.modules.network.netscaler import netscaler_cs_policy cs_policy_mock = MagicMock() attrs = { 'diff_object.return_value': {}, } cs_policy_mock.configure_mock(**attrs) m = MagicMock(return_value=cs_policy_mock) policy_exists_mock = Mock(side_effect=[False, False]) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', ConfigProxy=m, policy_exists=policy_exists_mock, nitro_exception=self.MockException, ensure_feature_is_enabled=Mock(), ): self.module = netscaler_cs_policy result = self.exited() cs_policy_mock.assert_not_called() self.assertFalse(result['changed'], msg='Changed status not set correctly') def test_graceful_nitro_exception_operation_present(self): self.set_module_state('present') from ansible.modules.network.netscaler import netscaler_cs_policy class MockException(Exception): def __init__(self, *args, **kwargs): self.errorcode = 0 self.message = '' m = Mock(side_effect=MockException) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', policy_exists=m, ensure_feature_is_enabled=Mock(), nitro_exception=MockException ): self.module = netscaler_cs_policy result = self.failed() self.assertTrue( result['msg'].startswith('nitro exception'), msg='Nitro exception not caught on operation present' ) def test_graceful_nitro_exception_operation_absent(self): self.set_module_state('absent') from ansible.modules.network.netscaler import netscaler_cs_policy class MockException(Exception): def __init__(self, *args, **kwargs): self.errorcode = 0 self.message = '' m = Mock(side_effect=MockException) with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', policy_exists=m, nitro_exception=MockException, ensure_feature_is_enabled=Mock(), ): self.module = netscaler_cs_policy result = self.failed() self.assertTrue( result['msg'].startswith('nitro exception'), msg='Nitro exception not caught on operation absent' ) def test_ensure_feature_is_enabled_called(self): self.set_module_state('present') from ansible.modules.network.netscaler import netscaler_cs_policy client_mock = Mock() ensure_feature_is_enabled_mock = Mock() with patch.multiple( 'ansible.modules.network.netscaler.netscaler_cs_policy', get_nitro_client=Mock(return_value=client_mock), policy_exists=Mock(side_effect=[True, True]), nitro_exception=self.MockException, ensure_feature_is_enabled=ensure_feature_is_enabled_mock, ): self.module = netscaler_cs_policy result = self.exited() ensure_feature_is_enabled_mock.assert_has_calls([call(client_mock, 'CS')])
gpl-3.0
aperigault/ansible
lib/ansible/modules/network/eos/eos_vrf.py
36
10760
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = """ --- module: eos_vrf version_added: "2.4" author: "Ricardo Carrillo Cruz (@rcarrillocruz)" short_description: Manage VRFs on Arista EOS network devices description: - This module provides declarative management of VRFs on Arista EOS network devices. notes: - Tested against EOS 4.15 options: name: description: - Name of the VRF. required: true rd: description: - Route distinguisher of the VRF interfaces: description: - Identifies the set of interfaces that should be configured in the VRF. Interfaces must be routed interfaces in order to be placed into a VRF. The name of interface should be in expanded format and not abbreviated. associated_interfaces: description: - This is a intent option and checks the operational state of the for given vrf C(name) for associated interfaces. If the value in the C(associated_interfaces) does not match with the operational state of vrf interfaces on device it will result in failure. version_added: "2.5" aggregate: description: List of VRFs definitions purge: description: - Purge VRFs not defined in the I(aggregate) parameter. default: no type: bool delay: description: - Time in seconds to wait before checking for the operational state on remote device. This wait is applicable for operational state arguments. default: 10 state: description: - State of the VRF configuration. default: present choices: ['present', 'absent'] extends_documentation_fragment: eos """ EXAMPLES = """ - name: Create vrf eos_vrf: name: test rd: 1:200 interfaces: - Ethernet2 state: present - name: Delete VRFs eos_vrf: name: test state: absent - name: Create aggregate of VRFs with purge eos_vrf: aggregate: - { name: test4, rd: "1:204" } - { name: test5, rd: "1:205" } state: present purge: yes - name: Delete aggregate of VRFs eos_vrf: aggregate: - name: test2 - name: test3 - name: test4 - name: test5 state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always type: list sample: - vrf definition test - rd 1:100 - interface Ethernet1 - vrf forwarding test """ import re import time from copy import deepcopy from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.common.utils import remove_default_spec from ansible.module_utils.network.eos.eos import load_config, run_commands from ansible.module_utils.network.eos.eos import eos_argument_spec, check_args def search_obj_in_list(name, lst): for o in lst: if o['name'] == name: return o def map_obj_to_commands(updates, module): commands = list() want, have = updates state = module.params['state'] purge = module.params['purge'] for w in want: name = w['name'] rd = w['rd'] interfaces = w['interfaces'] obj_in_have = search_obj_in_list(name, have) if state == 'absent': if obj_in_have: commands.append('no vrf definition %s' % name) elif state == 'present': if not obj_in_have: commands.append('vrf definition %s' % name) if rd is not None: commands.append('rd %s' % rd) if w['interfaces']: for i in w['interfaces']: commands.append('interface %s' % i) commands.append('vrf forwarding %s' % w['name']) else: if w['rd'] is not None and w['rd'] != obj_in_have['rd']: commands.append('vrf definition %s' % w['name']) commands.append('rd %s' % w['rd']) if w['interfaces']: if not obj_in_have['interfaces']: for i in w['interfaces']: commands.append('interface %s' % i) commands.append('vrf forwarding %s' % w['name']) elif set(w['interfaces']) != obj_in_have['interfaces']: missing_interfaces = list(set(w['interfaces']) - set(obj_in_have['interfaces'])) for i in missing_interfaces: commands.append('interface %s' % i) commands.append('vrf forwarding %s' % w['name']) if purge: for h in have: obj_in_want = search_obj_in_list(h['name'], want) if not obj_in_want: commands.append('no vrf definition %s' % h['name']) return commands def map_config_to_obj(module): objs = [] output = run_commands(module, {'command': 'show vrf', 'output': 'text'}) lines = output[0].strip().splitlines()[3:] out_len = len(lines) index = 0 while out_len > index: line = lines[index] if not line: continue splitted_line = re.split(r'\s{2,}', line.strip()) if len(splitted_line) == 1: index += 1 continue else: obj = dict() obj['name'] = splitted_line[0] obj['rd'] = splitted_line[1] obj['interfaces'] = [] if len(splitted_line) > 4: obj['interfaces'] = [] interfaces = splitted_line[4] if interfaces.endswith(','): while interfaces.endswith(','): # gather all comma separated interfaces if out_len <= index: break index += 1 line = lines[index] vrf_line = re.split(r'\s{2,}', line.strip()) interfaces += vrf_line[-1] for i in interfaces.split(','): obj['interfaces'].append(i.strip().lower()) index += 1 objs.append(obj) return objs def map_params_to_obj(module): obj = [] aggregate = module.params.get('aggregate') if aggregate: for item in aggregate: for key in item: if item.get(key) is None: item[key] = module.params[key] if item.get('interfaces'): item['interfaces'] = [intf.replace(" ", "").lower() for intf in item.get('interfaces') if intf] if item.get('associated_interfaces'): item['associated_interfaces'] = [intf.replace(" ", "").lower() for intf in item.get('associated_interfaces') if intf] obj.append(item.copy()) else: obj.append({ 'name': module.params['name'], 'state': module.params['state'], 'rd': module.params['rd'], 'interfaces': [intf.replace(" ", "").lower() for intf in module.params['interfaces']] if module.params['interfaces'] else [], 'associated_interfaces': [intf.replace(" ", "").lower() for intf in module.params['associated_interfaces']] if module.params['associated_interfaces'] else [] }) return obj def check_declarative_intent_params(want, module, result): have = None is_delay = False for w in want: if w.get('associated_interfaces') is None: continue if result['changed'] and not is_delay: time.sleep(module.params['delay']) is_delay = True if have is None: have = map_config_to_obj(module) for i in w['associated_interfaces']: obj_in_have = search_obj_in_list(w['name'], have) if obj_in_have: interfaces = obj_in_have.get('interfaces') if interfaces is not None and i not in interfaces: module.fail_json(msg="Interface %s not configured on vrf %s" % (i, w['name'])) def main(): """ main entry point for module execution """ element_spec = dict( name=dict(), interfaces=dict(type='list'), associated_interfaces=dict(type='list'), delay=dict(default=10, type='int'), rd=dict(), state=dict(default='present', choices=['present', 'absent']) ) aggregate_spec = deepcopy(element_spec) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec), purge=dict(default=False, type='bool') ) argument_spec.update(element_spec) argument_spec.update(eos_argument_spec) required_one_of = [['name', 'aggregate']] mutually_exclusive = [['name', 'aggregate']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() check_args(module, warnings) result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands((want, have), module) result['commands'] = commands if commands: commit = not module.check_mode response = load_config(module, commands, commit=commit) if response.get('diff') and module._diff: result['diff'] = {'prepared': response.get('diff')} result['session_name'] = response.get('session') result['changed'] = True check_declarative_intent_params(want, module, result) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
poljeff/odoo
openerp/tools/cache.py
226
6865
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 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/>. # ############################################################################## # decorator makes wrappers that have the same API as their wrapped function; # this is important for the openerp.api.guess() that relies on signatures from collections import defaultdict from decorator import decorator from inspect import getargspec import logging _logger = logging.getLogger(__name__) class ormcache_counter(object): """ Statistic counters for cache entries. """ __slots__ = ['hit', 'miss', 'err'] def __init__(self): self.hit = 0 self.miss = 0 self.err = 0 @property def ratio(self): return 100.0 * self.hit / (self.hit + self.miss or 1) # statistic counters dictionary, maps (dbname, modelname, method) to counter STAT = defaultdict(ormcache_counter) class ormcache(object): """ LRU cache decorator for orm methods. """ def __init__(self, skiparg=2, size=8192, multi=None, timeout=None): self.skiparg = skiparg def __call__(self, method): self.method = method lookup = decorator(self.lookup, method) lookup.clear_cache = self.clear return lookup def lru(self, model): counter = STAT[(model.pool.db_name, model._name, self.method)] return model.pool.cache, (model._name, self.method), counter def lookup(self, method, *args, **kwargs): d, key0, counter = self.lru(args[0]) key = key0 + args[self.skiparg:] try: r = d[key] counter.hit += 1 return r except KeyError: counter.miss += 1 value = d[key] = self.method(*args, **kwargs) return value except TypeError: counter.err += 1 return self.method(*args, **kwargs) def clear(self, model, *args): """ Remove *args entry from the cache or all keys if *args is undefined """ d, key0, _ = self.lru(model) if args: _logger.warn("ormcache.clear arguments are deprecated and ignored " "(while clearing caches on (%s).%s)", model._name, self.method.__name__) d.clear_prefix(key0) model.pool._any_cache_cleared = True class ormcache_context(ormcache): def __init__(self, skiparg=2, size=8192, accepted_keys=()): super(ormcache_context,self).__init__(skiparg,size) self.accepted_keys = accepted_keys def __call__(self, method): # remember which argument is context args = getargspec(method)[0] self.context_pos = args.index('context') return super(ormcache_context, self).__call__(method) def lookup(self, method, *args, **kwargs): d, key0, counter = self.lru(args[0]) # Note. The decorator() wrapper (used in __call__ above) will resolve # arguments, and pass them positionally to lookup(). This is why context # is not passed through kwargs! if self.context_pos < len(args): context = args[self.context_pos] or {} else: context = kwargs.get('context') or {} ckey = [(k, context[k]) for k in self.accepted_keys if k in context] # Beware: do not take the context from args! key = key0 + args[self.skiparg:self.context_pos] + tuple(ckey) try: r = d[key] counter.hit += 1 return r except KeyError: counter.miss += 1 value = d[key] = self.method(*args, **kwargs) return value except TypeError: counter.err += 1 return self.method(*args, **kwargs) class ormcache_multi(ormcache): def __init__(self, skiparg=2, size=8192, multi=3): assert skiparg <= multi super(ormcache_multi, self).__init__(skiparg, size) self.multi = multi def lookup(self, method, *args, **kwargs): d, key0, counter = self.lru(args[0]) base_key = key0 + args[self.skiparg:self.multi] + args[self.multi+1:] ids = args[self.multi] result = {} missed = [] # first take what is available in the cache for i in ids: key = base_key + (i,) try: result[i] = d[key] counter.hit += 1 except Exception: counter.miss += 1 missed.append(i) if missed: # call the method for the ids that were not in the cache args = list(args) args[self.multi] = missed result.update(method(*args, **kwargs)) # store those new results back in the cache for i in missed: key = base_key + (i,) d[key] = result[i] return result class dummy_cache(object): """ Cache decorator replacement to actually do no caching. """ def __init__(self, *l, **kw): pass def __call__(self, fn): fn.clear_cache = self.clear return fn def clear(self, *l, **kw): pass def log_ormcache_stats(sig=None, frame=None): """ Log statistics of ormcache usage by database, model, and method. """ from openerp.modules.registry import RegistryManager import threading me = threading.currentThread() me_dbname = me.dbname entries = defaultdict(int) for dbname, reg in RegistryManager.registries.iteritems(): for key in reg.cache.iterkeys(): entries[(dbname,) + key[:2]] += 1 for key, count in sorted(entries.items()): dbname, model_name, method = key me.dbname = dbname stat = STAT[key] _logger.info("%6d entries, %6d hit, %6d miss, %6d err, %4.1f%% ratio, for %s.%s", count, stat.hit, stat.miss, stat.err, stat.ratio, model_name, method.__name__) me.dbname = me_dbname # For backward compatibility cache = ormcache # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
gurneyalex/hr
__unported__/hr_policy_absence/__openerp__.py
2
1551
# -*- coding:utf-8 -*- # # # Copyright (C) 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>. # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # { 'name': 'Absence Policy', 'version': '1.0', 'category': 'Generic Modules/Human Resources', 'description': """ Define Absence Policies ======================== Define properties of an absence policy, such as: * Type (paid, unpaid) * Rate (multiplier of base wage) """, 'author': 'Michael Telahun Makonnen <mmakonnen@gmail.com>', 'website': 'http://miketelahun.wordpress.com', 'depends': [ 'hr_holidays', 'hr_payroll_period', 'hr_policy_group', ], 'data': [ 'security/ir.model.access.csv', 'data/leave_types.xml', 'data/salary_rules_data.xml', 'hr_policy_absence_view.xml', ], 'test': [ ], 'installable': False, }
agpl-3.0
Proggie02/TestRepo
django/forms/util.py
7
3658
from __future__ import unicode_literals from django.conf import settings from django.utils.html import format_html, format_html_join from django.utils.encoding import force_text, python_2_unicode_compatible from django.utils.safestring import mark_safe from django.utils import timezone from django.utils.translation import ugettext_lazy as _ # Import ValidationError so that it can be imported from this # module to maintain backwards compatibility. from django.core.exceptions import ValidationError def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. The result is passed through 'mark_safe'. """ return format_html_join('', ' {0}="{1}"', attrs.items()) @python_2_unicode_compatible class ErrorDict(dict): """ A collection of errors that knows how to display itself in various formats. The dictionary keys are the field names, and the values are the errors. """ def __str__(self): return self.as_ul() def as_ul(self): if not self: return '' return format_html('<ul class="errorlist">{0}</ul>', format_html_join('', '<li>{0}{1}</li>', ((k, force_text(v)) for k, v in self.items()) )) def as_text(self): return '\n'.join(['* %s\n%s' % (k, '\n'.join([' * %s' % force_text(i) for i in v])) for k, v in self.items()]) @python_2_unicode_compatible class ErrorList(list): """ A collection of errors that knows how to display itself in various formats. """ def __str__(self): return self.as_ul() def as_ul(self): if not self: return '' return format_html('<ul class="errorlist">{0}</ul>', format_html_join('', '<li>{0}</li>', ((force_text(e),) for e in self) ) ) def as_text(self): if not self: return '' return '\n'.join(['* %s' % force_text(e) for e in self]) def __repr__(self): return repr([force_text(e) for e in self]) # Utilities for time zone support in DateTimeField et al. def from_current_timezone(value): """ When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes. """ if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: return timezone.make_aware(value, current_timezone) except Exception: raise ValidationError(_('%(datetime)s couldn\'t be interpreted ' 'in time zone %(current_timezone)s; it ' 'may be ambiguous or it may not exist.') % {'datetime': value, 'current_timezone': current_timezone}) return value def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive dateimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): current_timezone = timezone.get_current_timezone() return timezone.make_naive(value, current_timezone) return value
bsd-3-clause
dbs/schemaorg
lib/rdflib/plugins/sparql/evalutils.py
23
2644
import collections from rdflib.term import Variable, Literal, BNode, URIRef from rdflib.plugins.sparql.operators import EBV from rdflib.plugins.sparql.parserutils import Expr, CompValue from rdflib.plugins.sparql.sparql import SPARQLError, NotBoundError def _diff(a, b, expr): res = set() for x in a: if all(not x.compatible(y) or not _ebv(expr, x.merge(y)) for y in b): res.add(x) return res def _minus(a, b): for x in a: if all((not x.compatible(y)) or x.disjointDomain(y) for y in b): yield x def _join(a, b): for x in a: for y in b: if x.compatible(y): yield x.merge(y) def _ebv(expr, ctx): """ Return true/false for the given expr Either the expr is itself true/false or evaluates to something, with the given ctx an error is false """ try: return EBV(expr) except SPARQLError: pass if isinstance(expr, Expr): try: return EBV(expr.eval(ctx)) except SPARQLError: return False # filter error == False elif isinstance(expr, CompValue): raise Exception( "Weird - filter got a CompValue without evalfn! %r" % expr) elif isinstance(expr, Variable): try: return EBV(ctx[expr]) except: return False return False def _eval(expr, ctx): if isinstance(expr, (Literal, URIRef)): return expr if isinstance(expr, Expr): return expr.eval(ctx) elif isinstance(expr, Variable): try: return ctx[expr] except KeyError: return NotBoundError("Variable %s is not bound" % expr) elif isinstance(expr, CompValue): raise Exception( "Weird - _eval got a CompValue without evalfn! %r" % expr) else: raise Exception("Cannot eval thing: %s (%s)" % (expr, type(expr))) def _filter(a, expr): for c in a: if _ebv(expr, c): yield c def _fillTemplate(template, solution): """ For construct/deleteWhere and friends Fill a triple template with instantiated variables """ bnodeMap = collections.defaultdict(BNode) for t in template: s, p, o = t _s = solution.get(s) _p = solution.get(p) _o = solution.get(o) # instantiate new bnodes for each solution _s, _p, _o = [bnodeMap[x] if isinstance( x, BNode) else y for x, y in zip(t, (_s, _p, _o))] if _s is not None and \ _p is not None and \ _o is not None: yield (_s, _p, _o)
apache-2.0
csm0042/rpihome_v3
rpihome_v3/schedule_service/service_main.py
1
6835
#!/usr/bin/python3 """ service_main.py: """ # Import Required Libraries (Standard, Third Party, Local) ******************** import asyncio import datetime import logging if __name__ == "__main__": import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) from rpihome_v3.occupancy_service.msg_processing import create_heartbeat_msg from rpihome_v3.occupancy_service.msg_processing import process_heartbeat_msg from rpihome_v3.schedule_service.msg_processing import process_get_device_scheduled_state_msg # Authorship Info ************************************************************* __author__ = "Christopher Maue" __copyright__ = "Copyright 2017, The RPi-Home Project" __credits__ = ["Christopher Maue"] __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "Christopher Maue" __email__ = "csmaue@gmail.com" __status__ = "Development" # Internal Service Work Task ************************************************** class MainTask(object): def __init__(self, log, **kwargs): # Configure logger self.log = log or logging.getLogger(__name__) # Define instance variables self.ref_num = None self.msg_in_queue = None self.msg_out_queue = None self.schedule = [] self.service_addresses = [] self.message_types = [] self.last_check_hb = datetime.datetime.now() self.out_msg = str() self.out_msg_list = [] self.next_msg = str() self.next_msg_split = [] self.msg_source_addr = str() self.msg_type = str() self.destinations = [] # Map input variables if kwargs is not None: for key, value in kwargs.items(): if key == "ref": self.ref_num = value self.log.debug('Ref number generator set during __init__ ' 'to: %s', self.ref_num) if key == "schedule": self.schedule = value self.log.debug('Schedule set during __init__ ' 'to: %s', self.schedule) if key == "msg_in_queue": self.msg_in_queue = value self.log.debug('Message in queue set during __init__ ' 'to: %s', self.msg_in_queue) if key == "msg_out_queue": self.msg_out_queue = value self.log.debug('Message out queue set during __init__ ' 'to: %s', self.msg_out_queue) if key == "service_addresses": self.service_addresses = value self.log.debug('Service address list set during __init__ ' 'to: %s', self.service_addresses) if key == "message_types": self.message_types = value self.log.debug('Message type list set during __init__ ' 'to: %s', self.message_types) @asyncio.coroutine def run(self): """ task to handle the work the service is intended to do """ self.log.info('Starting schedule service main task') while True: # Initialize result list self.out_msg_list = [] # INCOMING MESSAGE HANDLING if self.msg_in_queue.qsize() > 0: self.log.debug('Getting Incoming message from queue') self.next_msg = self.msg_in_queue.get_nowait() self.log.debug('Message pulled from queue: [%s]', self.next_msg) # Determine message type self.next_msg_split = self.next_msg.split(',') if len(self.next_msg_split) >= 6: self.log.debug('Extracting source address and message type') self.msg_source_addr = self.next_msg_split[1] self.msg_type = self.next_msg_split[5] self.log.debug('Source Address: %s', self.msg_source_addr) self.log.debug('Message Type: %s', self.msg_type) # Service Check (heartbeat) if self.msg_type == self.message_types['heartbeat']: self.log.debug('Message is a heartbeat') self.out_msg_list = process_heartbeat_msg( self.log, self.ref_num, self.next_msg, self.message_types) # Device scheduled command checks if self.msg_type == self.message_types['get_device_scheduled_state']: self.log.debug('Message is a get device scheduled state message') self.out_msg_list = process_get_device_scheduled_state_msg( self.log, self.ref_num, self.schedule, self.next_msg, self.message_types) # Que up response messages in outgoing msg que if len(self.out_msg_list) > 0: self.log.debug('Queueing response message(s)') for self.out_msg in self.out_msg_list: self.msg_out_queue.put_nowait(self.out_msg) self.log.debug('Message [%s] successfully queued', self.out_msg) # PERIODIC TASKS # Periodically send heartbeats to other services if datetime.datetime.now() >= (self.last_check_hb + datetime.timedelta(seconds=120)): self.destinations = [ (self.service_addresses['automation_addr'], self.service_addresses['automation_port']) ] self.out_msg_list = create_heartbeat_msg( self.log, self.ref_num, self.destinations, self.service_addresses['schedule_addr'], self.service_addresses['schedule_port'], self.message_types) # Que up response messages in outgoing msg que if len(self.out_msg_list) > 0: self.log.debug('Queueing response message(s)') for self.out_msg in self.out_msg_list: self.msg_out_queue.put_nowait(self.out_msg) self.log.debug('Response message [%s] successfully queued', self.out_msg) # Update last-check self.last_check_hb = datetime.datetime.now() # Yield to other tasks for a while yield from asyncio.sleep(0.25)
gpl-3.0
radiac/bleach
docs/conf.py
13
7775
# -*- coding: utf-8 -*- # # Bleach documentation build configuration file, created by # sphinx-quickstart on Fri May 11 21:11:39 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 # 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('.')) # -- 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.autodoc', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_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'Bleach' copyright = u'2012, James Socol' # 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.2' # The full version, including alpha/beta/rc tags. release = '1.2.0' # 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'] # 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 # 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 --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # 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 = [] # 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 = None # 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 = ['_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 = True # 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 = 'Bleachdoc' # -- 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', 'Bleach.tex', u'Bleach Documentation', u'James Socol', '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 = [ ('index', 'bleach', u'Bleach Documentation', [u'James Socol'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- 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', 'Bleach', u'Bleach Documentation', u'James Socol', 'Bleach', 'One line description of project.', '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'
bsd-3-clause
kevin-coder/tensorflow-fork
tensorflow/python/data/experimental/kernel_tests/make_batched_features_dataset_test.py
12
9466
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for `tf.data.experimental.make_batched_features_dataset()`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.data.experimental.kernel_tests import reader_dataset_ops_test_base from tensorflow.python.data.experimental.ops import readers from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.ops import readers as core_readers from tensorflow.python.data.util import nest from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import io_ops from tensorflow.python.ops import parsing_ops from tensorflow.python.platform import test @test_util.run_all_in_graph_and_eager_modes class MakeBatchedFeaturesDatasetTest( reader_dataset_ops_test_base.MakeBatchedFeaturesDatasetTestBase): def testRead(self): for batch_size in [1, 2]: for num_epochs in [1, 10]: # Basic test: read from file 0. self.outputs = self.getNext( self.make_batch_feature( filenames=self.test_filenames[0], label_key="label", num_epochs=num_epochs, batch_size=batch_size)) self.verify_records( batch_size, 0, num_epochs=num_epochs, label_key_provided=True) with self.assertRaises(errors.OutOfRangeError): self._next_actual_batch(label_key_provided=True) # Basic test: read from file 1. self.outputs = self.getNext( self.make_batch_feature( filenames=self.test_filenames[1], label_key="label", num_epochs=num_epochs, batch_size=batch_size)) self.verify_records( batch_size, 1, num_epochs=num_epochs, label_key_provided=True) with self.assertRaises(errors.OutOfRangeError): self._next_actual_batch(label_key_provided=True) # Basic test: read from both files. self.outputs = self.getNext( self.make_batch_feature( filenames=self.test_filenames, label_key="label", num_epochs=num_epochs, batch_size=batch_size)) self.verify_records( batch_size, num_epochs=num_epochs, label_key_provided=True) with self.assertRaises(errors.OutOfRangeError): self._next_actual_batch(label_key_provided=True) # Basic test: read from both files. self.outputs = self.getNext( self.make_batch_feature( filenames=self.test_filenames, num_epochs=num_epochs, batch_size=batch_size)) self.verify_records(batch_size, num_epochs=num_epochs) with self.assertRaises(errors.OutOfRangeError): self._next_actual_batch() def testReadWithEquivalentDataset(self): features = { "file": parsing_ops.FixedLenFeature([], dtypes.int64), "record": parsing_ops.FixedLenFeature([], dtypes.int64), } dataset = ( core_readers.TFRecordDataset(self.test_filenames) .map(lambda x: parsing_ops.parse_single_example(x, features)) .repeat(10).batch(2)) next_element = self.getNext(dataset) for file_batch, _, _, _, record_batch, _ in self._next_expected_batch( range(self._num_files), 2, 10): actual_batch = self.evaluate(next_element()) self.assertAllEqual(file_batch, actual_batch["file"]) self.assertAllEqual(record_batch, actual_batch["record"]) with self.assertRaises(errors.OutOfRangeError): self.evaluate(next_element()) def testReadWithFusedShuffleRepeatDataset(self): num_epochs = 5 total_records = num_epochs * self._num_records for batch_size in [1, 2]: # Test that shuffling with same seed produces the same result. outputs1 = self.getNext( self.make_batch_feature( filenames=self.test_filenames[0], num_epochs=num_epochs, batch_size=batch_size, shuffle=True, shuffle_seed=5)) outputs2 = self.getNext( self.make_batch_feature( filenames=self.test_filenames[0], num_epochs=num_epochs, batch_size=batch_size, shuffle=True, shuffle_seed=5)) for _ in range(total_records // batch_size): batch1 = self._run_actual_batch(outputs1) batch2 = self._run_actual_batch(outputs2) for i in range(len(batch1)): self.assertAllEqual(batch1[i], batch2[i]) # Test that shuffling with different seeds produces a different order. outputs1 = self.getNext( self.make_batch_feature( filenames=self.test_filenames[0], num_epochs=num_epochs, batch_size=batch_size, shuffle=True, shuffle_seed=5)) outputs2 = self.getNext( self.make_batch_feature( filenames=self.test_filenames[0], num_epochs=num_epochs, batch_size=batch_size, shuffle=True, shuffle_seed=15)) all_equal = True for _ in range(total_records // batch_size): batch1 = self._run_actual_batch(outputs1) batch2 = self._run_actual_batch(outputs2) for i in range(len(batch1)): all_equal = all_equal and np.array_equal(batch1[i], batch2[i]) self.assertFalse(all_equal) def testParallelReadersAndParsers(self): num_epochs = 5 for batch_size in [1, 2]: for reader_num_threads in [2, 4]: for parser_num_threads in [2, 4]: self.outputs = self.getNext( self.make_batch_feature( filenames=self.test_filenames, label_key="label", num_epochs=num_epochs, batch_size=batch_size, reader_num_threads=reader_num_threads, parser_num_threads=parser_num_threads)) self.verify_records( batch_size, num_epochs=num_epochs, label_key_provided=True, interleave_cycle_length=reader_num_threads) with self.assertRaises(errors.OutOfRangeError): self._next_actual_batch(label_key_provided=True) self.outputs = self.getNext( self.make_batch_feature( filenames=self.test_filenames, num_epochs=num_epochs, batch_size=batch_size, reader_num_threads=reader_num_threads, parser_num_threads=parser_num_threads)) self.verify_records( batch_size, num_epochs=num_epochs, interleave_cycle_length=reader_num_threads) with self.assertRaises(errors.OutOfRangeError): self._next_actual_batch() def testDropFinalBatch(self): for batch_size in [1, 2]: for num_epochs in [1, 10]: with ops.Graph().as_default(): # Basic test: read from file 0. outputs = self.make_batch_feature( filenames=self.test_filenames[0], label_key="label", num_epochs=num_epochs, batch_size=batch_size, drop_final_batch=True) for tensor in nest.flatten(outputs): if isinstance(tensor, ops.Tensor): # Guard against SparseTensor. self.assertEqual(tensor.shape[0], batch_size) def testIndefiniteRepeatShapeInference(self): dataset = self.make_batch_feature( filenames=self.test_filenames[0], label_key="label", num_epochs=None, batch_size=32) for shape, clazz in zip( nest.flatten(dataset_ops.get_legacy_output_shapes(dataset)), nest.flatten(dataset_ops.get_legacy_output_classes(dataset))): if issubclass(clazz, ops.Tensor): self.assertEqual(32, shape[0]) def testOldStyleReader(self): with self.assertRaisesRegexp( TypeError, r"The `reader` argument must return a `Dataset` object. " r"`tf.ReaderBase` subclasses are not supported."): _ = readers.make_batched_features_dataset( file_pattern=self.test_filenames[0], batch_size=32, features={ "file": parsing_ops.FixedLenFeature([], dtypes.int64), "record": parsing_ops.FixedLenFeature([], dtypes.int64), "keywords": parsing_ops.VarLenFeature(dtypes.string), "label": parsing_ops.FixedLenFeature([], dtypes.string), }, reader=io_ops.TFRecordReader) if __name__ == "__main__": test.main()
apache-2.0
srager13/ns3_qoi_symptotics
src/point-to-point/bindings/modulegen__gcc_ILP32.py
24
361770
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.point_to_point', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class] module.add_class('AsciiTraceHelper', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class] module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True, import_from_module='ns.network') ## 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') ## data-rate.h (module 'network'): ns3::DataRate [class] module.add_class('DataRate', import_from_module='ns.network') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', 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-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## pcap-file.h (module 'network'): ns3::PcapFile [class] module.add_class('PcapFile', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelper [class] module.add_class('PcapHelper', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelper [enumeration] module.add_enum('', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO', 'DLT_IEEE802_15_4'], outer_class=root_module['ns3::PcapHelper'], import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class] module.add_class('PcapHelperForDevice', allow_subclassing=True, import_from_module='ns.network') ## point-to-point-helper.h (module 'point-to-point'): ns3::PointToPointHelper [class] module.add_class('PointToPointHelper', parent=[root_module['ns3::PcapHelperForDevice'], root_module['ns3::AsciiTraceHelperForDevice']]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class] module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=root_module['ns3::Object']) ## ppp-header.h (module 'point-to-point'): ns3::PppHeader [class] module.add_class('PppHeader', parent=root_module['ns3::Header']) ## queue.h (module 'network'): ns3::Queue [class] module.add_class('Queue', import_from_module='ns.network', parent=root_module['ns3::Object']) ## queue.h (module 'network'): ns3::Queue::QueueMode [enumeration] module.add_enum('QueueMode', ['QUEUE_MODE_PACKETS', 'QUEUE_MODE_BYTES'], outer_class=root_module['ns3::Queue'], import_from_module='ns.network') ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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')) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## data-rate.h (module 'network'): ns3::DataRateChecker [class] module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## data-rate.h (module 'network'): ns3::DataRateValue [class] module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class] module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class] module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## error-model.h (module 'network'): ns3::ErrorModel [class] module.add_class('ErrorModel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class] module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## error-model.h (module 'network'): ns3::ListErrorModel [class] module.add_class('ListErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel']) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class] module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## point-to-point-channel.h (module 'point-to-point'): ns3::PointToPointChannel [class] module.add_class('PointToPointChannel', parent=root_module['ns3::Channel']) ## point-to-point-net-device.h (module 'point-to-point'): ns3::PointToPointNetDevice [class] module.add_class('PointToPointNetDevice', parent=root_module['ns3::NetDevice']) ## point-to-point-remote-channel.h (module 'point-to-point'): ns3::PointToPointRemoteChannel [class] module.add_class('PointToPointRemoteChannel', parent=root_module['ns3::PointToPointChannel']) ## error-model.h (module 'network'): ns3::RateErrorModel [class] module.add_class('RateErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel']) ## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit [enumeration] module.add_enum('ErrorUnit', ['ERROR_UNIT_BIT', 'ERROR_UNIT_BYTE', 'ERROR_UNIT_PACKET'], outer_class=root_module['ns3::RateErrorModel'], import_from_module='ns.network') ## error-model.h (module 'network'): ns3::ReceiveListErrorModel [class] module.add_class('ReceiveListErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel']) ## 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']) ## error-model.h (module 'network'): ns3::BurstErrorModel [class] module.add_class('BurstErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel']) module.add_container('std::list< unsigned int >', 'unsigned int', container_type=u'list') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper']) register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice']) register_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_Ns3DataRate_methods(root_module, root_module['ns3::DataRate']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile']) register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper']) register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice']) register_Ns3PointToPointHelper_methods(root_module, root_module['ns3::PointToPointHelper']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper']) register_Ns3PppHeader_methods(root_module, root_module['ns3::PppHeader']) register_Ns3Queue_methods(root_module, root_module['ns3::Queue']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__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_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker']) register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable']) register_Ns3ErrorModel_methods(root_module, root_module['ns3::ErrorModel']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3ListErrorModel_methods(root_module, root_module['ns3::ListErrorModel']) register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3PointToPointChannel_methods(root_module, root_module['ns3::PointToPointChannel']) register_Ns3PointToPointNetDevice_methods(root_module, root_module['ns3::PointToPointNetDevice']) register_Ns3PointToPointRemoteChannel_methods(root_module, root_module['ns3::PointToPointRemoteChannel']) register_Ns3RateErrorModel_methods(root_module, root_module['ns3::RateErrorModel']) register_Ns3ReceiveListErrorModel_methods(root_module, root_module['ns3::ReceiveListErrorModel']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3BurstErrorModel_methods(root_module, root_module['ns3::BurstErrorModel']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AsciiTraceHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::_Ios_Openmode filemode=std::ios_base::out) [member function] cls.add_method('CreateFileStream', 'ns3::Ptr< ns3::OutputStreamWrapper >', [param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode', default_value='std::ios_base::out')]) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3AsciiTraceHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice(ns3::AsciiTraceHelperForDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::NetDevice> nd) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::NetDevice >', 'nd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, std::string ndName, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ndName) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ndName')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t deviceid) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(std::string prefix) [member function] cls.add_method('EnableAsciiAll', 'void', [param('std::string', 'prefix')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiAll', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function] cls.add_method('EnableAsciiInternal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3DataRate_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('>=') ## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRate const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor] cls.add_constructor([param('uint64_t', 'bps')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor] cls.add_constructor([param('std::string', 'rate')]) ## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateTxTime', 'double', [param('uint32_t', 'bytes')], is_const=True) ## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function] cls.add_method('GetBitRate', 'uint64_t', [], is_const=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PcapFile_methods(root_module, cls): ## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor] cls.add_constructor([]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT) [member function] cls.add_method('Diff', 'bool', [param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint32_t &', 'sec'), param('uint32_t &', 'usec'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT')], is_static=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file.h (module 'network'): bool ns3::PcapFile::GetSwapMode() [member function] cls.add_method('GetSwapMode', 'bool', []) ## pcap-file.h (module 'network'): int32_t ns3::PcapFile::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Init(uint32_t dataLinkType, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT, int32_t timeZoneCorrection=ns3::PcapFile::ZONE_DEFAULT, bool swapMode=false) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT'), param('int32_t', 'timeZoneCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT'), param('bool', 'swapMode', default_value='false')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Read(uint8_t * const data, uint32_t maxBytes, uint32_t & tsSec, uint32_t & tsUsec, uint32_t & inclLen, uint32_t & origLen, uint32_t & readLen) [member function] cls.add_method('Read', 'void', [param('uint8_t * const', 'data'), param('uint32_t', 'maxBytes'), param('uint32_t &', 'tsSec'), param('uint32_t &', 'tsUsec'), param('uint32_t &', 'inclLen'), param('uint32_t &', 'origLen'), param('uint32_t &', 'readLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, uint8_t const * const data, uint32_t totalLen) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('uint8_t const * const', 'data'), param('uint32_t', 'totalLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Header & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): ns3::PcapFile::SNAPLEN_DEFAULT [variable] cls.add_static_attribute('SNAPLEN_DEFAULT', 'uint32_t const', is_const=True) ## pcap-file.h (module 'network'): ns3::PcapFile::ZONE_DEFAULT [variable] cls.add_static_attribute('ZONE_DEFAULT', 'int32_t const', is_const=True) return def register_Ns3PcapHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper(ns3::PcapHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::PcapFileWrapper> ns3::PcapHelper::CreateFile(std::string filename, std::_Ios_Openmode filemode, uint32_t dataLinkType, uint32_t snapLen=65535, int32_t tzCorrection=0) [member function] cls.add_method('CreateFile', 'ns3::Ptr< ns3::PcapFileWrapper >', [param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode'), param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='65535'), param('int32_t', 'tzCorrection', default_value='0')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3PcapHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function] cls.add_method('EnablePcapAll', 'void', [param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3PointToPointHelper_methods(root_module, cls): ## point-to-point-helper.h (module 'point-to-point'): ns3::PointToPointHelper::PointToPointHelper(ns3::PointToPointHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PointToPointHelper const &', 'arg0')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::PointToPointHelper::PointToPointHelper() [constructor] cls.add_constructor([]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(ns3::NodeContainer c) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer', 'c')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(ns3::Ptr<ns3::Node> a, ns3::Ptr<ns3::Node> b) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'a'), param('ns3::Ptr< ns3::Node >', 'b')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(ns3::Ptr<ns3::Node> a, std::string bName) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'a'), param('std::string', 'bName')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(std::string aName, ns3::Ptr<ns3::Node> b) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'aName'), param('ns3::Ptr< ns3::Node >', 'b')]) ## point-to-point-helper.h (module 'point-to-point'): ns3::NetDeviceContainer ns3::PointToPointHelper::Install(std::string aNode, std::string bNode) [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'aNode'), param('std::string', 'bNode')]) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::SetChannelAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetChannelAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::SetDeviceAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::SetQueue(std::string type, std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetQueue', 'void', [param('std::string', 'type'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()')]) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function] cls.add_method('EnableAsciiInternal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## point-to-point-helper.h (module 'point-to-point'): void ns3::PointToPointHelper::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3PcapFileWrapper_methods(root_module, cls): ## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor] cls.add_constructor([]) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::_Ios_Openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Header & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')]) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) return def register_Ns3PppHeader_methods(root_module, cls): ## ppp-header.h (module 'point-to-point'): ns3::PppHeader::PppHeader(ns3::PppHeader const & arg0) [copy constructor] cls.add_constructor([param('ns3::PppHeader const &', 'arg0')]) ## ppp-header.h (module 'point-to-point'): ns3::PppHeader::PppHeader() [constructor] cls.add_constructor([]) ## ppp-header.h (module 'point-to-point'): uint32_t ns3::PppHeader::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ppp-header.h (module 'point-to-point'): ns3::TypeId ns3::PppHeader::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ppp-header.h (module 'point-to-point'): uint16_t ns3::PppHeader::GetProtocol() [member function] cls.add_method('GetProtocol', 'uint16_t', []) ## ppp-header.h (module 'point-to-point'): uint32_t ns3::PppHeader::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ppp-header.h (module 'point-to-point'): static ns3::TypeId ns3::PppHeader::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ppp-header.h (module 'point-to-point'): void ns3::PppHeader::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ppp-header.h (module 'point-to-point'): void ns3::PppHeader::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ppp-header.h (module 'point-to-point'): void ns3::PppHeader::SetProtocol(uint16_t protocol) [member function] cls.add_method('SetProtocol', 'void', [param('uint16_t', 'protocol')]) return def register_Ns3Queue_methods(root_module, cls): ## queue.h (module 'network'): ns3::Queue::Queue(ns3::Queue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Queue const &', 'arg0')]) ## queue.h (module 'network'): ns3::Queue::Queue() [constructor] cls.add_constructor([]) ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue::Dequeue() [member function] cls.add_method('Dequeue', 'ns3::Ptr< ns3::Packet >', []) ## queue.h (module 'network'): void ns3::Queue::DequeueAll() [member function] cls.add_method('DequeueAll', 'void', []) ## queue.h (module 'network'): bool ns3::Queue::Enqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Enqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## queue.h (module 'network'): uint32_t ns3::Queue::GetNBytes() const [member function] cls.add_method('GetNBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetNPackets() const [member function] cls.add_method('GetNPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedBytes() const [member function] cls.add_method('GetTotalDroppedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedPackets() const [member function] cls.add_method('GetTotalDroppedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedBytes() const [member function] cls.add_method('GetTotalReceivedBytes', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedPackets() const [member function] cls.add_method('GetTotalReceivedPackets', 'uint32_t', [], is_const=True) ## queue.h (module 'network'): static ns3::TypeId ns3::Queue::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## queue.h (module 'network'): bool ns3::Queue::IsEmpty() const [member function] cls.add_method('IsEmpty', 'bool', [], is_const=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::Queue::Peek() const [member function] cls.add_method('Peek', 'ns3::Ptr< ns3::Packet const >', [], is_const=True) ## queue.h (module 'network'): void ns3::Queue::ResetStatistics() [member function] cls.add_method('ResetStatistics', 'void', []) ## queue.h (module 'network'): void ns3::Queue::Drop(ns3::Ptr<ns3::Packet> packet) [member function] cls.add_method('Drop', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet')], visibility='protected') ## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue::DoDequeue() [member function] cls.add_method('DoDequeue', 'ns3::Ptr< ns3::Packet >', [], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h (module 'network'): bool ns3::Queue::DoEnqueue(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoEnqueue', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], is_pure_virtual=True, visibility='private', is_virtual=True) ## queue.h (module 'network'): ns3::Ptr<const ns3::Packet> ns3::Queue::DoPeek() const [member function] cls.add_method('DoPeek', 'ns3::Ptr< ns3::Packet const >', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3RandomVariableStream_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function] cls.add_method('SetStream', 'void', [param('int64_t', 'stream')]) ## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function] cls.add_method('GetStream', 'int64_t', [], is_const=True) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function] cls.add_method('SetAntithetic', 'void', [param('bool', 'isAntithetic')]) ## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function] cls.add_method('IsAntithetic', 'bool', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function] cls.add_method('Peek', 'ns3::RngStream *', [], is_const=True, visibility='protected') return def register_Ns3SequentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function] cls.add_method('GetIncrement', 'ns3::Ptr< ns3::RandomVariableStream >', [], is_const=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function] cls.add_method('GetConsecutive', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__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_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TriangularRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_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_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3ConstantRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function] cls.add_method('GetConstant', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function] cls.add_method('GetValue', 'double', [param('double', 'constant')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'constant')]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3DataRateChecker_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')]) return def register_Ns3DataRateValue_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor] cls.add_constructor([param('ns3::DataRate const &', 'value')]) ## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): bool ns3::DataRateValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function] cls.add_method('Get', 'ns3::DataRate', [], is_const=True) ## data-rate.h (module 'network'): std::string ns3::DataRateValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function] cls.add_method('Set', 'void', [param('ns3::DataRate const &', 'value')]) return def register_Ns3DeterministicRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function] cls.add_method('SetValueArray', 'void', [param('double *', 'values'), param('uint64_t', 'length')]) ## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3EmpiricalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function] cls.add_method('CDF', 'void', [param('double', 'v'), param('double', 'c')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double arg0, double arg1, double arg2, double arg3, double arg4) [member function] cls.add_method('Interpolate', 'double', [param('double', 'arg0'), param('double', 'arg1'), param('double', 'arg2'), param('double', 'arg3'), param('double', 'arg4')], visibility='private', is_virtual=True) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function] cls.add_method('Validate', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3ErlangRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function] cls.add_method('GetK', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function] cls.add_method('GetLambda', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'k'), param('double', 'lambda')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'k'), param('uint32_t', 'lambda')]) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::ErrorModel::ErrorModel(ns3::ErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::ErrorModel::ErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): void ns3::ErrorModel::Disable() [member function] cls.add_method('Disable', 'void', []) ## error-model.h (module 'network'): void ns3::ErrorModel::Enable() [member function] cls.add_method('Enable', 'void', []) ## error-model.h (module 'network'): static ns3::TypeId ns3::ErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): bool ns3::ErrorModel::IsCorrupt(ns3::Ptr<ns3::Packet> pkt) [member function] cls.add_method('IsCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'pkt')]) ## error-model.h (module 'network'): bool ns3::ErrorModel::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## error-model.h (module 'network'): void ns3::ErrorModel::Reset() [member function] cls.add_method('Reset', 'void', []) ## error-model.h (module 'network'): bool ns3::ErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], is_pure_virtual=True, visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::ErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3ExponentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3GammaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function] cls.add_method('GetBeta', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha'), param('double', 'beta')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha'), param('uint32_t', 'beta')]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3ListErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::ListErrorModel::ListErrorModel(ns3::ListErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ListErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::ListErrorModel::ListErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ListErrorModel::GetList() const [member function] cls.add_method('GetList', 'std::list< unsigned int >', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::ListErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): void ns3::ListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function] cls.add_method('SetList', 'void', [param('std::list< unsigned int > const &', 'packetlist')]) ## error-model.h (module 'network'): bool ns3::ListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::ListErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3LogNormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function] cls.add_method('GetMu', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function] cls.add_method('GetSigma', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function] cls.add_method('GetValue', 'double', [param('double', 'mu'), param('double', 'sigma')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mu'), param('uint32_t', 'sigma')]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable] cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function] cls.add_method('GetVariance', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) return def register_Ns3ParetoRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3PointToPointChannel_methods(root_module, cls): ## point-to-point-channel.h (module 'point-to-point'): ns3::PointToPointChannel::PointToPointChannel(ns3::PointToPointChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::PointToPointChannel const &', 'arg0')]) ## point-to-point-channel.h (module 'point-to-point'): ns3::PointToPointChannel::PointToPointChannel() [constructor] cls.add_constructor([]) ## point-to-point-channel.h (module 'point-to-point'): void ns3::PointToPointChannel::Attach(ns3::Ptr<ns3::PointToPointNetDevice> device) [member function] cls.add_method('Attach', 'void', [param('ns3::Ptr< ns3::PointToPointNetDevice >', 'device')]) ## point-to-point-channel.h (module 'point-to-point'): ns3::Ptr<ns3::NetDevice> ns3::PointToPointChannel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## point-to-point-channel.h (module 'point-to-point'): uint32_t ns3::PointToPointChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## point-to-point-channel.h (module 'point-to-point'): ns3::Ptr<ns3::PointToPointNetDevice> ns3::PointToPointChannel::GetPointToPointDevice(uint32_t i) const [member function] cls.add_method('GetPointToPointDevice', 'ns3::Ptr< ns3::PointToPointNetDevice >', [param('uint32_t', 'i')], is_const=True) ## point-to-point-channel.h (module 'point-to-point'): static ns3::TypeId ns3::PointToPointChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## point-to-point-channel.h (module 'point-to-point'): bool ns3::PointToPointChannel::TransmitStart(ns3::Ptr<ns3::Packet> p, ns3::Ptr<ns3::PointToPointNetDevice> src, ns3::Time txTime) [member function] cls.add_method('TransmitStart', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ptr< ns3::PointToPointNetDevice >', 'src'), param('ns3::Time', 'txTime')], is_virtual=True) ## point-to-point-channel.h (module 'point-to-point'): ns3::Time ns3::PointToPointChannel::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True, visibility='protected') ## point-to-point-channel.h (module 'point-to-point'): ns3::Ptr<ns3::PointToPointNetDevice> ns3::PointToPointChannel::GetDestination(uint32_t i) const [member function] cls.add_method('GetDestination', 'ns3::Ptr< ns3::PointToPointNetDevice >', [param('uint32_t', 'i')], is_const=True, visibility='protected') ## point-to-point-channel.h (module 'point-to-point'): ns3::Ptr<ns3::PointToPointNetDevice> ns3::PointToPointChannel::GetSource(uint32_t i) const [member function] cls.add_method('GetSource', 'ns3::Ptr< ns3::PointToPointNetDevice >', [param('uint32_t', 'i')], is_const=True, visibility='protected') ## point-to-point-channel.h (module 'point-to-point'): bool ns3::PointToPointChannel::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True, visibility='protected') return def register_Ns3PointToPointNetDevice_methods(root_module, cls): ## point-to-point-net-device.h (module 'point-to-point'): static ns3::TypeId ns3::PointToPointNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## point-to-point-net-device.h (module 'point-to-point'): ns3::PointToPointNetDevice::PointToPointNetDevice() [constructor] cls.add_constructor([]) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::SetDataRate(ns3::DataRate bps) [member function] cls.add_method('SetDataRate', 'void', [param('ns3::DataRate', 'bps')]) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::SetInterframeGap(ns3::Time t) [member function] cls.add_method('SetInterframeGap', 'void', [param('ns3::Time', 't')]) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::Attach(ns3::Ptr<ns3::PointToPointChannel> ch) [member function] cls.add_method('Attach', 'bool', [param('ns3::Ptr< ns3::PointToPointChannel >', 'ch')]) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::SetQueue(ns3::Ptr<ns3::Queue> queue) [member function] cls.add_method('SetQueue', 'void', [param('ns3::Ptr< ns3::Queue >', 'queue')]) ## point-to-point-net-device.h (module 'point-to-point'): ns3::Ptr<ns3::Queue> ns3::PointToPointNetDevice::GetQueue() const [member function] cls.add_method('GetQueue', 'ns3::Ptr< ns3::Queue >', [], is_const=True) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::SetReceiveErrorModel(ns3::Ptr<ns3::ErrorModel> em) [member function] cls.add_method('SetReceiveErrorModel', 'void', [param('ns3::Ptr< ns3::ErrorModel >', 'em')]) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::Receive(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): uint32_t ns3::PointToPointNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): ns3::Ptr<ns3::Channel> ns3::PointToPointNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): ns3::Address ns3::PointToPointNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): uint16_t ns3::PointToPointNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): ns3::Address ns3::PointToPointNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): ns3::Address ns3::PointToPointNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): ns3::Ptr<ns3::Node> ns3::PointToPointNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): ns3::Address ns3::PointToPointNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): bool ns3::PointToPointNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::DoMpiReceive(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoMpiReceive', 'void', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='protected') ## point-to-point-net-device.h (module 'point-to-point'): void ns3::PointToPointNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3PointToPointRemoteChannel_methods(root_module, cls): ## point-to-point-remote-channel.h (module 'point-to-point'): ns3::PointToPointRemoteChannel::PointToPointRemoteChannel(ns3::PointToPointRemoteChannel const & arg0) [copy constructor] cls.add_constructor([param('ns3::PointToPointRemoteChannel const &', 'arg0')]) ## point-to-point-remote-channel.h (module 'point-to-point'): ns3::PointToPointRemoteChannel::PointToPointRemoteChannel() [constructor] cls.add_constructor([]) ## point-to-point-remote-channel.h (module 'point-to-point'): static ns3::TypeId ns3::PointToPointRemoteChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## point-to-point-remote-channel.h (module 'point-to-point'): bool ns3::PointToPointRemoteChannel::TransmitStart(ns3::Ptr<ns3::Packet> p, ns3::Ptr<ns3::PointToPointNetDevice> src, ns3::Time txTime) [member function] cls.add_method('TransmitStart', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ptr< ns3::PointToPointNetDevice >', 'src'), param('ns3::Time', 'txTime')], is_virtual=True) return def register_Ns3RateErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel(ns3::RateErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RateErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): int64_t ns3::RateErrorModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## error-model.h (module 'network'): double ns3::RateErrorModel::GetRate() const [member function] cls.add_method('GetRate', 'double', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::RateErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit ns3::RateErrorModel::GetUnit() const [member function] cls.add_method('GetUnit', 'ns3::RateErrorModel::ErrorUnit', [], is_const=True) ## error-model.h (module 'network'): void ns3::RateErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> arg0) [member function] cls.add_method('SetRandomVariable', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'arg0')]) ## error-model.h (module 'network'): void ns3::RateErrorModel::SetRate(double rate) [member function] cls.add_method('SetRate', 'void', [param('double', 'rate')]) ## error-model.h (module 'network'): void ns3::RateErrorModel::SetUnit(ns3::RateErrorModel::ErrorUnit error_unit) [member function] cls.add_method('SetUnit', 'void', [param('ns3::RateErrorModel::ErrorUnit', 'error_unit')]) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptBit(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorruptBit', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptByte(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorruptByte', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptPkt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorruptPkt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::RateErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3ReceiveListErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel(ns3::ReceiveListErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ReceiveListErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ReceiveListErrorModel::GetList() const [member function] cls.add_method('GetList', 'std::list< unsigned int >', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::ReceiveListErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function] cls.add_method('SetList', 'void', [param('std::list< unsigned int > const &', 'packetlist')]) ## error-model.h (module 'network'): bool ns3::ReceiveListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_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_Ns3BurstErrorModel_methods(root_module, cls): ## error-model.h (module 'network'): ns3::BurstErrorModel::BurstErrorModel(ns3::BurstErrorModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::BurstErrorModel const &', 'arg0')]) ## error-model.h (module 'network'): ns3::BurstErrorModel::BurstErrorModel() [constructor] cls.add_constructor([]) ## error-model.h (module 'network'): int64_t ns3::BurstErrorModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## error-model.h (module 'network'): double ns3::BurstErrorModel::GetBurstRate() const [member function] cls.add_method('GetBurstRate', 'double', [], is_const=True) ## error-model.h (module 'network'): static ns3::TypeId ns3::BurstErrorModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## error-model.h (module 'network'): void ns3::BurstErrorModel::SetBurstRate(double rate) [member function] cls.add_method('SetBurstRate', 'void', [param('double', 'rate')]) ## error-model.h (module 'network'): void ns3::BurstErrorModel::SetRandomBurstSize(ns3::Ptr<ns3::RandomVariableStream> burstSz) [member function] cls.add_method('SetRandomBurstSize', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'burstSz')]) ## error-model.h (module 'network'): void ns3::BurstErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> ranVar) [member function] cls.add_method('SetRandomVariable', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'ranVar')]) ## error-model.h (module 'network'): bool ns3::BurstErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('DoCorrupt', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p')], visibility='private', is_virtual=True) ## error-model.h (module 'network'): void ns3::BurstErrorModel::DoReset() [member function] cls.add_method('DoReset', 'void', [], visibility='private', is_virtual=True) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
gpl-2.0
cubing/tnoodle
git-tools/requests/packages/chardet/langhungarianmodel.py
2763
12536
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # 255: Control characters that usually does not exist in any text # 254: Carriage/Return # 253: symbol (punctuation) that does not belong to word # 252: 0 - 9 # Character Mapping Table: Latin2_HungarianCharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253, 28, 40, 54, 45, 32, 50, 49, 38, 39, 53, 36, 41, 34, 35, 47, 46, 71, 43, 33, 37, 57, 48, 64, 68, 55, 52,253,253,253,253,253, 253, 2, 18, 26, 17, 1, 27, 12, 20, 9, 22, 7, 6, 13, 4, 8, 23, 67, 10, 5, 3, 21, 19, 65, 62, 16, 11,253,253,253,253,253, 159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174, 175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190, 191,192,193,194,195,196,197, 75,198,199,200,201,202,203,204,205, 79,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220, 221, 51, 81,222, 78,223,224,225,226, 44,227,228,229, 61,230,231, 232,233,234, 58,235, 66, 59,236,237,238, 60, 69, 63,239,240,241, 82, 14, 74,242, 70, 80,243, 72,244, 15, 83, 77, 84, 30, 76, 85, 245,246,247, 25, 73, 42, 24,248,249,250, 31, 56, 29,251,252,253, ) win1250HungarianCharToOrderMap = ( 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30 253, 28, 40, 54, 45, 32, 50, 49, 38, 39, 53, 36, 41, 34, 35, 47, 46, 72, 43, 33, 37, 57, 48, 64, 68, 55, 52,253,253,253,253,253, 253, 2, 18, 26, 17, 1, 27, 12, 20, 9, 22, 7, 6, 13, 4, 8, 23, 67, 10, 5, 3, 21, 19, 65, 62, 16, 11,253,253,253,253,253, 161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176, 177,178,179,180, 78,181, 69,182,183,184,185,186,187,188,189,190, 191,192,193,194,195,196,197, 76,198,199,200,201,202,203,204,205, 81,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220, 221, 51, 83,222, 80,223,224,225,226, 44,227,228,229, 61,230,231, 232,233,234, 58,235, 66, 59,236,237,238, 60, 70, 63,239,240,241, 84, 14, 75,242, 71, 82,243, 73,244, 15, 85, 79, 86, 30, 77, 87, 245,246,247, 25, 74, 42, 24,248,249,250, 31, 56, 29,251,252,253, ) # Model Table: # total sequences: 100% # first 512 sequences: 94.7368% # first 1024 sequences:5.2623% # rest sequences: 0.8894% # negative sequences: 0.0009% HungarianLangModel = ( 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,2,3,3,1,1,2,2,2,2,2,1,2, 3,2,2,3,3,3,3,3,2,3,3,3,3,3,3,1,2,3,3,3,3,2,3,3,1,1,3,3,0,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0, 3,2,1,3,3,3,3,3,2,3,3,3,3,3,1,1,2,3,3,3,3,3,3,3,1,1,3,2,0,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,1,1,2,3,3,3,1,3,3,3,3,3,1,3,3,2,2,0,3,2,3, 0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,3,2,3,3,2,3,3,3,3,3,2,3,3,2,2,3,2,3,2,0,3,2,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,3,3,3,3,2,3,3,3,1,2,3,2,2,3,1,2,3,3,2,2,0,3,3,3, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,3,2,3,3,3,3,2,3,3,3,3,0,2,3,2, 0,0,0,1,1,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,2,1,3,2,2,3,2,1,3,2,2,1,0,3,3,1, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,2,2,3,3,3,3,3,1,2,3,3,3,3,1,2,1,3,3,3,3,2,2,3,1,1,3,2,0,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,2,1,3,3,3,3,3,2,2,1,3,3,3,0,1,1,2, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,2,3,3,3,2,0,3,2,3, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,3,3,2,3,2,3,3,3,1,3,2,2,2,3,1,1,3,3,1,1,0,3,3,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,2,3,3,3,2,3,2,3,3,3,2,3,3,3,3,3,1,2,3,2,2,0,2,2,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,2,2,2,3,1,3,3,2,2,1,3,3,3,1,1,3,1,2,3,2,3,2,2,2,1,0,2,2,2, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 3,1,1,3,3,3,3,3,1,2,3,3,3,3,1,2,1,3,3,3,2,2,3,2,1,0,3,2,0,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,3,3,3,3,3,1,2,3,3,3,3,1,1,0,3,3,3,3,0,2,3,0,0,2,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,2,3,3,2,2,2,2,3,3,0,1,2,3,2,3,2,2,3,2,1,2,0,2,2,2, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 3,3,3,3,3,3,1,2,3,3,3,2,1,2,3,3,2,2,2,3,2,3,3,1,3,3,1,1,0,2,3,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,1,2,2,2,2,3,3,3,1,1,1,3,3,1,1,3,1,1,3,2,1,2,3,1,1,0,2,2,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,2,1,2,1,1,3,3,1,1,1,1,3,3,1,1,2,2,1,2,1,1,2,2,1,1,0,2,2,1, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,1,1,2,1,1,3,3,1,0,1,1,3,3,2,0,1,1,2,3,1,0,2,2,1,0,0,1,3,2, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,2,1,3,3,3,3,3,1,2,3,2,3,3,2,1,1,3,2,3,2,1,2,2,0,1,2,1,0,0,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,2,2,2,2,3,1,2,2,1,1,3,3,0,3,2,1,2,3,2,1,3,3,1,1,0,2,1,3, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,2,2,2,3,2,3,3,3,2,1,1,3,3,1,1,1,2,2,3,2,3,2,2,2,1,0,2,2,1, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 1,0,0,3,3,3,3,3,0,0,3,3,2,3,0,0,0,2,3,3,1,0,1,2,0,0,1,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,2,3,3,3,3,3,1,2,3,3,2,2,1,1,0,3,3,2,2,1,2,2,1,0,2,2,0,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,2,1,3,1,2,3,3,2,2,1,1,2,2,1,1,1,1,3,2,1,1,1,1,2,1,0,1,2,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 2,3,3,1,1,1,1,1,3,3,3,0,1,1,3,3,1,1,1,1,1,2,2,0,3,1,1,2,0,2,1,1, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,1,0,1,2,1,2,2,0,1,2,3,1,2,0,0,0,2,1,1,1,1,1,2,0,0,1,1,0,0,0,0, 1,2,1,2,2,2,1,2,1,2,0,2,0,2,2,1,1,2,1,1,2,1,1,1,0,1,0,0,0,1,1,0, 1,1,1,2,3,2,3,3,0,1,2,2,3,1,0,1,0,2,1,2,2,0,1,1,0,0,1,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,3,3,2,2,1,0,0,3,2,3,2,0,0,0,1,1,3,0,0,1,1,0,0,2,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,2,2,3,3,1,0,1,3,2,3,1,1,1,0,1,1,1,1,1,3,1,0,0,2,2,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,1,2,2,2,1,0,1,2,3,3,2,0,0,0,2,1,1,1,2,1,1,1,0,1,1,1,0,0,0, 1,2,2,2,2,2,1,1,1,2,0,2,1,1,1,1,1,2,1,1,1,1,1,1,0,1,1,1,0,0,1,1, 3,2,2,1,0,0,1,1,2,2,0,3,0,1,2,1,1,0,0,1,1,1,0,1,1,1,1,0,2,1,1,1, 2,2,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,1,1,2,3,1,1,1,1,1,1,1,1,1,0,1, 2,3,3,0,1,0,0,0,3,3,1,0,0,1,2,2,1,0,0,0,0,2,0,0,1,1,1,0,2,1,1,1, 2,1,1,1,1,1,1,2,1,1,0,1,1,0,1,1,1,0,1,2,1,1,0,1,1,1,1,1,1,1,0,1, 2,3,3,0,1,0,0,0,2,2,0,0,0,0,1,2,2,0,0,0,0,1,0,0,1,1,0,0,2,0,1,0, 2,1,1,1,1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,2,0,1,1,1,1,1,0,1, 3,2,2,0,1,0,1,0,2,3,2,0,0,1,2,2,1,0,0,1,1,1,0,0,2,1,0,1,2,2,1,1, 2,1,1,1,1,1,1,2,1,1,1,1,1,1,0,2,1,0,1,1,0,1,1,1,0,1,1,2,1,1,0,1, 2,2,2,0,0,1,0,0,2,2,1,1,0,0,2,1,1,0,0,0,1,2,0,0,2,1,0,0,2,1,1,1, 2,1,1,1,1,2,1,2,1,1,1,2,2,1,1,2,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1, 1,2,3,0,0,0,1,0,3,2,1,0,0,1,2,1,1,0,0,0,0,2,1,0,1,1,0,0,2,1,2,1, 1,1,0,0,0,1,0,1,1,1,1,1,2,0,0,1,0,0,0,2,0,0,1,1,1,1,1,1,1,1,0,1, 3,0,0,2,1,2,2,1,0,0,2,1,2,2,0,0,0,2,1,1,1,0,1,1,0,0,1,1,2,0,0,0, 1,2,1,2,2,1,1,2,1,2,0,1,1,1,1,1,1,1,1,1,2,1,1,0,0,1,1,1,1,0,0,1, 1,3,2,0,0,0,1,0,2,2,2,0,0,0,2,2,1,0,0,0,0,3,1,1,1,1,0,0,2,1,1,1, 2,1,0,1,1,1,0,1,1,1,1,1,1,1,0,2,1,0,0,1,0,1,1,0,1,1,1,1,1,1,0,1, 2,3,2,0,0,0,1,0,2,2,0,0,0,0,2,1,1,0,0,0,0,2,1,0,1,1,0,0,2,1,1,0, 2,1,1,1,1,2,1,2,1,2,0,1,1,1,0,2,1,1,1,2,1,1,1,1,0,1,1,1,1,1,0,1, 3,1,1,2,2,2,3,2,1,1,2,2,1,1,0,1,0,2,2,1,1,1,1,1,0,0,1,1,0,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,0,0,0,0,0,2,2,0,0,0,0,2,2,1,0,0,0,1,1,0,0,1,2,0,0,2,1,1,1, 2,2,1,1,1,2,1,2,1,1,0,1,1,1,1,2,1,1,1,2,1,1,1,1,0,1,2,1,1,1,0,1, 1,0,0,1,2,3,2,1,0,0,2,0,1,1,0,0,0,1,1,1,1,0,1,1,0,0,1,0,0,0,0,0, 1,2,1,2,1,2,1,1,1,2,0,2,1,1,1,0,1,2,0,0,1,1,1,0,0,0,0,0,0,0,0,0, 2,3,2,0,0,0,0,0,1,1,2,1,0,0,1,1,1,0,0,0,0,2,0,0,1,1,0,0,2,1,1,1, 2,1,1,1,1,1,1,2,1,0,1,1,1,1,0,2,1,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1, 1,2,2,0,1,1,1,0,2,2,2,0,0,0,3,2,1,0,0,0,1,1,0,0,1,1,0,1,1,1,0,0, 1,1,0,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1,1,1,0,0,1,1,1,0,1,0,1, 2,1,0,2,1,1,2,2,1,1,2,1,1,1,0,0,0,1,1,0,1,1,1,1,0,0,1,1,1,0,0,0, 1,2,2,2,2,2,1,1,1,2,0,2,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,1,0, 1,2,3,0,0,0,1,0,2,2,0,0,0,0,2,2,0,0,0,0,0,1,0,0,1,0,0,0,2,0,1,0, 2,1,1,1,1,1,0,2,0,0,0,1,2,1,1,1,1,0,1,2,0,1,0,1,0,1,1,1,0,1,0,1, 2,2,2,0,0,0,1,0,2,1,2,0,0,0,1,1,2,0,0,0,0,1,0,0,1,1,0,0,2,1,0,1, 2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,1,1,1,1,1,0,1, 1,2,2,0,0,0,1,0,2,2,2,0,0,0,1,1,0,0,0,0,0,1,1,0,2,0,0,1,1,1,0,1, 1,0,1,1,1,1,1,1,0,1,1,1,1,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,0,0,1, 1,0,0,1,0,1,2,1,0,0,1,1,1,2,0,0,0,1,1,0,1,0,1,1,0,0,1,0,0,0,0,0, 0,2,1,2,1,1,1,1,1,2,0,2,0,1,1,0,1,2,1,0,1,1,1,0,0,0,0,0,0,1,0,0, 2,1,1,0,1,2,0,0,1,1,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,2,1,0,1, 2,2,1,1,1,1,1,2,1,1,0,1,1,1,1,2,1,1,1,2,1,1,0,1,0,1,1,1,1,1,0,1, 1,2,2,0,0,0,0,0,1,1,0,0,0,0,2,1,0,0,0,0,0,2,0,0,2,2,0,0,2,0,0,1, 2,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,1, 1,1,2,0,0,3,1,0,2,1,1,1,0,0,1,1,1,0,0,0,1,1,0,0,0,1,0,0,1,0,1,0, 1,2,1,0,1,1,1,2,1,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,0,1,0,0,0,1,0,0, 2,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,2,0,0,0, 2,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,2,1,1,0,0,1,1,1,1,1,0,1, 2,1,1,1,2,1,1,1,0,1,1,2,1,0,0,0,0,1,1,1,1,0,1,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,0,1,1,1,1,1,0,0,1,1,2,1,0,0,0,1,1,0,0,0,1,1,0,0,1,0,1,0,0,0, 1,2,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0, 2,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,2,0,0,1,0,0,1,0,1,0,0,0, 0,1,1,1,1,1,1,1,1,2,0,1,1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,1,1,1,0,0,2,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0, 0,1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,1,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 0,1,1,1,1,1,0,0,1,1,0,1,0,1,0,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,1,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,1,1,0,1,0,0,1,1,0,1,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0, 2,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,1,1,1,1,1,0,1,1,0,1,0,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0, ) Latin2HungarianModel = { 'charToOrderMap': Latin2_HungarianCharToOrderMap, 'precedenceMatrix': HungarianLangModel, 'mTypicalPositiveRatio': 0.947368, 'keepEnglishLetter': True, 'charsetName': "ISO-8859-2" } Win1250HungarianModel = { 'charToOrderMap': win1250HungarianCharToOrderMap, 'precedenceMatrix': HungarianLangModel, 'mTypicalPositiveRatio': 0.947368, 'keepEnglishLetter': True, 'charsetName': "windows-1250" } # flake8: noqa
gpl-3.0
xinxian0458/dcos
pkgpanda/test_fetch.py
10
1484
from pkgpanda.util import expect_fs, resources_test_dir, run fetch_output = """\rFetching: mesos--0.22.0\rFetched: mesos--0.22.0\n""" def test_fetch(tmpdir): # NOTE: tmpdir is explicitly empty because we want to be sure a fetch. # succeeds when there isn't anything yet. # Start a simpleHTTPServer to serve the packages # fetch a couple packages assert run([ "pkgpanda", "fetch", "mesos--0.22.0", "--repository={0}".format(tmpdir), "--repository-url=file://{}/".format(resources_test_dir('remote_repo')) ]) == fetch_output # Ensure that the package at least somewhat extracted correctly. expect_fs( "{0}".format(tmpdir), { "mesos--0.22.0": ["lib", "bin_master", "bin_slave", "pkginfo.json", "bin"] }) # TODO(cmaloney): Test multiple fetches on one line. # TODO(cmaloney): Test unable to fetch case. def test_add(tmpdir): assert run([ "pkgpanda", "add", resources_test_dir('remote_repo/packages/mesos/mesos--0.22.0.tar.xz'), "--repository={0}".format(tmpdir), ]) == "" # Ensure that the package at least somewhat extracted correctly. expect_fs( "{0}".format(tmpdir), { "mesos--0.22.0": ["lib", "bin_master", "bin_slave", "pkginfo.json", "bin"] }) # TODO(branden): Test unable to add case.
apache-2.0
faust64/ansible
lib/ansible/plugins/action/copy.py
18
15234
# (c) 2012-2014, Michael DeHaan <michael.dehaan@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/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import json import os import stat import tempfile from ansible.constants import mk_boolean as boolean from ansible.errors import AnsibleError, AnsibleFileNotFound from ansible.module_utils._text import to_bytes, to_native, to_text from ansible.plugins.action import ActionBase from ansible.utils.hashing import checksum class ActionModule(ActionBase): def run(self, tmp=None, task_vars=None): ''' handler for file transfer operations ''' if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) if result.get('skipped'): return result source = self._task.args.get('src', None) content = self._task.args.get('content', None) dest = self._task.args.get('dest', None) raw = boolean(self._task.args.get('raw', 'no')) force = boolean(self._task.args.get('force', 'yes')) remote_src = boolean(self._task.args.get('remote_src', False)) follow = boolean(self._task.args.get('follow', False)) result['failed'] = True if (source is None and content is None) or dest is None: result['msg'] = "src (or content) and dest are required" elif source is not None and content is not None: result['msg'] = "src and content are mutually exclusive" elif content is not None and dest is not None and dest.endswith("/"): result['msg'] = "dest must be a file if content is defined" else: del result['failed'] if result.get('failed'): return result # Check if the source ends with a "/" source_trailing_slash = False if source: source_trailing_slash = self._connection._shell.path_has_trailing_slash(source) # Define content_tempfile in case we set it after finding content populated. content_tempfile = None # If content is defined make a temp file and write the content into it. if content is not None: try: # If content comes to us as a dict it should be decoded json. # We need to encode it back into a string to write it out. if isinstance(content, dict) or isinstance(content, list): content_tempfile = self._create_content_tempfile(json.dumps(content)) else: content_tempfile = self._create_content_tempfile(content) source = content_tempfile except Exception as err: result['failed'] = True result['msg'] = "could not write content temp file: %s" % to_native(err) return result # if we have first_available_file in our vars # look up the files and use the first one we find as src elif remote_src: result.update(self._execute_module(task_vars=task_vars)) return result else: # find in expected paths try: source = self._find_needle('files', source) except AnsibleError as e: result['failed'] = True result['msg'] = to_text(e) return result # A list of source file tuples (full_path, relative_path) which will try to copy to the destination source_files = [] # If source is a directory populate our list else source is a file and translate it to a tuple. if os.path.isdir(to_bytes(source, errors='surrogate_or_strict')): # Get the amount of spaces to remove to get the relative path. if source_trailing_slash: sz = len(source) else: sz = len(source.rsplit('/', 1)[0]) + 1 # Walk the directory and append the file tuples to source_files. for base_path, sub_folders, files in os.walk(to_bytes(source)): for file in files: full_path = to_text(os.path.join(base_path, file), errors='surrogate_or_strict') rel_path = full_path[sz:] if rel_path.startswith('/'): rel_path = rel_path[1:] source_files.append((full_path, rel_path)) # recurse into subdirs for sf in sub_folders: source_files += self._get_recursive_files(os.path.join(source, to_text(sf)), sz=sz) # If it's recursive copy, destination is always a dir, # explicitly mark it so (note - copy module relies on this). if not self._connection._shell.path_has_trailing_slash(dest): dest = self._connection._shell.join_path(dest, '') else: source_files.append((source, os.path.basename(source))) changed = False module_return = dict(changed=False) # A register for if we executed a module. # Used to cut down on command calls when not recursive. module_executed = False # Tell _execute_module to delete the file if there is one file. delete_remote_tmp = (len(source_files) == 1) # If this is a recursive action create a tmp path that we can share as the _exec_module create is too late. if not delete_remote_tmp: if tmp is None or "-tmp-" not in tmp: tmp = self._make_tmp_path() # expand any user home dir specifier dest = self._remote_expand_user(dest) # Keep original value for mode parameter mode_value = self._task.args.get('mode', None) diffs = [] for source_full, source_rel in source_files: # If the local file does not exist, get_real_file() raises AnsibleFileNotFound try: source_full = self._loader.get_real_file(source_full) except AnsibleFileNotFound as e: result['failed'] = True result['msg'] = "could not find src=%s, %s" % (source_full, e) self._remove_tmp_path(tmp) return result # Get the local mode and set if user wanted it preserved # https://github.com/ansible/ansible-modules-core/issues/1124 if self._task.args.get('mode', None) == 'preserve': lmode = '0%03o' % stat.S_IMODE(os.stat(source_full).st_mode) self._task.args['mode'] = lmode # This is kind of optimization - if user told us destination is # dir, do path manipulation right away, otherwise we still check # for dest being a dir via remote call below. if self._connection._shell.path_has_trailing_slash(dest): dest_file = self._connection._shell.join_path(dest, source_rel) else: dest_file = self._connection._shell.join_path(dest) # Attempt to get remote file info dest_status = self._execute_remote_stat(dest_file, all_vars=task_vars, follow=follow, tmp=tmp, checksum=force) if dest_status['exists'] and dest_status['isdir']: # The dest is a directory. if content is not None: # If source was defined as content remove the temporary file and fail out. self._remove_tempfile_if_content_defined(content, content_tempfile) self._remove_tmp_path(tmp) result['failed'] = True result['msg'] = "can not use content with a dir as dest" return result else: # Append the relative source location to the destination and get remote stats again dest_file = self._connection._shell.join_path(dest, source_rel) dest_status = self._execute_remote_stat(dest_file, all_vars=task_vars, follow=follow, tmp=tmp, checksum=force) if dest_status['exists'] and not force: # remote_file exists so continue to next iteration. continue # Generate a hash of the local file. local_checksum = checksum(source_full) if local_checksum != dest_status['checksum']: # The checksums don't match and we will change or error out. changed = True # Create a tmp path if missing only if this is not recursive. # If this is recursive we already have a tmp path. if delete_remote_tmp: if tmp is None or "-tmp-" not in tmp: tmp = self._make_tmp_path() if self._play_context.diff and not raw: diffs.append(self._get_diff_data(dest_file, source_full, task_vars)) if self._play_context.check_mode: self._remove_tempfile_if_content_defined(content, content_tempfile) changed = True module_return = dict(changed=True) continue # Define a remote directory that we will copy the file to. tmp_src = self._connection._shell.join_path(tmp, 'source') remote_path = None if not raw: remote_path = self._transfer_file(source_full, tmp_src) else: self._transfer_file(source_full, dest_file) # We have copied the file remotely and no longer require our content_tempfile self._remove_tempfile_if_content_defined(content, content_tempfile) self._loader.cleanup_tmp_file(source_full) # fix file permissions when the copy is done as a different user if remote_path: self._fixup_perms2((tmp, remote_path)) if raw: # Continue to next iteration if raw is defined. continue # Run the copy module # src and dest here come after original and override them # we pass dest only to make sure it includes trailing slash in case of recursive copy new_module_args = self._task.args.copy() new_module_args.update( dict( src=tmp_src, dest=dest, original_basename=source_rel, ) ) if 'content' in new_module_args: del new_module_args['content'] module_return = self._execute_module(module_name='copy', module_args=new_module_args, task_vars=task_vars, tmp=tmp, delete_remote_tmp=delete_remote_tmp) module_executed = True else: # no need to transfer the file, already correct hash, but still need to call # the file module in case we want to change attributes self._remove_tempfile_if_content_defined(content, content_tempfile) self._loader.cleanup_tmp_file(source_full) if raw: # Continue to next iteration if raw is defined. self._remove_tmp_path(tmp) continue # Build temporary module_args. new_module_args = self._task.args.copy() new_module_args.update( dict( src=source_rel, dest=dest, original_basename=source_rel ) ) # Execute the file module. module_return = self._execute_module(module_name='file', module_args=new_module_args, task_vars=task_vars, tmp=tmp, delete_remote_tmp=delete_remote_tmp) module_executed = True if not module_return.get('checksum'): module_return['checksum'] = local_checksum if module_return.get('failed'): result.update(module_return) if not delete_remote_tmp: self._remove_tmp_path(tmp) return result if module_return.get('changed'): changed = True # the file module returns the file path as 'path', but # the copy module uses 'dest', so add it if it's not there if 'path' in module_return and 'dest' not in module_return: module_return['dest'] = module_return['path'] # reset the mode self._task.args['mode'] = mode_value # Delete tmp path if we were recursive or if we did not execute a module. if not delete_remote_tmp or (delete_remote_tmp and not module_executed): self._remove_tmp_path(tmp) if module_executed and len(source_files) == 1: result.update(module_return) else: result.update(dict(dest=dest, src=source, changed=changed)) if diffs: result['diff'] = diffs return result def _get_recursive_files(self, topdir, sz=0): ''' Recursively create file tuples for sub folders ''' r_files = [] for base_path, sub_folders, files in os.walk(to_bytes(topdir)): for fname in files: full_path = to_text(os.path.join(base_path, fname), errors='surrogate_or_strict') rel_path = full_path[sz:] if rel_path.startswith('/'): rel_path = rel_path[1:] r_files.append((full_path, rel_path)) for sf in sub_folders: r_files += self._get_recursive_files(os.path.join(topdir, to_text(sf)), sz=sz) return r_files def _create_content_tempfile(self, content): ''' Create a tempfile containing defined content ''' fd, content_tempfile = tempfile.mkstemp() f = os.fdopen(fd, 'wb') content = to_bytes(content) try: f.write(content) except Exception as err: os.remove(content_tempfile) raise Exception(err) finally: f.close() return content_tempfile def _remove_tempfile_if_content_defined(self, content, content_tempfile): if content is not None: os.remove(content_tempfile)
gpl-3.0
Ledoux/ShareYourSystem
Pythonlogy/ShareYourSystem/Standards/Classors/Switcher/Drafts/__init__ copy.py
1
8024
#<ImportSpecificModules> import operator ,Doer,Representer from ShareYourSystem.Functers import Functer,Triggerer,Hooker BaseModuleStr="ShareYourSystem.Functers.Functer" DecorationModuleStr="ShareYourSystem.Standards.Classors.Classer") #</ImportSpecificModules> #<DefineLocals> SYS.setSubModule(globals()) SwitchingBeforeStr='Before' SwitchingAfterStr='After' SwitchingBindStr='bind' #</DefineLocals> #<DefineClass> @DecorationClass() class SwitcherClass(BaseClass): def default_init(self,**_KwargVariablesDict): #<DefineSpecificDo> self.SwitchingFunction=None #<NotRepresented> self.SwitchedFunction=None #<NotRepresented> self.SwitchedFunctionStr="" #<NotRepresented> self.SwitchedBoolSuffixStr="" #<NotRepresented> self.SwitchedClassBoolKeyStr="" #<NotRepresented> self.SwitchedInstanceBoolKeyStr="" #<NotRepresented> #</DefineSpecificDo> #Call the parent init method BaseClass.__init__(self,**_KwargVariablesDict) def __call__(self,_Variable): #Switch self.switch(_Variable) #Link self.FunctedFunction=self.SwitchedFunction #Call the call of the parent class return BaseClass.__call__(self,self.SwitchingFunction) def switch(self,_Variable=None): #set the switching Function if self.SwitchingFunction==None: self.SwitchingFunction=_Variable #set the SwitchedFunctionStr this is the functing function..and we remove all the tagged Functer@ self.SwitchedFunctionStr=self.SwitchingFunction.__name__.split(Functer.FunctingDecorationStr)[-1] #debug self.debug(('self.',self,['SwitchedFunctionStr'])) #Cut the pre attributing part if there is one if Functer.FunctingAttributeStr in self.SwitchedFunctionStr: self.SwitchedFunctionStr=self.SwitchedFunctionStr.split(Functer.FunctingAttributeStr)[-1] #self.SwitchedDoneFunctionStr=Doer.getDoneStrWithDoStr(self.SwitchedFunctionStr) #SwitchedBoolSuffixStr=self.SwitchedDoneFunctionStr[0].upper()+self.SwitchedDoneFunctionStr[1:] self.SwitchedBoolSuffixStr=self.SwitchedFunctionStr[0].upper()+self.SwitchedFunctionStr[1:]+'Bool' self.SwitchedInstanceBoolKeyStr='Switching'+self.SwitchedBoolSuffixStr #self.SwitchedInstanceBoolKeyStr='SwitchedInstance'+self.SwitchedBoolSuffixStr self.SwitchedClassBoolKeyStr='SwitchedClass'+self.SwitchedBoolSuffixStr #debug self.debug(('self.',self,['SwitchedInstanceBoolKeyStr','SwitchedClassBoolKeyStr'])) #Definition the SwitchedFunction def SwitchedFunction(*_LiargVariablesList,**_KwargVariablesDict): #Alias InstanceVariable=_LiargVariablesList[0] #Append for debbuging #if hasattr(InstanceVariable,'DebuggingNotFrameFunctionStrsList'): # if 'SwitchedFunction' not in InstanceVariable.DebuggingNotFrameFunctionStrsList: # InstanceVariable.DebuggingNotFrameFunctionStrsList.append('SwitchedFunction') #debug ''' self.debug( [ ('self.',self,['SwitchedClassBoolKeyStr','SwitchedInstanceBoolKeyStr']), Representer.represent(InstanceVariable,**{'RepresentingAlineaIsBool':False}) ] ) ''' #set the SwitchedBool if it was not already if hasattr(InstanceVariable,self.SwitchedInstanceBoolKeyStr)==False: #debug ''' self.debug('The InstanceVariable has not the SwitchedBoolSuffixStr..so set it to False') ''' #set InstanceVariable.__setattr__(self.SwitchedInstanceBoolKeyStr,False) elif getattr(InstanceVariable,self.SwitchedInstanceBoolKeyStr): #debug ''' self.debug('The Instance has already done this method') ''' #Return return InstanceVariable #debug ''' self.debug(('self.',self,['SwitchedBoolSuffixStr'])) ''' #At the level of the class set the new binding set function if hasattr(InstanceVariable.__class__,self.SwitchedClassBoolKeyStr)==False: #Definition the binding function that will call the init one def bindBefore(*_TriggeringVariablesList,**_TriggeringVariablesDict): #Alias TriggeredInstanceVariable=_TriggeringVariablesList[0] #debug ''' self.debug('Reinit with '+Representer.represent( TriggeredInstanceVariable.SettingKeyVariable,**{'RepresentingAlineaIsBool':False} ) ) ''' #Definition the init method to trigger SwitchedInitMethod=Functer.getFunctingFunctionWithFuncFunction( TriggeredInstanceVariable.__class__.init ) #debug ''' self.debug( [ 'SwitchedInitMethod is '+str(SwitchedInitMethod), "SwitchedInitMethod.func_globals['__file__'] is "+SwitchedInitMethod.func_globals['__file__'] ] ) ''' #Call the init method (just at the level of this class definition) (so IMPORTANT this is init not __init__) SwitchedInitMethod(TriggeredInstanceVariable) #set the name TriggeredBeforeMethodStr='bindBeforeWith'+self.SwitchedBoolSuffixStr bindBefore.__name__=TriggeredBeforeMethodStr #debug ''' self.debug( [ ("self.",self,['SwitchedDoneFunctionStr','SwitchedBoolSuffixStr']), ("TriggeredMethodStr is "+TriggeredMethodStr) ] ) ''' #Link the bindBefore function setattr( InstanceVariable.__class__, TriggeredBeforeMethodStr, Triggerer.TriggererClass(** { 'TriggeringConditionVariable':[ ( 'SettingKeyVariable', (operator.eq,self.SwitchedInstanceBoolKeyStr) ), ( self.SwitchedInstanceBoolKeyStr, (operator.eq,True) ), ('SettingValueVariable',(operator.eq,False)) ], 'TriggeringHookStr':"Before" } )(bindBefore) ) #Call with a default instance this bind function to be installed getattr(InstanceVariable.__class__(),TriggeredBeforeMethodStr)() ''' #Definition the binding function that will set the switched bool to True def bindAfter(*_TriggeringVariablesList,**_TriggeringVariablesDict): #Alias TriggeredInstanceVariable=_TriggeringVariablesList[0] #Say that it is ok setattr(TriggeredInstanceVariable,self.SwitchedInstanceBoolKeyStr,False) setattr(TriggeredInstanceVariable,self.SwitchedInstanceBoolKeyStr,True) #set the name TriggeredAfterMethodStr='bindAfterWith'+self.SwitchedBoolSuffixStr bindAfter.__name__=TriggeredAfterMethodStr #Link the bindAfter function setattr( InstanceVariable.__class__, TriggeredAfterMethodStr, Triggerer.TriggererClass(** { 'TriggeringConditionVariable':[ ( 'SettingKeyVariable', (operator.eq,self.SwitchedInstanceBoolKeyStr) ), ( self.SwitchedInstanceBoolKeyStr, (operator.eq,True) ), ('SettingValueVariable',(operator.eq,False)) ], 'TriggeringHookStr':"After" } )(bindAfter) ) #Call with a default instance this bind function to be installed getattr(InstanceVariable.__class__(),TriggeredAfterMethodStr)() ''' #Say that it is ok setattr(InstanceVariable.__class__,self.SwitchedClassBoolKeyStr,True) #debug ''' self.debug( [ #('InstanceVariable is '+SYS._str(InstanceVariable)), ('_LiargVariablesList is '+str(_LiargVariablesList)) ] ) ''' #Call the SwitchingFunction self.SwitchingFunction(*_LiargVariablesList,**_KwargVariablesDict) #debug ''' self.debug(('self.',self,['SwitchedBoolSuffixStr'])) ''' #set True for the Bool after the call InstanceVariable.__setattr__(self.SwitchedInstanceBoolKeyStr,True) #debug ''' self.debug(('InstanceVariable.',InstanceVariable,[self.SwitchedBoolSuffixStr])) ''' #Return self for the wrapped method call return InstanceVariable #set self.SwitchedFunction=SwitchedFunction #Return self return self #</DefineClass>
mit
axbaretto/beam
sdks/python/.tox/lint/lib/python2.7/site-packages/pylint/test/functional/line_too_long.py
6
1119
# pylint: disable=invalid-encoded-data # +1: [line-too-long] ##################################################################################################### # +1: [line-too-long] """ that one is too long tooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo loooooong""" # The next line is exactly 80 characters long. A = '--------------------------------------------------------------------------' # Do not trigger the line-too-long warning if the only token that makes the # line longer than 80 characters is a trailing pylint disable. var = 'This line has a disable pragma and whitespace trailing beyond 80 chars. ' # pylint:disable=invalid-name # +1: [line-too-long] badname = 'This line is already longer than 100 characters even without the pragma. Trust me. Please.' # pylint:disable=invalid-name # http://example.com/this/is/a/very/long/url?but=splitting&urls=is&a=pain&so=they&can=be&long def function(): # +3: [line-too-long] """This is a docstring. That contains a very, very long line that exceeds the 100 characters limit by a good margin. So good? """ pass
apache-2.0
boberfly/gaffer
doc/source/WorkingWithScenes/AnatomyOfACamera/screengrab.py
4
2280
# BuildTarget: images/interfaceCameraParameters.png import IECore import time import imath import Gaffer import GafferUI import GafferScene import GafferSceneUI import GafferOSL import GafferAppleseed # Interface: the object and set sections of a camera in the Scene Inspector script["Camera"] = GafferScene.Camera() script["Camera"]["perspectiveMode"].setValue( 1 ) script["Camera"]["focalLength"].setValue( 50.0 ) script["Camera"]["renderSettingOverrides"]["resolution"]["enabled"].setValue( True ) script["Camera"]["renderSettingOverrides"]["overscan"]["value"].setValue( True ) script["Camera"]["renderSettingOverrides"]["overscan"]["enabled"].setValue( True ) script["Camera"]["renderSettingOverrides"]["overscanLeft"]["value"].setValue( 0.05 ) script["Camera"]["renderSettingOverrides"]["overscanLeft"]["enabled"].setValue( True ) script["Camera"]["renderSettingOverrides"]["overscanRight"]["value"].setValue( 0.05 ) script["Camera"]["renderSettingOverrides"]["overscanRight"]["enabled"].setValue( True ) script["Camera"]["renderSettingOverrides"]["overscanTop"]["value"].setValue( 0.05 ) script["Camera"]["renderSettingOverrides"]["overscanTop"]["enabled"].setValue( True ) script["Camera"]["renderSettingOverrides"]["overscanBottom"]["value"].setValue( 0.05 ) script["Camera"]["renderSettingOverrides"]["overscanBottom"]["enabled"].setValue( True ) script.selection().add( script["Camera"] ) __path = "/camera" __paths = IECore.PathMatcher( [ __path ] ) GafferSceneUI.ContextAlgo.expand( script.context(), __paths ) from GafferSceneUI.SceneInspector import __TransformSection, __BoundSection, __ObjectSection, __AttributesSection, __SetMembershipSection for imageName, sectionClass in [ ( "Parameters.png", __ObjectSection ), ( "Sets.png", __SetMembershipSection ) ] : section = sectionClass() section._Section__collapsible.setCollapsed( False ) with GafferUI.Window( "Property" ) as window : sceneInspector = GafferSceneUI.SceneInspector( script, sections = [ section ] ) sceneInspector.setNodeSet( Gaffer.StandardSet( [ script["Camera"] ] ) ) sceneInspector.setTargetPaths( [ __path ] ) window.resizeToFitChild() window.setVisible( True ) GafferUI.WidgetAlgo.grab( widget = sceneInspector, imagePath = "images/interfaceCamera" + imageName )
bsd-3-clause
numerigraphe/odoo
openerp/addons/base/module/module.py
2
37507
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2014 OpenERP S.A. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from docutils import nodes from docutils.core import publish_string from docutils.transforms import Transform, writer_aux from docutils.writers.html4css1 import Writer import imp import logging from operator import attrgetter import os import re import shutil import tempfile import urllib import urllib2 import urlparse import zipfile import zipimport import lxml.html try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # NOQA import openerp import openerp.exceptions from openerp import modules, tools from openerp.modules.db import create_categories from openerp.modules import get_module_resource from openerp.tools.parse_version import parse_version from openerp.tools.translate import _ from openerp.osv import osv, orm, fields from openerp import api, fields as fields2 _logger = logging.getLogger(__name__) ACTION_DICT = { 'view_type': 'form', 'view_mode': 'form', 'res_model': 'base.module.upgrade', 'target': 'new', 'type': 'ir.actions.act_window', 'nodestroy': True, } def backup(path, raise_exception=True): path = os.path.normpath(path) if not os.path.exists(path): if not raise_exception: return None raise OSError('path does not exists') cnt = 1 while True: bck = '%s~%d' % (path, cnt) if not os.path.exists(bck): shutil.move(path, bck) return bck cnt += 1 class module_category(osv.osv): _name = "ir.module.category" _description = "Application" def _module_nbr(self, cr, uid, ids, prop, unknow_none, context): cr.execute('SELECT category_id, COUNT(*) \ FROM ir_module_module \ WHERE category_id IN %(ids)s \ OR category_id IN (SELECT id \ FROM ir_module_category \ WHERE parent_id IN %(ids)s) \ GROUP BY category_id', {'ids': tuple(ids)} ) result = dict(cr.fetchall()) for id in ids: cr.execute('select id from ir_module_category where parent_id=%s', (id,)) result[id] = sum([result.get(c, 0) for (c,) in cr.fetchall()], result.get(id, 0)) return result _columns = { 'name': fields.char("Name", required=True, translate=True, select=True), 'parent_id': fields.many2one('ir.module.category', 'Parent Application', select=True), 'child_ids': fields.one2many('ir.module.category', 'parent_id', 'Child Applications'), 'module_nr': fields.function(_module_nbr, string='Number of Modules', type='integer'), 'module_ids': fields.one2many('ir.module.module', 'category_id', 'Modules'), 'description': fields.text("Description", translate=True), 'sequence': fields.integer('Sequence'), 'visible': fields.boolean('Visible'), 'xml_id': fields.function(osv.osv.get_external_id, type='char', string="External ID"), } _order = 'name' _defaults = { 'visible': 1, } class MyFilterMessages(Transform): """ Custom docutils transform to remove `system message` for a document and generate warnings. (The standard filter removes them based on some `report_level` passed in the `settings_override` dictionary, but if we use it, we can't see them and generate warnings.) """ default_priority = 870 def apply(self): for node in self.document.traverse(nodes.system_message): _logger.warning("docutils' system message present: %s", str(node)) node.parent.remove(node) class MyWriter(Writer): """ Custom docutils html4ccs1 writer that doesn't add the warnings to the output document. """ def get_transforms(self): return [MyFilterMessages, writer_aux.Admonitions] class module(osv.osv): _name = "ir.module.module" _rec_name = "shortdesc" _description = "Module" def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): res = super(module, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False) result = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'action_server_module_immediate_install')[1] if view_type == 'form': if res.get('toolbar',False): list = [rec for rec in res['toolbar']['action'] if rec.get('id', False) != result] res['toolbar'] = {'action': list} return res @classmethod def get_module_info(cls, name): info = {} try: info = modules.load_information_from_description_file(name) except Exception: _logger.debug('Error when trying to fetch informations for ' 'module %s', name, exc_info=True) return info def _get_desc(self, cr, uid, ids, field_name=None, arg=None, context=None): res = dict.fromkeys(ids, '') for module in self.browse(cr, uid, ids, context=context): path = get_module_resource(module.name, 'static/description/index.html') if path: with tools.file_open(path, 'rb') as desc_file: doc = desc_file.read() html = lxml.html.document_fromstring(doc) for element, attribute, link, pos in html.iterlinks(): if element.get('src') and not '//' in element.get('src') and not 'static/' in element.get('src'): element.set('src', "/%s/static/description/%s" % (module.name, element.get('src'))) res[module.id] = lxml.html.tostring(html) else: overrides = { 'embed_stylesheet': False, 'doctitle_xform': False, 'output_encoding': 'unicode', 'xml_declaration': False, } output = publish_string(source=module.description or '', settings_overrides=overrides, writer=MyWriter()) res[module.id] = output return res def _get_latest_version(self, cr, uid, ids, field_name=None, arg=None, context=None): default_version = modules.adapt_version('1.0') res = dict.fromkeys(ids, default_version) for m in self.browse(cr, uid, ids): res[m.id] = self.get_module_info(m.name).get('version', default_version) return res def _get_views(self, cr, uid, ids, field_name=None, arg=None, context=None): res = {} model_data_obj = self.pool.get('ir.model.data') dmodels = [] if field_name is None or 'views_by_module' in field_name: dmodels.append('ir.ui.view') if field_name is None or 'reports_by_module' in field_name: dmodels.append('ir.actions.report.xml') if field_name is None or 'menus_by_module' in field_name: dmodels.append('ir.ui.menu') assert dmodels, "no models for %s" % field_name for module_rec in self.browse(cr, uid, ids, context=context): res_mod_dic = res[module_rec.id] = { 'menus_by_module': [], 'reports_by_module': [], 'views_by_module': [] } # Skip uninstalled modules below, no data to find anyway. if module_rec.state not in ('installed', 'to upgrade', 'to remove'): continue # then, search and group ir.model.data records imd_models = dict([(m, []) for m in dmodels]) imd_ids = model_data_obj.search(cr, uid, [ ('module', '=', module_rec.name), ('model', 'in', tuple(dmodels)) ]) for imd_res in model_data_obj.read(cr, uid, imd_ids, ['model', 'res_id'], context=context): imd_models[imd_res['model']].append(imd_res['res_id']) def browse(model): M = self.pool[model] # as this method is called before the module update, some xmlid may be invalid at this stage # explictly filter records before reading them ids = M.exists(cr, uid, imd_models.get(model, []), context) return M.browse(cr, uid, ids, context) def format_view(v): aa = v.inherit_id and '* INHERIT ' or '' return '%s%s (%s)' % (aa, v.name, v.type) res_mod_dic['views_by_module'] = map(format_view, browse('ir.ui.view')) res_mod_dic['reports_by_module'] = map(attrgetter('name'), browse('ir.actions.report.xml')) res_mod_dic['menus_by_module'] = map(attrgetter('complete_name'), browse('ir.ui.menu')) for key in res.iterkeys(): for k, v in res[key].iteritems(): res[key][k] = "\n".join(sorted(v)) return res def _get_icon_image(self, cr, uid, ids, field_name=None, arg=None, context=None): res = dict.fromkeys(ids, '') for module in self.browse(cr, uid, ids, context=context): path = get_module_resource(module.name, 'static', 'description', 'icon.png') if path: image_file = tools.file_open(path, 'rb') try: res[module.id] = image_file.read().encode('base64') finally: image_file.close() return res _columns = { 'name': fields.char("Technical Name", readonly=True, required=True, select=True), 'category_id': fields.many2one('ir.module.category', 'Category', readonly=True, select=True), 'shortdesc': fields.char('Module Name', readonly=True, translate=True), 'summary': fields.char('Summary', readonly=True, translate=True), 'description': fields.text("Description", readonly=True, translate=True), 'description_html': fields.function(_get_desc, string='Description HTML', type='html', method=True, readonly=True), 'author': fields.char("Author", readonly=True), 'maintainer': fields.char('Maintainer', readonly=True), 'contributors': fields.text('Contributors', readonly=True), 'website': fields.char("Website", readonly=True), # attention: Incorrect field names !! # installed_version refers the latest version (the one on disk) # latest_version refers the installed version (the one in database) # published_version refers the version available on the repository 'installed_version': fields.function(_get_latest_version, string='Latest Version', type='char'), 'latest_version': fields.char('Installed Version', readonly=True), 'published_version': fields.char('Published Version', readonly=True), 'url': fields.char('URL', readonly=True), 'sequence': fields.integer('Sequence'), 'dependencies_id': fields.one2many('ir.module.module.dependency', 'module_id', 'Dependencies', readonly=True), 'auto_install': fields.boolean('Automatic Installation', help='An auto-installable module is automatically installed by the ' 'system when all its dependencies are satisfied. ' 'If the module has no dependency, it is always installed.'), 'state': fields.selection([ ('uninstallable', 'Not Installable'), ('uninstalled', 'Not Installed'), ('installed', 'Installed'), ('to upgrade', 'To be upgraded'), ('to remove', 'To be removed'), ('to install', 'To be installed') ], string='Status', readonly=True, select=True), 'demo': fields.boolean('Demo Data', readonly=True), 'license': fields.selection([ ('GPL-2', 'GPL Version 2'), ('GPL-2 or any later version', 'GPL-2 or later version'), ('GPL-3', 'GPL Version 3'), ('GPL-3 or any later version', 'GPL-3 or later version'), ('AGPL-3', 'Affero GPL-3'), ('Other OSI approved licence', 'Other OSI Approved Licence'), ('Other proprietary', 'Other Proprietary') ], string='License', readonly=True), 'menus_by_module': fields.function(_get_views, string='Menus', type='text', multi="meta", store=True), 'reports_by_module': fields.function(_get_views, string='Reports', type='text', multi="meta", store=True), 'views_by_module': fields.function(_get_views, string='Views', type='text', multi="meta", store=True), 'application': fields.boolean('Application', readonly=True), 'icon': fields.char('Icon URL'), 'icon_image': fields.function(_get_icon_image, string='Icon', type="binary"), } _defaults = { 'state': 'uninstalled', 'sequence': 100, 'demo': False, 'license': 'AGPL-3', } _order = 'sequence,name' def _name_uniq_msg(self, cr, uid, ids, context=None): return _('The name of the module must be unique !') _sql_constraints = [ ('name_uniq', 'UNIQUE (name)', _name_uniq_msg), ] def unlink(self, cr, uid, ids, context=None): if not ids: return True if isinstance(ids, (int, long)): ids = [ids] mod_names = [] for mod in self.read(cr, uid, ids, ['state', 'name'], context): if mod['state'] in ('installed', 'to upgrade', 'to remove', 'to install'): raise orm.except_orm(_('Error'), _('You try to remove a module that is installed or will be installed')) mod_names.append(mod['name']) #Removing the entry from ir_model_data #ids_meta = self.pool.get('ir.model.data').search(cr, uid, [('name', '=', 'module_meta_information'), ('module', 'in', mod_names)]) #if ids_meta: # self.pool.get('ir.model.data').unlink(cr, uid, ids_meta, context) return super(module, self).unlink(cr, uid, ids, context=context) @staticmethod def _check_external_dependencies(terp): depends = terp.get('external_dependencies') if not depends: return for pydep in depends.get('python', []): parts = pydep.split('.') parts.reverse() path = None while parts: part = parts.pop() try: _, path, _ = imp.find_module(part, path and [path] or None) except ImportError: raise ImportError('No module named %s' % (pydep,)) for binary in depends.get('bin', []): if tools.find_in_path(binary) is None: raise Exception('Unable to find %r in path' % (binary,)) @classmethod def check_external_dependencies(cls, module_name, newstate='to install'): terp = cls.get_module_info(module_name) try: cls._check_external_dependencies(terp) except Exception, e: if newstate == 'to install': msg = _('Unable to install module "%s" because an external dependency is not met: %s') elif newstate == 'to upgrade': msg = _('Unable to upgrade module "%s" because an external dependency is not met: %s') else: msg = _('Unable to process module "%s" because an external dependency is not met: %s') raise orm.except_orm(_('Error'), msg % (module_name, e.args[0])) @api.multi def state_update(self, newstate, states_to_update, level=100): if level < 1: raise orm.except_orm(_('Error'), _('Recursion error in modules dependencies !')) # whether some modules are installed with demo data demo = False for module in self: # determine dependency modules to update/others update_mods, ready_mods = self.browse(), self.browse() for dep in module.dependencies_id: if dep.state == 'unknown': raise orm.except_orm(_('Error'), _("You try to install module '%s' that depends on module '%s'.\nBut the latter module is not available in your system.") % (module.name, dep.name,)) if dep.depend_id.state == newstate: ready_mods += dep.depend_id else: update_mods += dep.depend_id # update dependency modules that require it, and determine demo for module update_demo = update_mods.state_update(newstate, states_to_update, level=level-1) module_demo = module.demo or update_demo or any(mod.demo for mod in ready_mods) demo = demo or module_demo # check dependencies and update module itself self.check_external_dependencies(module.name, newstate) if module.state in states_to_update: module.write({'state': newstate, 'demo': module_demo}) return demo def button_install(self, cr, uid, ids, context=None): # Mark the given modules to be installed. self.state_update(cr, uid, ids, 'to install', ['uninstalled'], context=context) # Mark (recursively) the newly satisfied modules to also be installed # Select all auto-installable (but not yet installed) modules. domain = [('state', '=', 'uninstalled'), ('auto_install', '=', True)] uninstalled_ids = self.search(cr, uid, domain, context=context) uninstalled_modules = self.browse(cr, uid, uninstalled_ids, context=context) # Keep those with: # - all dependencies satisfied (installed or to be installed), # - at least one dependency being 'to install' satisfied_states = frozenset(('installed', 'to install', 'to upgrade')) def all_depencies_satisfied(m): states = set(d.state for d in m.dependencies_id) return states.issubset(satisfied_states) and ('to install' in states) to_install_modules = filter(all_depencies_satisfied, uninstalled_modules) to_install_ids = map(lambda m: m.id, to_install_modules) # Mark them to be installed. if to_install_ids: self.button_install(cr, uid, to_install_ids, context=context) return dict(ACTION_DICT, name=_('Install')) def button_immediate_install(self, cr, uid, ids, context=None): """ Installs the selected module(s) immediately and fully, returns the next res.config action to execute :param ids: identifiers of the modules to install :returns: next res.config item to execute :rtype: dict[str, object] """ return self._button_immediate_function(cr, uid, ids, self.button_install, context=context) def button_install_cancel(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'uninstalled', 'demo': False}) return True def module_uninstall(self, cr, uid, ids, context=None): """Perform the various steps required to uninstall a module completely including the deletion of all database structures created by the module: tables, columns, constraints, etc.""" ir_model_data = self.pool.get('ir.model.data') modules_to_remove = [m.name for m in self.browse(cr, uid, ids, context)] ir_model_data._module_data_uninstall(cr, uid, modules_to_remove, context) return self.write( cr, uid, ids, {'state': 'uninstalled', 'latest_version': False}, context=context) def downstream_dependencies(self, cr, uid, ids, known_dep_ids=None, exclude_states=['uninstalled', 'uninstallable', 'to remove'], context=None): """Return the ids of all modules that directly or indirectly depend on the given module `ids`, and that satisfy the `exclude_states` filter""" if not ids: return [] known_dep_ids = set(known_dep_ids or []) cr.execute('''SELECT DISTINCT m.id FROM ir_module_module_dependency d JOIN ir_module_module m ON (d.module_id=m.id) WHERE d.name IN (SELECT name from ir_module_module where id in %s) AND m.state NOT IN %s AND m.id NOT IN %s ''', (tuple(ids), tuple(exclude_states), tuple(known_dep_ids or ids))) new_dep_ids = set([m[0] for m in cr.fetchall()]) missing_mod_ids = new_dep_ids - known_dep_ids known_dep_ids |= new_dep_ids if missing_mod_ids: known_dep_ids |= set(self.downstream_dependencies(cr, uid, list(missing_mod_ids), known_dep_ids, exclude_states, context)) return list(known_dep_ids) def _button_immediate_function(self, cr, uid, ids, function, context=None): function(cr, uid, ids, context=context) cr.commit() api.Environment.reset() registry = openerp.modules.registry.RegistryManager.new(cr.dbname, update_module=True) config = registry['res.config'].next(cr, uid, [], context=context) or {} if config.get('type') not in ('ir.actions.act_window_close',): return config # reload the client; open the first available root menu menu_obj = registry['ir.ui.menu'] menu_ids = menu_obj.search(cr, uid, [('parent_id', '=', False)], context=context) return { 'type': 'ir.actions.client', 'tag': 'reload', 'params': {'menu_id': menu_ids and menu_ids[0] or False} } #TODO remove me in master, not called anymore def button_immediate_uninstall(self, cr, uid, ids, context=None): """ Uninstall the selected module(s) immediately and fully, returns the next res.config action to execute """ return self._button_immediate_function(cr, uid, ids, self.button_uninstall, context=context) def button_uninstall(self, cr, uid, ids, context=None): if any(m.name == 'base' for m in self.browse(cr, uid, ids, context=context)): raise orm.except_orm(_('Error'), _("The `base` module cannot be uninstalled")) dep_ids = self.downstream_dependencies(cr, uid, ids, context=context) self.write(cr, uid, ids + dep_ids, {'state': 'to remove'}) return dict(ACTION_DICT, name=_('Uninstall')) def button_uninstall_cancel(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'installed'}) return True def button_immediate_upgrade(self, cr, uid, ids, context=None): """ Upgrade the selected module(s) immediately and fully, return the next res.config action to execute """ return self._button_immediate_function(cr, uid, ids, self.button_upgrade, context=context) def button_upgrade(self, cr, uid, ids, context=None): depobj = self.pool.get('ir.module.module.dependency') todo = list(self.browse(cr, uid, ids, context=context)) self.update_list(cr, uid) i = 0 while i < len(todo): mod = todo[i] i += 1 if mod.state not in ('installed', 'to upgrade'): raise orm.except_orm(_('Error'), _("Can not upgrade module '%s'. It is not installed.") % (mod.name,)) self.check_external_dependencies(mod.name, 'to upgrade') iids = depobj.search(cr, uid, [('name', '=', mod.name)], context=context) for dep in depobj.browse(cr, uid, iids, context=context): if dep.module_id.state == 'installed' and dep.module_id not in todo: todo.append(dep.module_id) ids = map(lambda x: x.id, todo) self.write(cr, uid, ids, {'state': 'to upgrade'}, context=context) to_install = [] for mod in todo: for dep in mod.dependencies_id: if dep.state == 'unknown': raise orm.except_orm(_('Error'), _('You try to upgrade a module that depends on the module: %s.\nBut this module is not available in your system.') % (dep.name,)) if dep.state == 'uninstalled': ids2 = self.search(cr, uid, [('name', '=', dep.name)]) to_install.extend(ids2) self.button_install(cr, uid, to_install, context=context) return dict(ACTION_DICT, name=_('Apply Schedule Upgrade')) def button_upgrade_cancel(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {'state': 'installed'}) return True def button_update_translations(self, cr, uid, ids, context=None): self.update_translations(cr, uid, ids) return True @staticmethod def get_values_from_terp(terp): return { 'description': terp.get('description', ''), 'shortdesc': terp.get('name', ''), 'author': terp.get('author', 'Unknown'), 'maintainer': terp.get('maintainer', False), 'contributors': ', '.join(terp.get('contributors', [])) or False, 'website': terp.get('website', ''), 'license': terp.get('license', 'AGPL-3'), 'sequence': terp.get('sequence', 100), 'application': terp.get('application', False), 'auto_install': terp.get('auto_install', False), 'icon': terp.get('icon', False), 'summary': terp.get('summary', ''), } def create(self, cr, uid, vals, context=None): new_id = super(module, self).create(cr, uid, vals, context=context) module_metadata = { 'name': 'module_%s' % vals['name'], 'model': 'ir.module.module', 'module': 'base', 'res_id': new_id, 'noupdate': True, } self.pool['ir.model.data'].create(cr, uid, module_metadata) return new_id # update the list of available packages def update_list(self, cr, uid, context=None): res = [0, 0] # [update, add] default_version = modules.adapt_version('1.0') known_mods = self.browse(cr, uid, self.search(cr, uid, [])) known_mods_names = dict([(m.name, m) for m in known_mods]) # iterate through detected modules and update/create them in db for mod_name in modules.get_modules(): mod = known_mods_names.get(mod_name) terp = self.get_module_info(mod_name) values = self.get_values_from_terp(terp) if mod: updated_values = {} for key in values: old = getattr(mod, key) updated = isinstance(values[key], basestring) and tools.ustr(values[key]) or values[key] if (old or updated) and updated != old: updated_values[key] = values[key] if terp.get('installable', True) and mod.state == 'uninstallable': updated_values['state'] = 'uninstalled' if parse_version(terp.get('version', default_version)) > parse_version(mod.latest_version or default_version): res[0] += 1 if updated_values: self.write(cr, uid, mod.id, updated_values) else: mod_path = modules.get_module_path(mod_name) if not mod_path: continue if not terp or not terp.get('installable', True): continue id = self.create(cr, uid, dict(name=mod_name, state='uninstalled', **values)) mod = self.browse(cr, uid, id) res[1] += 1 self._update_dependencies(cr, uid, mod, terp.get('depends', [])) self._update_category(cr, uid, mod, terp.get('category', 'Uncategorized')) # Trigger load_addons if new module have been discovered it exists on # wsgi handlers, so they can react accordingly if tuple(res) != (0, 0): for handler in openerp.service.wsgi_server.module_handlers: if hasattr(handler, 'load_addons'): handler.load_addons() return res def download(self, cr, uid, ids, download=True, context=None): return [] def install_from_urls(self, cr, uid, urls, context=None): if not self.pool['res.users'].has_group(cr, uid, 'base.group_system'): raise openerp.exceptions.AccessDenied() apps_server = urlparse.urlparse(self.get_apps_server(cr, uid, context=context)) OPENERP = openerp.release.product_name.lower() tmp = tempfile.mkdtemp() _logger.debug('Install from url: %r', urls) try: # 1. Download & unzip missing modules for module_name, url in urls.items(): if not url: continue # nothing to download, local version is already the last one up = urlparse.urlparse(url) if up.scheme != apps_server.scheme or up.netloc != apps_server.netloc: raise openerp.exceptions.AccessDenied() try: _logger.info('Downloading module `%s` from OpenERP Apps', module_name) content = urllib2.urlopen(url).read() except Exception: _logger.exception('Failed to fetch module %s', module_name) raise osv.except_osv(_('Module not found'), _('The `%s` module appears to be unavailable at the moment, please try again later.') % module_name) else: zipfile.ZipFile(StringIO(content)).extractall(tmp) assert os.path.isdir(os.path.join(tmp, module_name)) # 2a. Copy/Replace module source in addons path for module_name, url in urls.items(): if module_name == OPENERP or not url: continue # OPENERP is special case, handled below, and no URL means local module module_path = modules.get_module_path(module_name, downloaded=True, display_warning=False) bck = backup(module_path, False) _logger.info('Copy downloaded module `%s` to `%s`', module_name, module_path) shutil.move(os.path.join(tmp, module_name), module_path) if bck: shutil.rmtree(bck) # 2b. Copy/Replace server+base module source if downloaded if urls.get(OPENERP, None): # special case. it contains the server and the base module. # extract path is not the same base_path = os.path.dirname(modules.get_module_path('base')) # copy all modules in the SERVER/openerp/addons directory to the new "openerp" module (except base itself) for d in os.listdir(base_path): if d != 'base' and os.path.isdir(os.path.join(base_path, d)): destdir = os.path.join(tmp, OPENERP, 'addons', d) # XXX 'openerp' subdirectory ? shutil.copytree(os.path.join(base_path, d), destdir) # then replace the server by the new "base" module server_dir = openerp.tools.config['root_path'] # XXX or dirname() bck = backup(server_dir) _logger.info('Copy downloaded module `openerp` to `%s`', server_dir) shutil.move(os.path.join(tmp, OPENERP), server_dir) #if bck: # shutil.rmtree(bck) self.update_list(cr, uid, context=context) with_urls = [m for m, u in urls.items() if u] downloaded_ids = self.search(cr, uid, [('name', 'in', with_urls)], context=context) already_installed = self.search(cr, uid, [('id', 'in', downloaded_ids), ('state', '=', 'installed')], context=context) to_install_ids = self.search(cr, uid, [('name', 'in', urls.keys()), ('state', '=', 'uninstalled')], context=context) post_install_action = self.button_immediate_install(cr, uid, to_install_ids, context=context) if already_installed: # in this case, force server restart to reload python code... cr.commit() openerp.service.server.restart() return { 'type': 'ir.actions.client', 'tag': 'home', 'params': {'wait': True}, } return post_install_action finally: shutil.rmtree(tmp) def get_apps_server(self, cr, uid, context=None): return tools.config.get('apps_server', 'https://apps.openerp.com/apps') def _update_dependencies(self, cr, uid, mod_browse, depends=None): if depends is None: depends = [] existing = set(x.name for x in mod_browse.dependencies_id) needed = set(depends) for dep in (needed - existing): cr.execute('INSERT INTO ir_module_module_dependency (module_id, name) values (%s, %s)', (mod_browse.id, dep)) for dep in (existing - needed): cr.execute('DELETE FROM ir_module_module_dependency WHERE module_id = %s and name = %s', (mod_browse.id, dep)) self.invalidate_cache(cr, uid, ['dependencies_id'], [mod_browse.id]) def _update_category(self, cr, uid, mod_browse, category='Uncategorized'): current_category = mod_browse.category_id current_category_path = [] while current_category: current_category_path.insert(0, current_category.name) current_category = current_category.parent_id categs = category.split('/') if categs != current_category_path: cat_id = create_categories(cr, categs) mod_browse.write({'category_id': cat_id}) def update_translations(self, cr, uid, ids, filter_lang=None, context=None): if not filter_lang: res_lang = self.pool.get('res.lang') lang_ids = res_lang.search(cr, uid, [('translatable', '=', True)]) filter_lang = [lang.code for lang in res_lang.browse(cr, uid, lang_ids)] elif not isinstance(filter_lang, (list, tuple)): filter_lang = [filter_lang] modules = [m.name for m in self.browse(cr, uid, ids) if m.state == 'installed'] self.pool.get('ir.translation').load_module_terms(cr, modules, filter_lang, context=context) def check(self, cr, uid, ids, context=None): for mod in self.browse(cr, uid, ids, context=context): if not mod.description: _logger.warning('module %s: description is empty !', mod.name) DEP_STATES = [ ('uninstallable', 'Uninstallable'), ('uninstalled', 'Not Installed'), ('installed', 'Installed'), ('to upgrade', 'To be upgraded'), ('to remove', 'To be removed'), ('to install', 'To be installed'), ('unknown', 'Unknown'), ] class module_dependency(osv.Model): _name = "ir.module.module.dependency" _description = "Module dependency" # the dependency name name = fields2.Char(index=True) # the module that depends on it module_id = fields2.Many2one('ir.module.module', 'Module', ondelete='cascade') # the module corresponding to the dependency, and its status depend_id = fields2.Many2one('ir.module.module', 'Dependency', compute='_compute_depend') state = fields2.Selection(DEP_STATES, string='Status', compute='_compute_state') @api.multi @api.depends('name') def _compute_depend(self): # retrieve all modules corresponding to the dependency names names = list(set(dep.name for dep in self)) mods = self.env['ir.module.module'].search([('name', 'in', names)]) # index modules by name, and assign dependencies name_mod = dict((mod.name, mod) for mod in mods) for dep in self: dep.depend_id = name_mod.get(dep.name) @api.one @api.depends('depend_id.state') def _compute_state(self): self.state = self.depend_id.state or 'unknown' # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ficlatte/main
django-bbcode-master/bbcode/util.py
3
3388
#!/usr/bin/env python # -*- coding: utf-8 -*- ## # django-bbcode: util.py ## import re import bbcode.settings def to_html(text, tags_alternative_definition={}, escape_html=True, method='disable', *tags): """ Convert a string with BBCode markup into its corresponding HTML markup. Basic Usage ----------- The first parameter is the string off BBCode markup to be processed >>> text = "[b]some bold text to markup[/b]" >>> output = bbcode.util.to_html(text) >>> print output <strong>some bold text to markup</strong> Custom BBCode translations -------------------------- You can supply your own BBCode markup translations to create your own custom markup, or override the default BBRuby translations (parameter is a dictionary of custom translations). The dictionary takes the following format: 'name': [regexp, replacement, description, example, enable_symbol] For example, custom_blockquote = { 'Quote': [ r"\[quote(:.*)?=(.*?)\](.*?)\[\/quote\1?\]", '<div class="quote"><p><cite>\\2</cite></p><blockquote>\\3</blockquote></div>', 'Quote with citation', '[quote=mike]please quote me[/quote]', 'quote' ], } Enable and Disable specific tags -------------------------------- Django-bbcode will allow you to only enable certain BBCode tags, or to explicitly disable certain tags. Pass in either 'disable' or 'enable' to set your method, followed by the comma-separated list of tags you wish to disable or enable. ## # Translate BBCode to HTML, enabling 'image', 'bold', and 'quote' tags # *only*. bbcode.util.to_html(text, {}, True, 'enable', 'image', 'bold', 'quote') ## # Translate BBCode to HTML, enabling all tags *except* 'image', # 'bold', and 'quote'. bbcode.util.to_html(text, {}, True, 'disable', 'image', 'video', 'color') """ # escape <, >, and & to remove any html if escape_html: text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') # merge in the alternate definitions, if any. Unfortunately there is no # Python 2.3 compatible efficient way to do this. tags_definition = bbcode.settings.TAGS for x in tags_alternative_definition: tags_definition[x] = tags_alternative_definition[x] # parse bbcode tags if method == 'enable': for x in tags_definition: t = tags_definition[x] if t[4] in tags: regex = re.compile(t[0], re.IGNORECASE|re.DOTALL) text = regex.sub(t[1], text) if method == 'disable': # this works nicely because the default is disable and the default set # of tags is [] (so none disabled) :) for x in tags_definition: t = tags_definition[x] if t[4] not in tags: regex = re.compile(t[0], re.IGNORECASE|re.DOTALL) text = regex.sub(t[1], text) # parse spacing text = re.sub(r"\r\n?", "\n", text) text = re.sub(r"\n", "<br />", text) # return markup return text ## # End of File ##
agpl-3.0
beatle/node-gyp
gyp/tools/pretty_vcproj.py
2637
9586
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Make the format of a vcproj really pretty. This script normalize and sort an xml. It also fetches all the properties inside linked vsprops and include them explicitly in the vcproj. It outputs the resulting xml to stdout. """ __author__ = 'nsylvain (Nicolas Sylvain)' import os import sys from xml.dom.minidom import parse from xml.dom.minidom import Node REPLACEMENTS = dict() ARGUMENTS = None class CmpTuple(object): """Compare function between 2 tuple.""" def __call__(self, x, y): return cmp(x[0], y[0]) class CmpNode(object): """Compare function between 2 xml nodes.""" def __call__(self, x, y): def get_string(node): node_string = "node" node_string += node.nodeName if node.nodeValue: node_string += node.nodeValue if node.attributes: # We first sort by name, if present. node_string += node.getAttribute("Name") all_nodes = [] for (name, value) in node.attributes.items(): all_nodes.append((name, value)) all_nodes.sort(CmpTuple()) for (name, value) in all_nodes: node_string += name node_string += value return node_string return cmp(get_string(x), get_string(y)) def PrettyPrintNode(node, indent=0): if node.nodeType == Node.TEXT_NODE: if node.data.strip(): print '%s%s' % (' '*indent, node.data.strip()) return if node.childNodes: node.normalize() # Get the number of attributes attr_count = 0 if node.attributes: attr_count = node.attributes.length # Print the main tag if attr_count == 0: print '%s<%s>' % (' '*indent, node.nodeName) else: print '%s<%s' % (' '*indent, node.nodeName) all_attributes = [] for (name, value) in node.attributes.items(): all_attributes.append((name, value)) all_attributes.sort(CmpTuple()) for (name, value) in all_attributes: print '%s %s="%s"' % (' '*indent, name, value) print '%s>' % (' '*indent) if node.nodeValue: print '%s %s' % (' '*indent, node.nodeValue) for sub_node in node.childNodes: PrettyPrintNode(sub_node, indent=indent+2) print '%s</%s>' % (' '*indent, node.nodeName) def FlattenFilter(node): """Returns a list of all the node and sub nodes.""" node_list = [] if (node.attributes and node.getAttribute('Name') == '_excluded_files'): # We don't add the "_excluded_files" filter. return [] for current in node.childNodes: if current.nodeName == 'Filter': node_list.extend(FlattenFilter(current)) else: node_list.append(current) return node_list def FixFilenames(filenames, current_directory): new_list = [] for filename in filenames: if filename: for key in REPLACEMENTS: filename = filename.replace(key, REPLACEMENTS[key]) os.chdir(current_directory) filename = filename.strip('"\' ') if filename.startswith('$'): new_list.append(filename) else: new_list.append(os.path.abspath(filename)) return new_list def AbsoluteNode(node): """Makes all the properties we know about in this node absolute.""" if node.attributes: for (name, value) in node.attributes.items(): if name in ['InheritedPropertySheets', 'RelativePath', 'AdditionalIncludeDirectories', 'IntermediateDirectory', 'OutputDirectory', 'AdditionalLibraryDirectories']: # We want to fix up these paths path_list = value.split(';') new_list = FixFilenames(path_list, os.path.dirname(ARGUMENTS[1])) node.setAttribute(name, ';'.join(new_list)) if not value: node.removeAttribute(name) def CleanupVcproj(node): """For each sub node, we call recursively this function.""" for sub_node in node.childNodes: AbsoluteNode(sub_node) CleanupVcproj(sub_node) # Normalize the node, and remove all extranous whitespaces. for sub_node in node.childNodes: if sub_node.nodeType == Node.TEXT_NODE: sub_node.data = sub_node.data.replace("\r", "") sub_node.data = sub_node.data.replace("\n", "") sub_node.data = sub_node.data.rstrip() # Fix all the semicolon separated attributes to be sorted, and we also # remove the dups. if node.attributes: for (name, value) in node.attributes.items(): sorted_list = sorted(value.split(';')) unique_list = [] for i in sorted_list: if not unique_list.count(i): unique_list.append(i) node.setAttribute(name, ';'.join(unique_list)) if not value: node.removeAttribute(name) if node.childNodes: node.normalize() # For each node, take a copy, and remove it from the list. node_array = [] while node.childNodes and node.childNodes[0]: # Take a copy of the node and remove it from the list. current = node.childNodes[0] node.removeChild(current) # If the child is a filter, we want to append all its children # to this same list. if current.nodeName == 'Filter': node_array.extend(FlattenFilter(current)) else: node_array.append(current) # Sort the list. node_array.sort(CmpNode()) # Insert the nodes in the correct order. for new_node in node_array: # But don't append empty tool node. if new_node.nodeName == 'Tool': if new_node.attributes and new_node.attributes.length == 1: # This one was empty. continue if new_node.nodeName == 'UserMacro': continue node.appendChild(new_node) def GetConfiguationNodes(vcproj): #TODO(nsylvain): Find a better way to navigate the xml. nodes = [] for node in vcproj.childNodes: if node.nodeName == "Configurations": for sub_node in node.childNodes: if sub_node.nodeName == "Configuration": nodes.append(sub_node) return nodes def GetChildrenVsprops(filename): dom = parse(filename) if dom.documentElement.attributes: vsprops = dom.documentElement.getAttribute('InheritedPropertySheets') return FixFilenames(vsprops.split(';'), os.path.dirname(filename)) return [] def SeekToNode(node1, child2): # A text node does not have properties. if child2.nodeType == Node.TEXT_NODE: return None # Get the name of the current node. current_name = child2.getAttribute("Name") if not current_name: # There is no name. We don't know how to merge. return None # Look through all the nodes to find a match. for sub_node in node1.childNodes: if sub_node.nodeName == child2.nodeName: name = sub_node.getAttribute("Name") if name == current_name: return sub_node # No match. We give up. return None def MergeAttributes(node1, node2): # No attributes to merge? if not node2.attributes: return for (name, value2) in node2.attributes.items(): # Don't merge the 'Name' attribute. if name == 'Name': continue value1 = node1.getAttribute(name) if value1: # The attribute exist in the main node. If it's equal, we leave it # untouched, otherwise we concatenate it. if value1 != value2: node1.setAttribute(name, ';'.join([value1, value2])) else: # The attribute does nto exist in the main node. We append this one. node1.setAttribute(name, value2) # If the attribute was a property sheet attributes, we remove it, since # they are useless. if name == 'InheritedPropertySheets': node1.removeAttribute(name) def MergeProperties(node1, node2): MergeAttributes(node1, node2) for child2 in node2.childNodes: child1 = SeekToNode(node1, child2) if child1: MergeProperties(child1, child2) else: node1.appendChild(child2.cloneNode(True)) def main(argv): """Main function of this vcproj prettifier.""" global ARGUMENTS ARGUMENTS = argv # check if we have exactly 1 parameter. if len(argv) < 2: print ('Usage: %s "c:\\path\\to\\vcproj.vcproj" [key1=value1] ' '[key2=value2]' % argv[0]) return 1 # Parse the keys for i in range(2, len(argv)): (key, value) = argv[i].split('=') REPLACEMENTS[key] = value # Open the vcproj and parse the xml. dom = parse(argv[1]) # First thing we need to do is find the Configuration Node and merge them # with the vsprops they include. for configuration_node in GetConfiguationNodes(dom.documentElement): # Get the property sheets associated with this configuration. vsprops = configuration_node.getAttribute('InheritedPropertySheets') # Fix the filenames to be absolute. vsprops_list = FixFilenames(vsprops.strip().split(';'), os.path.dirname(argv[1])) # Extend the list of vsprops with all vsprops contained in the current # vsprops. for current_vsprops in vsprops_list: vsprops_list.extend(GetChildrenVsprops(current_vsprops)) # Now that we have all the vsprops, we need to merge them. for current_vsprops in vsprops_list: MergeProperties(configuration_node, parse(current_vsprops).documentElement) # Now that everything is merged, we need to cleanup the xml. CleanupVcproj(dom.documentElement) # Finally, we use the prett xml function to print the vcproj back to the # user. #print dom.toprettyxml(newl="\n") PrettyPrintNode(dom.documentElement) return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
mit
Averroes/simplejson
simplejson/tests/test_scanstring.py
134
4060
import sys from unittest import TestCase import simplejson as json import simplejson.decoder class TestScanString(TestCase): def test_py_scanstring(self): self._test_scanstring(simplejson.decoder.py_scanstring) def test_c_scanstring(self): if not simplejson.decoder.c_scanstring: return self._test_scanstring(simplejson.decoder.c_scanstring) def _test_scanstring(self, scanstring): self.assertEquals( scanstring('"z\\ud834\\udd20x"', 1, None, True), (u'z\U0001d120x', 16)) if sys.maxunicode == 65535: self.assertEquals( scanstring(u'"z\U0001d120x"', 1, None, True), (u'z\U0001d120x', 6)) else: self.assertEquals( scanstring(u'"z\U0001d120x"', 1, None, True), (u'z\U0001d120x', 5)) self.assertEquals( scanstring('"\\u007b"', 1, None, True), (u'{', 8)) self.assertEquals( scanstring('"A JSON payload should be an object or array, not a string."', 1, None, True), (u'A JSON payload should be an object or array, not a string.', 60)) self.assertEquals( scanstring('["Unclosed array"', 2, None, True), (u'Unclosed array', 17)) self.assertEquals( scanstring('["extra comma",]', 2, None, True), (u'extra comma', 14)) self.assertEquals( scanstring('["double extra comma",,]', 2, None, True), (u'double extra comma', 21)) self.assertEquals( scanstring('["Comma after the close"],', 2, None, True), (u'Comma after the close', 24)) self.assertEquals( scanstring('["Extra close"]]', 2, None, True), (u'Extra close', 14)) self.assertEquals( scanstring('{"Extra comma": true,}', 2, None, True), (u'Extra comma', 14)) self.assertEquals( scanstring('{"Extra value after close": true} "misplaced quoted value"', 2, None, True), (u'Extra value after close', 26)) self.assertEquals( scanstring('{"Illegal expression": 1 + 2}', 2, None, True), (u'Illegal expression', 21)) self.assertEquals( scanstring('{"Illegal invocation": alert()}', 2, None, True), (u'Illegal invocation', 21)) self.assertEquals( scanstring('{"Numbers cannot have leading zeroes": 013}', 2, None, True), (u'Numbers cannot have leading zeroes', 37)) self.assertEquals( scanstring('{"Numbers cannot be hex": 0x14}', 2, None, True), (u'Numbers cannot be hex', 24)) self.assertEquals( scanstring('[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 21, None, True), (u'Too deep', 30)) self.assertEquals( scanstring('{"Missing colon" null}', 2, None, True), (u'Missing colon', 16)) self.assertEquals( scanstring('{"Double colon":: null}', 2, None, True), (u'Double colon', 15)) self.assertEquals( scanstring('{"Comma instead of colon", null}', 2, None, True), (u'Comma instead of colon', 25)) self.assertEquals( scanstring('["Colon instead of comma": false]', 2, None, True), (u'Colon instead of comma', 25)) self.assertEquals( scanstring('["Bad value", truth]', 2, None, True), (u'Bad value', 12)) def test_issue3623(self): self.assertRaises(ValueError, json.decoder.scanstring, "xxx", 1, "xxx") self.assertRaises(UnicodeDecodeError, json.encoder.encode_basestring_ascii, "xx\xff") def test_overflow(self): # Python 2.5 does not have maxsize maxsize = getattr(sys, 'maxsize', sys.maxint) self.assertRaises(OverflowError, json.decoder.scanstring, "xxx", maxsize + 1)
mit
bokeh-cookbook/bokeh-cookbook
plugins/ipynb/markup.py
1
5935
from __future__ import absolute_import, print_function, division import os import json try: # Py3k from html.parser import HTMLParser except ImportError: # Py2.7 from HTMLParser import HTMLParser from pelican import signals from pelican.readers import MarkdownReader, HTMLReader, BaseReader from .ipynb import get_html_from_filepath, fix_css def register(): """ Register the new "ipynb" reader """ def add_reader(arg): arg.settings["READERS"]["ipynb"] = IPythonNB signals.initialized.connect(add_reader) class IPythonNB(BaseReader): """ Extend the Pelican.BaseReader to `.ipynb` files can be recognized as a markup language: Setup: `pelicanconf.py`: ``` MARKUP = ('md', 'ipynb') ``` """ enabled = True file_extensions = ['ipynb'] def read(self, filepath): metadata = {} metadata['ipython'] = True # Files filedir = os.path.dirname(filepath) filename = os.path.basename(filepath) metadata_filename = filename.split('.')[0] + '.ipynb-meta' metadata_filepath = os.path.join(filedir, metadata_filename) if os.path.exists(metadata_filepath): # Metadata is on a external file, process using Pelican MD Reader md_reader = MarkdownReader(self.settings) _content, metadata = md_reader.read(metadata_filepath) else: # Load metadata from ipython notebook file ipynb_file = open(filepath) notebook_metadata = json.load(ipynb_file)['metadata'] # Change to standard pelican metadata for key, value in notebook_metadata.items(): key = key.lower() if key in ("title", "date", "category", "tags", "slug", "author"): metadata[key] = self.process_metadata(key, value) keys = [k.lower() for k in metadata.keys()] if not set(['title', 'date']).issubset(set(keys)): # Probably using ipynb.liquid mode md_filename = filename.split('.')[0] + '.md' md_filepath = os.path.join(filedir, md_filename) if not os.path.exists(md_filepath): raise Exception("Could not find metadata in `.ipynb-meta`, inside `.ipynb` or external `.md` file.") else: raise Exception("""Could not find metadata in `.ipynb-meta` or inside `.ipynb` but found `.md` file, assuming that this notebook is for liquid tag usage if true ignore this error""") content, info = get_html_from_filepath(filepath) # Generate Summary: Do it before cleaning CSS if 'summary' not in [key.lower() for key in self.settings.keys()]: parser = MyHTMLParser(self.settings, filename) if hasattr(content, 'decode'): # PY2 content = '<body>%s</body>' % content.encode('utf-8') content = content.decode("utf-8") else: content = '<body>%s</body>' % content parser.feed(content) parser.close() content = parser.body if ('IPYNB_USE_META_SUMMARY' in self.settings.keys() and self.settings['IPYNB_USE_META_SUMMARY'] is False) or 'IPYNB_USE_META_SUMMARY' not in self.settings.keys(): metadata['summary'] = parser.summary content = fix_css(content, info) return content, metadata class MyHTMLParser(HTMLReader._HTMLParser): """ Custom Pelican `HTMLReader._HTMLParser` to create the summary of the content based on settings['SUMMARY_MAX_LENGTH']. Summary is stoped if founds any div containing ipython notebook code cells. This is needed in order to generate valid HTML for the summary, a simple string split will break the html generating errors on the theme. The downside is that the summary length is not exactly the specified, it stops at completed div/p/li/etc tags. """ def __init__(self, settings, filename): HTMLReader._HTMLParser.__init__(self, settings, filename) self.settings = settings self.filename = filename self.wordcount = 0 self.summary = None self.stop_tags = [('div', ('class', 'input')), ('div', ('class', 'output')), ('h2', ('id', 'Header-2'))] if 'IPYNB_STOP_SUMMARY_TAGS' in self.settings.keys(): self.stop_tags = self.settings['IPYNB_STOP_SUMMARY_TAGS'] if 'IPYNB_EXTEND_STOP_SUMMARY_TAGS' in self.settings.keys(): self.stop_tags.extend(self.settings['IPYNB_EXTEND_STOP_SUMMARY_TAGS']) def handle_starttag(self, tag, attrs): HTMLReader._HTMLParser.handle_starttag(self, tag, attrs) if self.wordcount < self.settings['SUMMARY_MAX_LENGTH']: mask = [stoptag[0] == tag and (stoptag[1] is None or stoptag[1] in attrs) for stoptag in self.stop_tags] if any(mask): self.summary = self._data_buffer self.wordcount = self.settings['SUMMARY_MAX_LENGTH'] def handle_endtag(self, tag): HTMLReader._HTMLParser.handle_endtag(self, tag) if self.wordcount < self.settings['SUMMARY_MAX_LENGTH']: self.wordcount = len(strip_tags(self._data_buffer).split(' ')) if self.wordcount >= self.settings['SUMMARY_MAX_LENGTH']: self.summary = self._data_buffer def strip_tags(html): """ Strip html tags from html content (str) Useful for summary creation """ s = HTMLTagStripper() s.feed(html) return s.get_data() class HTMLTagStripper(HTMLParser): """ Custom HTML Parser to strip HTML tags Useful for summary creation """ def __init__(self): HTMLParser.__init__(self) self.reset() self.fed = [] def handle_data(self, html): self.fed.append(html) def get_data(self): return ''.join(self.fed)
agpl-3.0
quoclieu/codebrew17-starving
env/lib/python3.5/site-packages/pip/_vendor/html5lib/treewalkers/pulldom.py
1729
2302
from __future__ import absolute_import, division, unicode_literals from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS from . import _base from ..constants import voidElements class TreeWalker(_base.TreeWalker): def __iter__(self): ignore_until = None previous = None for event in self.tree: if previous is not None and \ (ignore_until is None or previous[1] is ignore_until): if previous[1] is ignore_until: ignore_until = None for token in self.tokens(previous, event): yield token if token["type"] == "EmptyTag": ignore_until = previous[1] previous = event if ignore_until is None or previous[1] is ignore_until: for token in self.tokens(previous, None): yield token elif ignore_until is not None: raise ValueError("Illformed DOM event stream: void element without END_ELEMENT") def tokens(self, event, next): type, node = event if type == START_ELEMENT: name = node.nodeName namespace = node.namespaceURI attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) attrs[(attr.namespaceURI, attr.localName)] = attr.value if name in voidElements: for token in self.emptyTag(namespace, name, attrs, not next or next[1] is not node): yield token else: yield self.startTag(namespace, name, attrs) elif type == END_ELEMENT: name = node.nodeName namespace = node.namespaceURI if name not in voidElements: yield self.endTag(namespace, name) elif type == COMMENT: yield self.comment(node.nodeValue) elif type in (IGNORABLE_WHITESPACE, CHARACTERS): for token in self.text(node.nodeValue): yield token else: yield self.unknown(type)
mit
WhireCrow/openwrt-mt7620
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/root-ralink/usr/lib/python2.7/distutils/emxccompiler.py
250
11931
"""distutils.emxccompiler Provides the EMXCCompiler class, a subclass of UnixCCompiler that handles the EMX port of the GNU C compiler to OS/2. """ # issues: # # * OS/2 insists that DLLs can have names no longer than 8 characters # We put export_symbols in a def-file, as though the DLL can have # an arbitrary length name, but truncate the output filename. # # * only use OMF objects and use LINK386 as the linker (-Zomf) # # * always build for multithreading (-Zmt) as the accompanying OS/2 port # of Python is only distributed with threads enabled. # # tested configurations: # # * EMX gcc 2.81/EMX 0.9d fix03 __revision__ = "$Id$" import os,sys,copy from distutils.ccompiler import gen_preprocess_options, gen_lib_options from distutils.unixccompiler import UnixCCompiler from distutils.file_util import write_file from distutils.errors import DistutilsExecError, CompileError, UnknownFileError from distutils import log class EMXCCompiler (UnixCCompiler): compiler_type = 'emx' obj_extension = ".obj" static_lib_extension = ".lib" shared_lib_extension = ".dll" static_lib_format = "%s%s" shared_lib_format = "%s%s" res_extension = ".res" # compiled resource file exe_extension = ".exe" def __init__ (self, verbose=0, dry_run=0, force=0): UnixCCompiler.__init__ (self, verbose, dry_run, force) (status, details) = check_config_h() self.debug_print("Python's GCC status: %s (details: %s)" % (status, details)) if status is not CONFIG_H_OK: self.warn( "Python's pyconfig.h doesn't seem to support your compiler. " + ("Reason: %s." % details) + "Compiling may fail because of undefined preprocessor macros.") (self.gcc_version, self.ld_version) = \ get_versions() self.debug_print(self.compiler_type + ": gcc %s, ld %s\n" % (self.gcc_version, self.ld_version) ) # Hard-code GCC because that's what this is all about. # XXX optimization, warnings etc. should be customizable. self.set_executables(compiler='gcc -Zomf -Zmt -O3 -fomit-frame-pointer -mprobe -Wall', compiler_so='gcc -Zomf -Zmt -O3 -fomit-frame-pointer -mprobe -Wall', linker_exe='gcc -Zomf -Zmt -Zcrtdll', linker_so='gcc -Zomf -Zmt -Zcrtdll -Zdll') # want the gcc library statically linked (so that we don't have # to distribute a version dependent on the compiler we have) self.dll_libraries=["gcc"] # __init__ () def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): if ext == '.rc': # gcc requires '.rc' compiled to binary ('.res') files !!! try: self.spawn(["rc", "-r", src]) except DistutilsExecError, msg: raise CompileError, msg else: # for other files use the C-compiler try: self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs) except DistutilsExecError, msg: raise CompileError, msg def link (self, target_desc, objects, output_filename, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None): # use separate copies, so we can modify the lists extra_preargs = copy.copy(extra_preargs or []) libraries = copy.copy(libraries or []) objects = copy.copy(objects or []) # Additional libraries libraries.extend(self.dll_libraries) # handle export symbols by creating a def-file # with executables this only works with gcc/ld as linker if ((export_symbols is not None) and (target_desc != self.EXECUTABLE)): # (The linker doesn't do anything if output is up-to-date. # So it would probably better to check if we really need this, # but for this we had to insert some unchanged parts of # UnixCCompiler, and this is not what we want.) # we want to put some files in the same directory as the # object files are, build_temp doesn't help much # where are the object files temp_dir = os.path.dirname(objects[0]) # name of dll to give the helper files the same base name (dll_name, dll_extension) = os.path.splitext( os.path.basename(output_filename)) # generate the filenames for these files def_file = os.path.join(temp_dir, dll_name + ".def") # Generate .def file contents = [ "LIBRARY %s INITINSTANCE TERMINSTANCE" % \ os.path.splitext(os.path.basename(output_filename))[0], "DATA MULTIPLE NONSHARED", "EXPORTS"] for sym in export_symbols: contents.append(' "%s"' % sym) self.execute(write_file, (def_file, contents), "writing %s" % def_file) # next add options for def-file and to creating import libraries # for gcc/ld the def-file is specified as any other object files objects.append(def_file) #end: if ((export_symbols is not None) and # (target_desc != self.EXECUTABLE or self.linker_dll == "gcc")): # who wants symbols and a many times larger output file # should explicitly switch the debug mode on # otherwise we let dllwrap/ld strip the output file # (On my machine: 10KB < stripped_file < ??100KB # unstripped_file = stripped_file + XXX KB # ( XXX=254 for a typical python extension)) if not debug: extra_preargs.append("-s") UnixCCompiler.link(self, target_desc, objects, output_filename, output_dir, libraries, library_dirs, runtime_library_dirs, None, # export_symbols, we do this in our def-file debug, extra_preargs, extra_postargs, build_temp, target_lang) # link () # -- Miscellaneous methods ----------------------------------------- # override the object_filenames method from CCompiler to # support rc and res-files def object_filenames (self, source_filenames, strip_dir=0, output_dir=''): if output_dir is None: output_dir = '' obj_names = [] for src_name in source_filenames: # use normcase to make sure '.rc' is really '.rc' and not '.RC' (base, ext) = os.path.splitext (os.path.normcase(src_name)) if ext not in (self.src_extensions + ['.rc']): raise UnknownFileError, \ "unknown file type '%s' (from '%s')" % \ (ext, src_name) if strip_dir: base = os.path.basename (base) if ext == '.rc': # these need to be compiled to object files obj_names.append (os.path.join (output_dir, base + self.res_extension)) else: obj_names.append (os.path.join (output_dir, base + self.obj_extension)) return obj_names # object_filenames () # override the find_library_file method from UnixCCompiler # to deal with file naming/searching differences def find_library_file(self, dirs, lib, debug=0): shortlib = '%s.lib' % lib longlib = 'lib%s.lib' % lib # this form very rare # get EMX's default library directory search path try: emx_dirs = os.environ['LIBRARY_PATH'].split(';') except KeyError: emx_dirs = [] for dir in dirs + emx_dirs: shortlibp = os.path.join(dir, shortlib) longlibp = os.path.join(dir, longlib) if os.path.exists(shortlibp): return shortlibp elif os.path.exists(longlibp): return longlibp # Oops, didn't find it in *any* of 'dirs' return None # class EMXCCompiler # Because these compilers aren't configured in Python's pyconfig.h file by # default, we should at least warn the user if he is using a unmodified # version. CONFIG_H_OK = "ok" CONFIG_H_NOTOK = "not ok" CONFIG_H_UNCERTAIN = "uncertain" def check_config_h(): """Check if the current Python installation (specifically, pyconfig.h) appears amenable to building extensions with GCC. Returns a tuple (status, details), where 'status' is one of the following constants: CONFIG_H_OK all is well, go ahead and compile CONFIG_H_NOTOK doesn't look good CONFIG_H_UNCERTAIN not sure -- unable to read pyconfig.h 'details' is a human-readable string explaining the situation. Note there are two ways to conclude "OK": either 'sys.version' contains the string "GCC" (implying that this Python was built with GCC), or the installed "pyconfig.h" contains the string "__GNUC__". """ # XXX since this function also checks sys.version, it's not strictly a # "pyconfig.h" check -- should probably be renamed... from distutils import sysconfig import string # if sys.version contains GCC then python was compiled with # GCC, and the pyconfig.h file should be OK if string.find(sys.version,"GCC") >= 0: return (CONFIG_H_OK, "sys.version mentions 'GCC'") fn = sysconfig.get_config_h_filename() try: # It would probably better to read single lines to search. # But we do this only once, and it is fast enough f = open(fn) try: s = f.read() finally: f.close() except IOError, exc: # if we can't read this file, we cannot say it is wrong # the compiler will complain later about this file as missing return (CONFIG_H_UNCERTAIN, "couldn't read '%s': %s" % (fn, exc.strerror)) else: # "pyconfig.h" contains an "#ifdef __GNUC__" or something similar if string.find(s,"__GNUC__") >= 0: return (CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn) else: return (CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn) def get_versions(): """ Try to find out the versions of gcc and ld. If not possible it returns None for it. """ from distutils.version import StrictVersion from distutils.spawn import find_executable import re gcc_exe = find_executable('gcc') if gcc_exe: out = os.popen(gcc_exe + ' -dumpversion','r') try: out_string = out.read() finally: out.close() result = re.search('(\d+\.\d+\.\d+)',out_string) if result: gcc_version = StrictVersion(result.group(1)) else: gcc_version = None else: gcc_version = None # EMX ld has no way of reporting version number, and we use GCC # anyway - so we can link OMF DLLs ld_version = None return (gcc_version, ld_version)
gpl-2.0
copperhead/copperhead
copperhead/compiler/__init__.py
5
1312
# # Copyright 2012 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # import binarygenerator import parsetypes import passes import pltools import pyast import rewrites import typeinference import unifier import utility import visitor import imp as _imp import os as _os import glob as _glob _cur_dir, _cur_file = _os.path.split(__file__) def _find_module(name): _ext_poss = [ path for path in _glob.glob(_os.path.join(_cur_dir, name+'*')) if _os.path.splitext(path)[1] in ['.so', '.dll'] ] if len(_ext_poss) != 1: raise ImportError(name) return _imp.load_dynamic(name, _ext_poss[0]) backendcompiler = _find_module('backendcompiler') backendsyntax = _find_module('backendsyntax') backendtypes = _find_module('backendtypes') import conversions
apache-2.0
chiamingyen/pygroup
wsgi/static/Brython2.1.4-20140810-083054/Lib/logging/config.py
739
35619
# Copyright 2001-2013 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ Configuration functions for the logging package for Python. The core package is based on PEP 282 and comments thereto in comp.lang.python, and influenced by Apache's log4j system. Copyright (C) 2001-2013 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ import sys, logging, logging.handlers, socket, struct, traceback, re import io try: import _thread as thread import threading except ImportError: #pragma: no cover thread = None from socketserver import ThreadingTCPServer, StreamRequestHandler DEFAULT_LOGGING_CONFIG_PORT = 9030 if sys.platform == "win32": RESET_ERROR = 10054 #WSAECONNRESET else: RESET_ERROR = 104 #ECONNRESET # # The following code implements a socket listener for on-the-fly # reconfiguration of logging. # # _listener holds the server object doing the listening _listener = None def fileConfig(fname, defaults=None, disable_existing_loggers=True): """ Read the logging configuration from a ConfigParser-format file. This can be called several times from an application, allowing an end user the ability to select from various pre-canned configurations (if the developer provides a mechanism to present the choices and load the chosen configuration). """ import configparser cp = configparser.ConfigParser(defaults) if hasattr(fname, 'readline'): cp.read_file(fname) else: cp.read(fname) formatters = _create_formatters(cp) # critical section logging._acquireLock() try: logging._handlers.clear() del logging._handlerList[:] # Handlers add themselves to logging._handlers handlers = _install_handlers(cp, formatters) _install_loggers(cp, handlers, disable_existing_loggers) finally: logging._releaseLock() def _resolve(name): """Resolve a dotted name to a global object.""" name = name.split('.') used = name.pop(0) found = __import__(used) for n in name: used = used + '.' + n try: found = getattr(found, n) except AttributeError: __import__(used) found = getattr(found, n) return found def _strip_spaces(alist): return map(lambda x: x.strip(), alist) def _create_formatters(cp): """Create and return formatters""" flist = cp["formatters"]["keys"] if not len(flist): return {} flist = flist.split(",") flist = _strip_spaces(flist) formatters = {} for form in flist: sectname = "formatter_%s" % form fs = cp.get(sectname, "format", raw=True, fallback=None) dfs = cp.get(sectname, "datefmt", raw=True, fallback=None) c = logging.Formatter class_name = cp[sectname].get("class") if class_name: c = _resolve(class_name) f = c(fs, dfs) formatters[form] = f return formatters def _install_handlers(cp, formatters): """Install and return handlers""" hlist = cp["handlers"]["keys"] if not len(hlist): return {} hlist = hlist.split(",") hlist = _strip_spaces(hlist) handlers = {} fixups = [] #for inter-handler references for hand in hlist: section = cp["handler_%s" % hand] klass = section["class"] fmt = section.get("formatter", "") try: klass = eval(klass, vars(logging)) except (AttributeError, NameError): klass = _resolve(klass) args = section["args"] args = eval(args, vars(logging)) h = klass(*args) if "level" in section: level = section["level"] h.setLevel(logging._levelNames[level]) if len(fmt): h.setFormatter(formatters[fmt]) if issubclass(klass, logging.handlers.MemoryHandler): target = section.get("target", "") if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for h, t in fixups: h.setTarget(handlers[t]) return handlers def _handle_existing_loggers(existing, child_loggers, disable_existing): """ When (re)configuring logging, handle loggers which were in the previous configuration but are not in the new configuration. There's no point deleting them as other threads may continue to hold references to them; and by disabling them, you stop them doing any logging. However, don't disable children of named loggers, as that's probably not what was intended by the user. Also, allow existing loggers to NOT be disabled if disable_existing is false. """ root = logging.root for log in existing: logger = root.manager.loggerDict[log] if log in child_loggers: logger.level = logging.NOTSET logger.handlers = [] logger.propagate = True else: logger.disabled = disable_existing def _install_loggers(cp, handlers, disable_existing): """Create and install loggers""" # configure the root first llist = cp["loggers"]["keys"] llist = llist.split(",") llist = list(map(lambda x: x.strip(), llist)) llist.remove("root") section = cp["logger_root"] root = logging.root log = root if "level" in section: level = section["level"] log.setLevel(logging._levelNames[level]) for h in root.handlers[:]: root.removeHandler(h) hlist = section["handlers"] if len(hlist): hlist = hlist.split(",") hlist = _strip_spaces(hlist) for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = list(root.manager.loggerDict.keys()) #The list needs to be sorted so that we can #avoid disabling child loggers of explicitly #named loggers. With a sorted list it is easier #to find the child loggers. existing.sort() #We'll keep the list of existing loggers #which are children of named loggers here... child_loggers = [] #now set up the new ones... for log in llist: section = cp["logger_%s" % log] qn = section["qualname"] propagate = section.getint("propagate", fallback=1) logger = logging.getLogger(qn) if qn in existing: i = existing.index(qn) + 1 # start with the entry after qn prefixed = qn + "." pflen = len(prefixed) num_existing = len(existing) while i < num_existing: if existing[i][:pflen] == prefixed: child_loggers.append(existing[i]) i += 1 existing.remove(qn) if "level" in section: level = section["level"] logger.setLevel(logging._levelNames[level]) for h in logger.handlers[:]: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = section["handlers"] if len(hlist): hlist = hlist.split(",") hlist = _strip_spaces(hlist) for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. #However, don't disable children of named loggers, as that's #probably not what was intended by the user. #for log in existing: # logger = root.manager.loggerDict[log] # if log in child_loggers: # logger.level = logging.NOTSET # logger.handlers = [] # logger.propagate = 1 # elif disable_existing_loggers: # logger.disabled = 1 _handle_existing_loggers(existing, child_loggers, disable_existing) IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I) def valid_ident(s): m = IDENTIFIER.match(s) if not m: raise ValueError('Not a valid Python identifier: %r' % s) return True # The ConvertingXXX classes are wrappers around standard Python containers, # and they serve to convert any suitable values in the container. The # conversion converts base dicts, lists and tuples to their wrapped # equivalents, whereas strings which match a conversion format are converted # appropriately. # # Each wrapper should have a configurator attribute holding the actual # configurator to use for conversion. class ConvertingDict(dict): """A converting dictionary wrapper.""" def __getitem__(self, key): value = dict.__getitem__(self, key) result = self.configurator.convert(value) #If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def get(self, key, default=None): value = dict.get(self, key, default) result = self.configurator.convert(value) #If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def pop(self, key, default=None): value = dict.pop(self, key, default) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result class ConvertingList(list): """A converting list wrapper.""" def __getitem__(self, key): value = list.__getitem__(self, key) result = self.configurator.convert(value) #If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result def pop(self, idx=-1): value = list.pop(self, idx) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self return result class ConvertingTuple(tuple): """A converting tuple wrapper.""" def __getitem__(self, key): value = tuple.__getitem__(self, key) result = self.configurator.convert(value) if value is not result: if type(result) in (ConvertingDict, ConvertingList, ConvertingTuple): result.parent = self result.key = key return result class BaseConfigurator(object): """ The configurator base class which defines some useful defaults. """ CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$') WORD_PATTERN = re.compile(r'^\s*(\w+)\s*') DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*') INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*') DIGIT_PATTERN = re.compile(r'^\d+$') value_converters = { 'ext' : 'ext_convert', 'cfg' : 'cfg_convert', } # We might want to use a different one, e.g. importlib importer = staticmethod(__import__) def __init__(self, config): self.config = ConvertingDict(config) self.config.configurator = self def resolve(self, s): """ Resolve strings to objects using standard import and attribute syntax. """ name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += '.' + frag try: found = getattr(found, frag) except AttributeError: self.importer(used) found = getattr(found, frag) return found except ImportError: e, tb = sys.exc_info()[1:] v = ValueError('Cannot resolve %r: %s' % (s, e)) v.__cause__, v.__traceback__ = e, tb raise v def ext_convert(self, value): """Default converter for the ext:// protocol.""" return self.resolve(value) def cfg_convert(self, value): """Default converter for the cfg:// protocol.""" rest = value m = self.WORD_PATTERN.match(rest) if m is None: raise ValueError("Unable to convert %r" % value) else: rest = rest[m.end():] d = self.config[m.groups()[0]] #print d, rest while rest: m = self.DOT_PATTERN.match(rest) if m: d = d[m.groups()[0]] else: m = self.INDEX_PATTERN.match(rest) if m: idx = m.groups()[0] if not self.DIGIT_PATTERN.match(idx): d = d[idx] else: try: n = int(idx) # try as number first (most likely) d = d[n] except TypeError: d = d[idx] if m: rest = rest[m.end():] else: raise ValueError('Unable to convert ' '%r at %r' % (value, rest)) #rest should be empty return d def convert(self, value): """ Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. """ if not isinstance(value, ConvertingDict) and isinstance(value, dict): value = ConvertingDict(value) value.configurator = self elif not isinstance(value, ConvertingList) and isinstance(value, list): value = ConvertingList(value) value.configurator = self elif not isinstance(value, ConvertingTuple) and\ isinstance(value, tuple): value = ConvertingTuple(value) value.configurator = self elif isinstance(value, str): # str for py3k m = self.CONVERT_PATTERN.match(value) if m: d = m.groupdict() prefix = d['prefix'] converter = self.value_converters.get(prefix, None) if converter: suffix = d['suffix'] converter = getattr(self, converter) value = converter(suffix) return value def configure_custom(self, config): """Configure an object with a user-supplied factory.""" c = config.pop('()') if not callable(c): c = self.resolve(c) props = config.pop('.', None) # Check for valid identifiers kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) result = c(**kwargs) if props: for name, value in props.items(): setattr(result, name, value) return result def as_tuple(self, value): """Utility function which converts lists to tuples.""" if isinstance(value, list): value = tuple(value) return value class DictConfigurator(BaseConfigurator): """ Configure logging using a dictionary-like object to describe the configuration. """ def configure(self): """Do the configuration.""" config = self.config if 'version' not in config: raise ValueError("dictionary doesn't specify a version") if config['version'] != 1: raise ValueError("Unsupported version: %s" % config['version']) incremental = config.pop('incremental', False) EMPTY_DICT = {} logging._acquireLock() try: if incremental: handlers = config.get('handlers', EMPTY_DICT) for name in handlers: if name not in logging._handlers: raise ValueError('No handler found with ' 'name %r' % name) else: try: handler = logging._handlers[name] handler_config = handlers[name] level = handler_config.get('level', None) if level: handler.setLevel(logging._checkLevel(level)) except Exception as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) loggers = config.get('loggers', EMPTY_DICT) for name in loggers: try: self.configure_logger(name, loggers[name], True) except Exception as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) root = config.get('root', None) if root: try: self.configure_root(root, True) except Exception as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) else: disable_existing = config.pop('disable_existing_loggers', True) logging._handlers.clear() del logging._handlerList[:] # Do formatters first - they don't refer to anything else formatters = config.get('formatters', EMPTY_DICT) for name in formatters: try: formatters[name] = self.configure_formatter( formatters[name]) except Exception as e: raise ValueError('Unable to configure ' 'formatter %r: %s' % (name, e)) # Next, do filters - they don't refer to anything else, either filters = config.get('filters', EMPTY_DICT) for name in filters: try: filters[name] = self.configure_filter(filters[name]) except Exception as e: raise ValueError('Unable to configure ' 'filter %r: %s' % (name, e)) # Next, do handlers - they refer to formatters and filters # As handlers can refer to other handlers, sort the keys # to allow a deterministic order of configuration handlers = config.get('handlers', EMPTY_DICT) deferred = [] for name in sorted(handlers): try: handler = self.configure_handler(handlers[name]) handler.name = name handlers[name] = handler except Exception as e: if 'target not configured yet' in str(e): deferred.append(name) else: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) # Now do any that were deferred for name in deferred: try: handler = self.configure_handler(handlers[name]) handler.name = name handlers[name] = handler except Exception as e: raise ValueError('Unable to configure handler ' '%r: %s' % (name, e)) # Next, do loggers - they refer to handlers and filters #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. root = logging.root existing = list(root.manager.loggerDict.keys()) #The list needs to be sorted so that we can #avoid disabling child loggers of explicitly #named loggers. With a sorted list it is easier #to find the child loggers. existing.sort() #We'll keep the list of existing loggers #which are children of named loggers here... child_loggers = [] #now set up the new ones... loggers = config.get('loggers', EMPTY_DICT) for name in loggers: if name in existing: i = existing.index(name) + 1 # look after name prefixed = name + "." pflen = len(prefixed) num_existing = len(existing) while i < num_existing: if existing[i][:pflen] == prefixed: child_loggers.append(existing[i]) i += 1 existing.remove(name) try: self.configure_logger(name, loggers[name]) except Exception as e: raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. #However, don't disable children of named loggers, as that's #probably not what was intended by the user. #for log in existing: # logger = root.manager.loggerDict[log] # if log in child_loggers: # logger.level = logging.NOTSET # logger.handlers = [] # logger.propagate = True # elif disable_existing: # logger.disabled = True _handle_existing_loggers(existing, child_loggers, disable_existing) # And finally, do the root logger root = config.get('root', None) if root: try: self.configure_root(root) except Exception as e: raise ValueError('Unable to configure root ' 'logger: %s' % e) finally: logging._releaseLock() def configure_formatter(self, config): """Configure a formatter from a dictionary.""" if '()' in config: factory = config['()'] # for use in exception handler try: result = self.configure_custom(config) except TypeError as te: if "'format'" not in str(te): raise #Name of parameter changed from fmt to format. #Retry with old name. #This is so that code can be used with older Python versions #(e.g. by Django) config['fmt'] = config.pop('format') config['()'] = factory result = self.configure_custom(config) else: fmt = config.get('format', None) dfmt = config.get('datefmt', None) style = config.get('style', '%') result = logging.Formatter(fmt, dfmt, style) return result def configure_filter(self, config): """Configure a filter from a dictionary.""" if '()' in config: result = self.configure_custom(config) else: name = config.get('name', '') result = logging.Filter(name) return result def add_filters(self, filterer, filters): """Add filters to a filterer from a list of names.""" for f in filters: try: filterer.addFilter(self.config['filters'][f]) except Exception as e: raise ValueError('Unable to add filter %r: %s' % (f, e)) def configure_handler(self, config): """Configure a handler from a dictionary.""" config_copy = dict(config) # for restoring in case of error formatter = config.pop('formatter', None) if formatter: try: formatter = self.config['formatters'][formatter] except Exception as e: raise ValueError('Unable to set formatter ' '%r: %s' % (formatter, e)) level = config.pop('level', None) filters = config.pop('filters', None) if '()' in config: c = config.pop('()') if not callable(c): c = self.resolve(c) factory = c else: cname = config.pop('class') klass = self.resolve(cname) #Special case for handler which refers to another handler if issubclass(klass, logging.handlers.MemoryHandler) and\ 'target' in config: try: th = self.config['handlers'][config['target']] if not isinstance(th, logging.Handler): config.update(config_copy) # restore for deferred cfg raise TypeError('target not configured yet') config['target'] = th except Exception as e: raise ValueError('Unable to set target handler ' '%r: %s' % (config['target'], e)) elif issubclass(klass, logging.handlers.SMTPHandler) and\ 'mailhost' in config: config['mailhost'] = self.as_tuple(config['mailhost']) elif issubclass(klass, logging.handlers.SysLogHandler) and\ 'address' in config: config['address'] = self.as_tuple(config['address']) factory = klass kwargs = dict([(k, config[k]) for k in config if valid_ident(k)]) try: result = factory(**kwargs) except TypeError as te: if "'stream'" not in str(te): raise #The argument name changed from strm to stream #Retry with old name. #This is so that code can be used with older Python versions #(e.g. by Django) kwargs['strm'] = kwargs.pop('stream') result = factory(**kwargs) if formatter: result.setFormatter(formatter) if level is not None: result.setLevel(logging._checkLevel(level)) if filters: self.add_filters(result, filters) return result def add_handlers(self, logger, handlers): """Add handlers to a logger from a list of names.""" for h in handlers: try: logger.addHandler(self.config['handlers'][h]) except Exception as e: raise ValueError('Unable to add handler %r: %s' % (h, e)) def common_logger_config(self, logger, config, incremental=False): """ Perform configuration which is common to root and non-root loggers. """ level = config.get('level', None) if level is not None: logger.setLevel(logging._checkLevel(level)) if not incremental: #Remove any existing handlers for h in logger.handlers[:]: logger.removeHandler(h) handlers = config.get('handlers', None) if handlers: self.add_handlers(logger, handlers) filters = config.get('filters', None) if filters: self.add_filters(logger, filters) def configure_logger(self, name, config, incremental=False): """Configure a non-root logger from a dictionary.""" logger = logging.getLogger(name) self.common_logger_config(logger, config, incremental) propagate = config.get('propagate', None) if propagate is not None: logger.propagate = propagate def configure_root(self, config, incremental=False): """Configure a root logger from a dictionary.""" root = logging.getLogger() self.common_logger_config(root, config, incremental) dictConfigClass = DictConfigurator def dictConfig(config): """Configure logging using a dictionary.""" dictConfigClass(config).configure() def listen(port=DEFAULT_LOGGING_CONFIG_PORT): """ Start up a socket server on the specified port, and listen for new configurations. These will be sent as a file suitable for processing by fileConfig(). Returns a Thread object on which you can call start() to start the server, and which you can join() when appropriate. To stop the server, call stopListening(). """ if not thread: #pragma: no cover raise NotImplementedError("listen() needs threading to work") class ConfigStreamHandler(StreamRequestHandler): """ Handler for a logging configuration request. It expects a completely new logging configuration and uses fileConfig to install it. """ def handle(self): """ Handle a request. Each request is expected to be a 4-byte length, packed using struct.pack(">L", n), followed by the config file. Uses fileConfig() to do the grunt work. """ try: conn = self.connection chunk = conn.recv(4) if len(chunk) == 4: slen = struct.unpack(">L", chunk)[0] chunk = self.connection.recv(slen) while len(chunk) < slen: chunk = chunk + conn.recv(slen - len(chunk)) chunk = chunk.decode("utf-8") try: import json d =json.loads(chunk) assert isinstance(d, dict) dictConfig(d) except: #Apply new configuration. file = io.StringIO(chunk) try: fileConfig(file) except (KeyboardInterrupt, SystemExit): #pragma: no cover raise except: traceback.print_exc() if self.server.ready: self.server.ready.set() except socket.error as e: if not isinstance(e.args, tuple): raise else: errcode = e.args[0] if errcode != RESET_ERROR: raise class ConfigSocketReceiver(ThreadingTCPServer): """ A simple TCP socket-based logging config receiver. """ allow_reuse_address = 1 def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT, handler=None, ready=None): ThreadingTCPServer.__init__(self, (host, port), handler) logging._acquireLock() self.abort = 0 logging._releaseLock() self.timeout = 1 self.ready = ready def serve_until_stopped(self): import select abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() logging._acquireLock() abort = self.abort logging._releaseLock() self.socket.close() class Server(threading.Thread): def __init__(self, rcvr, hdlr, port): super(Server, self).__init__() self.rcvr = rcvr self.hdlr = hdlr self.port = port self.ready = threading.Event() def run(self): server = self.rcvr(port=self.port, handler=self.hdlr, ready=self.ready) if self.port == 0: self.port = server.server_address[1] self.ready.set() global _listener logging._acquireLock() _listener = server logging._releaseLock() server.serve_until_stopped() return Server(ConfigSocketReceiver, ConfigStreamHandler, port) def stopListening(): """ Stop the listening server which was created with a call to listen(). """ global _listener logging._acquireLock() try: if _listener: _listener.abort = 1 _listener = None finally: logging._releaseLock()
gpl-2.0