repo_name
stringlengths 5
100
| path
stringlengths 4
299
| copies
stringclasses 990
values | size
stringlengths 4
7
| content
stringlengths 666
1.03M
| license
stringclasses 15
values | hash
int64 -9,223,351,895,964,839,000
9,223,297,778B
| line_mean
float64 3.17
100
| line_max
int64 7
1k
| alpha_frac
float64 0.25
0.98
| autogenerated
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|
EricNeedham/assignment-1 | venv/lib/python2.7/site-packages/sqlalchemy/events.py | 22 | 39746 | # sqlalchemy/events.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
"""Core event interfaces."""
from . import event, exc
from .pool import Pool
from .engine import Connectable, Engine, Dialect
from .sql.base import SchemaEventTarget
class DDLEvents(event.Events):
"""
Define event listeners for schema objects,
that is, :class:`.SchemaItem` and other :class:`.SchemaEventTarget`
subclasses, including :class:`.MetaData`, :class:`.Table`,
:class:`.Column`.
:class:`.MetaData` and :class:`.Table` support events
specifically regarding when CREATE and DROP
DDL is emitted to the database.
Attachment events are also provided to customize
behavior whenever a child schema element is associated
with a parent, such as, when a :class:`.Column` is associated
with its :class:`.Table`, when a :class:`.ForeignKeyConstraint`
is associated with a :class:`.Table`, etc.
Example using the ``after_create`` event::
from sqlalchemy import event
from sqlalchemy import Table, Column, Metadata, Integer
m = MetaData()
some_table = Table('some_table', m, Column('data', Integer))
def after_create(target, connection, **kw):
connection.execute("ALTER TABLE %s SET name=foo_%s" %
(target.name, target.name))
event.listen(some_table, "after_create", after_create)
DDL events integrate closely with the
:class:`.DDL` class and the :class:`.DDLElement` hierarchy
of DDL clause constructs, which are themselves appropriate
as listener callables::
from sqlalchemy import DDL
event.listen(
some_table,
"after_create",
DDL("ALTER TABLE %(table)s SET name=foo_%(table)s")
)
The methods here define the name of an event as well
as the names of members that are passed to listener
functions.
See also:
:ref:`event_toplevel`
:class:`.DDLElement`
:class:`.DDL`
:ref:`schema_ddl_sequences`
"""
_target_class_doc = "SomeSchemaClassOrObject"
_dispatch_target = SchemaEventTarget
def before_create(self, target, connection, **kw):
"""Called before CREATE statements are emitted.
:param target: the :class:`.MetaData` or :class:`.Table`
object which is the target of the event.
:param connection: the :class:`.Connection` where the
CREATE statement or statements will be emitted.
:param \**kw: additional keyword arguments relevant
to the event. The contents of this dictionary
may vary across releases, and include the
list of tables being generated for a metadata-level
event, the checkfirst flag, and other
elements used by internal events.
"""
def after_create(self, target, connection, **kw):
"""Called after CREATE statements are emitted.
:param target: the :class:`.MetaData` or :class:`.Table`
object which is the target of the event.
:param connection: the :class:`.Connection` where the
CREATE statement or statements have been emitted.
:param \**kw: additional keyword arguments relevant
to the event. The contents of this dictionary
may vary across releases, and include the
list of tables being generated for a metadata-level
event, the checkfirst flag, and other
elements used by internal events.
"""
def before_drop(self, target, connection, **kw):
"""Called before DROP statements are emitted.
:param target: the :class:`.MetaData` or :class:`.Table`
object which is the target of the event.
:param connection: the :class:`.Connection` where the
DROP statement or statements will be emitted.
:param \**kw: additional keyword arguments relevant
to the event. The contents of this dictionary
may vary across releases, and include the
list of tables being generated for a metadata-level
event, the checkfirst flag, and other
elements used by internal events.
"""
def after_drop(self, target, connection, **kw):
"""Called after DROP statements are emitted.
:param target: the :class:`.MetaData` or :class:`.Table`
object which is the target of the event.
:param connection: the :class:`.Connection` where the
DROP statement or statements have been emitted.
:param \**kw: additional keyword arguments relevant
to the event. The contents of this dictionary
may vary across releases, and include the
list of tables being generated for a metadata-level
event, the checkfirst flag, and other
elements used by internal events.
"""
def before_parent_attach(self, target, parent):
"""Called before a :class:`.SchemaItem` is associated with
a parent :class:`.SchemaItem`.
:param target: the target object
:param parent: the parent to which the target is being attached.
:func:`.event.listen` also accepts a modifier for this event:
:param propagate=False: When True, the listener function will
be established for any copies made of the target object,
i.e. those copies that are generated when
:meth:`.Table.tometadata` is used.
"""
def after_parent_attach(self, target, parent):
"""Called after a :class:`.SchemaItem` is associated with
a parent :class:`.SchemaItem`.
:param target: the target object
:param parent: the parent to which the target is being attached.
:func:`.event.listen` also accepts a modifier for this event:
:param propagate=False: When True, the listener function will
be established for any copies made of the target object,
i.e. those copies that are generated when
:meth:`.Table.tometadata` is used.
"""
def column_reflect(self, inspector, table, column_info):
"""Called for each unit of 'column info' retrieved when
a :class:`.Table` is being reflected.
The dictionary of column information as returned by the
dialect is passed, and can be modified. The dictionary
is that returned in each element of the list returned
by :meth:`.reflection.Inspector.get_columns`.
The event is called before any action is taken against
this dictionary, and the contents can be modified.
The :class:`.Column` specific arguments ``info``, ``key``,
and ``quote`` can also be added to the dictionary and
will be passed to the constructor of :class:`.Column`.
Note that this event is only meaningful if either
associated with the :class:`.Table` class across the
board, e.g.::
from sqlalchemy.schema import Table
from sqlalchemy import event
def listen_for_reflect(inspector, table, column_info):
"receive a column_reflect event"
# ...
event.listen(
Table,
'column_reflect',
listen_for_reflect)
...or with a specific :class:`.Table` instance using
the ``listeners`` argument::
def listen_for_reflect(inspector, table, column_info):
"receive a column_reflect event"
# ...
t = Table(
'sometable',
autoload=True,
listeners=[
('column_reflect', listen_for_reflect)
])
This because the reflection process initiated by ``autoload=True``
completes within the scope of the constructor for :class:`.Table`.
"""
class PoolEvents(event.Events):
"""Available events for :class:`.Pool`.
The methods here define the name of an event as well
as the names of members that are passed to listener
functions.
e.g.::
from sqlalchemy import event
def my_on_checkout(dbapi_conn, connection_rec, connection_proxy):
"handle an on checkout event"
event.listen(Pool, 'checkout', my_on_checkout)
In addition to accepting the :class:`.Pool` class and
:class:`.Pool` instances, :class:`.PoolEvents` also accepts
:class:`.Engine` objects and the :class:`.Engine` class as
targets, which will be resolved to the ``.pool`` attribute of the
given engine or the :class:`.Pool` class::
engine = create_engine("postgresql://scott:tiger@localhost/test")
# will associate with engine.pool
event.listen(engine, 'checkout', my_on_checkout)
"""
_target_class_doc = "SomeEngineOrPool"
_dispatch_target = Pool
@classmethod
def _accept_with(cls, target):
if isinstance(target, type):
if issubclass(target, Engine):
return Pool
elif issubclass(target, Pool):
return target
elif isinstance(target, Engine):
return target.pool
else:
return target
def connect(self, dbapi_connection, connection_record):
"""Called at the moment a particular DBAPI connection is first
created for a given :class:`.Pool`.
This event allows one to capture the point directly after which
the DBAPI module-level ``.connect()`` method has been used in order
to produce a new DBAPI connection.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
"""
def first_connect(self, dbapi_connection, connection_record):
"""Called exactly once for the first time a DBAPI connection is
checked out from a particular :class:`.Pool`.
The rationale for :meth:`.PoolEvents.first_connect` is to determine
information about a particular series of database connections based
on the settings used for all connections. Since a particular
:class:`.Pool` refers to a single "creator" function (which in terms
of a :class:`.Engine` refers to the URL and connection options used),
it is typically valid to make observations about a single connection
that can be safely assumed to be valid about all subsequent
connections, such as the database version, the server and client
encoding settings, collation settings, and many others.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
"""
def checkout(self, dbapi_connection, connection_record, connection_proxy):
"""Called when a connection is retrieved from the Pool.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
:param connection_proxy: the :class:`._ConnectionFairy` object which
will proxy the public interface of the DBAPI connection for the
lifespan of the checkout.
If you raise a :class:`~sqlalchemy.exc.DisconnectionError`, the current
connection will be disposed and a fresh connection retrieved.
Processing of all checkout listeners will abort and restart
using the new connection.
.. seealso:: :meth:`.ConnectionEvents.engine_connect` - a similar event
which occurs upon creation of a new :class:`.Connection`.
"""
def checkin(self, dbapi_connection, connection_record):
"""Called when a connection returns to the pool.
Note that the connection may be closed, and may be None if the
connection has been invalidated. ``checkin`` will not be called
for detached connections. (They do not return to the pool.)
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
"""
def reset(self, dbapi_connnection, connection_record):
"""Called before the "reset" action occurs for a pooled connection.
This event represents
when the ``rollback()`` method is called on the DBAPI connection
before it is returned to the pool. The behavior of "reset" can
be controlled, including disabled, using the ``reset_on_return``
pool argument.
The :meth:`.PoolEvents.reset` event is usually followed by the
:meth:`.PoolEvents.checkin` event is called, except in those
cases where the connection is discarded immediately after reset.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
.. versionadded:: 0.8
.. seealso::
:meth:`.ConnectionEvents.rollback`
:meth:`.ConnectionEvents.commit`
"""
def invalidate(self, dbapi_connection, connection_record, exception):
"""Called when a DBAPI connection is to be "invalidated".
This event is called any time the :meth:`._ConnectionRecord.invalidate`
method is invoked, either from API usage or via "auto-invalidation".
The event occurs before a final attempt to call ``.close()`` on the
connection occurs.
:param dbapi_connection: a DBAPI connection.
:param connection_record: the :class:`._ConnectionRecord` managing the
DBAPI connection.
:param exception: the exception object corresponding to the reason
for this invalidation, if any. May be ``None``.
.. versionadded:: 0.9.2 Added support for connection invalidation
listening.
.. seealso::
:ref:`pool_connection_invalidation`
"""
class ConnectionEvents(event.Events):
"""Available events for :class:`.Connectable`, which includes
:class:`.Connection` and :class:`.Engine`.
The methods here define the name of an event as well as the names of
members that are passed to listener functions.
An event listener can be associated with any :class:`.Connectable`
class or instance, such as an :class:`.Engine`, e.g.::
from sqlalchemy import event, create_engine
def before_cursor_execute(conn, cursor, statement, parameters, context,
executemany):
log.info("Received statement: %s" % statement)
engine = create_engine('postgresql://scott:tiger@localhost/test')
event.listen(engine, "before_cursor_execute", before_cursor_execute)
or with a specific :class:`.Connection`::
with engine.begin() as conn:
@event.listens_for(conn, 'before_cursor_execute')
def before_cursor_execute(conn, cursor, statement, parameters,
context, executemany):
log.info("Received statement: %s" % statement)
The :meth:`.before_execute` and :meth:`.before_cursor_execute`
events can also be established with the ``retval=True`` flag, which
allows modification of the statement and parameters to be sent
to the database. The :meth:`.before_cursor_execute` event is
particularly useful here to add ad-hoc string transformations, such
as comments, to all executions::
from sqlalchemy.engine import Engine
from sqlalchemy import event
@event.listens_for(Engine, "before_cursor_execute", retval=True)
def comment_sql_calls(conn, cursor, statement, parameters,
context, executemany):
statement = statement + " -- some comment"
return statement, parameters
.. note:: :class:`.ConnectionEvents` can be established on any
combination of :class:`.Engine`, :class:`.Connection`, as well
as instances of each of those classes. Events across all
four scopes will fire off for a given instance of
:class:`.Connection`. However, for performance reasons, the
:class:`.Connection` object determines at instantiation time
whether or not its parent :class:`.Engine` has event listeners
established. Event listeners added to the :class:`.Engine`
class or to an instance of :class:`.Engine` *after* the instantiation
of a dependent :class:`.Connection` instance will usually
*not* be available on that :class:`.Connection` instance. The newly
added listeners will instead take effect for :class:`.Connection`
instances created subsequent to those event listeners being
established on the parent :class:`.Engine` class or instance.
:param retval=False: Applies to the :meth:`.before_execute` and
:meth:`.before_cursor_execute` events only. When True, the
user-defined event function must have a return value, which
is a tuple of parameters that replace the given statement
and parameters. See those methods for a description of
specific return arguments.
.. versionchanged:: 0.8 :class:`.ConnectionEvents` can now be associated
with any :class:`.Connectable` including :class:`.Connection`,
in addition to the existing support for :class:`.Engine`.
"""
_target_class_doc = "SomeEngine"
_dispatch_target = Connectable
@classmethod
def _listen(cls, event_key, retval=False):
target, identifier, fn = \
event_key.dispatch_target, event_key.identifier, \
event_key._listen_fn
target._has_events = True
if not retval:
if identifier == 'before_execute':
orig_fn = fn
def wrap_before_execute(conn, clauseelement,
multiparams, params):
orig_fn(conn, clauseelement, multiparams, params)
return clauseelement, multiparams, params
fn = wrap_before_execute
elif identifier == 'before_cursor_execute':
orig_fn = fn
def wrap_before_cursor_execute(conn, cursor, statement,
parameters, context,
executemany):
orig_fn(conn, cursor, statement,
parameters, context, executemany)
return statement, parameters
fn = wrap_before_cursor_execute
elif retval and \
identifier not in ('before_execute',
'before_cursor_execute', 'handle_error'):
raise exc.ArgumentError(
"Only the 'before_execute', "
"'before_cursor_execute' and 'handle_error' engine "
"event listeners accept the 'retval=True' "
"argument.")
event_key.with_wrapper(fn).base_listen()
def before_execute(self, conn, clauseelement, multiparams, params):
"""Intercept high level execute() events, receiving uncompiled
SQL constructs and other objects prior to rendering into SQL.
This event is good for debugging SQL compilation issues as well
as early manipulation of the parameters being sent to the database,
as the parameter lists will be in a consistent format here.
This event can be optionally established with the ``retval=True``
flag. The ``clauseelement``, ``multiparams``, and ``params``
arguments should be returned as a three-tuple in this case::
@event.listens_for(Engine, "before_execute", retval=True)
def before_execute(conn, conn, clauseelement, multiparams, params):
# do something with clauseelement, multiparams, params
return clauseelement, multiparams, params
:param conn: :class:`.Connection` object
:param clauseelement: SQL expression construct, :class:`.Compiled`
instance, or string statement passed to :meth:`.Connection.execute`.
:param multiparams: Multiple parameter sets, a list of dictionaries.
:param params: Single parameter set, a single dictionary.
See also:
:meth:`.before_cursor_execute`
"""
def after_execute(self, conn, clauseelement, multiparams, params, result):
"""Intercept high level execute() events after execute.
:param conn: :class:`.Connection` object
:param clauseelement: SQL expression construct, :class:`.Compiled`
instance, or string statement passed to :meth:`.Connection.execute`.
:param multiparams: Multiple parameter sets, a list of dictionaries.
:param params: Single parameter set, a single dictionary.
:param result: :class:`.ResultProxy` generated by the execution.
"""
def before_cursor_execute(self, conn, cursor, statement,
parameters, context, executemany):
"""Intercept low-level cursor execute() events before execution,
receiving the string
SQL statement and DBAPI-specific parameter list to be invoked
against a cursor.
This event is a good choice for logging as well as late modifications
to the SQL string. It's less ideal for parameter modifications except
for those which are specific to a target backend.
This event can be optionally established with the ``retval=True``
flag. The ``statement`` and ``parameters`` arguments should be
returned as a two-tuple in this case::
@event.listens_for(Engine, "before_cursor_execute", retval=True)
def before_cursor_execute(conn, cursor, statement,
parameters, context, executemany):
# do something with statement, parameters
return statement, parameters
See the example at :class:`.ConnectionEvents`.
:param conn: :class:`.Connection` object
:param cursor: DBAPI cursor object
:param statement: string SQL statement
:param parameters: Dictionary, tuple, or list of parameters being
passed to the ``execute()`` or ``executemany()`` method of the
DBAPI ``cursor``. In some cases may be ``None``.
:param context: :class:`.ExecutionContext` object in use. May
be ``None``.
:param executemany: boolean, if ``True``, this is an ``executemany()``
call, if ``False``, this is an ``execute()`` call.
See also:
:meth:`.before_execute`
:meth:`.after_cursor_execute`
"""
def after_cursor_execute(self, conn, cursor, statement,
parameters, context, executemany):
"""Intercept low-level cursor execute() events after execution.
:param conn: :class:`.Connection` object
:param cursor: DBAPI cursor object. Will have results pending
if the statement was a SELECT, but these should not be consumed
as they will be needed by the :class:`.ResultProxy`.
:param statement: string SQL statement
:param parameters: Dictionary, tuple, or list of parameters being
passed to the ``execute()`` or ``executemany()`` method of the
DBAPI ``cursor``. In some cases may be ``None``.
:param context: :class:`.ExecutionContext` object in use. May
be ``None``.
:param executemany: boolean, if ``True``, this is an ``executemany()``
call, if ``False``, this is an ``execute()`` call.
"""
def dbapi_error(self, conn, cursor, statement, parameters,
context, exception):
"""Intercept a raw DBAPI error.
This event is called with the DBAPI exception instance
received from the DBAPI itself, *before* SQLAlchemy wraps the
exception with it's own exception wrappers, and before any
other operations are performed on the DBAPI cursor; the
existing transaction remains in effect as well as any state
on the cursor.
The use case here is to inject low-level exception handling
into an :class:`.Engine`, typically for logging and
debugging purposes.
.. warning::
Code should **not** modify
any state or throw any exceptions here as this will
interfere with SQLAlchemy's cleanup and error handling
routines. For exception modification, please refer to the
new :meth:`.ConnectionEvents.handle_error` event.
Subsequent to this hook, SQLAlchemy may attempt any
number of operations on the connection/cursor, including
closing the cursor, rolling back of the transaction in the
case of connectionless execution, and disposing of the entire
connection pool if a "disconnect" was detected. The
exception is then wrapped in a SQLAlchemy DBAPI exception
wrapper and re-thrown.
:param conn: :class:`.Connection` object
:param cursor: DBAPI cursor object
:param statement: string SQL statement
:param parameters: Dictionary, tuple, or list of parameters being
passed to the ``execute()`` or ``executemany()`` method of the
DBAPI ``cursor``. In some cases may be ``None``.
:param context: :class:`.ExecutionContext` object in use. May
be ``None``.
:param exception: The **unwrapped** exception emitted directly from the
DBAPI. The class here is specific to the DBAPI module in use.
.. deprecated:: 0.9.7 - replaced by
:meth:`.ConnectionEvents.handle_error`
"""
def handle_error(self, exception_context):
"""Intercept all exceptions processed by the :class:`.Connection`.
This includes all exceptions emitted by the DBAPI as well as
within SQLAlchemy's statement invocation process, including
encoding errors and other statement validation errors. Other areas
in which the event is invoked include transaction begin and end,
result row fetching, cursor creation.
Note that :meth:`.handle_error` may support new kinds of exceptions
and new calling scenarios at *any time*. Code which uses this
event must expect new calling patterns to be present in minor
releases.
To support the wide variety of members that correspond to an exception,
as well as to allow extensibility of the event without backwards
incompatibility, the sole argument received is an instance of
:class:`.ExceptionContext`. This object contains data members
representing detail about the exception.
Use cases supported by this hook include:
* read-only, low-level exception handling for logging and
debugging purposes
* exception re-writing
The hook is called while the cursor from the failed operation
(if any) is still open and accessible. Special cleanup operations
can be called on this cursor; SQLAlchemy will attempt to close
this cursor subsequent to this hook being invoked. If the connection
is in "autocommit" mode, the transaction also remains open within
the scope of this hook; the rollback of the per-statement transaction
also occurs after the hook is called.
The user-defined event handler has two options for replacing
the SQLAlchemy-constructed exception into one that is user
defined. It can either raise this new exception directly, in
which case all further event listeners are bypassed and the
exception will be raised, after appropriate cleanup as taken
place::
@event.listens_for(Engine, "handle_error")
def handle_exception(context):
if isinstance(context.original_exception,
psycopg2.OperationalError) and \\
"failed" in str(context.original_exception):
raise MySpecialException("failed operation")
Alternatively, a "chained" style of event handling can be
used, by configuring the handler with the ``retval=True``
modifier and returning the new exception instance from the
function. In this case, event handling will continue onto the
next handler. The "chained" exception is available using
:attr:`.ExceptionContext.chained_exception`::
@event.listens_for(Engine, "handle_error", retval=True)
def handle_exception(context):
if context.chained_exception is not None and \\
"special" in context.chained_exception.message:
return MySpecialException("failed",
cause=context.chained_exception)
Handlers that return ``None`` may remain within this chain; the
last non-``None`` return value is the one that continues to be
passed to the next handler.
When a custom exception is raised or returned, SQLAlchemy raises
this new exception as-is, it is not wrapped by any SQLAlchemy
object. If the exception is not a subclass of
:class:`sqlalchemy.exc.StatementError`,
certain features may not be available; currently this includes
the ORM's feature of adding a detail hint about "autoflush" to
exceptions raised within the autoflush process.
:param context: an :class:`.ExceptionContext` object. See this
class for details on all available members.
.. versionadded:: 0.9.7 Added the
:meth:`.ConnectionEvents.handle_error` hook.
"""
def engine_connect(self, conn, branch):
"""Intercept the creation of a new :class:`.Connection`.
This event is called typically as the direct result of calling
the :meth:`.Engine.connect` method.
It differs from the :meth:`.PoolEvents.connect` method, which
refers to the actual connection to a database at the DBAPI level;
a DBAPI connection may be pooled and reused for many operations.
In contrast, this event refers only to the production of a higher level
:class:`.Connection` wrapper around such a DBAPI connection.
It also differs from the :meth:`.PoolEvents.checkout` event
in that it is specific to the :class:`.Connection` object, not the
DBAPI connection that :meth:`.PoolEvents.checkout` deals with, although
this DBAPI connection is available here via the
:attr:`.Connection.connection` attribute. But note there can in fact
be multiple :meth:`.PoolEvents.checkout` events within the lifespan
of a single :class:`.Connection` object, if that :class:`.Connection`
is invalidated and re-established. There can also be multiple
:class:`.Connection` objects generated for the same already-checked-out
DBAPI connection, in the case that a "branch" of a :class:`.Connection`
is produced.
:param conn: :class:`.Connection` object.
:param branch: if True, this is a "branch" of an existing
:class:`.Connection`. A branch is generated within the course
of a statement execution to invoke supplemental statements, most
typically to pre-execute a SELECT of a default value for the purposes
of an INSERT statement.
.. versionadded:: 0.9.0
.. seealso::
:meth:`.PoolEvents.checkout` the lower-level pool checkout event
for an individual DBAPI connection
:meth:`.ConnectionEvents.set_connection_execution_options` - a copy
of a :class:`.Connection` is also made when the
:meth:`.Connection.execution_options` method is called.
"""
def set_connection_execution_options(self, conn, opts):
"""Intercept when the :meth:`.Connection.execution_options`
method is called.
This method is called after the new :class:`.Connection` has been
produced, with the newly updated execution options collection, but
before the :class:`.Dialect` has acted upon any of those new options.
Note that this method is not called when a new :class:`.Connection`
is produced which is inheriting execution options from its parent
:class:`.Engine`; to intercept this condition, use the
:meth:`.ConnectionEvents.engine_connect` event.
:param conn: The newly copied :class:`.Connection` object
:param opts: dictionary of options that were passed to the
:meth:`.Connection.execution_options` method.
.. versionadded:: 0.9.0
.. seealso::
:meth:`.ConnectionEvents.set_engine_execution_options` - event
which is called when :meth:`.Engine.execution_options` is called.
"""
def set_engine_execution_options(self, engine, opts):
"""Intercept when the :meth:`.Engine.execution_options`
method is called.
The :meth:`.Engine.execution_options` method produces a shallow
copy of the :class:`.Engine` which stores the new options. That new
:class:`.Engine` is passed here. A particular application of this
method is to add a :meth:`.ConnectionEvents.engine_connect` event
handler to the given :class:`.Engine` which will perform some per-
:class:`.Connection` task specific to these execution options.
:param conn: The newly copied :class:`.Engine` object
:param opts: dictionary of options that were passed to the
:meth:`.Connection.execution_options` method.
.. versionadded:: 0.9.0
.. seealso::
:meth:`.ConnectionEvents.set_connection_execution_options` - event
which is called when :meth:`.Connection.execution_options` is
called.
"""
def begin(self, conn):
"""Intercept begin() events.
:param conn: :class:`.Connection` object
"""
def rollback(self, conn):
"""Intercept rollback() events, as initiated by a
:class:`.Transaction`.
Note that the :class:`.Pool` also "auto-rolls back"
a DBAPI connection upon checkin, if the ``reset_on_return``
flag is set to its default value of ``'rollback'``.
To intercept this
rollback, use the :meth:`.PoolEvents.reset` hook.
:param conn: :class:`.Connection` object
.. seealso::
:meth:`.PoolEvents.reset`
"""
def commit(self, conn):
"""Intercept commit() events, as initiated by a
:class:`.Transaction`.
Note that the :class:`.Pool` may also "auto-commit"
a DBAPI connection upon checkin, if the ``reset_on_return``
flag is set to the value ``'commit'``. To intercept this
commit, use the :meth:`.PoolEvents.reset` hook.
:param conn: :class:`.Connection` object
"""
def savepoint(self, conn, name):
"""Intercept savepoint() events.
:param conn: :class:`.Connection` object
:param name: specified name used for the savepoint.
"""
def rollback_savepoint(self, conn, name, context):
"""Intercept rollback_savepoint() events.
:param conn: :class:`.Connection` object
:param name: specified name used for the savepoint.
:param context: :class:`.ExecutionContext` in use. May be ``None``.
"""
def release_savepoint(self, conn, name, context):
"""Intercept release_savepoint() events.
:param conn: :class:`.Connection` object
:param name: specified name used for the savepoint.
:param context: :class:`.ExecutionContext` in use. May be ``None``.
"""
def begin_twophase(self, conn, xid):
"""Intercept begin_twophase() events.
:param conn: :class:`.Connection` object
:param xid: two-phase XID identifier
"""
def prepare_twophase(self, conn, xid):
"""Intercept prepare_twophase() events.
:param conn: :class:`.Connection` object
:param xid: two-phase XID identifier
"""
def rollback_twophase(self, conn, xid, is_prepared):
"""Intercept rollback_twophase() events.
:param conn: :class:`.Connection` object
:param xid: two-phase XID identifier
:param is_prepared: boolean, indicates if
:meth:`.TwoPhaseTransaction.prepare` was called.
"""
def commit_twophase(self, conn, xid, is_prepared):
"""Intercept commit_twophase() events.
:param conn: :class:`.Connection` object
:param xid: two-phase XID identifier
:param is_prepared: boolean, indicates if
:meth:`.TwoPhaseTransaction.prepare` was called.
"""
class DialectEvents(event.Events):
"""event interface for execution-replacement functions.
These events allow direct instrumentation and replacement
of key dialect functions which interact with the DBAPI.
.. note::
:class:`.DialectEvents` hooks should be considered **semi-public**
and experimental.
These hooks are not for general use and are only for those situations
where intricate re-statement of DBAPI mechanics must be injected onto
an existing dialect. For general-use statement-interception events,
please use the :class:`.ConnectionEvents` interface.
.. seealso::
:meth:`.ConnectionEvents.before_cursor_execute`
:meth:`.ConnectionEvents.before_execute`
:meth:`.ConnectionEvents.after_cursor_execute`
:meth:`.ConnectionEvents.after_execute`
.. versionadded:: 0.9.4
"""
_target_class_doc = "SomeEngine"
_dispatch_target = Dialect
@classmethod
def _listen(cls, event_key, retval=False):
target, identifier, fn = \
event_key.dispatch_target, event_key.identifier, event_key.fn
target._has_events = True
event_key.base_listen()
@classmethod
def _accept_with(cls, target):
if isinstance(target, type):
if issubclass(target, Engine):
return Dialect
elif issubclass(target, Dialect):
return target
elif isinstance(target, Engine):
return target.dialect
else:
return target
def do_executemany(self, cursor, statement, parameters, context):
"""Receive a cursor to have executemany() called.
Return the value True to halt further events from invoking,
and to indicate that the cursor execution has already taken
place within the event handler.
"""
def do_execute_no_params(self, cursor, statement, context):
"""Receive a cursor to have execute() with no parameters called.
Return the value True to halt further events from invoking,
and to indicate that the cursor execution has already taken
place within the event handler.
"""
def do_execute(self, cursor, statement, parameters, context):
"""Receive a cursor to have execute() called.
Return the value True to halt further events from invoking,
and to indicate that the cursor execution has already taken
place within the event handler.
"""
| mit | 154,911,117,829,488,700 | 38.197239 | 79 | 0.640593 | false |
maciejkula/scipy | scipy/sparse/linalg/tests/test_onenormest.py | 4 | 9575 | """Test functions for the sparse.linalg._onenormest module
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import (assert_allclose, assert_equal, assert_,
decorators, TestCase, run_module_suite)
import scipy.linalg
import scipy.sparse.linalg
from scipy.sparse.linalg._onenormest import _onenormest_core, _algorithm_2_2
class MatrixProductOperator(scipy.sparse.linalg.LinearOperator):
"""
This is purely for onenormest testing.
"""
def __init__(self, A, B):
if A.ndim != 2 or B.ndim != 2:
raise ValueError('expected ndarrays representing matrices')
if A.shape[1] != B.shape[0]:
raise ValueError('incompatible shapes')
self.A = A
self.B = B
self.ndim = 2
self.shape = (A.shape[0], B.shape[1])
def matvec(self, x):
return np.dot(self.A, np.dot(self.B, x))
def rmatvec(self, x):
return np.dot(np.dot(x, self.A), self.B)
def matmat(self, X):
return np.dot(self.A, np.dot(self.B, X))
@property
def T(self):
return MatrixProductOperator(self.B.T, self.A.T)
class TestOnenormest(TestCase):
@decorators.slow
@decorators.skipif(True, 'this test is annoyingly slow')
def test_onenormest_table_3_t_2(self):
# This will take multiple seconds if your computer is slow like mine.
# It is stochastic, so the tolerance could be too strict.
np.random.seed(1234)
t = 2
n = 100
itmax = 5
nsamples = 5000
observed = []
expected = []
nmult_list = []
nresample_list = []
for i in range(nsamples):
A = scipy.linalg.inv(np.random.randn(n, n))
est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)
observed.append(est)
expected.append(scipy.linalg.norm(A, 1))
nmult_list.append(nmults)
nresample_list.append(nresamples)
observed = np.array(observed, dtype=float)
expected = np.array(expected, dtype=float)
relative_errors = np.abs(observed - expected) / expected
# check the mean underestimation ratio
underestimation_ratio = observed / expected
assert_(0.99 < np.mean(underestimation_ratio) < 1.0)
# check the max and mean required column resamples
assert_equal(np.max(nresample_list), 2)
assert_(0.05 < np.mean(nresample_list) < 0.2)
# check the proportion of norms computed exactly correctly
nexact = np.count_nonzero(relative_errors < 1e-14)
proportion_exact = nexact / float(nsamples)
assert_(0.9 < proportion_exact < 0.95)
# check the average number of matrix*vector multiplications
assert_(3.5 < np.mean(nmult_list) < 4.5)
@decorators.slow
@decorators.skipif(True, 'this test is annoyingly slow')
def test_onenormest_table_4_t_7(self):
# This will take multiple seconds if your computer is slow like mine.
# It is stochastic, so the tolerance could be too strict.
np.random.seed(1234)
t = 7
n = 100
itmax = 5
nsamples = 5000
observed = []
expected = []
nmult_list = []
nresample_list = []
for i in range(nsamples):
A = np.random.randint(-1, 2, size=(n, n))
est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)
observed.append(est)
expected.append(scipy.linalg.norm(A, 1))
nmult_list.append(nmults)
nresample_list.append(nresamples)
observed = np.array(observed, dtype=float)
expected = np.array(expected, dtype=float)
relative_errors = np.abs(observed - expected) / expected
# check the mean underestimation ratio
underestimation_ratio = observed / expected
assert_(0.90 < np.mean(underestimation_ratio) < 0.99)
# check the required column resamples
assert_equal(np.max(nresample_list), 0)
# check the proportion of norms computed exactly correctly
nexact = np.count_nonzero(relative_errors < 1e-14)
proportion_exact = nexact / float(nsamples)
assert_(0.15 < proportion_exact < 0.25)
# check the average number of matrix*vector multiplications
assert_(3.5 < np.mean(nmult_list) < 4.5)
def test_onenormest_table_5_t_1(self):
# "note that there is no randomness and hence only one estimate for t=1"
t = 1
n = 100
itmax = 5
alpha = 1 - 1e-6
A = -scipy.linalg.inv(np.identity(n) + alpha*np.eye(n, k=1))
first_col = np.array([1] + [0]*(n-1))
first_row = np.array([(-alpha)**i for i in range(n)])
B = -scipy.linalg.toeplitz(first_col, first_row)
assert_allclose(A, B)
est, v, w, nmults, nresamples = _onenormest_core(B, B.T, t, itmax)
exact_value = scipy.linalg.norm(B, 1)
underest_ratio = est / exact_value
assert_allclose(underest_ratio, 0.05, rtol=1e-4)
assert_equal(nmults, 11)
assert_equal(nresamples, 0)
# check the non-underscored version of onenormest
est_plain = scipy.sparse.linalg.onenormest(B, t=t, itmax=itmax)
assert_allclose(est, est_plain)
@decorators.slow
@decorators.skipif(True, 'this test is annoyingly slow')
def test_onenormest_table_6_t_1(self):
#TODO this test seems to give estimates that match the table,
#TODO even though no attempt has been made to deal with
#TODO complex numbers in the one-norm estimation.
# This will take multiple seconds if your computer is slow like mine.
# It is stochastic, so the tolerance could be too strict.
np.random.seed(1234)
t = 1
n = 100
itmax = 5
nsamples = 5000
observed = []
expected = []
nmult_list = []
nresample_list = []
for i in range(nsamples):
A_inv = np.random.rand(n, n) + 1j * np.random.rand(n, n)
A = scipy.linalg.inv(A_inv)
est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)
observed.append(est)
expected.append(scipy.linalg.norm(A, 1))
nmult_list.append(nmults)
nresample_list.append(nresamples)
observed = np.array(observed, dtype=float)
expected = np.array(expected, dtype=float)
relative_errors = np.abs(observed - expected) / expected
# check the mean underestimation ratio
underestimation_ratio = observed / expected
underestimation_ratio_mean = np.mean(underestimation_ratio)
assert_(0.90 < underestimation_ratio_mean < 0.99)
# check the required column resamples
max_nresamples = np.max(nresample_list)
assert_equal(max_nresamples, 0)
# check the proportion of norms computed exactly correctly
nexact = np.count_nonzero(relative_errors < 1e-14)
proportion_exact = nexact / float(nsamples)
assert_(0.7 < proportion_exact < 0.8)
# check the average number of matrix*vector multiplications
mean_nmult = np.mean(nmult_list)
assert_(4 < mean_nmult < 5)
def _help_product_norm_slow(self, A, B):
# for profiling
C = np.dot(A, B)
return scipy.linalg.norm(C, 1)
def _help_product_norm_fast(self, A, B):
# for profiling
t = 2
itmax = 5
D = MatrixProductOperator(A, B)
est, v, w, nmults, nresamples = _onenormest_core(D, D.T, t, itmax)
return est
@decorators.slow
def test_onenormest_linear_operator(self):
# Define a matrix through its product A B.
# Depending on the shapes of A and B,
# it could be easy to multiply this product by a small matrix,
# but it could be annoying to look at all of
# the entries of the product explicitly.
np.random.seed(1234)
n = 6000
k = 3
A = np.random.randn(n, k)
B = np.random.randn(k, n)
fast_estimate = self._help_product_norm_fast(A, B)
exact_value = self._help_product_norm_slow(A, B)
assert_(fast_estimate <= exact_value <= 3*fast_estimate,
'fast: %g\nexact:%g' % (fast_estimate, exact_value))
def test_returns(self):
np.random.seed(1234)
A = scipy.sparse.rand(50, 50, 0.1)
s0 = scipy.linalg.norm(A.todense(), 1)
s1, v = scipy.sparse.linalg.onenormest(A, compute_v=True)
s2, w = scipy.sparse.linalg.onenormest(A, compute_w=True)
s3, v2, w2 = scipy.sparse.linalg.onenormest(A, compute_w=True, compute_v=True)
assert_allclose(s1, s0, rtol=1e-9)
assert_allclose(np.linalg.norm(A.dot(v), 1), s0*np.linalg.norm(v, 1), rtol=1e-9)
assert_allclose(A.dot(v), w, rtol=1e-9)
class TestAlgorithm_2_2(TestCase):
def test_randn_inv(self):
np.random.seed(1234)
n = 20
nsamples = 100
for i in range(nsamples):
# Choose integer t uniformly between 1 and 3 inclusive.
t = np.random.randint(1, 4)
# Choose n uniformly between 10 and 40 inclusive.
n = np.random.randint(10, 41)
# Sample the inverse of a matrix with random normal entries.
A = scipy.linalg.inv(np.random.randn(n, n))
# Compute the 1-norm bounds.
g, ind = _algorithm_2_2(A, A.T, t)
if __name__ == '__main__':
run_module_suite()
| bsd-3-clause | 2,964,660,327,789,552,000 | 35.826923 | 88 | 0.60094 | false |
drcapulet/sentry | src/sentry/web/frontend/projects/quotas.py | 24 | 2011 | """
sentry.web.frontend.projects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from sentry import app, features
from sentry.constants import MEMBER_ADMIN
from sentry.quotas.base import Quota
from sentry.web.decorators import has_access
from sentry.web.forms.projects import ProjectQuotasForm
from sentry.web.helpers import render_to_response
ERR_NO_SSO = _('The quotas feature is not enabled for this project.')
@has_access(MEMBER_ADMIN)
def manage_project_quotas(request, organization, project):
if not features.has('projects:quotas', project, actor=request.user):
messages.add_message(
request, messages.ERROR,
ERR_NO_SSO,
)
redirect = reverse('sentry-manage-project',
args=[organization.slug, project.slug])
return HttpResponseRedirect(redirect)
form = ProjectQuotasForm(project, request.POST or None)
if form and form.is_valid():
form.save()
messages.add_message(
request, messages.SUCCESS,
_('Your settings were saved successfully.'))
return HttpResponseRedirect(reverse('sentry-manage-project-quotas', args=[project.organization.slug, project.slug]))
context = {
'organization': organization,
'team': project.team,
'page': 'quotas',
# TODO(dcramer): has_quotas is an awful hack
'has_quotas': type(app.quotas) != Quota,
'system_quota': int(app.quotas.get_system_quota()),
'team_quota': int(app.quotas.get_team_quota(project.team)),
'project': project,
'form': form,
}
return render_to_response('sentry/projects/quotas.html', context, request)
| bsd-3-clause | -7,598,812,396,621,180,000 | 33.084746 | 124 | 0.675286 | false |
sander76/home-assistant | homeassistant/components/smart_meter_texas/config_flow.py | 3 | 2779 | """Config flow for Smart Meter Texas integration."""
import asyncio
import logging
from aiohttp import ClientError
from smart_meter_texas import Account, Client
from smart_meter_texas.exceptions import (
SmartMeterTexasAPIError,
SmartMeterTexasAuthError,
)
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import aiohttp_client
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
DATA_SCHEMA = vol.Schema(
{vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
)
async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.
Data has the keys from DATA_SCHEMA with values provided by the user.
"""
client_session = aiohttp_client.async_get_clientsession(hass)
account = Account(data["username"], data["password"])
client = Client(client_session, account)
try:
await client.authenticate()
except (asyncio.TimeoutError, ClientError, SmartMeterTexasAPIError) as error:
raise CannotConnect from error
except SmartMeterTexasAuthError as error:
raise InvalidAuth(error) from error
# Return info that you want to store in the config entry.
return {"title": account.username}
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Smart Meter Texas."""
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL
async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
info = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
if not errors:
# Ensure the same account cannot be setup more than once.
await self.async_set_unique_id(user_input[CONF_USERNAME])
self._abort_if_unique_id_configured()
return self.async_create_entry(title=info["title"], data=user_input)
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
)
class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""
class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indicate there is invalid auth."""
| apache-2.0 | 3,250,314,867,892,210,700 | 31.694118 | 88 | 0.666787 | false |
xinwu/horizon | openstack_dashboard/test/test_data/sahara_data.py | 1 | 18950 | # 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 copy
from openstack_dashboard.test.test_data import utils
from saharaclient.api import cluster_templates
from saharaclient.api import clusters
from saharaclient.api import data_sources
from saharaclient.api import job_binaries
from saharaclient.api import job_executions
from saharaclient.api import job_types
from saharaclient.api import jobs
from saharaclient.api import node_group_templates
from saharaclient.api import plugins
def data(TEST):
TEST.plugins = utils.TestDataContainer()
TEST.plugins_configs = utils.TestDataContainer()
TEST.nodegroup_templates = utils.TestDataContainer()
TEST.cluster_templates = utils.TestDataContainer()
TEST.clusters = utils.TestDataContainer()
TEST.data_sources = utils.TestDataContainer()
TEST.job_binaries = utils.TestDataContainer()
TEST.jobs = utils.TestDataContainer()
TEST.job_executions = utils.TestDataContainer()
TEST.registered_images = copy.copy(TEST.images)
TEST.job_types = utils.TestDataContainer()
plugin1_dict = {
"description": "vanilla plugin",
"name": "vanilla",
"title": "Vanilla Apache Hadoop",
"versions": ["2.3.0", "1.2.1"]
}
plugin1 = plugins.Plugin(plugins.PluginManager(None), plugin1_dict)
TEST.plugins.add(plugin1)
plugin_config1_dict = {
"node_processes": {
"HDFS": [
"namenode",
"datanode",
"secondarynamenode"
],
"MapReduce": [
"tasktracker",
"jobtracker"
]
},
"description": "This plugin provides an ability to launch vanilla "
"Apache Hadoop cluster without any management "
"consoles.",
"versions": [
"1.2.1"
],
"required_image_tags": [
"vanilla",
"1.2.1"
],
"configs": [
{
"default_value": "/tmp/hadoop-${user.name}",
"name": "hadoop.tmp.dir",
"priority": 2,
"config_type": "string",
"applicable_target": "HDFS",
"is_optional": True,
"scope": "node",
"description": "A base for other temporary directories."
},
{
"default_value": True,
"name": "hadoop.native.lib",
"priority": 2,
"config_type": "bool",
"applicable_target": "HDFS",
"is_optional": True,
"scope": "node",
"description": "Should native hadoop libraries, if present, "
"be used."
},
],
"title": "Vanilla Apache Hadoop",
"name": "vanilla"
}
TEST.plugins_configs.add(plugins.Plugin(plugins.PluginManager(None),
plugin_config1_dict))
# Nodegroup_Templates.
ngt1_dict = {
"created_at": "2014-06-04 14:01:03.701243",
"description": None,
"flavor_id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
"availability_zone": None,
"floating_ip_pool": None,
"auto_security_group": True,
"security_groups": [],
"hadoop_version": "1.2.1",
"id": "c166dfcc-9cc7-4b48-adc9-f0946169bb36",
"image_id": None,
"name": "sample-template",
"node_configs": {},
"node_processes": [
"namenode",
"jobtracker",
"secondarynamenode",
"hiveserver",
"oozie"
],
"plugin_name": "vanilla",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"updated_at": None,
"volume_mount_prefix": "/volumes/disk",
"volumes_per_node": 0,
"volumes_size": 0,
"security_groups": [],
"volumes_availability_zone": None,
}
ngt1 = node_group_templates.NodeGroupTemplate(
node_group_templates.NodeGroupTemplateManager(None), ngt1_dict)
TEST.nodegroup_templates.add(ngt1)
# Cluster_templates.
ct1_dict = {
"anti_affinity": [],
"cluster_configs": {},
"created_at": "2014-06-04 14:01:06.460711",
"default_image_id": None,
"description": "Sample description",
"hadoop_version": "1.2.1",
"id": "a2c3743f-31a2-4919-8d02-792138a87a98",
"name": "sample-cluster-template",
"neutron_management_network": None,
"node_groups": [
{
"count": 1,
"created_at": "2014-06-04 14:01:06.462512",
"flavor_id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
"floating_ip_pool": None,
"image_id": None,
"name": "master",
"node_configs": {},
"node_group_template_id": "c166dfcc-9cc7-4b48-adc9",
"node_processes": [
"namenode",
"jobtracker",
"secondarynamenode",
"hiveserver",
"oozie"
],
"updated_at": None,
"volume_mount_prefix": "/volumes/disk",
"volumes_per_node": 0,
"volumes_size": 0,
"volumes_availability_zone": None,
},
{
"count": 2,
"created_at": "2014-06-04 14:01:06.463214",
"flavor_id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
"floating_ip_pool": None,
"image_id": None,
"name": "workers",
"node_configs": {},
"node_group_template_id": "4eb5504c-94c9-4049-a440",
"node_processes": [
"datanode",
"tasktracker"
],
"updated_at": None,
"volume_mount_prefix": "/volumes/disk",
"volumes_per_node": 0,
"volumes_size": 0,
"volumes_availability_zone": None,
}
],
"plugin_name": "vanilla",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"updated_at": None
}
ct1 = cluster_templates.ClusterTemplate(
cluster_templates.ClusterTemplateManager(None), ct1_dict)
TEST.cluster_templates.add(ct1)
# Clusters.
cluster1_dict = {
"anti_affinity": [],
"cluster_configs": {},
"cluster_template_id": "a2c3743f-31a2-4919-8d02-792138a87a98",
"created_at": "2014-06-04 20:02:14.051328",
"default_image_id": "9eb4643c-dca8-4ea7-92d2-b773f88a8dc6",
"description": "",
"hadoop_version": "1.2.1",
"id": "ec9a0d28-5cfb-4028-a0b5-40afe23f1533",
"info": {},
"is_transient": False,
"management_public_key": "fakekey",
"name": "cercluster",
"neutron_management_network": None,
"node_groups": [
{
"count": 1,
"created_at": "2014-06-04 20:02:14.053153",
"flavor_id": "0",
"floating_ip_pool": None,
"image_id": None,
"instances": [
{
"created_at": "2014-06-04 20:02:14.834529",
"id": "c3b8004b-7063-4b99-a082-820cdc6e961c",
"instance_id": "a45f5495-4a10-4f17-8fae",
"instance_name": "cercluster-master-001",
"internal_ip": None,
"management_ip": None,
"updated_at": None,
"volumes": []
}
],
"name": "master",
"node_configs": {},
"node_group_template_id": "c166dfcc-9cc7-4b48-adc9",
"node_processes": [
"namenode",
"jobtracker",
"secondarynamenode",
"hiveserver",
"oozie"
],
"updated_at": "2014-06-04 20:02:14.841760",
"volume_mount_prefix": "/volumes/disk",
"volumes_per_node": 0,
"volumes_size": 0,
"security_groups": [],
"volumes_availability_zone": None,
},
{
"count": 2,
"created_at": "2014-06-04 20:02:14.053849",
"flavor_id": "0",
"floating_ip_pool": None,
"image_id": None,
"instances": [
{
"created_at": "2014-06-04 20:02:15.097655",
"id": "6a8ae0b1-bb28-4de2-bfbb-bdd3fd2d72b2",
"instance_id": "38bf8168-fb30-483f-8d52",
"instance_name": "cercluster-workers-001",
"internal_ip": None,
"management_ip": None,
"updated_at": None,
"volumes": []
},
{
"created_at": "2014-06-04 20:02:15.344515",
"id": "17b98ed3-a776-467a-90cf-9f46a841790b",
"instance_id": "85606938-8e53-46a5-a50b",
"instance_name": "cercluster-workers-002",
"internal_ip": None,
"management_ip": None,
"updated_at": None,
"volumes": []
}
],
"name": "workers",
"node_configs": {},
"node_group_template_id": "4eb5504c-94c9-4049-a440",
"node_processes": [
"datanode",
"tasktracker"
],
"updated_at": "2014-06-04 20:02:15.355745",
"volume_mount_prefix": "/volumes/disk",
"volumes_per_node": 0,
"volumes_size": 0,
"security_groups": ["b7857890-09bf-4ee0-a0d5-322d7a6978bf"],
"volumes_availability_zone": None,
}
],
"plugin_name": "vanilla",
"status": "Active",
"status_description": "",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"trust_id": None,
"updated_at": "2014-06-04 20:02:15.446087",
"user_keypair_id": "stackboxkp"
}
cluster1 = clusters.Cluster(
clusters.ClusterManager(None), cluster1_dict)
TEST.clusters.add(cluster1)
# Data Sources.
data_source1_dict = {
"created_at": "2014-06-04 14:01:10.371562",
"description": "sample output",
"id": "426fb01c-5c7e-472d-bba2-b1f0fe7e0ede",
"name": "sampleOutput",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"type": "swift",
"updated_at": None,
"url": "swift://example.sahara/output"
}
data_source2_dict = {
"created_at": "2014-06-05 15:01:12.331361",
"description": "second sample output",
"id": "ab3413-adfb-bba2-123456785675",
"name": "sampleOutput2",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"type": "hdfs",
"updated_at": None,
"url": "hdfs://example.sahara/output"
}
data_source1 = data_sources.DataSources(
data_sources.DataSourceManager(None), data_source1_dict)
data_source2 = data_sources.DataSources(
data_sources.DataSourceManager(None), data_source2_dict)
TEST.data_sources.add(data_source1)
TEST.data_sources.add(data_source2)
# Job Binaries.
job_binary1_dict = {
"created_at": "2014-06-05 18:15:15.581285",
"description": "",
"id": "3f3a07ac-7d6f-49e8-8669-40b25ee891b7",
"name": "example.pig",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"updated_at": None,
"url": "internal-db://80121dea-f8bd-4ad3-bcc7-096f4bfc722d"
}
job_binary2_dict = {
"created_at": "2014-10-10 13:12:15.583631",
"description": "Test for spaces in name",
"id": "abcdef56-1234-abcd-abcd-defabcdaedcb",
"name": "example with spaces.pig",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"updated_at": None,
"url": "internal-db://abcdef56-1234-abcd-abcd-defabcdaedcb"
}
job_binary1 = job_binaries.JobBinaries(
job_binaries.JobBinariesManager(None), job_binary1_dict)
job_binary2 = job_binaries.JobBinaries(
job_binaries.JobBinariesManager(None), job_binary2_dict)
TEST.job_binaries.add(job_binary1)
TEST.job_binaries.add(job_binary2)
# Jobs.
job1_dict = {
"created_at": "2014-06-05 19:23:59.637165",
"description": "",
"id": "a077b851-46be-4ad7-93c3-2d83894546ef",
"libs": [
{
"created_at": "2014-06-05 19:23:42.742057",
"description": "",
"id": "ab140807-59f8-4235-b4f2-e03daf946256",
"name": "udf.jar",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"updated_at": None,
"url": "internal-db://d186e2bb-df93-47eb-8c0e-ce21e7ecb78b"
}
],
"mains": [
{
"created_at": "2014-06-05 18:15:15.581285",
"description": "",
"id": "3f3a07ac-7d6f-49e8-8669-40b25ee891b7",
"name": "example.pig",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"updated_at": None,
"url": "internal-db://80121dea-f8bd-4ad3-bcc7-096f4bfc722d"
}
],
"name": "pigjob",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"type": "Pig",
"updated_at": None
}
job1 = jobs.Job(jobs.JobsManager(None), job1_dict)
TEST.jobs.add(job1)
# Job Executions.
jobex1_dict = {
"cluster_id": "ec9a0d28-5cfb-4028-a0b5-40afe23f1533",
"created_at": "2014-06-05 20:03:06.195937",
"end_time": None,
"id": "4b6c1cbf-c713-49d3-8025-808a87c514a6",
"info": {
"acl": None,
"actions": [
{
"consoleUrl": "-",
"cred": "None",
"data": None,
"endTime": "Thu,05 Jun 2014 20:03:32 GMT",
"errorCode": None,
"errorMessage": None,
"externalChildIDs": None,
"externalId": "-",
"externalStatus": "OK",
"id": "0000000-140604200538581-oozie-hado-W@:start:",
"name": ":start:",
"retries": 0,
"startTime": "Thu,05 Jun 2014 20:03:32 GMT",
"stats": None,
"status": "OK",
"toString": "Action name[:start:] status[OK]",
"trackerUri": "-",
"transition": "job-node",
"type": ":START:"
},
{
"consoleUrl": "fake://console.url",
"cred": "None",
"data": None,
"endTime": None,
"errorCode": None,
"errorMessage": None,
"externalChildIDs": None,
"externalId": "job_201406042004_0001",
"externalStatus": "RUNNING",
"id": "0000000-140604200538581-oozie-hado-W@job-node",
"name": "job-node",
"retries": 0,
"startTime": "Thu,05 Jun 2014 20:03:33 GMT",
"stats": None,
"status": "RUNNING",
"toString": "Action name[job-node] status[RUNNING]",
"trackerUri": "cercluster-master-001:8021",
"transition": None,
"type": "pig"
}
],
"appName": "job-wf",
"appPath": "hdfs://fakepath/workflow.xml",
"conf": "<configuration>fakeconfig</configuration>",
"consoleUrl": "fake://consoleURL",
"createdTime": "Thu,05 Jun 2014 20:03:32 GMT",
"endTime": None,
"externalId": None,
"group": None,
"id": "0000000-140604200538581-oozie-hado-W",
"lastModTime": "Thu,05 Jun 2014 20:03:35 GMT",
"parentId": None,
"run": 0,
"startTime": "Thu,05 Jun 2014 20:03:32 GMT",
"status": "RUNNING",
"toString": "Workflow ...status[RUNNING]",
"user": "hadoop"
},
"input_id": "85884883-3083-49eb-b442-71dd3734d02c",
"job_configs": {
"args": [],
"configs": {},
"params": {}
},
"job_id": "a077b851-46be-4ad7-93c3-2d83894546ef",
"oozie_job_id": "0000000-140604200538581-oozie-hado-W",
"output_id": "426fb01c-5c7e-472d-bba2-b1f0fe7e0ede",
"progress": None,
"return_code": None,
"start_time": "2014-06-05T16:03:32",
"tenant_id": "429ad8447c2d47bc8e0382d244e1d1df",
"updated_at": "2014-06-05 20:03:46.438248",
"cluster_name_set": True,
"job_name_set": True,
"cluster_name": "cluster-1",
"job_name": "job-1"
}
jobex1 = job_executions.JobExecution(
job_executions.JobExecutionsManager(None), jobex1_dict)
TEST.job_executions.add(jobex1)
augmented_image = TEST.registered_images.first()
augmented_image.tags = {}
augmented_image.username = 'myusername'
augmented_image.description = 'mydescription'
job_type1_dict = {
"name": "Pig",
"plugins": [
{
"description": "Fake description",
"versions": {
"2.6.0": {
},
"1.2.1": {
}
},
"name": "vanilla",
"title": "Vanilla Apache Hadoop"
},
]
}
job_types1 = job_types.JobType(
job_types.JobTypesManager(None), job_type1_dict)
TEST.job_types.add(job_types1)
| apache-2.0 | -7,523,586,367,454,752,000 | 35.372361 | 77 | 0.487916 | false |
irmen/Tale | setup.py | 1 | 3027 | """
Setup script for distutils
'Tale' mud driver, mudlib and interactive fiction framework
Copyright by Irmen de Jong ([email protected])
"""
import re
from setuptools import setup
with open("tale/__init__.py") as version_file:
# extract the VERSION definition from the tale package without importing it
version_line = next(line for line in version_file if line.startswith("__version__"))
tale_version = re.match(r"__version__\s?=\s?['\"](.+)['\"]", version_line).group(1)
print("version=" + tale_version)
setup(
name='tale',
version=tale_version,
url='http://tale.readthedocs.io/',
author='Irmen de Jong',
author_email='[email protected]',
license="LGPL3",
description='Interactive Fiction, MUD & mudlib framework',
long_description="""Tale is a framework for creating interactive fiction (text adventures), or MUDs (multi-user dungeons).
It's still being developed and new features are implement along the way,
but the current version is quite capable of running an interactive fiction story world.
Also the basics for a multi-user (MUD) server are working nicely.
An example test/demo story is included in the ``stories`` directory of the distribution archive.
This will require you to extract the source archive manually.
You can also run the tiny embedded test story like this, after you've installed the framework::
$ python -m tale.demo.story
The source code repository is on Github: https://github.com/irmen/Tale
""",
packages=['tale', 'tale.cmds', 'tale.items', 'tale.tio', 'tale.demo', 'tale.demo.zones', 'tale.web'],
package_data={
'tale': ['soul_adverbs.txt'],
'tale.tio': ['quill_pen_paper.ico', 'quill_pen_paper.gif'],
'tale.web': ['*']
},
include_package_data=True,
keywords="mud, mudlib, interactive fiction, text adventure",
scripts=["scripts/tale-run.cmd", "scripts/tale-run"],
platforms="any",
zip_safe=True,
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Communications :: Chat",
"Topic :: Games/Entertainment",
"Topic :: Games/Entertainment :: Role-Playing",
"Topic :: Games/Entertainment :: Multi-User Dungeons (MUD)"
],
install_requires=["appdirs", "colorama>=0.3.6", "smartypants>=1.8.6", "serpent>=1.23"],
setup_requires=["pytest-runner"],
tests_require=["pytest"],
options={"install": {"optimize": 0}},
test_suite="tests"
)
| lgpl-3.0 | 1,328,493,924,708,206,800 | 39.36 | 126 | 0.657086 | false |
ParthGanatra/mitmproxy | mitmproxy/flow_format_compat.py | 2 | 1814 | """
This module handles the import of mitmproxy flows generated by old versions.
"""
from __future__ import absolute_import, print_function, division
from . import version
def convert_013_014(data):
data["request"]["first_line_format"] = data["request"].pop("form_in")
data["request"]["http_version"] = "HTTP/" + ".".join(str(x) for x in data["request"].pop("httpversion"))
data["response"]["status_code"] = data["response"].pop("code")
data["response"]["body"] = data["response"].pop("content")
data["server_conn"].pop("state")
data["server_conn"]["via"] = None
data["version"] = (0, 14)
return data
def convert_014_015(data):
data["version"] = (0, 15)
return data
def convert_015_016(data):
for m in ("request", "response"):
if "body" in data[m]:
data[m]["content"] = data[m].pop("body")
if "httpversion" in data[m]:
data[m]["http_version"] = data[m].pop("httpversion")
if "msg" in data["response"]:
data["response"]["reason"] = data["response"].pop("msg")
data["request"].pop("form_out", None)
data["version"] = (0, 16)
return data
def convert_016_017(data):
data["version"] = (0, 17)
return data
converters = {
(0, 13): convert_013_014,
(0, 14): convert_014_015,
(0, 15): convert_015_016,
(0, 16): convert_016_017,
}
def migrate_flow(flow_data):
while True:
flow_version = tuple(flow_data["version"][:2])
if flow_version == version.IVERSION[:2]:
break
elif flow_version in converters:
flow_data = converters[flow_version](flow_data)
else:
v = ".".join(str(i) for i in flow_data["version"])
raise ValueError("Incompatible serialized data version: {}".format(v))
return flow_data
| mit | 9,159,714,350,214,749,000 | 29.233333 | 108 | 0.590959 | false |
tedlaz/pyted | pykoinoxrista/koinoxrista/hml_dapanes.py | 1 | 2568 | # -*- coding: utf-8 -*-
from pymiles.sqlite import db_select as dbs
import greek_str as gs
def html_dapanes(ida, dbf):
sql_koi = "SELECT * FROM koi WHERE id=%s" % ida
sql_koid = "SELECT * FROM koi_d WHERE koi_id=%s ORDER BY pdate" % ida
sql_ej = "SELECT * FROM ej ORDER BY id"
head = dbs.select(dbf, sql_koi)['rows'][0]
lines = dbs.select(dbf, sql_koid)['rows']
ej = dbs.select(dbf, sql_ej)['rows']
ht = u'<p><center><span style="font-size:14pt">'
ht += u'<b>ΚΟΙΝΟΧΡΗΣΤΕΣ ΔΑΠΑΝΕΣ (%s)</b></span></center></p>\n' % head['koip']
ht += u'Ημ/νία έκδοσης : %s\n' % gs.gr_date_str(head['kdat'])
ht += u'%s' % head['sxol']
ht += u'<table width="100%" border="0.5" cellpadding="4" cellspacing="0" style="font-size:10pt"><tbody>'
# Create Headers
ht += u'<tr>\n'
ht += u' <th>Ημ/νία</th>\n'
ht += u' <th>Παρ/κό</th>\n'
ht += u' <th>Περιγραφή</th>\n'
lej = len(ej)
arej = {}
ejt = {}
for i, el in enumerate(ej):
ht += u' <th>%s</th>\n' % el['ej']
arej[el['id']] = i
ejt[i] = 0
ht += u'</tr>\n'
# Fill lines
for line in lines:
ht += u'<tr>\n'
ht += ' <td>%s</td>\n' % gs.gr_date_str(line['pdate'])
ht += ' <td>%s</td>\n' % line['par']
ht += ' <td>%s</td>\n' % line['parp']
for el in range(lej):
if arej[line['ej_id']] == el:
ht += ' <td align="right">%s</td>\n' % gs.gr_num_str(line['poso'])
ejt[el] += line['poso']
else:
ht += ' <td></td>\n'
ht += u'</tr>\n'
# Create Footer
total = 0
ht += u'<tr>\n'
ht += u' <td colspan=3><center><b>Σύνολα</b></center></td>\n'
for el in range(lej):
ht += ' <td align="right"><b>%s</b></td>\n' % gs.gr_num_str(ejt[el])
total += ejt[el]
ht += u'</tr>\n'
ht += u'<tr>\n'
stotal = gs.gr_num_str(total)
ht += u' <td colspan=3><center><b>ΓΕΝΙΚΟ ΣΥΝΟΛΟ</b></center></td>\n'
ht += u' <td colspan=%s><center><b>%s</b></center></td>\n' % (lej, stotal)
ht += u'</tr>\n'
ht += '</tbody></table>\n'
return ht
if __name__ == '__main__':
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
from report_viewer import view_html_report
from html_katanomi import html_katanomi
num = 47
db = 'tst.sql3'
html_brake = '<p style="page-break-after:always;">'
h1 = html_dapanes(num, db)
h2 = html_katanomi(num, db)
view_html_report(h1+h2)
| gpl-3.0 | -657,954,688,774,943,400 | 31.467532 | 108 | 0.5048 | false |
ConPaaS-team/conpaas | conpaas-services/src/conpaas/services/helloworld/manager/manager.py | 1 | 4220 | from threading import Thread
from conpaas.core.expose import expose
from conpaas.core.manager import BaseManager
from conpaas.core.https.server import HttpJsonResponse, HttpErrorResponse
from conpaas.services.helloworld.agent import client
from conpaas.core.misc import check_arguments, is_in_list, is_not_in_list,\
is_list, is_non_empty_list, is_list_dict, is_list_dict2, is_string,\
is_int, is_pos_nul_int, is_pos_int, is_dict, is_dict2, is_bool,\
is_uploaded_file
class HelloWorldManager(BaseManager):
def __init__(self, config_parser, **kwargs):
BaseManager.__init__(self, config_parser)
self.state = self.S_INIT
def get_service_type(self):
return 'helloworld'
def get_context_replacement(self):
return dict(STRING='helloworld')
def on_start(self, nodes):
return self.on_new_nodes(nodes)
def on_stop(self):
self.logger.info("Removing nodes: %s" %[ node.id for node in self.nodes ])
return self.nodes[:]
def on_add_nodes(self, nodes):
return self.on_new_nodes(nodes)
def on_remove_nodes(self, node_roles):
count = sum(node_roles.values())
del_nodes = []
cp_nodes = self.nodes[:]
for _ in range(0, count):
node = cp_nodes.pop()
del_nodes += [ node ]
if not cp_nodes:
self.state = self.S_STOPPED
else:
self.state = self.S_RUNNING
self.logger.info("Removing nodes: %s" %[ node.id for node in del_nodes ])
return del_nodes
def on_new_nodes(self, nodes):
try:
for node in nodes:
client.startup(node.ip, self.AGENT_PORT)
return True
except Exception, err:
self.logger.exception('_do_startup: Failed to create node: %s' % err)
return False
@expose('GET')
def list_nodes(self, kwargs):
try:
exp_params = []
check_arguments(exp_params, kwargs)
except Exception as ex:
return HttpErrorResponse("%s" % ex)
try:
self.check_state([self.S_RUNNING, self.S_ADAPTING])
except:
return HttpJsonResponse({})
return HttpJsonResponse({
'helloworld': [ node.id for node in self.nodes ],
})
@expose('GET')
def get_service_info(self, kwargs):
try:
exp_params = []
check_arguments(exp_params, kwargs)
except Exception as ex:
return HttpErrorResponse("%s" % ex)
return HttpJsonResponse({'state': self.state_get(), 'type': 'helloworld'})
@expose('GET')
def get_node_info(self, kwargs):
node_ids = [ str(node.id) for node in self.nodes ]
exp_params = [('serviceNodeId', is_in_list(node_ids))]
try:
serviceNodeId = check_arguments(exp_params, kwargs)
except Exception as ex:
return HttpErrorResponse("%s" % ex)
for node in self.nodes:
if serviceNodeId == node.id:
serviceNode = node
break
return HttpJsonResponse({
'serviceNode': {
'id': serviceNode.id,
'ip': serviceNode.ip,
'vmid': serviceNode.vmid,
'cloud': serviceNode.cloud_name,
'role': serviceNode.role,
'logs': self.get_role_logs(serviceNode.role)
}
})
@expose('GET')
def get_helloworld(self, kwargs):
try:
exp_params = []
check_arguments(exp_params, kwargs)
self.check_state([self.S_RUNNING])
except Exception as ex:
return HttpErrorResponse("%s" % ex)
messages = []
# Just get_helloworld from all the agents
for node in self.nodes:
data = client.get_helloworld(node.ip, self.AGENT_PORT)
message = 'Received %s from %s' % (data['result'], node.id)
self.logger.info(message)
messages.append(message)
return HttpJsonResponse({ 'helloworld': "\n".join(messages) })
| bsd-3-clause | 8,140,809,065,478,551,000 | 31.21374 | 82 | 0.556635 | false |
confirm/ansibleci | ansibleci/tests/tag.py | 1 | 2631 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015 confirm IT solutions
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from ansibleci.test import Test
import os
class Tag(Test):
'''
Test to check if all tasks are tagged properly with the ``tags:`` parameter.
If the ``TAG_ROLE_NAME`` config flag is set to ``True``, the test will also
make sure that all tasks are tagged with the role's name.
'''
def run(self):
'''
Run method which will be called by the framework.
'''
config = self.get_config()
helper = self.get_helper()
for name, path in helper.get_roles().iteritems():
dir_path = os.path.join(path, 'tasks')
items = helper.get_yaml_items(dir_path)
for item in items:
kwargs = {
'task': helper.get_item_identifier(item),
'role': name
}
if 'tags' in item:
if config.TAG_ROLE_NAME:
tags = item['tags']
if (isinstance(tags, list) and name in tags) or tags == name:
self.passed('Task "{task}" in role {role} is tagged with the role name'.format(**kwargs))
else:
self.failed('Task "{task}" in role {role} is not tagged with the role name'.format(**kwargs))
else:
self.passed('Task "{task}" in role {role} is tagged'.format(**kwargs))
else:
self.failed('Task "{task}" in role {role} is untagged'.format(**kwargs))
| mit | 8,228,025,650,757,928,000 | 51.54 | 462 | 0.622002 | false |
vicky2135/lucious | oscar/lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py | 2 | 47618 | # -*- coding: utf-8 -*-
"""
sqldiff.py - Prints the (approximated) difference between models and database
TODO:
- better support for relations
- better support for constraints (mainly postgresql?)
- support for table spaces with postgresql
- when a table is not managed (meta.managed==False) then only do a one-way
sqldiff ? show differences from db->table but not the other way around since
it's not managed.
KNOWN ISSUES:
- MySQL has by far the most problems with introspection. Please be
carefull when using MySQL with sqldiff.
- Booleans are reported back as Integers, so there's no way to know if
there was a real change.
- Varchar sizes are reported back without unicode support so their size
may change in comparison to the real length of the varchar.
- Some of the 'fixes' to counter these problems might create false
positives or false negatives.
"""
import importlib
import sys
import six
from django.apps import apps
from django.core.management import BaseCommand, CommandError, sql as _sql
from django.core.management.base import OutputWrapper
from django.core.management.color import no_style
from django.db import connection, transaction
from django.db.models.fields import AutoField, IntegerField
from django_extensions.management.utils import signalcommand
ORDERING_FIELD = IntegerField('_order', null=True)
def flatten(l, ltypes=(list, tuple)):
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return ltype(l)
def all_local_fields(meta):
all_fields = []
if meta.proxy:
for parent in meta.parents:
all_fields.extend(all_local_fields(parent._meta))
else:
for f in meta.local_fields:
col_type = f.db_type(connection=connection)
if col_type is None:
continue
all_fields.append(f)
return all_fields
class SQLDiff(object):
DATA_TYPES_REVERSE_OVERRIDE = {}
IGNORE_MISSING_TABLES = [
"django_migrations",
]
DIFF_TYPES = [
'error',
'comment',
'table-missing-in-db',
'table-missing-in-model',
'field-missing-in-db',
'field-missing-in-model',
'fkey-missing-in-db',
'fkey-missing-in-model',
'index-missing-in-db',
'index-missing-in-model',
'unique-missing-in-db',
'unique-missing-in-model',
'field-type-differ',
'field-parameter-differ',
'notnull-differ',
]
DIFF_TEXTS = {
'error': 'error: %(0)s',
'comment': 'comment: %(0)s',
'table-missing-in-db': "table '%(0)s' missing in database",
'table-missing-in-model': "table '%(0)s' missing in models",
'field-missing-in-db': "field '%(1)s' defined in model but missing in database",
'field-missing-in-model': "field '%(1)s' defined in database but missing in model",
'fkey-missing-in-db': "field '%(1)s' FOREIGN KEY defined in model but missing in database",
'fkey-missing-in-model': "field '%(1)s' FOREIGN KEY defined in database but missing in model",
'index-missing-in-db': "field '%(1)s' INDEX defined in model but missing in database",
'index-missing-in-model': "field '%(1)s' INDEX defined in database schema but missing in model",
'unique-missing-in-db': "field '%(1)s' UNIQUE defined in model but missing in database",
'unique-missing-in-model': "field '%(1)s' UNIQUE defined in database schema but missing in model",
'field-type-differ': "field '%(1)s' not of same type: db='%(3)s', model='%(2)s'",
'field-parameter-differ': "field '%(1)s' parameters differ: db='%(3)s', model='%(2)s'",
'notnull-differ': "field '%(1)s' null constraint should be '%(2)s' in the database",
}
SQL_FIELD_MISSING_IN_DB = lambda self, style, qn, args: "%s %s\n\t%s %s %s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD('ADD COLUMN'), style.SQL_FIELD(qn(args[1])), ' '.join(style.SQL_COLTYPE(a) if i == 0 else style.SQL_KEYWORD(a) for i, a in enumerate(args[2:])))
SQL_FIELD_MISSING_IN_MODEL = lambda self, style, qn, args: "%s %s\n\t%s %s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD('DROP COLUMN'), style.SQL_FIELD(qn(args[1])))
SQL_FKEY_MISSING_IN_DB = lambda self, style, qn, args: "%s %s\n\t%s %s %s %s %s (%s)%s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD('ADD COLUMN'), style.SQL_FIELD(qn(args[1])), ' '.join(style.SQL_COLTYPE(a) if i == 0 else style.SQL_KEYWORD(a) for i, a in enumerate(args[4:])), style.SQL_KEYWORD('REFERENCES'), style.SQL_TABLE(qn(args[2])), style.SQL_FIELD(qn(args[3])), connection.ops.deferrable_sql())
SQL_INDEX_MISSING_IN_DB = lambda self, style, qn, args: "%s %s\n\t%s %s (%s%s);" % (style.SQL_KEYWORD('CREATE INDEX'), style.SQL_TABLE(qn("%s" % '_'.join(a for a in args[0:3] if a))), style.SQL_KEYWORD('ON'), style.SQL_TABLE(qn(args[0])), style.SQL_FIELD(qn(args[1])), style.SQL_KEYWORD(args[3]))
# FIXME: need to lookup index name instead of just appending _idx to table + fieldname
SQL_INDEX_MISSING_IN_MODEL = lambda self, style, qn, args: "%s %s;" % (style.SQL_KEYWORD('DROP INDEX'), style.SQL_TABLE(qn("%s" % '_'.join(a for a in args[0:3] if a))))
SQL_UNIQUE_MISSING_IN_DB = lambda self, style, qn, args: "%s %s\n\t%s %s (%s);" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD('ADD'), style.SQL_KEYWORD('UNIQUE'), style.SQL_FIELD(qn(args[1])))
# FIXME: need to lookup unique constraint name instead of appending _key to table + fieldname
SQL_UNIQUE_MISSING_IN_MODEL = lambda self, style, qn, args: "%s %s\n\t%s %s %s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD('DROP'), style.SQL_KEYWORD('CONSTRAINT'), style.SQL_TABLE(qn("%s_key" % ('_'.join(args[:2])))))
SQL_FIELD_TYPE_DIFFER = lambda self, style, qn, args: "%s %s\n\t%s %s %s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD("MODIFY"), style.SQL_FIELD(qn(args[1])), style.SQL_COLTYPE(args[2]))
SQL_FIELD_PARAMETER_DIFFER = lambda self, style, qn, args: "%s %s\n\t%s %s %s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD("MODIFY"), style.SQL_FIELD(qn(args[1])), style.SQL_COLTYPE(args[2]))
SQL_NOTNULL_DIFFER = lambda self, style, qn, args: "%s %s\n\t%s %s %s %s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD('MODIFY'), style.SQL_FIELD(qn(args[1])), style.SQL_KEYWORD(args[2]), style.SQL_KEYWORD('NOT NULL'))
SQL_ERROR = lambda self, style, qn, args: style.NOTICE('-- Error: %s' % style.ERROR(args[0]))
SQL_COMMENT = lambda self, style, qn, args: style.NOTICE('-- Comment: %s' % style.SQL_TABLE(args[0]))
SQL_TABLE_MISSING_IN_DB = lambda self, style, qn, args: style.NOTICE('-- Table missing: %s' % args[0])
SQL_TABLE_MISSING_IN_MODEL = lambda self, style, qn, args: style.NOTICE('-- Model missing for table: %s' % args[0])
can_detect_notnull_differ = False
can_detect_unsigned_differ = False
unsigned_suffix = None
def __init__(self, app_models, options):
self.has_differences = None
self.app_models = app_models
self.options = options
self.dense = options.get('dense_output', False)
try:
self.introspection = connection.introspection
except AttributeError:
from django.db import get_introspection_module
self.introspection = get_introspection_module()
self.cursor = connection.cursor()
self.django_tables = self.get_django_tables(options.get('only_existing', True))
# TODO: We are losing information about tables which are views here
self.db_tables = [table_info.name for table_info in self.introspection.get_table_list(self.cursor)]
self.differences = []
self.unknown_db_fields = {}
self.new_db_fields = set()
self.null = {}
self.unsigned = set()
self.DIFF_SQL = {
'error': self.SQL_ERROR,
'comment': self.SQL_COMMENT,
'table-missing-in-db': self.SQL_TABLE_MISSING_IN_DB,
'table-missing-in-model': self.SQL_TABLE_MISSING_IN_MODEL,
'field-missing-in-db': self.SQL_FIELD_MISSING_IN_DB,
'field-missing-in-model': self.SQL_FIELD_MISSING_IN_MODEL,
'fkey-missing-in-db': self.SQL_FKEY_MISSING_IN_DB,
'fkey-missing-in-model': self.SQL_FIELD_MISSING_IN_MODEL,
'index-missing-in-db': self.SQL_INDEX_MISSING_IN_DB,
'index-missing-in-model': self.SQL_INDEX_MISSING_IN_MODEL,
'unique-missing-in-db': self.SQL_UNIQUE_MISSING_IN_DB,
'unique-missing-in-model': self.SQL_UNIQUE_MISSING_IN_MODEL,
'field-type-differ': self.SQL_FIELD_TYPE_DIFFER,
'field-parameter-differ': self.SQL_FIELD_PARAMETER_DIFFER,
'notnull-differ': self.SQL_NOTNULL_DIFFER,
}
if self.can_detect_notnull_differ:
self.load_null()
if self.can_detect_unsigned_differ:
self.load_unsigned()
def load_null(self):
raise NotImplementedError("load_null functions must be implemented if diff backend has 'can_detect_notnull_differ' set to True")
def load_unsigned(self):
raise NotImplementedError("load_unsigned function must be implemented if diff backend has 'can_detect_unsigned_differ' set to True")
def add_app_model_marker(self, app_label, model_name):
self.differences.append((app_label, model_name, []))
def add_difference(self, diff_type, *args):
assert diff_type in self.DIFF_TYPES, 'Unknown difference type'
self.differences[-1][-1].append((diff_type, args))
def get_django_tables(self, only_existing):
try:
django_tables = self.introspection.django_table_names(only_existing=only_existing)
except AttributeError:
# backwards compatibility for before introspection refactoring (r8296)
try:
django_tables = _sql.django_table_names(only_existing=only_existing)
except AttributeError:
# backwards compatibility for before svn r7568
django_tables = _sql.django_table_list(only_existing=only_existing)
return django_tables
def sql_to_dict(self, query, param):
""" sql_to_dict(query, param) -> list of dicts
code from snippet at http://www.djangosnippets.org/snippets/1383/
"""
cursor = connection.cursor()
cursor.execute(query, param)
fieldnames = [name[0] for name in cursor.description]
result = []
for row in cursor.fetchall():
rowset = []
for field in zip(fieldnames, row):
rowset.append(field)
result.append(dict(rowset))
return result
def get_field_model_type(self, field):
return field.db_type(connection=connection)
def get_field_db_type(self, description, field=None, table_name=None):
from django.db import models
# DB-API cursor.description
# (name, type_code, display_size, internal_size, precision, scale, null_ok) = description
type_code = description[1]
if type_code in self.DATA_TYPES_REVERSE_OVERRIDE:
reverse_type = self.DATA_TYPES_REVERSE_OVERRIDE[type_code]
else:
try:
try:
reverse_type = self.introspection.data_types_reverse[type_code]
except AttributeError:
# backwards compatibility for before introspection refactoring (r8296)
reverse_type = self.introspection.DATA_TYPES_REVERSE.get(type_code)
except KeyError:
reverse_type = self.get_field_db_type_lookup(type_code)
if not reverse_type:
# type_code not found in data_types_reverse map
key = (self.differences[-1][:2], description[:2])
if key not in self.unknown_db_fields:
self.unknown_db_fields[key] = 1
self.add_difference('comment', "Unknown database type for field '%s' (%s)" % (description[0], type_code))
return None
kwargs = {}
if type_code == 16946 and field and getattr(field, 'geom_type', None) == 'POINT':
reverse_type = 'django.contrib.gis.db.models.fields.PointField'
if isinstance(reverse_type, tuple):
kwargs.update(reverse_type[1])
reverse_type = reverse_type[0]
if reverse_type == "CharField" and description[3]:
kwargs['max_length'] = description[3]
if reverse_type == "DecimalField":
kwargs['max_digits'] = description[4]
kwargs['decimal_places'] = description[5] and abs(description[5]) or description[5]
if description[6]:
kwargs['blank'] = True
if reverse_type not in ('TextField', 'CharField'):
kwargs['null'] = True
if field and getattr(field, 'geography', False):
kwargs['geography'] = True
if '.' in reverse_type:
module_path, package_name = reverse_type.rsplit('.', 1)
module = importlib.import_module(module_path)
field_db_type = getattr(module, package_name)(**kwargs).db_type(connection=connection)
else:
field_db_type = getattr(models, reverse_type)(**kwargs).db_type(connection=connection)
tablespace = field.db_tablespace
if not tablespace:
tablespace = "public"
if (tablespace, table_name, field.column) in self.unsigned:
field_db_type = '%s %s' % (field_db_type, self.unsigned_suffix)
return field_db_type
def get_field_db_type_lookup(self, type_code):
return None
def get_field_db_nullable(self, field, table_name):
tablespace = field.db_tablespace
if tablespace == "":
tablespace = "public"
attname = field.db_column or field.attname
return self.null.get((tablespace, table_name, attname), 'fixme')
def strip_parameters(self, field_type):
if field_type and field_type != 'double precision':
return field_type.split(" ")[0].split("(")[0].lower()
return field_type
def find_unique_missing_in_db(self, meta, table_indexes, table_constraints, table_name):
for field in all_local_fields(meta):
if field.unique and meta.managed:
attname = field.db_column or field.attname
db_field_unique = table_indexes.get(attname, {}).get('unique')
if not db_field_unique and table_constraints:
db_field_unique = any(constraint['unique'] for contraint_name, constraint in six.iteritems(table_constraints) if [attname] == constraint['columns'])
if attname in table_indexes and db_field_unique:
continue
self.add_difference('unique-missing-in-db', table_name, attname)
def find_unique_missing_in_model(self, meta, table_indexes, table_constraints, table_name):
# TODO: Postgresql does not list unique_togethers in table_indexes
# MySQL does
fields = dict([(field.db_column or field.name, field.unique) for field in all_local_fields(meta)])
for att_name, att_opts in six.iteritems(table_indexes):
db_field_unique = att_opts['unique']
if not db_field_unique and table_constraints:
db_field_unique = any(constraint['unique'] for contraint_name, constraint in six.iteritems(table_constraints) if att_name in constraint['columns'])
if db_field_unique and att_name in fields and not fields[att_name]:
if att_name in flatten(meta.unique_together):
continue
self.add_difference('unique-missing-in-model', table_name, att_name)
def find_index_missing_in_db(self, meta, table_indexes, table_constraints, table_name):
for field in all_local_fields(meta):
if field.db_index:
attname = field.db_column or field.attname
if attname not in table_indexes:
self.add_difference('index-missing-in-db', table_name, attname, '', '')
db_type = field.db_type(connection=connection)
if db_type.startswith('varchar'):
self.add_difference('index-missing-in-db', table_name, attname, 'like', ' varchar_pattern_ops')
if db_type.startswith('text'):
self.add_difference('index-missing-in-db', table_name, attname, 'like', ' text_pattern_ops')
def find_index_missing_in_model(self, meta, table_indexes, table_constraints, table_name):
fields = dict([(field.name, field) for field in all_local_fields(meta)])
for att_name, att_opts in six.iteritems(table_indexes):
if att_name in fields:
field = fields[att_name]
db_field_unique = att_opts['unique']
if not db_field_unique and table_constraints:
db_field_unique = any(constraint['unique'] for contraint_name, constraint in six.iteritems(table_constraints) if att_name in constraint['columns'])
if field.db_index:
continue
if getattr(field, 'spatial_index', False):
continue
if att_opts['primary_key'] and field.primary_key:
continue
if db_field_unique and field.unique:
continue
if db_field_unique and att_name in flatten(meta.unique_together):
continue
self.add_difference('index-missing-in-model', table_name, att_name)
db_type = field.db_type(connection=connection)
if db_type.startswith('varchar') or db_type.startswith('text'):
self.add_difference('index-missing-in-model', table_name, att_name, 'like')
def find_field_missing_in_model(self, fieldmap, table_description, table_name):
for row in table_description:
if row[0] not in fieldmap:
self.add_difference('field-missing-in-model', table_name, row[0])
def find_field_missing_in_db(self, fieldmap, table_description, table_name):
db_fields = [row[0] for row in table_description]
for field_name, field in six.iteritems(fieldmap):
if field_name not in db_fields:
field_output = []
if field.rel:
field_output.extend([field.rel.to._meta.db_table, field.rel.to._meta.get_field(field.rel.field_name).column])
op = 'fkey-missing-in-db'
else:
op = 'field-missing-in-db'
field_output.append(field.db_type(connection=connection))
if not field.null:
field_output.append('NOT NULL')
self.add_difference(op, table_name, field_name, *field_output)
self.new_db_fields.add((table_name, field_name))
def find_field_type_differ(self, meta, table_description, table_name, func=None):
db_fields = dict([(row[0], row) for row in table_description])
for field in all_local_fields(meta):
if field.name not in db_fields:
continue
description = db_fields[field.name]
model_type = self.get_field_model_type(field)
db_type = self.get_field_db_type(description, field, table_name)
# use callback function if defined
if func:
model_type, db_type = func(field, description, model_type, db_type)
if not self.strip_parameters(db_type) == self.strip_parameters(model_type):
self.add_difference('field-type-differ', table_name, field.name, model_type, db_type)
def find_field_parameter_differ(self, meta, table_description, table_name, func=None):
db_fields = dict([(row[0], row) for row in table_description])
for field in all_local_fields(meta):
if field.name not in db_fields:
continue
description = db_fields[field.name]
model_type = self.get_field_model_type(field)
db_type = self.get_field_db_type(description, field, table_name)
if not self.strip_parameters(model_type) == self.strip_parameters(db_type):
continue
# use callback function if defined
if func:
model_type, db_type = func(field, description, model_type, db_type)
model_check = field.db_parameters(connection=connection)['check']
if ' CHECK' in db_type:
db_type, db_check = db_type.split(" CHECK", 1)
db_check = db_check.strip().lstrip("(").rstrip(")")
else:
db_check = None
if not model_type == db_type and not model_check == db_check:
self.add_difference('field-parameter-differ', table_name, field.name, model_type, db_type)
def find_field_notnull_differ(self, meta, table_description, table_name):
if not self.can_detect_notnull_differ:
return
for field in all_local_fields(meta):
attname = field.db_column or field.attname
if (table_name, attname) in self.new_db_fields:
continue
null = self.get_field_db_nullable(field, table_name)
if field.null != null:
action = field.null and 'DROP' or 'SET'
self.add_difference('notnull-differ', table_name, attname, action)
def get_constraints(self, cursor, table_name, introspection):
return {}
def find_differences(self):
if self.options['all_applications']:
self.add_app_model_marker(None, None)
for table in self.db_tables:
if table not in self.django_tables and table not in self.IGNORE_MISSING_TABLES:
self.add_difference('table-missing-in-model', table)
cur_app_label = None
for app_model in self.app_models:
meta = app_model._meta
table_name = meta.db_table
app_label = meta.app_label
if self.options.get('include_proxy_models', False) and meta.proxy:
continue
if cur_app_label != app_label:
# Marker indicating start of difference scan for this table_name
self.add_app_model_marker(app_label, app_model.__name__)
if table_name not in self.db_tables:
# Table is missing from database
self.add_difference('table-missing-in-db', table_name)
continue
table_indexes = self.introspection.get_indexes(self.cursor, table_name)
if hasattr(self.introspection, 'get_constraints'):
table_constraints = self.introspection.get_constraints(self.cursor, table_name)
else:
table_constraints = self.get_constraints(self.cursor, table_name, self.introspection)
fieldmap = dict([(field.db_column or field.get_attname(), field) for field in all_local_fields(meta)])
# add ordering field if model uses order_with_respect_to
if meta.order_with_respect_to:
fieldmap['_order'] = ORDERING_FIELD
try:
table_description = self.introspection.get_table_description(self.cursor, table_name)
except Exception as e:
self.add_difference('error', 'unable to introspect table: %s' % str(e).strip())
transaction.rollback() # reset transaction
continue
# Fields which are defined in database but not in model
# 1) find: 'unique-missing-in-model'
self.find_unique_missing_in_model(meta, table_indexes, table_constraints, table_name)
# 2) find: 'index-missing-in-model'
self.find_index_missing_in_model(meta, table_indexes, table_constraints, table_name)
# 3) find: 'field-missing-in-model'
self.find_field_missing_in_model(fieldmap, table_description, table_name)
# Fields which are defined in models but not in database
# 4) find: 'field-missing-in-db'
self.find_field_missing_in_db(fieldmap, table_description, table_name)
# 5) find: 'unique-missing-in-db'
self.find_unique_missing_in_db(meta, table_indexes, table_constraints, table_name)
# 6) find: 'index-missing-in-db'
self.find_index_missing_in_db(meta, table_indexes, table_constraints, table_name)
# Fields which have a different type or parameters
# 7) find: 'type-differs'
self.find_field_type_differ(meta, table_description, table_name)
# 8) find: 'type-parameter-differs'
self.find_field_parameter_differ(meta, table_description, table_name)
# 9) find: 'field-notnull'
self.find_field_notnull_differ(meta, table_description, table_name)
self.has_differences = max([len(diffs) for _app_label, _model_name, diffs in self.differences])
def print_diff(self, style=no_style()):
""" print differences to stdout """
if self.options.get('sql', True):
self.print_diff_sql(style)
else:
self.print_diff_text(style)
def print_diff_text(self, style):
if not self.can_detect_notnull_differ:
print(style.NOTICE("# Detecting notnull changes not implemented for this database backend"))
print("")
if not self.can_detect_unsigned_differ:
print(style.NOTICE("# Detecting unsigned changes not implemented for this database backend"))
print("")
cur_app_label = None
for app_label, model_name, diffs in self.differences:
if not diffs:
continue
if not self.dense and app_label and cur_app_label != app_label:
print("%s %s" % (style.NOTICE("+ Application:"), style.SQL_TABLE(app_label)))
cur_app_label = app_label
if not self.dense and model_name:
print("%s %s" % (style.NOTICE("|-+ Differences for model:"), style.SQL_TABLE(model_name)))
for diff in diffs:
diff_type, diff_args = diff
text = self.DIFF_TEXTS[diff_type] % dict((str(i), style.SQL_TABLE(e)) for i, e in enumerate(diff_args))
text = "'".join(i % 2 == 0 and style.ERROR(e) or e for i, e in enumerate(text.split("'")))
if not self.dense:
print("%s %s" % (style.NOTICE("|--+"), text))
else:
if app_label:
print("%s %s %s %s %s" % (style.NOTICE("App"), style.SQL_TABLE(app_label), style.NOTICE('Model'), style.SQL_TABLE(model_name), text))
else:
print(text)
def print_diff_sql(self, style):
if not self.can_detect_notnull_differ:
print(style.NOTICE("-- Detecting notnull changes not implemented for this database backend"))
print("")
cur_app_label = None
qn = connection.ops.quote_name
if not self.has_differences:
if not self.dense:
print(style.SQL_KEYWORD("-- No differences"))
else:
print(style.SQL_KEYWORD("BEGIN;"))
for app_label, model_name, diffs in self.differences:
if not diffs:
continue
if not self.dense and cur_app_label != app_label:
print(style.NOTICE("-- Application: %s" % style.SQL_TABLE(app_label)))
cur_app_label = app_label
if not self.dense and model_name:
print(style.NOTICE("-- Model: %s" % style.SQL_TABLE(model_name)))
for diff in diffs:
diff_type, diff_args = diff
text = self.DIFF_SQL[diff_type](style, qn, diff_args)
if self.dense:
text = text.replace("\n\t", " ")
print(text)
print(style.SQL_KEYWORD("COMMIT;"))
class GenericSQLDiff(SQLDiff):
can_detect_notnull_differ = False
class MySQLDiff(SQLDiff):
can_detect_notnull_differ = True
can_detect_unsigned_differ = True
unsigned_suffix = 'UNSIGNED'
def __init__(self, app_models, options):
super(MySQLDiff, self).__init__(app_models, options)
self.auto_increment = set()
self.load_auto_increment()
def load_null(self):
tablespace = 'public'
for table_name in self.db_tables:
result = self.sql_to_dict("""
SELECT column_name, is_nullable
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = %s""", [table_name])
for table_info in result:
key = (tablespace, table_name, table_info['column_name'])
self.null[key] = table_info['is_nullable'] == 'YES'
def load_unsigned(self):
tablespace = 'public'
for table_name in self.db_tables:
result = self.sql_to_dict("""
SELECT column_name
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = %s
AND column_type LIKE '%%unsigned'""", [table_name])
for table_info in result:
key = (tablespace, table_name, table_info['column_name'])
self.unsigned.add(key)
def load_auto_increment(self):
for table_name in self.db_tables:
result = self.sql_to_dict("""
SELECT column_name
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = %s
AND extra = 'auto_increment'""", [table_name])
for table_info in result:
key = (table_name, table_info['column_name'])
self.auto_increment.add(key)
# All the MySQL hacks together create something of a problem
# Fixing one bug in MySQL creates another issue. So just keep in mind
# that this is way unreliable for MySQL atm.
def get_field_db_type(self, description, field=None, table_name=None):
from MySQLdb.constants import FIELD_TYPE
db_type = super(MySQLDiff, self).get_field_db_type(description, field, table_name)
if not db_type:
return
if field:
# MySQL isn't really sure about char's and varchar's like sqlite
field_type = self.get_field_model_type(field)
# Fix char/varchar inconsistencies
if self.strip_parameters(field_type) == 'char' and self.strip_parameters(db_type) == 'varchar':
db_type = db_type.lstrip("var")
# They like to call 'bool's 'tinyint(1)' and introspection makes that a integer
# just convert it back to it's proper type, a bool is a bool and nothing else.
if db_type == 'integer' and description[1] == FIELD_TYPE.TINY and description[4] == 1:
db_type = 'bool'
if (table_name, field.column) in self.auto_increment:
db_type += ' AUTO_INCREMENT'
return db_type
class SqliteSQLDiff(SQLDiff):
can_detect_notnull_differ = True
def load_null(self):
for table_name in self.db_tables:
# sqlite does not support tablespaces
tablespace = "public"
# index, column_name, column_type, nullable, default_value
# see: http://www.sqlite.org/pragma.html#pragma_table_info
for table_info in self.sql_to_dict("PRAGMA table_info(%s);" % table_name, []):
key = (tablespace, table_name, table_info['name'])
self.null[key] = not table_info['notnull']
# Unique does not seem to be implied on Sqlite for Primary_key's
# if this is more generic among databases this might be usefull
# to add to the superclass's find_unique_missing_in_db method
def find_unique_missing_in_db(self, meta, table_indexes, table_constraints, table_name):
for field in all_local_fields(meta):
if field.unique:
attname = field.db_column or field.attname
if attname in table_indexes and table_indexes[attname]['unique']:
continue
if attname in table_indexes and table_indexes[attname]['primary_key']:
continue
self.add_difference('unique-missing-in-db', table_name, attname)
# Finding Indexes by using the get_indexes dictionary doesn't seem to work
# for sqlite.
def find_index_missing_in_db(self, meta, table_indexes, table_constraints, table_name):
pass
def find_index_missing_in_model(self, meta, table_indexes, table_constraints, table_name):
pass
def get_field_db_type(self, description, field=None, table_name=None):
db_type = super(SqliteSQLDiff, self).get_field_db_type(description, field, table_name)
if not db_type:
return
if field:
field_type = self.get_field_model_type(field)
# Fix char/varchar inconsistencies
if self.strip_parameters(field_type) == 'char' and self.strip_parameters(db_type) == 'varchar':
db_type = db_type.lstrip("var")
return db_type
class PostgresqlSQLDiff(SQLDiff):
can_detect_notnull_differ = True
can_detect_unsigned_differ = True
DATA_TYPES_REVERSE_OVERRIDE = {
1042: 'CharField',
# postgis types (TODO: support is very incomplete)
17506: 'django.contrib.gis.db.models.fields.PointField',
16392: 'django.contrib.gis.db.models.fields.PointField',
55902: 'django.contrib.gis.db.models.fields.MultiPolygonField',
16946: 'django.contrib.gis.db.models.fields.MultiPolygonField'
}
DATA_TYPES_REVERSE_NAME = {
'hstore': 'django_hstore.hstore.DictionaryField',
}
# Hopefully in the future we can add constraint checking and other more
# advanced checks based on this database.
SQL_LOAD_CONSTRAINTS = """
SELECT nspname, relname, conname, attname, pg_get_constraintdef(pg_constraint.oid)
FROM pg_constraint
INNER JOIN pg_attribute ON pg_constraint.conrelid = pg_attribute.attrelid AND pg_attribute.attnum = any(pg_constraint.conkey)
INNER JOIN pg_class ON conrelid=pg_class.oid
INNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace
ORDER BY CASE WHEN contype='f' THEN 0 ELSE 1 END,contype,nspname,relname,conname;
"""
SQL_LOAD_NULL = """
SELECT nspname, relname, attname, attnotnull
FROM pg_attribute
INNER JOIN pg_class ON attrelid=pg_class.oid
INNER JOIN pg_namespace ON pg_namespace.oid=pg_class.relnamespace;
"""
SQL_FIELD_TYPE_DIFFER = lambda self, style, qn, args: "%s %s\n\t%s %s %s %s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD('ALTER'), style.SQL_FIELD(qn(args[1])), style.SQL_KEYWORD("TYPE"), style.SQL_COLTYPE(args[2]))
SQL_FIELD_PARAMETER_DIFFER = lambda self, style, qn, args: "%s %s\n\t%s %s %s %s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD('ALTER'), style.SQL_FIELD(qn(args[1])), style.SQL_KEYWORD("TYPE"), style.SQL_COLTYPE(args[2]))
SQL_NOTNULL_DIFFER = lambda self, style, qn, args: "%s %s\n\t%s %s %s %s;" % (style.SQL_KEYWORD('ALTER TABLE'), style.SQL_TABLE(qn(args[0])), style.SQL_KEYWORD('ALTER COLUMN'), style.SQL_FIELD(qn(args[1])), style.SQL_KEYWORD(args[2]), style.SQL_KEYWORD('NOT NULL'))
def __init__(self, app_models, options):
super(PostgresqlSQLDiff, self).__init__(app_models, options)
self.check_constraints = {}
self.load_constraints()
def load_null(self):
for dct in self.sql_to_dict(self.SQL_LOAD_NULL, []):
key = (dct['nspname'], dct['relname'], dct['attname'])
self.null[key] = not dct['attnotnull']
def load_unsigned(self):
# PostgreSQL does not support unsigned, so no columns are
# unsigned. Nothing to do.
pass
def load_constraints(self):
for dct in self.sql_to_dict(self.SQL_LOAD_CONSTRAINTS, []):
key = (dct['nspname'], dct['relname'], dct['attname'])
if 'CHECK' in dct['pg_get_constraintdef']:
self.check_constraints[key] = dct
def get_constraints(self, cursor, table_name, introspection):
""" backport of django's introspection.get_constraints(...) """
constraints = {}
# Loop over the key table, collecting things as constraints
# This will get PKs, FKs, and uniques, but not CHECK
cursor.execute("""
SELECT
kc.constraint_name,
kc.column_name,
c.constraint_type,
array(SELECT table_name::text || '.' || column_name::text FROM information_schema.constraint_column_usage WHERE constraint_name = kc.constraint_name)
FROM information_schema.key_column_usage AS kc
JOIN information_schema.table_constraints AS c ON
kc.table_schema = c.table_schema AND
kc.table_name = c.table_name AND
kc.constraint_name = c.constraint_name
WHERE
kc.table_schema = %s AND
kc.table_name = %s
""", ["public", table_name])
for constraint, column, kind, used_cols in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": kind.lower() == "primary key",
"unique": kind.lower() in ["primary key", "unique"],
"foreign_key": tuple(used_cols[0].split(".", 1)) if kind.lower() == "foreign key" else None,
"check": False,
"index": False,
}
# Record the details
constraints[constraint]['columns'].append(column)
# Now get CHECK constraint columns
cursor.execute("""
SELECT kc.constraint_name, kc.column_name
FROM information_schema.constraint_column_usage AS kc
JOIN information_schema.table_constraints AS c ON
kc.table_schema = c.table_schema AND
kc.table_name = c.table_name AND
kc.constraint_name = c.constraint_name
WHERE
c.constraint_type = 'CHECK' AND
kc.table_schema = %s AND
kc.table_name = %s
""", ["public", table_name])
for constraint, column in cursor.fetchall():
# If we're the first column, make the record
if constraint not in constraints:
constraints[constraint] = {
"columns": [],
"primary_key": False,
"unique": False,
"foreign_key": None,
"check": True,
"index": False,
}
# Record the details
constraints[constraint]['columns'].append(column)
# Now get indexes
cursor.execute("""
SELECT
c2.relname,
ARRAY(
SELECT (SELECT attname FROM pg_catalog.pg_attribute WHERE attnum = i AND attrelid = c.oid)
FROM unnest(idx.indkey) i
),
idx.indisunique,
idx.indisprimary
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2,
pg_catalog.pg_index idx
WHERE c.oid = idx.indrelid
AND idx.indexrelid = c2.oid
AND c.relname = %s
""", [table_name])
for index, columns, unique, primary in cursor.fetchall():
if index not in constraints:
constraints[index] = {
"columns": list(columns),
"primary_key": primary,
"unique": unique,
"foreign_key": None,
"check": False,
"index": True,
}
return constraints
def get_field_db_type(self, description, field=None, table_name=None):
db_type = super(PostgresqlSQLDiff, self).get_field_db_type(description, field, table_name)
if not db_type:
return
if field:
if field.primary_key and isinstance(field, AutoField):
if db_type == 'integer':
db_type = 'serial'
elif db_type == 'bigint':
db_type = 'bigserial'
if table_name:
tablespace = field.db_tablespace
if tablespace == "":
tablespace = "public"
attname = field.db_column or field.attname
check_constraint = self.check_constraints.get((tablespace, table_name, attname), {}).get('pg_get_constraintdef', None)
if check_constraint:
check_constraint = check_constraint.replace("((", "(")
check_constraint = check_constraint.replace("))", ")")
check_constraint = '("'.join([')' in e and '" '.join(p.strip('"') for p in e.split(" ", 1)) or e for e in check_constraint.split("(")])
# TODO: might be more then one constraint in definition ?
db_type += ' ' + check_constraint
return db_type
def get_field_db_type_lookup(self, type_code):
try:
name = self.sql_to_dict("SELECT typname FROM pg_type WHERE typelem=%s;", [type_code])[0]['typname']
return self.DATA_TYPES_REVERSE_NAME.get(name.strip('_'))
except (IndexError, KeyError):
pass
"""
def find_field_type_differ(self, meta, table_description, table_name):
def callback(field, description, model_type, db_type):
if field.primary_key and db_type=='integer':
db_type = 'serial'
return model_type, db_type
super(PostgresqlSQLDiff, self).find_field_type_differ(meta, table_description, table_name, callback)
"""
DATABASE_SQLDIFF_CLASSES = {
'postgis': PostgresqlSQLDiff,
'postgresql_psycopg2': PostgresqlSQLDiff,
'postgresql': PostgresqlSQLDiff,
'mysql': MySQLDiff,
'sqlite3': SqliteSQLDiff,
'oracle': GenericSQLDiff
}
class Command(BaseCommand):
help = """Prints the (approximated) difference between models and fields in the database for the given app name(s).
It indicates how columns in the database are different from the sql that would
be generated by Django. This command is not a database migration tool. (Though
it can certainly help) It's purpose is to show the current differences as a way
to check/debug ur models compared to the real database tables and columns."""
output_transaction = False
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument('app_label', nargs='*')
parser.add_argument(
'--all-applications', '-a', action='store_true',
dest='all_applications',
help="Automaticly include all application from INSTALLED_APPS.")
parser.add_argument(
'--not-only-existing', '-e', action='store_false',
dest='only_existing',
help="Check all tables that exist in the database, not only "
"tables that should exist based on models.")
parser.add_argument(
'--dense-output', '-d', action='store_true', dest='dense_output',
help="Shows the output in dense format, normally output is "
"spreaded over multiple lines.")
parser.add_argument(
'--output_text', '-t', action='store_false', dest='sql',
default=True,
help="Outputs the differences as descriptive text instead of SQL")
parser.add_argument(
'--include-proxy-models', action='store_true', dest='include_proxy_models',
default=False,
help="Include proxy models in the graph")
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
self.exit_code = 1
@signalcommand
def handle(self, *args, **options):
from django.conf import settings
app_labels = options.get('app_label')
engine = None
if hasattr(settings, 'DATABASES'):
engine = settings.DATABASES['default']['ENGINE']
else:
engine = settings.DATABASE_ENGINE
if engine == 'dummy':
# This must be the "dummy" database backend, which means the user
# hasn't set DATABASE_ENGINE.
raise CommandError("""Django doesn't know which syntax to use for your SQL statements,
because you haven't specified the DATABASE_ENGINE setting.
Edit your settings file and change DATABASE_ENGINE to something like 'postgresql' or 'mysql'.""")
if options.get('all_applications', False):
app_models = apps.get_models(include_auto_created=True)
else:
if not app_labels:
raise CommandError('Enter at least one appname.')
if not isinstance(app_labels, (list, tuple, set)):
app_labels = [app_labels]
app_models = []
for app_label in app_labels:
app_config = apps.get_app_config(app_label)
app_models.extend(app_config.get_models(include_auto_created=True))
if not app_models:
raise CommandError('Unable to execute sqldiff no models founds.')
if not engine:
engine = connection.__module__.split('.')[-2]
if '.' in engine:
engine = engine.split('.')[-1]
cls = DATABASE_SQLDIFF_CLASSES.get(engine, GenericSQLDiff)
sqldiff_instance = cls(app_models, options)
sqldiff_instance.find_differences()
if not sqldiff_instance.has_differences:
self.exit_code = 0
sqldiff_instance.print_diff(self.style)
def execute(self, *args, **options):
try:
super(Command, self).execute(*args, **options)
except CommandError as e:
if options.get('traceback', False):
raise
# self.stderr is not guaranteed to be set here
stderr = getattr(self, 'stderr', None)
if not stderr:
stderr = OutputWrapper(sys.stderr, self.style.ERROR)
stderr.write('%s: %s' % (e.__class__.__name__, e))
sys.exit(2)
def run_from_argv(self, argv):
super(Command, self).run_from_argv(argv)
sys.exit(self.exit_code)
| bsd-3-clause | -3,176,328,924,806,518,300 | 46.905433 | 448 | 0.593536 | false |
ningchi/scikit-learn | sklearn/neighbors/approximate.py | 9 | 22278 | """Approximate nearest neighbor search"""
# Author: Maheshakya Wijewardena <[email protected]>
# Joel Nothman <[email protected]>
import numpy as np
import warnings
from scipy import sparse
from .base import KNeighborsMixin, RadiusNeighborsMixin
from ..base import BaseEstimator
from ..utils.validation import check_array
from ..utils import check_random_state
from ..metrics.pairwise import pairwise_distances
from ..random_projection import GaussianRandomProjection
__all__ = ["LSHForest"]
HASH_DTYPE = '>u4'
MAX_HASH_SIZE = np.dtype(HASH_DTYPE).itemsize * 8
def _find_matching_indices(tree, bin_X, left_mask, right_mask):
"""Finds indices in sorted array of integers.
Most significant h bits in the binary representations of the
integers are matched with the items' most significant h bits.
"""
left_index = np.searchsorted(tree, bin_X & left_mask)
right_index = np.searchsorted(tree, bin_X | right_mask,
side='right')
return left_index, right_index
def _find_longest_prefix_match(tree, bin_X, hash_size,
left_masks, right_masks):
"""Find the longest prefix match in tree for each query in bin_X
Most significant bits are considered as the prefix.
"""
hi = np.empty_like(bin_X, dtype=np.intp)
hi.fill(hash_size)
lo = np.zeros_like(bin_X, dtype=np.intp)
res = np.empty_like(bin_X, dtype=np.intp)
left_idx, right_idx = _find_matching_indices(tree, bin_X,
left_masks[hi],
right_masks[hi])
found = right_idx > left_idx
res[found] = lo[found] = hash_size
r = np.arange(bin_X.shape[0])
kept = r[lo < hi] # indices remaining in bin_X mask
while kept.shape[0]:
mid = (lo.take(kept) + hi.take(kept)) // 2
left_idx, right_idx = _find_matching_indices(tree,
bin_X.take(kept),
left_masks[mid],
right_masks[mid])
found = right_idx > left_idx
mid_found = mid[found]
lo[kept[found]] = mid_found + 1
res[kept[found]] = mid_found
hi[kept[~found]] = mid[~found]
kept = r[lo < hi]
return res
class ProjectionToHashMixin(object):
"""Turn a transformed real-valued array into a hash"""
@staticmethod
def _to_hash(projected):
if projected.shape[1] % 8 != 0:
raise ValueError('Require reduced dimensionality to be a multiple '
'of 8 for hashing')
# XXX: perhaps non-copying operation better
out = np.packbits((projected > 0).astype(int)).view(dtype=HASH_DTYPE)
return out.reshape(projected.shape[0], -1)
def fit_transform(self, X, y=None):
self.fit(X)
return self.transform(X)
def transform(self, X, y=None):
return self._to_hash(super(ProjectionToHashMixin, self).transform(X))
class GaussianRandomProjectionHash(ProjectionToHashMixin,
GaussianRandomProjection):
"""Use GaussianRandomProjection to produce a cosine LSH fingerprint"""
def __init__(self,
n_components=8,
random_state=None):
super(GaussianRandomProjectionHash, self).__init__(
n_components=n_components,
random_state=random_state)
def _array_of_arrays(list_of_arrays):
"""Creates an array of array from list of arrays."""
out = np.empty(len(list_of_arrays), dtype=object)
out[:] = list_of_arrays
return out
class LSHForest(BaseEstimator, KNeighborsMixin, RadiusNeighborsMixin):
"""Performs approximate nearest neighbor search using LSH forest.
LSH Forest: Locality Sensitive Hashing forest [1] is an alternative
method for vanilla approximate nearest neighbor search methods.
LSH forest data structure has been implemented using sorted
arrays and binary search and 32 bit fixed-length hashes.
Random projection is used as the hash family which approximates
cosine distance.
The cosine distance is defined as ``1 - cosine_similarity``: the lowest
value is 0 (identical point) but it is bounded above by 2 for the farthest
points. Its value does not depend on the norm of the vector points but
only on their relative angles.
Parameters
----------
n_estimators : int (default = 10)
Number of trees in the LSH Forest.
min_hash_match : int (default = 4)
lowest hash length to be searched when candidate selection is
performed for nearest neighbors.
n_candidates : int (default = 10)
Minimum number of candidates evaluated per estimator, assuming enough
items meet the `min_hash_match` constraint.
n_neighbors : int (default = 5)
Number of neighbors to be returned from query function when
it is not provided to the :meth:`kneighbors` method.
radius : float, optinal (default = 1.0)
Radius from the data point to its neighbors. This is the parameter
space to use by default for the :meth`radius_neighbors` queries.
radius_cutoff_ratio : float, optional (default = 0.9)
A value ranges from 0 to 1. Radius neighbors will be searched until
the ratio between total neighbors within the radius and the total
candidates becomes less than this value unless it is terminated by
hash length reaching `min_hash_match`.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by `np.random`.
Attributes
----------
hash_functions_ : list of GaussianRandomProjectionHash objects
Hash function g(p,x) for a tree is an array of 32 randomly generated
float arrays with the same dimenstion as the data set. This array is
stored in GaussianRandomProjectionHash object and can be obtained
from ``components_`` attribute.
trees_ : array, shape (n_estimators, n_samples)
Each tree (corresponding to a hash function) contains an array of
sorted hashed values. The array representation may change in future
versions.
original_indices_ : array, shape (n_estimators, n_samples)
Original indices of sorted hashed values in the fitted index.
References
----------
.. [1] M. Bawa, T. Condie and P. Ganesan, "LSH Forest: Self-Tuning
Indexes for Similarity Search", WWW '05 Proceedings of the
14th international conference on World Wide Web, 651-660,
2005.
Examples
--------
>>> from sklearn.neighbors import LSHForest
>>> X_train = [[5, 5, 2], [21, 5, 5], [1, 1, 1], [8, 9, 1], [6, 10, 2]]
>>> X_test = [[9, 1, 6], [3, 1, 10], [7, 10, 3]]
>>> lshf = LSHForest()
>>> lshf.fit(X_train) # doctest: +NORMALIZE_WHITESPACE
LSHForest(min_hash_match=4, n_candidates=50, n_estimators=10,
n_neighbors=5, radius=1.0, radius_cutoff_ratio=0.9,
random_state=None)
>>> distances, indices = lshf.kneighbors(X_test, n_neighbors=2)
>>> distances # doctest: +ELLIPSIS
array([[ 0.069..., 0.149...],
[ 0.229..., 0.481...],
[ 0.004..., 0.014...]])
>>> indices
array([[1, 2],
[2, 0],
[4, 0]])
"""
def __init__(self, n_estimators=10, radius=1.0, n_candidates=50,
n_neighbors=5, min_hash_match=4, radius_cutoff_ratio=.9,
random_state=None):
self.n_estimators = n_estimators
self.radius = radius
self.random_state = random_state
self.n_candidates = n_candidates
self.n_neighbors = n_neighbors
self.min_hash_match = min_hash_match
self.radius_cutoff_ratio = radius_cutoff_ratio
def _compute_distances(self, query, candidates):
"""Computes the cosine distance.
Distance is from the query to points in the candidates array.
Returns argsort of distances in the candidates
array and sorted distances.
"""
if candidates.shape == (0,):
# needed since _fit_X[np.array([])] doesn't work if _fit_X sparse
return np.empty(0, dtype=np.int), np.empty(0, dtype=float)
if sparse.issparse(self._fit_X):
candidate_X = self._fit_X[candidates]
else:
candidate_X = self._fit_X.take(candidates, axis=0, mode='clip')
distances = pairwise_distances(query, candidate_X,
metric='cosine')[0]
distance_positions = np.argsort(distances)
distances = distances.take(distance_positions, mode='clip', axis=0)
return distance_positions, distances
def _generate_masks(self):
"""Creates left and right masks for all hash lengths."""
tri_size = MAX_HASH_SIZE + 1
# Called once on fitting, output is independent of hashes
left_mask = np.tril(np.ones((tri_size, tri_size), dtype=int))[:, 1:]
right_mask = left_mask[::-1, ::-1]
self._left_mask = np.packbits(left_mask).view(dtype=HASH_DTYPE)
self._right_mask = np.packbits(right_mask).view(dtype=HASH_DTYPE)
def _get_candidates(self, query, max_depth, bin_queries, n_neighbors):
"""Performs the Synchronous ascending phase.
Returns an array of candidates, their distance ranks and
distances.
"""
index_size = self._fit_X.shape[0]
# Number of candidates considered including duplicates
# XXX: not sure whether this is being calculated correctly wrt
# duplicates from different iterations through a single tree
n_candidates = 0
candidate_set = set()
min_candidates = self.n_candidates * self.n_estimators
while (max_depth > self.min_hash_match and
(n_candidates < min_candidates or
len(candidate_set) < n_neighbors)):
left_mask = self._left_mask[max_depth]
right_mask = self._right_mask[max_depth]
for i in range(self.n_estimators):
start, stop = _find_matching_indices(self.trees_[i],
bin_queries[i],
left_mask, right_mask)
n_candidates += stop - start
candidate_set.update(
self.original_indices_[i][start:stop].tolist())
max_depth -= 1
candidates = np.fromiter(candidate_set, count=len(candidate_set),
dtype=np.intp)
# For insufficient candidates, candidates are filled.
# Candidates are filled from unselected indices uniformly.
if candidates.shape[0] < n_neighbors:
warnings.warn(
"Number of candidates is not sufficient to retrieve"
" %i neighbors with"
" min_hash_match = %i. Candidates are filled up"
" uniformly from unselected"
" indices." % (n_neighbors, self.min_hash_match))
remaining = np.setdiff1d(np.arange(0, index_size), candidates)
to_fill = n_neighbors - candidates.shape[0]
candidates = np.concatenate((candidates, remaining[:to_fill]))
ranks, distances = self._compute_distances(query,
candidates.astype(int))
return (candidates[ranks[:n_neighbors]],
distances[:n_neighbors])
def _get_radius_neighbors(self, query, max_depth, bin_queries, radius):
"""Finds radius neighbors from the candidates obtained.
Their distances from query are smaller than radius.
Returns radius neighbors and distances.
"""
ratio_within_radius = 1
threshold = 1 - self.radius_cutoff_ratio
total_candidates = np.array([], dtype=int)
total_neighbors = np.array([], dtype=int)
total_distances = np.array([], dtype=float)
while (max_depth > self.min_hash_match and
ratio_within_radius > threshold):
left_mask = self._left_mask[max_depth]
right_mask = self._right_mask[max_depth]
candidates = []
for i in range(self.n_estimators):
start, stop = _find_matching_indices(self.trees_[i],
bin_queries[i],
left_mask, right_mask)
candidates.extend(
self.original_indices_[i][start:stop].tolist())
candidates = np.setdiff1d(candidates, total_candidates)
total_candidates = np.append(total_candidates, candidates)
ranks, distances = self._compute_distances(query, candidates)
m = np.searchsorted(distances, radius, side='right')
positions = np.searchsorted(total_distances, distances[:m])
total_neighbors = np.insert(total_neighbors, positions,
candidates[ranks[:m]])
total_distances = np.insert(total_distances, positions,
distances[:m])
ratio_within_radius = (total_neighbors.shape[0] /
float(total_candidates.shape[0]))
max_depth = max_depth - 1
return total_neighbors, total_distances
def fit(self, X, y=None):
"""Fit the LSH forest on the data.
This creates binary hashes of input data points by getting the
dot product of input points and hash_function then
transforming the projection into a binary string array based
on the sign (positive/negative) of the projection.
A sorted array of binary hashes is created.
Parameters
----------
X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
Returns
-------
self : object
Returns self.
"""
self._fit_X = check_array(X, accept_sparse='csr')
# Creates a g(p,x) for each tree
self.hash_functions_ = []
self.trees_ = []
self.original_indices_ = []
rng = check_random_state(self.random_state)
int_max = np.iinfo(np.int32).max
for i in range(self.n_estimators):
# This is g(p,x) for a particular tree.
# Builds a single tree. Hashing is done on an array of data points.
# `GaussianRandomProjection` is used for hashing.
# `n_components=hash size and n_features=n_dim.
hasher = GaussianRandomProjectionHash(MAX_HASH_SIZE,
rng.randint(0, int_max))
hashes = hasher.fit_transform(self._fit_X)[:, 0]
original_index = np.argsort(hashes)
bin_hashes = hashes[original_index]
self.original_indices_.append(original_index)
self.trees_.append(bin_hashes)
self.hash_functions_.append(hasher)
self._generate_masks()
return self
def _query(self, X):
"""Performs descending phase to find maximum depth."""
# Calculate hashes of shape (n_samples, n_estimators, [hash_size])
bin_queries = np.asarray([hasher.transform(X)[:, 0]
for hasher in self.hash_functions_])
bin_queries = np.rollaxis(bin_queries, 1)
# descend phase
depths = [_find_longest_prefix_match(tree, tree_queries, MAX_HASH_SIZE,
self._left_mask, self._right_mask)
for tree, tree_queries in zip(self.trees_,
np.rollaxis(bin_queries, 1))]
return bin_queries, np.max(depths, axis=0)
def kneighbors(self, X, n_neighbors=None, return_distance=True):
"""Returns n_neighbors of approximate nearest neighbors.
Parameters
----------
X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single query.
n_neighbors : int, opitonal (default = None)
Number of neighbors required. If not provided, this will
return the number specified at the initialization.
return_distance : boolean, optional (default = False)
Returns the distances of neighbors if set to True.
Returns
-------
dist : array, shape (n_samples, n_neighbors)
Array representing the cosine distances to each point,
only present if return_distance=True.
ind : array, shape (n_samples, n_neighbors)
Indices of the approximate nearest points in the population
matrix.
"""
if not hasattr(self, 'hash_functions_'):
raise ValueError("estimator should be fitted.")
if n_neighbors is None:
n_neighbors = self.n_neighbors
X = check_array(X, accept_sparse='csr')
neighbors, distances = [], []
bin_queries, max_depth = self._query(X)
for i in range(X.shape[0]):
neighs, dists = self._get_candidates(X[i], max_depth[i],
bin_queries[i],
n_neighbors)
neighbors.append(neighs)
distances.append(dists)
if return_distance:
return np.array(distances), np.array(neighbors)
else:
return np.array(neighbors)
def radius_neighbors(self, X, radius=None, return_distance=True):
"""Finds the neighbors within a given radius of a point or points.
Return the indices and distances of some points from the dataset
lying in a ball with size ``radius`` around the points of the query
array. Points lying on the boundary are included in the results.
The result points are *not* necessarily sorted by distance to their
query point.
LSH Forest being an approximate method, some true neighbors from the
indexed dataset might be missing from the results.
Parameters
----------
X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single query.
radius : float
Limiting distance of neighbors to return.
(default is the value passed to the constructor).
return_distance : boolean, optional (default = False)
Returns the distances of neighbors if set to True.
Returns
-------
dist : array, shape (n_samples,) of arrays
Each element is an array representing the cosine distances
to some points found within ``radius`` of the respective query.
Only present if ``return_distance=True``.
ind : array, shape (n_samples,) of arrays
Each element is an array of indices for neighbors within ``radius``
of the respective query.
"""
if not hasattr(self, 'hash_functions_'):
raise ValueError("estimator should be fitted.")
if radius is None:
radius = self.radius
X = check_array(X, accept_sparse='csr')
neighbors, distances = [], []
bin_queries, max_depth = self._query(X)
for i in range(X.shape[0]):
neighs, dists = self._get_radius_neighbors(X[i], max_depth[i],
bin_queries[i], radius)
neighbors.append(neighs)
distances.append(dists)
if return_distance:
return _array_of_arrays(distances), _array_of_arrays(neighbors)
else:
return _array_of_arrays(neighbors)
def partial_fit(self, X, y=None):
"""
Inserts new data into the already fitted LSH Forest.
Cost is proportional to new total size, so additions
should be batched.
Parameters
----------
X : array_like or sparse (CSR) matrix, shape (n_samples, n_features)
New data point to be inserted into the LSH Forest.
"""
X = check_array(X, accept_sparse='csr')
if not hasattr(self, 'hash_functions_'):
return self.fit(X)
if X.shape[1] != self._fit_X.shape[1]:
raise ValueError("Number of features in X and"
" fitted array does not match.")
n_samples = X.shape[0]
n_indexed = self._fit_X.shape[0]
for i in range(self.n_estimators):
bin_X = self.hash_functions_[i].transform(X)[:, 0]
# gets the position to be added in the tree.
positions = self.trees_[i].searchsorted(bin_X)
# adds the hashed value into the tree.
self.trees_[i] = np.insert(self.trees_[i],
positions, bin_X)
# add the entry into the original_indices_.
self.original_indices_[i] = np.insert(self.original_indices_[i],
positions,
np.arange(n_indexed,
n_indexed +
n_samples))
# adds the entry into the input_array.
if sparse.issparse(X) or sparse.issparse(self._fit_X):
self._fit_X = sparse.vstack((self._fit_X, X))
else:
self._fit_X = np.row_stack((self._fit_X, X))
return self
| bsd-3-clause | -7,452,445,684,876,584,000 | 39.802198 | 79 | 0.579091 | false |
danieldmm/minerva | scripts/postprocess_features.py | 1 | 1813 | from models.keyword_features import FeaturesReader, getAnnotationListsForContext, tokenWeight, getRootDir
import os
import gzip
import json
from tqdm import tqdm
def getOneContextFeatures(context):
"""
Prepares a single context's data for any nn. Takes ["token_features"] from list
of sentences and returns a single list of token features.
"""
all_keywords = {t[0]: tokenWeight(t) for t in context["best_kws"]}
featureset = getAnnotationListsForContext(context["tokens"], all_keywords)
tokens, to_extract, weights = zip(*featureset)
max_weight = max(weights)
if max_weight > 0:
weights = [w / max_weight for w in weights]
context["extract_mask"] = to_extract
context["tokens"] = tokens
context["weight_mask"] = weights
return context
def processContexts(contexts):
res = []
for context in contexts:
res.append(getOneContextFeatures(context))
return res
def saveFixedContexts(path, precomputed_contexts):
if ".gz" in path:
f = gzip.open(path, "wt")
else:
f = open(path, "w")
written = 0
print("Exporting feature data...")
for context in tqdm(precomputed_contexts):
feature_data = getOneContextFeatures(context)
f.write(json.dumps(feature_data) + "\n")
written += 1
f.close()
print("Total written", written)
def main():
exp_dir = os.path.join(getRootDir("aac"), "experiments", "aac_generate_kw_trace")
to_process = [
"feature_data_w.json.gz",
# "feature_data_test_w.json.gz"
]
for filename in to_process:
full_filename = os.path.join(exp_dir, filename)
features = FeaturesReader(full_filename)
saveFixedContexts(full_filename + ".fixed", features)
if __name__ == '__main__':
main()
| gpl-3.0 | 7,134,670,011,104,532,000 | 26.059701 | 105 | 0.648649 | false |
bitemyapp/ganeti | test/py/ganeti.cli_unittest.py | 5 | 55966 | #!/usr/bin/python
#
# Copyright (C) 2008, 2011, 2012, 2013 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 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.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Script for unittesting the cli module"""
import copy
import testutils
import time
import unittest
import yaml
from cStringIO import StringIO
from ganeti import constants
from ganeti import cli
from ganeti import errors
from ganeti import utils
from ganeti import objects
from ganeti import qlang
from ganeti.errors import OpPrereqError, ParameterError
class TestParseTimespec(unittest.TestCase):
"""Testing case for ParseTimespec"""
def testValidTimes(self):
"""Test valid timespecs"""
test_data = [
("1s", 1),
("1", 1),
("1m", 60),
("1h", 60 * 60),
("1d", 60 * 60 * 24),
("1w", 60 * 60 * 24 * 7),
("4h", 4 * 60 * 60),
("61m", 61 * 60),
]
for value, expected_result in test_data:
self.failUnlessEqual(cli.ParseTimespec(value), expected_result)
def testInvalidTime(self):
"""Test invalid timespecs"""
test_data = [
"1y",
"",
"aaa",
"s",
]
for value in test_data:
self.failUnlessRaises(OpPrereqError, cli.ParseTimespec, value)
class TestToStream(unittest.TestCase):
"""Test the ToStream functions"""
def testBasic(self):
for data in ["foo",
"foo %s",
"foo %(test)s",
"foo %s %s",
"",
]:
buf = StringIO()
cli._ToStream(buf, data)
self.failUnlessEqual(buf.getvalue(), data + "\n")
def testParams(self):
buf = StringIO()
cli._ToStream(buf, "foo %s", 1)
self.failUnlessEqual(buf.getvalue(), "foo 1\n")
buf = StringIO()
cli._ToStream(buf, "foo %s", (15,16))
self.failUnlessEqual(buf.getvalue(), "foo (15, 16)\n")
buf = StringIO()
cli._ToStream(buf, "foo %s %s", "a", "b")
self.failUnlessEqual(buf.getvalue(), "foo a b\n")
class TestGenerateTable(unittest.TestCase):
HEADERS = dict([("f%s" % i, "Field%s" % i) for i in range(5)])
FIELDS1 = ["f1", "f2"]
DATA1 = [
["abc", 1234],
["foobar", 56],
["b", -14],
]
def _test(self, headers, fields, separator, data,
numfields, unitfields, units, expected):
table = cli.GenerateTable(headers, fields, separator, data,
numfields=numfields, unitfields=unitfields,
units=units)
self.assertEqual(table, expected)
def testPlain(self):
exp = [
"Field1 Field2",
"abc 1234",
"foobar 56",
"b -14",
]
self._test(self.HEADERS, self.FIELDS1, None, self.DATA1,
None, None, "m", exp)
def testNoFields(self):
self._test(self.HEADERS, [], None, [[], []],
None, None, "m", ["", "", ""])
self._test(None, [], None, [[], []],
None, None, "m", ["", ""])
def testSeparator(self):
for sep in ["#", ":", ",", "^", "!", "%", "|", "###", "%%", "!!!", "||"]:
exp = [
"Field1%sField2" % sep,
"abc%s1234" % sep,
"foobar%s56" % sep,
"b%s-14" % sep,
]
self._test(self.HEADERS, self.FIELDS1, sep, self.DATA1,
None, None, "m", exp)
def testNoHeader(self):
exp = [
"abc 1234",
"foobar 56",
"b -14",
]
self._test(None, self.FIELDS1, None, self.DATA1,
None, None, "m", exp)
def testUnknownField(self):
headers = {
"f1": "Field1",
}
exp = [
"Field1 UNKNOWN",
"abc 1234",
"foobar 56",
"b -14",
]
self._test(headers, ["f1", "UNKNOWN"], None, self.DATA1,
None, None, "m", exp)
def testNumfields(self):
fields = ["f1", "f2", "f3"]
data = [
["abc", 1234, 0],
["foobar", 56, 3],
["b", -14, "-"],
]
exp = [
"Field1 Field2 Field3",
"abc 1234 0",
"foobar 56 3",
"b -14 -",
]
self._test(self.HEADERS, fields, None, data,
["f2", "f3"], None, "m", exp)
def testUnitfields(self):
expnosep = [
"Field1 Field2 Field3",
"abc 1234 0M",
"foobar 56 3M",
"b -14 -",
]
expsep = [
"Field1:Field2:Field3",
"abc:1234:0M",
"foobar:56:3M",
"b:-14:-",
]
for sep, expected in [(None, expnosep), (":", expsep)]:
fields = ["f1", "f2", "f3"]
data = [
["abc", 1234, 0],
["foobar", 56, 3],
["b", -14, "-"],
]
self._test(self.HEADERS, fields, sep, data,
["f2", "f3"], ["f3"], "h", expected)
def testUnusual(self):
data = [
["%", "xyz"],
["%%", "abc"],
]
exp = [
"Field1 Field2",
"% xyz",
"%% abc",
]
self._test(self.HEADERS, ["f1", "f2"], None, data,
None, None, "m", exp)
class TestFormatQueryResult(unittest.TestCase):
def test(self):
fields = [
objects.QueryFieldDefinition(name="name", title="Name",
kind=constants.QFT_TEXT),
objects.QueryFieldDefinition(name="size", title="Size",
kind=constants.QFT_NUMBER),
objects.QueryFieldDefinition(name="act", title="Active",
kind=constants.QFT_BOOL),
objects.QueryFieldDefinition(name="mem", title="Memory",
kind=constants.QFT_UNIT),
objects.QueryFieldDefinition(name="other", title="SomeList",
kind=constants.QFT_OTHER),
]
response = objects.QueryResponse(fields=fields, data=[
[(constants.RS_NORMAL, "nodeA"), (constants.RS_NORMAL, 128),
(constants.RS_NORMAL, False), (constants.RS_NORMAL, 1468006),
(constants.RS_NORMAL, [])],
[(constants.RS_NORMAL, "other"), (constants.RS_NORMAL, 512),
(constants.RS_NORMAL, True), (constants.RS_NORMAL, 16),
(constants.RS_NORMAL, [1, 2, 3])],
[(constants.RS_NORMAL, "xyz"), (constants.RS_NORMAL, 1024),
(constants.RS_NORMAL, True), (constants.RS_NORMAL, 4096),
(constants.RS_NORMAL, [{}, {}])],
])
self.assertEqual(cli.FormatQueryResult(response, unit="h", header=True),
(cli.QR_NORMAL, [
"Name Size Active Memory SomeList",
"nodeA 128 N 1.4T []",
"other 512 Y 16M [1, 2, 3]",
"xyz 1024 Y 4.0G [{}, {}]",
]))
def testTimestampAndUnit(self):
fields = [
objects.QueryFieldDefinition(name="name", title="Name",
kind=constants.QFT_TEXT),
objects.QueryFieldDefinition(name="size", title="Size",
kind=constants.QFT_UNIT),
objects.QueryFieldDefinition(name="mtime", title="ModTime",
kind=constants.QFT_TIMESTAMP),
]
response = objects.QueryResponse(fields=fields, data=[
[(constants.RS_NORMAL, "a"), (constants.RS_NORMAL, 1024),
(constants.RS_NORMAL, 0)],
[(constants.RS_NORMAL, "b"), (constants.RS_NORMAL, 144996),
(constants.RS_NORMAL, 1291746295)],
])
self.assertEqual(cli.FormatQueryResult(response, unit="m", header=True),
(cli.QR_NORMAL, [
"Name Size ModTime",
"a 1024 %s" % utils.FormatTime(0),
"b 144996 %s" % utils.FormatTime(1291746295),
]))
def testOverride(self):
fields = [
objects.QueryFieldDefinition(name="name", title="Name",
kind=constants.QFT_TEXT),
objects.QueryFieldDefinition(name="cust", title="Custom",
kind=constants.QFT_OTHER),
objects.QueryFieldDefinition(name="xt", title="XTime",
kind=constants.QFT_TIMESTAMP),
]
response = objects.QueryResponse(fields=fields, data=[
[(constants.RS_NORMAL, "x"), (constants.RS_NORMAL, ["a", "b", "c"]),
(constants.RS_NORMAL, 1234)],
[(constants.RS_NORMAL, "y"), (constants.RS_NORMAL, range(10)),
(constants.RS_NORMAL, 1291746295)],
])
override = {
"cust": (utils.CommaJoin, False),
"xt": (hex, True),
}
self.assertEqual(cli.FormatQueryResult(response, unit="h", header=True,
format_override=override),
(cli.QR_NORMAL, [
"Name Custom XTime",
"x a, b, c 0x4d2",
"y 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 0x4cfe7bf7",
]))
def testSeparator(self):
fields = [
objects.QueryFieldDefinition(name="name", title="Name",
kind=constants.QFT_TEXT),
objects.QueryFieldDefinition(name="count", title="Count",
kind=constants.QFT_NUMBER),
objects.QueryFieldDefinition(name="desc", title="Description",
kind=constants.QFT_TEXT),
]
response = objects.QueryResponse(fields=fields, data=[
[(constants.RS_NORMAL, "instance1.example.com"),
(constants.RS_NORMAL, 21125), (constants.RS_NORMAL, "Hello World!")],
[(constants.RS_NORMAL, "mail.other.net"),
(constants.RS_NORMAL, -9000), (constants.RS_NORMAL, "a,b,c")],
])
for sep in [":", "|", "#", "|||", "###", "@@@", "@#@"]:
for header in [None, "Name%sCount%sDescription" % (sep, sep)]:
exp = []
if header:
exp.append(header)
exp.extend([
"instance1.example.com%s21125%sHello World!" % (sep, sep),
"mail.other.net%s-9000%sa,b,c" % (sep, sep),
])
self.assertEqual(cli.FormatQueryResult(response, separator=sep,
header=bool(header)),
(cli.QR_NORMAL, exp))
def testStatusWithUnknown(self):
fields = [
objects.QueryFieldDefinition(name="id", title="ID",
kind=constants.QFT_NUMBER),
objects.QueryFieldDefinition(name="unk", title="unk",
kind=constants.QFT_UNKNOWN),
objects.QueryFieldDefinition(name="unavail", title="Unavail",
kind=constants.QFT_BOOL),
objects.QueryFieldDefinition(name="nodata", title="NoData",
kind=constants.QFT_TEXT),
objects.QueryFieldDefinition(name="offline", title="OffLine",
kind=constants.QFT_TEXT),
]
response = objects.QueryResponse(fields=fields, data=[
[(constants.RS_NORMAL, 1), (constants.RS_UNKNOWN, None),
(constants.RS_NORMAL, False), (constants.RS_NORMAL, ""),
(constants.RS_OFFLINE, None)],
[(constants.RS_NORMAL, 2), (constants.RS_UNKNOWN, None),
(constants.RS_NODATA, None), (constants.RS_NORMAL, "x"),
(constants.RS_OFFLINE, None)],
[(constants.RS_NORMAL, 3), (constants.RS_UNKNOWN, None),
(constants.RS_NORMAL, False), (constants.RS_UNAVAIL, None),
(constants.RS_OFFLINE, None)],
])
self.assertEqual(cli.FormatQueryResult(response, header=True,
separator="|", verbose=True),
(cli.QR_UNKNOWN, [
"ID|unk|Unavail|NoData|OffLine",
"1|(unknown)|N||(offline)",
"2|(unknown)|(nodata)|x|(offline)",
"3|(unknown)|N|(unavail)|(offline)",
]))
self.assertEqual(cli.FormatQueryResult(response, header=True,
separator="|", verbose=False),
(cli.QR_UNKNOWN, [
"ID|unk|Unavail|NoData|OffLine",
"1|??|N||*",
"2|??|?|x|*",
"3|??|N|-|*",
]))
def testNoData(self):
fields = [
objects.QueryFieldDefinition(name="id", title="ID",
kind=constants.QFT_NUMBER),
objects.QueryFieldDefinition(name="name", title="Name",
kind=constants.QFT_TEXT),
]
response = objects.QueryResponse(fields=fields, data=[])
self.assertEqual(cli.FormatQueryResult(response, header=True),
(cli.QR_NORMAL, ["ID Name"]))
def testNoDataWithUnknown(self):
fields = [
objects.QueryFieldDefinition(name="id", title="ID",
kind=constants.QFT_NUMBER),
objects.QueryFieldDefinition(name="unk", title="unk",
kind=constants.QFT_UNKNOWN),
]
response = objects.QueryResponse(fields=fields, data=[])
self.assertEqual(cli.FormatQueryResult(response, header=False),
(cli.QR_UNKNOWN, []))
def testStatus(self):
fields = [
objects.QueryFieldDefinition(name="id", title="ID",
kind=constants.QFT_NUMBER),
objects.QueryFieldDefinition(name="unavail", title="Unavail",
kind=constants.QFT_BOOL),
objects.QueryFieldDefinition(name="nodata", title="NoData",
kind=constants.QFT_TEXT),
objects.QueryFieldDefinition(name="offline", title="OffLine",
kind=constants.QFT_TEXT),
]
response = objects.QueryResponse(fields=fields, data=[
[(constants.RS_NORMAL, 1), (constants.RS_NORMAL, False),
(constants.RS_NORMAL, ""), (constants.RS_OFFLINE, None)],
[(constants.RS_NORMAL, 2), (constants.RS_NODATA, None),
(constants.RS_NORMAL, "x"), (constants.RS_NORMAL, "abc")],
[(constants.RS_NORMAL, 3), (constants.RS_NORMAL, False),
(constants.RS_UNAVAIL, None), (constants.RS_OFFLINE, None)],
])
self.assertEqual(cli.FormatQueryResult(response, header=False,
separator="|", verbose=True),
(cli.QR_INCOMPLETE, [
"1|N||(offline)",
"2|(nodata)|x|abc",
"3|N|(unavail)|(offline)",
]))
self.assertEqual(cli.FormatQueryResult(response, header=False,
separator="|", verbose=False),
(cli.QR_INCOMPLETE, [
"1|N||*",
"2|?|x|abc",
"3|N|-|*",
]))
def testInvalidFieldType(self):
fields = [
objects.QueryFieldDefinition(name="x", title="x",
kind="#some#other#type"),
]
response = objects.QueryResponse(fields=fields, data=[])
self.assertRaises(NotImplementedError, cli.FormatQueryResult, response)
def testInvalidFieldStatus(self):
fields = [
objects.QueryFieldDefinition(name="x", title="x",
kind=constants.QFT_TEXT),
]
response = objects.QueryResponse(fields=fields, data=[[(-1, None)]])
self.assertRaises(NotImplementedError, cli.FormatQueryResult, response)
response = objects.QueryResponse(fields=fields, data=[[(-1, "x")]])
self.assertRaises(AssertionError, cli.FormatQueryResult, response)
def testEmptyFieldTitle(self):
fields = [
objects.QueryFieldDefinition(name="x", title="",
kind=constants.QFT_TEXT),
]
response = objects.QueryResponse(fields=fields, data=[])
self.assertRaises(AssertionError, cli.FormatQueryResult, response)
class _MockJobPollCb(cli.JobPollCbBase, cli.JobPollReportCbBase):
def __init__(self, tc, job_id):
self.tc = tc
self.job_id = job_id
self._wfjcr = []
self._jobstatus = []
self._expect_notchanged = False
self._expect_log = []
def CheckEmpty(self):
self.tc.assertFalse(self._wfjcr)
self.tc.assertFalse(self._jobstatus)
self.tc.assertFalse(self._expect_notchanged)
self.tc.assertFalse(self._expect_log)
def AddWfjcResult(self, *args):
self._wfjcr.append(args)
def AddQueryJobsResult(self, *args):
self._jobstatus.append(args)
def WaitForJobChangeOnce(self, job_id, fields,
prev_job_info, prev_log_serial):
self.tc.assertEqual(job_id, self.job_id)
self.tc.assertEqualValues(fields, ["status"])
self.tc.assertFalse(self._expect_notchanged)
self.tc.assertFalse(self._expect_log)
(exp_prev_job_info, exp_prev_log_serial, result) = self._wfjcr.pop(0)
self.tc.assertEqualValues(prev_job_info, exp_prev_job_info)
self.tc.assertEqual(prev_log_serial, exp_prev_log_serial)
if result == constants.JOB_NOTCHANGED:
self._expect_notchanged = True
elif result:
(_, logmsgs) = result
if logmsgs:
self._expect_log.extend(logmsgs)
return result
def QueryJobs(self, job_ids, fields):
self.tc.assertEqual(job_ids, [self.job_id])
self.tc.assertEqualValues(fields, ["status", "opstatus", "opresult"])
self.tc.assertFalse(self._expect_notchanged)
self.tc.assertFalse(self._expect_log)
result = self._jobstatus.pop(0)
self.tc.assertEqual(len(fields), len(result))
return [result]
def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
self.tc.assertEqual(job_id, self.job_id)
self.tc.assertEqualValues((serial, timestamp, log_type, log_msg),
self._expect_log.pop(0))
def ReportNotChanged(self, job_id, status):
self.tc.assertEqual(job_id, self.job_id)
self.tc.assert_(self._expect_notchanged)
self._expect_notchanged = False
class TestGenericPollJob(testutils.GanetiTestCase):
def testSuccessWithLog(self):
job_id = 29609
cbs = _MockJobPollCb(self, job_id)
cbs.AddWfjcResult(None, None, constants.JOB_NOTCHANGED)
cbs.AddWfjcResult(None, None,
((constants.JOB_STATUS_QUEUED, ), None))
cbs.AddWfjcResult((constants.JOB_STATUS_QUEUED, ), None,
constants.JOB_NOTCHANGED)
cbs.AddWfjcResult((constants.JOB_STATUS_QUEUED, ), None,
((constants.JOB_STATUS_RUNNING, ),
[(1, utils.SplitTime(1273491611.0),
constants.ELOG_MESSAGE, "Step 1"),
(2, utils.SplitTime(1273491615.9),
constants.ELOG_MESSAGE, "Step 2"),
(3, utils.SplitTime(1273491625.02),
constants.ELOG_MESSAGE, "Step 3"),
(4, utils.SplitTime(1273491635.05),
constants.ELOG_MESSAGE, "Step 4"),
(37, utils.SplitTime(1273491645.0),
constants.ELOG_MESSAGE, "Step 5"),
(203, utils.SplitTime(127349155.0),
constants.ELOG_MESSAGE, "Step 6")]))
cbs.AddWfjcResult((constants.JOB_STATUS_RUNNING, ), 203,
((constants.JOB_STATUS_RUNNING, ),
[(300, utils.SplitTime(1273491711.01),
constants.ELOG_MESSAGE, "Step X"),
(302, utils.SplitTime(1273491815.8),
constants.ELOG_MESSAGE, "Step Y"),
(303, utils.SplitTime(1273491925.32),
constants.ELOG_MESSAGE, "Step Z")]))
cbs.AddWfjcResult((constants.JOB_STATUS_RUNNING, ), 303,
((constants.JOB_STATUS_SUCCESS, ), None))
cbs.AddQueryJobsResult(constants.JOB_STATUS_SUCCESS,
[constants.OP_STATUS_SUCCESS,
constants.OP_STATUS_SUCCESS],
["Hello World", "Foo man bar"])
self.assertEqual(["Hello World", "Foo man bar"],
cli.GenericPollJob(job_id, cbs, cbs))
cbs.CheckEmpty()
def testJobLost(self):
job_id = 13746
cbs = _MockJobPollCb(self, job_id)
cbs.AddWfjcResult(None, None, constants.JOB_NOTCHANGED)
cbs.AddWfjcResult(None, None, None)
self.assertRaises(errors.JobLost, cli.GenericPollJob, job_id, cbs, cbs)
cbs.CheckEmpty()
def testError(self):
job_id = 31088
cbs = _MockJobPollCb(self, job_id)
cbs.AddWfjcResult(None, None, constants.JOB_NOTCHANGED)
cbs.AddWfjcResult(None, None, ((constants.JOB_STATUS_ERROR, ), None))
cbs.AddQueryJobsResult(constants.JOB_STATUS_ERROR,
[constants.OP_STATUS_SUCCESS,
constants.OP_STATUS_ERROR],
["Hello World", "Error code 123"])
self.assertRaises(errors.OpExecError, cli.GenericPollJob, job_id, cbs, cbs)
cbs.CheckEmpty()
def testError2(self):
job_id = 22235
cbs = _MockJobPollCb(self, job_id)
cbs.AddWfjcResult(None, None, ((constants.JOB_STATUS_ERROR, ), None))
encexc = errors.EncodeException(errors.LockError("problem"))
cbs.AddQueryJobsResult(constants.JOB_STATUS_ERROR,
[constants.OP_STATUS_ERROR], [encexc])
self.assertRaises(errors.LockError, cli.GenericPollJob, job_id, cbs, cbs)
cbs.CheckEmpty()
def testWeirdError(self):
job_id = 28847
cbs = _MockJobPollCb(self, job_id)
cbs.AddWfjcResult(None, None, ((constants.JOB_STATUS_ERROR, ), None))
cbs.AddQueryJobsResult(constants.JOB_STATUS_ERROR,
[constants.OP_STATUS_RUNNING,
constants.OP_STATUS_RUNNING],
[None, None])
self.assertRaises(errors.OpExecError, cli.GenericPollJob, job_id, cbs, cbs)
cbs.CheckEmpty()
def testCancel(self):
job_id = 4275
cbs = _MockJobPollCb(self, job_id)
cbs.AddWfjcResult(None, None, constants.JOB_NOTCHANGED)
cbs.AddWfjcResult(None, None, ((constants.JOB_STATUS_CANCELING, ), None))
cbs.AddQueryJobsResult(constants.JOB_STATUS_CANCELING,
[constants.OP_STATUS_CANCELING,
constants.OP_STATUS_CANCELING],
[None, None])
self.assertRaises(errors.OpExecError, cli.GenericPollJob, job_id, cbs, cbs)
cbs.CheckEmpty()
class TestFormatLogMessage(unittest.TestCase):
def test(self):
self.assertEqual(cli.FormatLogMessage(constants.ELOG_MESSAGE,
"Hello World"),
"Hello World")
self.assertRaises(TypeError, cli.FormatLogMessage,
constants.ELOG_MESSAGE, [1, 2, 3])
self.assert_(cli.FormatLogMessage("some other type", (1, 2, 3)))
class TestParseFields(unittest.TestCase):
def test(self):
self.assertEqual(cli.ParseFields(None, []), [])
self.assertEqual(cli.ParseFields("name,foo,hello", []),
["name", "foo", "hello"])
self.assertEqual(cli.ParseFields(None, ["def", "ault", "fields", "here"]),
["def", "ault", "fields", "here"])
self.assertEqual(cli.ParseFields("name,foo", ["def", "ault"]),
["name", "foo"])
self.assertEqual(cli.ParseFields("+name,foo", ["def", "ault"]),
["def", "ault", "name", "foo"])
class TestParseNicOption(unittest.TestCase):
def test(self):
self.assertEqual(cli.ParseNicOption([("0", { "link": "eth0", })]),
[{ "link": "eth0", }])
self.assertEqual(cli.ParseNicOption([("5", { "ip": "192.0.2.7", })]),
[{}, {}, {}, {}, {}, { "ip": "192.0.2.7", }])
def testErrors(self):
for i in [None, "", "abc", "zero", "Hello World", "\0", []]:
self.assertRaises(errors.OpPrereqError, cli.ParseNicOption,
[(i, { "link": "eth0", })])
self.assertRaises(errors.OpPrereqError, cli.ParseNicOption,
[("0", i)])
self.assertRaises(errors.TypeEnforcementError, cli.ParseNicOption,
[(0, { True: False, })])
self.assertRaises(errors.TypeEnforcementError, cli.ParseNicOption,
[(3, { "mode": [], })])
class TestFormatResultError(unittest.TestCase):
def testNormal(self):
for verbose in [False, True]:
self.assertRaises(AssertionError, cli.FormatResultError,
constants.RS_NORMAL, verbose)
def testUnknown(self):
for verbose in [False, True]:
self.assertRaises(NotImplementedError, cli.FormatResultError,
"#some!other!status#", verbose)
def test(self):
for status in constants.RS_ALL:
if status == constants.RS_NORMAL:
continue
self.assertNotEqual(cli.FormatResultError(status, False),
cli.FormatResultError(status, True))
result = cli.FormatResultError(status, True)
self.assertTrue(result.startswith("("))
self.assertTrue(result.endswith(")"))
class TestGetOnlineNodes(unittest.TestCase):
class _FakeClient:
def __init__(self):
self._query = []
def AddQueryResult(self, *args):
self._query.append(args)
def CountPending(self):
return len(self._query)
def Query(self, res, fields, qfilter):
if res != constants.QR_NODE:
raise Exception("Querying wrong resource")
(exp_fields, check_filter, result) = self._query.pop(0)
if exp_fields != fields:
raise Exception("Expected fields %s, got %s" % (exp_fields, fields))
if not (qfilter is None or check_filter(qfilter)):
raise Exception("Filter doesn't match expectations")
return objects.QueryResponse(fields=None, data=result)
def testEmpty(self):
cl = self._FakeClient()
cl.AddQueryResult(["name", "offline", "sip"], None, [])
self.assertEqual(cli.GetOnlineNodes(None, cl=cl), [])
self.assertEqual(cl.CountPending(), 0)
def testNoSpecialFilter(self):
cl = self._FakeClient()
cl.AddQueryResult(["name", "offline", "sip"], None, [
[(constants.RS_NORMAL, "master.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.1")],
[(constants.RS_NORMAL, "node2.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.2")],
])
self.assertEqual(cli.GetOnlineNodes(None, cl=cl),
["master.example.com", "node2.example.com"])
self.assertEqual(cl.CountPending(), 0)
def testNoMaster(self):
cl = self._FakeClient()
def _CheckFilter(qfilter):
self.assertEqual(qfilter, [qlang.OP_NOT, [qlang.OP_TRUE, "master"]])
return True
cl.AddQueryResult(["name", "offline", "sip"], _CheckFilter, [
[(constants.RS_NORMAL, "node2.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.2")],
])
self.assertEqual(cli.GetOnlineNodes(None, cl=cl, filter_master=True),
["node2.example.com"])
self.assertEqual(cl.CountPending(), 0)
def testSecondaryIpAddress(self):
cl = self._FakeClient()
cl.AddQueryResult(["name", "offline", "sip"], None, [
[(constants.RS_NORMAL, "master.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.1")],
[(constants.RS_NORMAL, "node2.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.2")],
])
self.assertEqual(cli.GetOnlineNodes(None, cl=cl, secondary_ips=True),
["192.0.2.1", "192.0.2.2"])
self.assertEqual(cl.CountPending(), 0)
def testNoMasterFilterNodeName(self):
cl = self._FakeClient()
def _CheckFilter(qfilter):
self.assertEqual(qfilter,
[qlang.OP_AND,
[qlang.OP_OR] + [[qlang.OP_EQUAL, "name", name]
for name in ["node2", "node3"]],
[qlang.OP_NOT, [qlang.OP_TRUE, "master"]]])
return True
cl.AddQueryResult(["name", "offline", "sip"], _CheckFilter, [
[(constants.RS_NORMAL, "node2.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.12")],
[(constants.RS_NORMAL, "node3.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.13")],
])
self.assertEqual(cli.GetOnlineNodes(["node2", "node3"], cl=cl,
secondary_ips=True, filter_master=True),
["192.0.2.12", "192.0.2.13"])
self.assertEqual(cl.CountPending(), 0)
def testOfflineNodes(self):
cl = self._FakeClient()
cl.AddQueryResult(["name", "offline", "sip"], None, [
[(constants.RS_NORMAL, "master.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.1")],
[(constants.RS_NORMAL, "node2.example.com"),
(constants.RS_NORMAL, True),
(constants.RS_NORMAL, "192.0.2.2")],
[(constants.RS_NORMAL, "node3.example.com"),
(constants.RS_NORMAL, True),
(constants.RS_NORMAL, "192.0.2.3")],
])
self.assertEqual(cli.GetOnlineNodes(None, cl=cl, nowarn=True),
["master.example.com"])
self.assertEqual(cl.CountPending(), 0)
def testNodeGroup(self):
cl = self._FakeClient()
def _CheckFilter(qfilter):
self.assertEqual(qfilter,
[qlang.OP_OR, [qlang.OP_EQUAL, "group", "foobar"],
[qlang.OP_EQUAL, "group.uuid", "foobar"]])
return True
cl.AddQueryResult(["name", "offline", "sip"], _CheckFilter, [
[(constants.RS_NORMAL, "master.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.1")],
[(constants.RS_NORMAL, "node3.example.com"),
(constants.RS_NORMAL, False),
(constants.RS_NORMAL, "192.0.2.3")],
])
self.assertEqual(cli.GetOnlineNodes(None, cl=cl, nodegroup="foobar"),
["master.example.com", "node3.example.com"])
self.assertEqual(cl.CountPending(), 0)
class TestFormatTimestamp(unittest.TestCase):
def testGood(self):
self.assertEqual(cli.FormatTimestamp((0, 1)),
time.strftime("%F %T", time.localtime(0)) + ".000001")
self.assertEqual(cli.FormatTimestamp((1332944009, 17376)),
(time.strftime("%F %T", time.localtime(1332944009)) +
".017376"))
def testWrong(self):
for i in [0, [], {}, "", [1]]:
self.assertEqual(cli.FormatTimestamp(i), "?")
class TestFormatUsage(unittest.TestCase):
def test(self):
binary = "gnt-unittest"
commands = {
"cmdA":
(NotImplemented, NotImplemented, NotImplemented, NotImplemented,
"description of A"),
"bbb":
(NotImplemented, NotImplemented, NotImplemented, NotImplemented,
"Hello World," * 10),
"longname":
(NotImplemented, NotImplemented, NotImplemented, NotImplemented,
"Another description"),
}
self.assertEqual(list(cli._FormatUsage(binary, commands)), [
"Usage: gnt-unittest {command} [options...] [argument...]",
"gnt-unittest <command> --help to see details, or man gnt-unittest",
"",
"Commands:",
(" bbb - Hello World,Hello World,Hello World,Hello World,Hello"
" World,Hello"),
" World,Hello World,Hello World,Hello World,Hello World,",
" cmdA - description of A",
" longname - Another description",
"",
])
class TestParseArgs(unittest.TestCase):
def testNoArguments(self):
for argv in [[], ["gnt-unittest"]]:
try:
cli._ParseArgs("gnt-unittest", argv, {}, {}, set())
except cli._ShowUsage, err:
self.assertTrue(err.exit_error)
else:
self.fail("Did not raise exception")
def testVersion(self):
for argv in [["test", "--version"], ["test", "--version", "somethingelse"]]:
try:
cli._ParseArgs("test", argv, {}, {}, set())
except cli._ShowVersion:
pass
else:
self.fail("Did not raise exception")
def testHelp(self):
for argv in [["test", "--help"], ["test", "--help", "somethingelse"]]:
try:
cli._ParseArgs("test", argv, {}, {}, set())
except cli._ShowUsage, err:
self.assertFalse(err.exit_error)
else:
self.fail("Did not raise exception")
def testUnknownCommandOrAlias(self):
for argv in [["test", "list"], ["test", "somethingelse", "--help"]]:
try:
cli._ParseArgs("test", argv, {}, {}, set())
except cli._ShowUsage, err:
self.assertTrue(err.exit_error)
else:
self.fail("Did not raise exception")
def testInvalidAliasList(self):
cmd = {
"list": NotImplemented,
"foo": NotImplemented,
}
aliases = {
"list": NotImplemented,
"foo": NotImplemented,
}
assert sorted(cmd.keys()) == sorted(aliases.keys())
self.assertRaises(AssertionError, cli._ParseArgs, "test",
["test", "list"], cmd, aliases, set())
def testAliasForNonExistantCommand(self):
cmd = {}
aliases = {
"list": NotImplemented,
}
self.assertRaises(errors.ProgrammerError, cli._ParseArgs, "test",
["test", "list"], cmd, aliases, set())
class TestQftNames(unittest.TestCase):
def testComplete(self):
self.assertEqual(frozenset(cli._QFT_NAMES), constants.QFT_ALL)
def testUnique(self):
lcnames = map(lambda s: s.lower(), cli._QFT_NAMES.values())
self.assertFalse(utils.FindDuplicates(lcnames))
def testUppercase(self):
for name in cli._QFT_NAMES.values():
self.assertEqual(name[0], name[0].upper())
class TestFieldDescValues(unittest.TestCase):
def testKnownKind(self):
fdef = objects.QueryFieldDefinition(name="aname",
title="Atitle",
kind=constants.QFT_TEXT,
doc="aaa doc aaa")
self.assertEqual(cli._FieldDescValues(fdef),
["aname", "Text", "Atitle", "aaa doc aaa"])
def testUnknownKind(self):
kind = "#foo#"
self.assertFalse(kind in constants.QFT_ALL)
self.assertFalse(kind in cli._QFT_NAMES)
fdef = objects.QueryFieldDefinition(name="zname", title="Ztitle",
kind=kind, doc="zzz doc zzz")
self.assertEqual(cli._FieldDescValues(fdef),
["zname", kind, "Ztitle", "zzz doc zzz"])
class TestSerializeGenericInfo(unittest.TestCase):
"""Test case for cli._SerializeGenericInfo"""
def _RunTest(self, data, expected):
buf = StringIO()
cli._SerializeGenericInfo(buf, data, 0)
self.assertEqual(buf.getvalue(), expected)
def testSimple(self):
test_samples = [
("abc", "abc\n"),
([], "\n"),
({}, "\n"),
(["1", "2", "3"], "- 1\n- 2\n- 3\n"),
([("z", "26")], "z: 26\n"),
({"z": "26"}, "z: 26\n"),
([("z", "26"), ("a", "1")], "z: 26\na: 1\n"),
({"z": "26", "a": "1"}, "a: 1\nz: 26\n"),
]
for (data, expected) in test_samples:
self._RunTest(data, expected)
def testLists(self):
adict = {
"aa": "11",
"bb": "22",
"cc": "33",
}
adict_exp = ("- aa: 11\n"
" bb: 22\n"
" cc: 33\n")
anobj = [
("zz", "11"),
("ww", "33"),
("xx", "22"),
]
anobj_exp = ("- zz: 11\n"
" ww: 33\n"
" xx: 22\n")
alist = ["aa", "cc", "bb"]
alist_exp = ("- - aa\n"
" - cc\n"
" - bb\n")
test_samples = [
(adict, adict_exp),
(anobj, anobj_exp),
(alist, alist_exp),
]
for (base_data, base_expected) in test_samples:
for k in range(1, 4):
data = k * [base_data]
expected = k * base_expected
self._RunTest(data, expected)
def testDictionaries(self):
data = [
("aaa", ["x", "y"]),
("bbb", {
"w": "1",
"z": "2",
}),
("ccc", [
("xyz", "123"),
("efg", "456"),
]),
]
expected = ("aaa: \n"
" - x\n"
" - y\n"
"bbb: \n"
" w: 1\n"
" z: 2\n"
"ccc: \n"
" xyz: 123\n"
" efg: 456\n")
self._RunTest(data, expected)
self._RunTest(dict(data), expected)
class TestFormatPolicyInfo(unittest.TestCase):
"""Test case for cli.FormatPolicyInfo.
These tests rely on cli._SerializeGenericInfo (tested elsewhere).
"""
def setUp(self):
# Policies are big, and we want to see the difference in case of an error
self.maxDiff = None
def _RenameDictItem(self, parsed, old, new):
self.assertTrue(old in parsed)
self.assertTrue(new not in parsed)
parsed[new] = parsed[old]
del parsed[old]
def _TranslateParsedNames(self, parsed):
for (pretty, raw) in [
("bounds specs", constants.ISPECS_MINMAX),
("allowed disk templates", constants.IPOLICY_DTS)
]:
self._RenameDictItem(parsed, pretty, raw)
for minmax in parsed[constants.ISPECS_MINMAX]:
for key in minmax:
keyparts = key.split("/", 1)
if len(keyparts) > 1:
self._RenameDictItem(minmax, key, keyparts[0])
self.assertTrue(constants.IPOLICY_DTS in parsed)
parsed[constants.IPOLICY_DTS] = yaml.load("[%s]" %
parsed[constants.IPOLICY_DTS])
@staticmethod
def _PrintAndParsePolicy(custom, effective, iscluster):
formatted = cli.FormatPolicyInfo(custom, effective, iscluster)
buf = StringIO()
cli._SerializeGenericInfo(buf, formatted, 0)
return yaml.load(buf.getvalue())
def _PrintAndCheckParsed(self, policy):
parsed = self._PrintAndParsePolicy(policy, NotImplemented, True)
self._TranslateParsedNames(parsed)
self.assertEqual(parsed, policy)
def _CompareClusterGroupItems(self, cluster, group, skip=None):
if isinstance(group, dict):
self.assertTrue(isinstance(cluster, dict))
if skip is None:
skip = frozenset()
self.assertEqual(frozenset(cluster.keys()).difference(skip),
frozenset(group.keys()))
for key in group:
self._CompareClusterGroupItems(cluster[key], group[key])
elif isinstance(group, list):
self.assertTrue(isinstance(cluster, list))
self.assertEqual(len(cluster), len(group))
for (cval, gval) in zip(cluster, group):
self._CompareClusterGroupItems(cval, gval)
else:
self.assertTrue(isinstance(group, basestring))
self.assertEqual("default (%s)" % cluster, group)
def _TestClusterVsGroup(self, policy):
cluster = self._PrintAndParsePolicy(policy, NotImplemented, True)
group = self._PrintAndParsePolicy({}, policy, False)
self._CompareClusterGroupItems(cluster, group, ["std"])
def testWithDefaults(self):
self._PrintAndCheckParsed(constants.IPOLICY_DEFAULTS)
self._TestClusterVsGroup(constants.IPOLICY_DEFAULTS)
class TestCreateIPolicyFromOpts(unittest.TestCase):
"""Test case for cli.CreateIPolicyFromOpts."""
def setUp(self):
# Policies are big, and we want to see the difference in case of an error
self.maxDiff = None
def _RecursiveCheckMergedDicts(self, default_pol, diff_pol, merged_pol,
merge_minmax=False):
self.assertTrue(type(default_pol) is dict)
self.assertTrue(type(diff_pol) is dict)
self.assertTrue(type(merged_pol) is dict)
self.assertEqual(frozenset(default_pol.keys()),
frozenset(merged_pol.keys()))
for (key, val) in merged_pol.items():
if key in diff_pol:
if type(val) is dict:
self._RecursiveCheckMergedDicts(default_pol[key], diff_pol[key], val)
elif (merge_minmax and key == "minmax" and type(val) is list and
len(val) == 1):
self.assertEqual(len(default_pol[key]), 1)
self.assertEqual(len(diff_pol[key]), 1)
self._RecursiveCheckMergedDicts(default_pol[key][0],
diff_pol[key][0], val[0])
else:
self.assertEqual(val, diff_pol[key])
else:
self.assertEqual(val, default_pol[key])
def testClusterPolicy(self):
pol0 = cli.CreateIPolicyFromOpts(
ispecs_mem_size={},
ispecs_cpu_count={},
ispecs_disk_count={},
ispecs_disk_size={},
ispecs_nic_count={},
ipolicy_disk_templates=None,
ipolicy_vcpu_ratio=None,
ipolicy_spindle_ratio=None,
fill_all=True
)
self.assertEqual(pol0, constants.IPOLICY_DEFAULTS)
exp_pol1 = {
constants.ISPECS_MINMAX: [
{
constants.ISPECS_MIN: {
constants.ISPEC_CPU_COUNT: 2,
constants.ISPEC_DISK_COUNT: 1,
},
constants.ISPECS_MAX: {
constants.ISPEC_MEM_SIZE: 12*1024,
constants.ISPEC_DISK_COUNT: 2,
},
},
],
constants.ISPECS_STD: {
constants.ISPEC_CPU_COUNT: 2,
constants.ISPEC_DISK_COUNT: 2,
},
constants.IPOLICY_VCPU_RATIO: 3.1,
}
pol1 = cli.CreateIPolicyFromOpts(
ispecs_mem_size={"max": "12g"},
ispecs_cpu_count={"min": 2, "std": 2},
ispecs_disk_count={"min": 1, "max": 2, "std": 2},
ispecs_disk_size={},
ispecs_nic_count={},
ipolicy_disk_templates=None,
ipolicy_vcpu_ratio=3.1,
ipolicy_spindle_ratio=None,
fill_all=True
)
self._RecursiveCheckMergedDicts(constants.IPOLICY_DEFAULTS,
exp_pol1, pol1, merge_minmax=True)
exp_pol2 = {
constants.ISPECS_MINMAX: [
{
constants.ISPECS_MIN: {
constants.ISPEC_DISK_SIZE: 512,
constants.ISPEC_NIC_COUNT: 2,
},
constants.ISPECS_MAX: {
constants.ISPEC_NIC_COUNT: 3,
},
},
],
constants.ISPECS_STD: {
constants.ISPEC_CPU_COUNT: 2,
constants.ISPEC_NIC_COUNT: 3,
},
constants.IPOLICY_SPINDLE_RATIO: 1.3,
constants.IPOLICY_DTS: ["templates"],
}
pol2 = cli.CreateIPolicyFromOpts(
ispecs_mem_size={},
ispecs_cpu_count={"std": 2},
ispecs_disk_count={},
ispecs_disk_size={"min": "0.5g"},
ispecs_nic_count={"min": 2, "max": 3, "std": 3},
ipolicy_disk_templates=["templates"],
ipolicy_vcpu_ratio=None,
ipolicy_spindle_ratio=1.3,
fill_all=True
)
self._RecursiveCheckMergedDicts(constants.IPOLICY_DEFAULTS,
exp_pol2, pol2, merge_minmax=True)
for fill_all in [False, True]:
exp_pol3 = {
constants.ISPECS_STD: {
constants.ISPEC_CPU_COUNT: 2,
constants.ISPEC_NIC_COUNT: 3,
},
}
pol3 = cli.CreateIPolicyFromOpts(
std_ispecs={
constants.ISPEC_CPU_COUNT: "2",
constants.ISPEC_NIC_COUNT: "3",
},
ipolicy_disk_templates=None,
ipolicy_vcpu_ratio=None,
ipolicy_spindle_ratio=None,
fill_all=fill_all
)
if fill_all:
self._RecursiveCheckMergedDicts(constants.IPOLICY_DEFAULTS,
exp_pol3, pol3, merge_minmax=True)
else:
self.assertEqual(pol3, exp_pol3)
def testPartialPolicy(self):
exp_pol0 = objects.MakeEmptyIPolicy()
pol0 = cli.CreateIPolicyFromOpts(
minmax_ispecs=None,
std_ispecs=None,
ipolicy_disk_templates=None,
ipolicy_vcpu_ratio=None,
ipolicy_spindle_ratio=None,
fill_all=False
)
self.assertEqual(pol0, exp_pol0)
exp_pol1 = {
constants.IPOLICY_VCPU_RATIO: 3.1,
}
pol1 = cli.CreateIPolicyFromOpts(
minmax_ispecs=None,
std_ispecs=None,
ipolicy_disk_templates=None,
ipolicy_vcpu_ratio=3.1,
ipolicy_spindle_ratio=None,
fill_all=False
)
self.assertEqual(pol1, exp_pol1)
exp_pol2 = {
constants.IPOLICY_SPINDLE_RATIO: 1.3,
constants.IPOLICY_DTS: ["templates"],
}
pol2 = cli.CreateIPolicyFromOpts(
minmax_ispecs=None,
std_ispecs=None,
ipolicy_disk_templates=["templates"],
ipolicy_vcpu_ratio=None,
ipolicy_spindle_ratio=1.3,
fill_all=False
)
self.assertEqual(pol2, exp_pol2)
def _TestInvalidISpecs(self, minmax_ispecs, std_ispecs, fail=True):
for fill_all in [False, True]:
if fail:
self.assertRaises((errors.OpPrereqError,
errors.UnitParseError,
errors.TypeEnforcementError),
cli.CreateIPolicyFromOpts,
minmax_ispecs=minmax_ispecs,
std_ispecs=std_ispecs,
fill_all=fill_all)
else:
cli.CreateIPolicyFromOpts(minmax_ispecs=minmax_ispecs,
std_ispecs=std_ispecs,
fill_all=fill_all)
def testInvalidPolicies(self):
self.assertRaises(AssertionError, cli.CreateIPolicyFromOpts,
std_ispecs={constants.ISPEC_MEM_SIZE: 1024},
ipolicy_disk_templates=None, ipolicy_vcpu_ratio=None,
ipolicy_spindle_ratio=None, group_ipolicy=True)
self.assertRaises(errors.OpPrereqError, cli.CreateIPolicyFromOpts,
ispecs_mem_size={"wrong": "x"}, ispecs_cpu_count={},
ispecs_disk_count={}, ispecs_disk_size={},
ispecs_nic_count={}, ipolicy_disk_templates=None,
ipolicy_vcpu_ratio=None, ipolicy_spindle_ratio=None,
fill_all=True)
self.assertRaises(errors.TypeEnforcementError, cli.CreateIPolicyFromOpts,
ispecs_mem_size={}, ispecs_cpu_count={"min": "default"},
ispecs_disk_count={}, ispecs_disk_size={},
ispecs_nic_count={}, ipolicy_disk_templates=None,
ipolicy_vcpu_ratio=None, ipolicy_spindle_ratio=None,
fill_all=True)
good_mmspecs = [
constants.ISPECS_MINMAX_DEFAULTS,
constants.ISPECS_MINMAX_DEFAULTS,
]
self._TestInvalidISpecs(good_mmspecs, None, fail=False)
broken_mmspecs = copy.deepcopy(good_mmspecs)
for minmaxpair in broken_mmspecs:
for key in constants.ISPECS_MINMAX_KEYS:
for par in constants.ISPECS_PARAMETERS:
old = minmaxpair[key][par]
del minmaxpair[key][par]
self._TestInvalidISpecs(broken_mmspecs, None)
minmaxpair[key][par] = "invalid"
self._TestInvalidISpecs(broken_mmspecs, None)
minmaxpair[key][par] = old
minmaxpair[key]["invalid_key"] = None
self._TestInvalidISpecs(broken_mmspecs, None)
del minmaxpair[key]["invalid_key"]
minmaxpair["invalid_key"] = None
self._TestInvalidISpecs(broken_mmspecs, None)
del minmaxpair["invalid_key"]
assert broken_mmspecs == good_mmspecs
good_stdspecs = constants.IPOLICY_DEFAULTS[constants.ISPECS_STD]
self._TestInvalidISpecs(None, good_stdspecs, fail=False)
broken_stdspecs = copy.deepcopy(good_stdspecs)
for par in constants.ISPECS_PARAMETERS:
old = broken_stdspecs[par]
broken_stdspecs[par] = "invalid"
self._TestInvalidISpecs(None, broken_stdspecs)
broken_stdspecs[par] = old
broken_stdspecs["invalid_key"] = None
self._TestInvalidISpecs(None, broken_stdspecs)
del broken_stdspecs["invalid_key"]
assert broken_stdspecs == good_stdspecs
def testAllowedValues(self):
allowedv = "blah"
exp_pol1 = {
constants.ISPECS_MINMAX: allowedv,
constants.IPOLICY_DTS: allowedv,
constants.IPOLICY_VCPU_RATIO: allowedv,
constants.IPOLICY_SPINDLE_RATIO: allowedv,
}
pol1 = cli.CreateIPolicyFromOpts(minmax_ispecs=[{allowedv: {}}],
std_ispecs=None,
ipolicy_disk_templates=allowedv,
ipolicy_vcpu_ratio=allowedv,
ipolicy_spindle_ratio=allowedv,
allowed_values=[allowedv])
self.assertEqual(pol1, exp_pol1)
@staticmethod
def _ConvertSpecToStrings(spec):
ret = {}
for (par, val) in spec.items():
ret[par] = str(val)
return ret
def _CheckNewStyleSpecsCall(self, exp_ipolicy, minmax_ispecs, std_ispecs,
group_ipolicy, fill_all):
ipolicy = cli.CreateIPolicyFromOpts(minmax_ispecs=minmax_ispecs,
std_ispecs=std_ispecs,
group_ipolicy=group_ipolicy,
fill_all=fill_all)
self.assertEqual(ipolicy, exp_ipolicy)
def _TestFullISpecsInner(self, skel_exp_ipol, exp_minmax, exp_std,
group_ipolicy, fill_all):
exp_ipol = skel_exp_ipol.copy()
if exp_minmax is not None:
minmax_ispecs = []
for exp_mm_pair in exp_minmax:
mmpair = {}
for (key, spec) in exp_mm_pair.items():
mmpair[key] = self._ConvertSpecToStrings(spec)
minmax_ispecs.append(mmpair)
exp_ipol[constants.ISPECS_MINMAX] = exp_minmax
else:
minmax_ispecs = None
if exp_std is not None:
std_ispecs = self._ConvertSpecToStrings(exp_std)
exp_ipol[constants.ISPECS_STD] = exp_std
else:
std_ispecs = None
self._CheckNewStyleSpecsCall(exp_ipol, minmax_ispecs, std_ispecs,
group_ipolicy, fill_all)
if minmax_ispecs:
for mmpair in minmax_ispecs:
for (key, spec) in mmpair.items():
for par in [constants.ISPEC_MEM_SIZE, constants.ISPEC_DISK_SIZE]:
if par in spec:
spec[par] += "m"
self._CheckNewStyleSpecsCall(exp_ipol, minmax_ispecs, std_ispecs,
group_ipolicy, fill_all)
if std_ispecs:
for par in [constants.ISPEC_MEM_SIZE, constants.ISPEC_DISK_SIZE]:
if par in std_ispecs:
std_ispecs[par] += "m"
self._CheckNewStyleSpecsCall(exp_ipol, minmax_ispecs, std_ispecs,
group_ipolicy, fill_all)
def testFullISpecs(self):
exp_minmax1 = [
{
constants.ISPECS_MIN: {
constants.ISPEC_MEM_SIZE: 512,
constants.ISPEC_CPU_COUNT: 2,
constants.ISPEC_DISK_COUNT: 2,
constants.ISPEC_DISK_SIZE: 512,
constants.ISPEC_NIC_COUNT: 2,
constants.ISPEC_SPINDLE_USE: 2,
},
constants.ISPECS_MAX: {
constants.ISPEC_MEM_SIZE: 768*1024,
constants.ISPEC_CPU_COUNT: 7,
constants.ISPEC_DISK_COUNT: 6,
constants.ISPEC_DISK_SIZE: 2048*1024,
constants.ISPEC_NIC_COUNT: 3,
constants.ISPEC_SPINDLE_USE: 3,
},
},
]
exp_minmax2 = [
{
constants.ISPECS_MIN: {
constants.ISPEC_MEM_SIZE: 512,
constants.ISPEC_CPU_COUNT: 2,
constants.ISPEC_DISK_COUNT: 2,
constants.ISPEC_DISK_SIZE: 512,
constants.ISPEC_NIC_COUNT: 2,
constants.ISPEC_SPINDLE_USE: 2,
},
constants.ISPECS_MAX: {
constants.ISPEC_MEM_SIZE: 768*1024,
constants.ISPEC_CPU_COUNT: 7,
constants.ISPEC_DISK_COUNT: 6,
constants.ISPEC_DISK_SIZE: 2048*1024,
constants.ISPEC_NIC_COUNT: 3,
constants.ISPEC_SPINDLE_USE: 3,
},
},
{
constants.ISPECS_MIN: {
constants.ISPEC_MEM_SIZE: 1024*1024,
constants.ISPEC_CPU_COUNT: 3,
constants.ISPEC_DISK_COUNT: 3,
constants.ISPEC_DISK_SIZE: 256,
constants.ISPEC_NIC_COUNT: 4,
constants.ISPEC_SPINDLE_USE: 5,
},
constants.ISPECS_MAX: {
constants.ISPEC_MEM_SIZE: 2048*1024,
constants.ISPEC_CPU_COUNT: 5,
constants.ISPEC_DISK_COUNT: 5,
constants.ISPEC_DISK_SIZE: 1024*1024,
constants.ISPEC_NIC_COUNT: 5,
constants.ISPEC_SPINDLE_USE: 7,
},
},
]
exp_std1 = {
constants.ISPEC_MEM_SIZE: 768*1024,
constants.ISPEC_CPU_COUNT: 7,
constants.ISPEC_DISK_COUNT: 6,
constants.ISPEC_DISK_SIZE: 2048*1024,
constants.ISPEC_NIC_COUNT: 3,
constants.ISPEC_SPINDLE_USE: 1,
}
for fill_all in [False, True]:
if fill_all:
skel_ipolicy = constants.IPOLICY_DEFAULTS
else:
skel_ipolicy = {}
self._TestFullISpecsInner(skel_ipolicy, None, exp_std1,
False, fill_all)
for exp_minmax in [exp_minmax1, exp_minmax2]:
self._TestFullISpecsInner(skel_ipolicy, exp_minmax, exp_std1,
False, fill_all)
self._TestFullISpecsInner(skel_ipolicy, exp_minmax, None,
False, fill_all)
class TestPrintIPolicyCommand(unittest.TestCase):
"""Test case for cli.PrintIPolicyCommand"""
_SPECS1 = {
"par1": 42,
"par2": "xyz",
}
_SPECS1_STR = "par1=42,par2=xyz"
_SPECS2 = {
"param": 10,
"another_param": 101,
}
_SPECS2_STR = "another_param=101,param=10"
_SPECS3 = {
"par1": 1024,
"param": "abc",
}
_SPECS3_STR = "par1=1024,param=abc"
def _CheckPrintIPolicyCommand(self, ipolicy, isgroup, expected):
buf = StringIO()
cli.PrintIPolicyCommand(buf, ipolicy, isgroup)
self.assertEqual(buf.getvalue(), expected)
def testIgnoreStdForGroup(self):
self._CheckPrintIPolicyCommand({"std": self._SPECS1}, True, "")
def testIgnoreEmpty(self):
policies = [
{},
{"std": {}},
{"minmax": []},
{"minmax": [{}]},
{"minmax": [{
"min": {},
"max": {},
}]},
{"minmax": [{
"min": self._SPECS1,
"max": {},
}]},
]
for pol in policies:
self._CheckPrintIPolicyCommand(pol, False, "")
def testFullPolicies(self):
cases = [
({"std": self._SPECS1},
" %s %s" % (cli.IPOLICY_STD_SPECS_STR, self._SPECS1_STR)),
({"minmax": [{
"min": self._SPECS1,
"max": self._SPECS2,
}]},
" %s min:%s/max:%s" % (cli.IPOLICY_BOUNDS_SPECS_STR,
self._SPECS1_STR, self._SPECS2_STR)),
({"minmax": [
{
"min": self._SPECS1,
"max": self._SPECS2,
},
{
"min": self._SPECS2,
"max": self._SPECS3,
},
]},
" %s min:%s/max:%s//min:%s/max:%s" %
(cli.IPOLICY_BOUNDS_SPECS_STR, self._SPECS1_STR, self._SPECS2_STR,
self._SPECS2_STR, self._SPECS3_STR)),
]
for (pol, exp) in cases:
self._CheckPrintIPolicyCommand(pol, False, exp)
if __name__ == "__main__":
testutils.GanetiTestProgram()
| bsd-2-clause | -6,707,811,661,163,229,000 | 33.804726 | 80 | 0.565897 | false |
vermamanoj/soc_2017Jul | qradar/qradar_connector.py | 1 | 1977 | #!/usr/bin/env python3
import os
import sys
import requests
from configparser import ConfigParser
from gentelella.core import global_config
import logging
logger = logging.getLogger('root')
FORMAT = "[%(filename)s:%(lineno)s-%(funcName)s] %(message)s"
logging.basicConfig(format=FORMAT)
logger.setLevel(logging.INFO)
def get_qradar_config():
# The function does not take any input
# In the output it sends URL, username and password of ServiceNow
# The variable snow_config_exists is used to verify if config was read properly or not
# and its used to return error message if it remains False
qradar_config_exists = 0
# Call get_global_config function to read name and path of ServiceNow credentials file
global_configuration = global_config.get_global_config()
if global_configuration['outcome'] == 'success':
configFile = global_configuration['data']['credentials_file']
logger.warning(configFile)
try:
if os.path.exists(configFile):
config = ConfigParser()
config.read(r'./config/config.ini')
print(config)
if 'qradar' in config.sections():
logger.warning("Qradar config exists..................")
host = config['qradar']['host']
port = config['qradar']['port']
username = config['qradar']['username']
password = config['qradar']['password']
result = {
"outcome":"success",
"success":{"host": host, "port":port, "username":username, "password":password}
}
qradar_config_exists = 1
return result
except:
logger.error(sys.exc_info())
if qradar_config_exists == 0:
result = {
"outcome": "error",
"error": "Configuration does not exist"
}
return result
| mit | 6,896,249,320,087,742,000 | 31.95 | 99 | 0.583713 | false |
danielfrg/cyhdfs3 | cyhdfs3/tests/test_others.py | 2 | 2534 | from __future__ import print_function, absolute_import
from utils import *
import posixpath
def test_is_pickeable(hdfs):
import pickle
hdfs2 = pickle.loads(pickle.dumps(hdfs))
assert hdfs.host == hdfs2.host
assert hdfs.port == hdfs2.port
def multiprocess_func(section):
import os
import cyhdfs3
host = os.environ.get('HDFS_HOSTNAME', 'localhost')
port = os.environ.get('HDFS_port', 8020)
hdfs = cyhdfs3.HDFSClient(host=host, port=port)
# Hardcoded
data1 = b'0' * 1 * 2**20
data2 = b'1' * 1 * 2**20
data3 = b'2' * 1 * 2**20
data4 = b'3' * 1 * 2**20
data5 = b'4' * 1 * 2**20
data_l = [data1, data2, data3, data4, data5]
data = b''.join(data_l)
fname = '/tmp/cyhdfs3-test/test_multiprocess'
#
with hdfs.open(fname, 'r') as f:
f.seek(section * 2**20)
read = f.read(2**20)
assert len(read) == 2**20
assert read == data_l[section]
def test_multiprocess(hdfs, request):
testname = request.node.name
fname = posixpath.join(TEST_DIR, testname)
data = b'0' * 1 * 2**20
data += b'1' * 1 * 2**20
data += b'2' * 1 * 2**20
data += b'3' * 1 * 2**20
data += b'4' * 1 * 2**20
with hdfs.open(fname, 'w', replication=1) as f:
f.write(data)
from multiprocessing import Pool
p = Pool(3)
p.map(multiprocess_func, [0, 1, 2, 3, 4])
def multiprocess_func_2(hdfs, section):
# Hardcoded
data1 = b'0' * 1 * 2**20
data2 = b'1' * 1 * 2**20
data3 = b'2' * 1 * 2**20
data4 = b'3' * 1 * 2**20
data5 = b'4' * 1 * 2**20
data_l = [data1, data2, data3, data4, data5]
data = b''.join(data_l)
fname = '/tmp/cyhdfs3-test/test_stress_read'
#
with hdfs.open(fname, 'r') as f:
f.seek(section * 2**20)
read = f.read(2**20)
assert len(read) == 2**20
assert read == data_l[section]
def test_stress_read(hdfs, request):
import multiprocessing
from threading import Thread
testname = request.node.name
fname = posixpath.join(TEST_DIR, testname)
data = b'0' * 1 * 2**20
data += b'1' * 1 * 2**20
data += b'2' * 1 * 2**20
data += b'3' * 1 * 2**20
data += b'4' * 1 * 2**20
with hdfs.open(fname, 'w') as f:
f.write(data)
for T in (Thread, multiprocessing.Process,):
threads = [T(target=multiprocess_func_2, args=(hdfs, i)) for i in range(5)]
for t in threads:
t.daemon = True
t.start()
for t in threads:
t.join()
| apache-2.0 | -1,614,664,590,902,767,900 | 24.59596 | 83 | 0.554065 | false |
malirod/dip | src/client.py | 1 | 1093 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from util.path import get_input_files, get_file_ext
from config import (INPUT_DIR, VALID_EXTS, BEANSTALK_HOST,
BEANSTALK_PORT, BEANSTALK_TUBE)
from util.log import setup_logging
from os.path import join
import logging
import beanstalkc
logger = logging.getLogger('client')
def process_image(connection, input_file_path):
try:
logger.info('Processing file "{}"'.format(input_file_path))
connection.put(input_file_path)
except Exception as e:
logger.error('Failed to process image {}. Error: {}'.format(input_file_path, e))
def process_input():
logger.info('Creating connection')
connection = beanstalkc.Connection(
host=BEANSTALK_HOST, port=BEANSTALK_PORT, parse_yaml=False)
connection.use(BEANSTALK_TUBE)
files = get_input_files(INPUT_DIR)
for item in files:
if get_file_ext(item) in VALID_EXTS:
process_image(connection, join(INPUT_DIR, item))
logger.info('Done')
if __name__ == '__main__':
setup_logging()
process_input()
| gpl-3.0 | 5,113,143,107,435,902,000 | 26.325 | 88 | 0.666057 | false |
oliverlee/sympy | sympy/combinatorics/tensor_can.py | 13 | 40944 | from __future__ import print_function, division
from sympy.core.compatibility import range
from sympy.combinatorics.permutations import Permutation, _af_rmul, \
_af_invert, _af_new
from sympy.combinatorics.perm_groups import PermutationGroup, _orbit, \
_orbit_transversal
from sympy.combinatorics.util import _distribute_gens_by_base, \
_orbits_transversals_from_bsgs
"""
References for tensor canonicalization:
[1] R. Portugal "Algorithmic simplification of tensor expressions",
J. Phys. A 32 (1999) 7779-7789
[2] R. Portugal, B.F. Svaiter "Group-theoretic Approach for Symbolic
Tensor Manipulation: I. Free Indices"
arXiv:math-ph/0107031v1
[3] L.R.U. Manssur, R. Portugal "Group-theoretic Approach for Symbolic
Tensor Manipulation: II. Dummy Indices"
arXiv:math-ph/0107032v1
[4] xperm.c part of XPerm written by J. M. Martin-Garcia
http://www.xact.es/index.html
"""
def dummy_sgs(dummies, sym, n):
"""
Return the strong generators for dummy indices
Parameters
==========
dummies : list of dummy indices
`dummies[2k], dummies[2k+1]` are paired indices
sym : symmetry under interchange of contracted dummies::
* None no symmetry
* 0 commuting
* 1 anticommuting
n : number of indices
in base form the dummy indices are always in consecutive positions
Examples
========
>>> from sympy.combinatorics.tensor_can import dummy_sgs
>>> dummy_sgs(range(2, 8), 0, 8)
[[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9],
[0, 1, 2, 3, 6, 7, 4, 5, 8, 9]]
"""
if len(dummies) > n:
raise ValueError("List too large")
res = []
# exchange of contravariant and covariant indices
if sym is not None:
for j in dummies[::2]:
a = list(range(n + 2))
if sym == 1:
a[n] = n + 1
a[n + 1] = n
a[j], a[j + 1] = a[j + 1], a[j]
res.append(a)
# rename dummy indices
for j in dummies[:-3:2]:
a = list(range(n + 2))
a[j:j + 4] = a[j + 2], a[j + 3], a[j], a[j + 1]
res.append(a)
return res
def _min_dummies(dummies, sym, indices):
"""
Return list of minima of the orbits of indices in group of dummies
see `double_coset_can_rep` for the description of `dummies` and `sym`
indices is the initial list of dummy indices
Examples
========
>>> from sympy.combinatorics.tensor_can import _min_dummies
>>> _min_dummies([list(range(2, 8))], [0], list(range(10)))
[0, 1, 2, 2, 2, 2, 2, 2, 8, 9]
"""
num_types = len(sym)
m = []
for dx in dummies:
if dx:
m.append(min(dx))
else:
m.append(None)
res = indices[:]
for i in range(num_types):
for c, i in enumerate(indices):
for j in range(num_types):
if i in dummies[j]:
res[c] = m[j]
break
return res
def _trace_S(s, j, b, S_cosets):
"""
Return the representative h satisfying s[h[b]] == j
If there is not such a representative return None
"""
for h in S_cosets[b]:
if s[h[b]] == j:
return h
return None
def _trace_D(gj, p_i, Dxtrav):
"""
Return the representative h satisfying h[gj] == p_i
If there is not such a representative return None
"""
for h in Dxtrav:
if h[gj] == p_i:
return h
return None
def _dumx_remove(dumx, dumx_flat, p0):
"""
remove p0 from dumx
"""
res = []
for dx in dumx:
if p0 not in dx:
res.append(dx)
continue
k = dx.index(p0)
if k % 2 == 0:
p0_paired = dx[k + 1]
else:
p0_paired = dx[k - 1]
dx.remove(p0)
dx.remove(p0_paired)
dumx_flat.remove(p0)
dumx_flat.remove(p0_paired)
res.append(dx)
def transversal2coset(size, base, transversal):
a = []
j = 0
for i in range(size):
if i in base:
a.append(sorted(transversal[j].values()))
j += 1
else:
a.append([list(range(size))])
j = len(a) - 1
while a[j] == [list(range(size))]:
j -= 1
return a[:j + 1]
def double_coset_can_rep(dummies, sym, b_S, sgens, S_transversals, g):
"""
Butler-Portugal algorithm for tensor canonicalization with dummy indices
dummies
list of lists of dummy indices,
one list for each type of index;
the dummy indices are put in order contravariant, covariant
[d0, -d0, d1, -d1, ...].
sym
list of the symmetries of the index metric for each type.
possible symmetries of the metrics
* 0 symmetric
* 1 antisymmetric
* None no symmetry
b_S
base of a minimal slot symmetry BSGS.
sgens
generators of the slot symmetry BSGS.
S_transversals
transversals for the slot BSGS.
g
permutation representing the tensor.
Return 0 if the tensor is zero, else return the array form of
the permutation representing the canonical form of the tensor.
A tensor with dummy indices can be represented in a number
of equivalent ways which typically grows exponentially with
the number of indices. To be able to establish if two tensors
with many indices are equal becomes computationally very slow
in absence of an efficient algorithm.
The Butler-Portugal algorithm [3] is an efficient algorithm to
put tensors in canonical form, solving the above problem.
Portugal observed that a tensor can be represented by a permutation,
and that the class of tensors equivalent to it under slot and dummy
symmetries is equivalent to the double coset `D*g*S`
(Note: in this documentation we use the conventions for multiplication
of permutations p, q with (p*q)(i) = p[q[i]] which is opposite
to the one used in the Permutation class)
Using the algorithm by Butler to find a representative of the
double coset one can find a canonical form for the tensor.
To see this correspondence,
let `g` be a permutation in array form; a tensor with indices `ind`
(the indices including both the contravariant and the covariant ones)
can be written as
`t = T(ind[g[0],..., ind[g[n-1]])`,
where `n= len(ind)`;
`g` has size `n + 2`, the last two indices for the sign of the tensor
(trick introduced in [4]).
A slot symmetry transformation `s` is a permutation acting on the slots
`t -> T(ind[(g*s)[0]],..., ind[(g*s)[n-1]])`
A dummy symmetry transformation acts on `ind`
`t -> T(ind[(d*g)[0]],..., ind[(d*g)[n-1]])`
Being interested only in the transformations of the tensor under
these symmetries, one can represent the tensor by `g`, which transforms
as
`g -> d*g*s`, so it belongs to the coset `D*g*S`.
Let us explain the conventions by an example.
Given a tensor `T^{d3 d2 d1}{}_{d1 d2 d3}` with the slot symmetries
`T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`
`T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}`
and symmetric metric, find the tensor equivalent to it which
is the lowest under the ordering of indices:
lexicographic ordering `d1, d2, d3` then and contravariant index
before covariant index; that is the canonical form of the tensor.
The canonical form is `-T^{d1 d2 d3}{}_{d1 d2 d3}`
obtained using `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`.
To convert this problem in the input for this function,
use the following labelling of the index names
(- for covariant for short) `d1, -d1, d2, -d2, d3, -d3`
`T^{d3 d2 d1}{}_{d1 d2 d3}` corresponds to `g = [4, 2, 0, 1, 3, 5, 6, 7]`
where the last two indices are for the sign
`sgens = [Permutation(0, 2)(6, 7), Permutation(0, 4)(6, 7)]`
sgens[0] is the slot symmetry `-(0, 2)`
`T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`
sgens[1] is the slot symmetry `-(0, 4)`
`T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}`
The dummy symmetry group D is generated by the strong base generators
`[(0, 1), (2, 3), (4, 5), (0, 1)(2, 3),(2, 3)(4, 5)]`
The dummy symmetry acts from the left
`d = [1, 0, 2, 3, 4, 5, 6, 7]` exchange `d1 -> -d1`
`T^{d3 d2 d1}{}_{d1 d2 d3} == T^{d3 d2}{}_{d1}{}^{d1}{}_{d2 d3}`
`g=[4, 2, 0, 1, 3, 5, 6, 7] -> [4, 2, 1, 0, 3, 5, 6, 7] = _af_rmul(d, g)`
which differs from `_af_rmul(g, d)`.
The slot symmetry acts from the right
`s = [2, 1, 0, 3, 4, 5, 7, 6]` exchanges slots 0 and 2 and changes sign
`T^{d3 d2 d1}{}_{d1 d2 d3} == -T^{d1 d2 d3}{}_{d1 d2 d3}`
`g=[4,2,0,1,3,5,6,7] -> [0, 2, 4, 1, 3, 5, 7, 6] = _af_rmul(g, s)`
Example in which the tensor is zero, same slot symmetries as above:
`T^{d3}{}_{d1,d2}{}^{d1}{}_{d3}{}^{d2}`
`= -T^{d3}{}_{d1,d3}{}^{d1}{}_{d2}{}^{d2}` under slot symmetry `-(2,4)`;
`= T_{d3 d1}{}^{d3}{}^{d1}{}_{d2}{}^{d2}` under slot symmetry `-(0,2)`;
`= T^{d3}{}_{d1 d3}{}^{d1}{}_{d2}{}^{d2}` symmetric metric;
`= 0` since two of these lines have tensors differ only for the sign.
The double coset D*g*S consists of permutations `h = d*g*s` corresponding
to equivalent tensors; if there are two `h` which are the same apart
from the sign, return zero; otherwise
choose as representative the tensor with indices
ordered lexicographically according to `[d1, -d1, d2, -d2, d3, -d3]`
that is `rep = min(D*g*S) = min([d*g*s for d in D for s in S])`
The indices are fixed one by one; first choose the lowest index
for slot 0, then the lowest remaining index for slot 1, etc.
Doing this one obtains a chain of stabilizers
`S -> S_{b0} -> S_{b0,b1} -> ...` and
`D -> D_{p0} -> D_{p0,p1} -> ...`
where `[b0, b1, ...] = range(b)` is a base of the symmetric group;
the strong base `b_S` of S is an ordered sublist of it;
therefore it is sufficient to compute once the
strong base generators of S using the Schreier-Sims algorithm;
the stabilizers of the strong base generators are the
strong base generators of the stabilizer subgroup.
`dbase = [p0, p1, ...]` is not in general in lexicographic order,
so that one must recompute the strong base generators each time;
however this is trivial, there is no need to use the Schreier-Sims
algorithm for D.
The algorithm keeps a TAB of elements `(s_i, d_i, h_i)`
where `h_i = d_i*g*s_i` satisfying `h_i[j] = p_j` for `0 <= j < i`
starting from `s_0 = id, d_0 = id, h_0 = g`.
The equations `h_0[0] = p_0, h_1[1] = p_1,...` are solved in this order,
choosing each time the lowest possible value of p_i
For `j < i`
`d_i*g*s_i*S_{b_0,...,b_{i-1}}*b_j = D_{p_0,...,p_{i-1}}*p_j`
so that for dx in `D_{p_0,...,p_{i-1}}` and sx in
`S_{base[0],...,base[i-1]}` one has `dx*d_i*g*s_i*sx*b_j = p_j`
Search for dx, sx such that this equation holds for `j = i`;
it can be written as `s_i*sx*b_j = J, dx*d_i*g*J = p_j`
`sx*b_j = s_i**-1*J; sx = trace(s_i**-1, S_{b_0,...,b_{i-1}})`
`dx**-1*p_j = d_i*g*J; dx = trace(d_i*g*J, D_{p_0,...,p_{i-1}})`
`s_{i+1} = s_i*trace(s_i**-1*J, S_{b_0,...,b_{i-1}})`
`d_{i+1} = trace(d_i*g*J, D_{p_0,...,p_{i-1}})**-1*d_i`
`h_{i+1}*b_i = d_{i+1}*g*s_{i+1}*b_i = p_i`
`h_n*b_j = p_j` for all j, so that `h_n` is the solution.
Add the found `(s, d, h)` to TAB1.
At the end of the iteration sort TAB1 with respect to the `h`;
if there are two consecutive `h` in TAB1 which differ only for the
sign, the tensor is zero, so return 0;
if there are two consecutive `h` which are equal, keep only one.
Then stabilize the slot generators under `i` and the dummy generators
under `p_i`.
Assign `TAB = TAB1` at the end of the iteration step.
At the end `TAB` contains a unique `(s, d, h)`, since all the slots
of the tensor `h` have been fixed to have the minimum value according
to the symmetries. The algorithm returns `h`.
It is important that the slot BSGS has lexicographic minimal base,
otherwise there is an `i` which does not belong to the slot base
for which `p_i` is fixed by the dummy symmetry only, while `i`
is not invariant from the slot stabilizer, so `p_i` is not in
general the minimal value.
This algorithm differs slightly from the original algorithm [3]:
the canonical form is minimal lexicographically, and
the BSGS has minimal base under lexicographic order.
Equal tensors `h` are eliminated from TAB.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> from sympy.combinatorics.tensor_can import double_coset_can_rep, get_transversals
>>> gens = [Permutation(x) for x in [[2, 1, 0, 3, 4, 5, 7, 6], [4, 1, 2, 3, 0, 5, 7, 6]]]
>>> base = [0, 2]
>>> g = Permutation([4, 2, 0, 1, 3, 5, 6, 7])
>>> transversals = get_transversals(base, gens)
>>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g)
[0, 1, 2, 3, 4, 5, 7, 6]
>>> g = Permutation([4, 1, 3, 0, 5, 2, 6, 7])
>>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g)
0
"""
size = g.size
g = g.array_form
num_dummies = size - 2
indices = list(range(num_dummies))
all_metrics_with_sym = all([_ is not None for _ in sym])
num_types = len(sym)
dumx = dummies[:]
dumx_flat = []
for dx in dumx:
dumx_flat.extend(dx)
b_S = b_S[:]
sgensx = [h._array_form for h in sgens]
if b_S:
S_transversals = transversal2coset(size, b_S, S_transversals)
# strong generating set for D
dsgsx = []
for i in range(num_types):
dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies))
ginv = _af_invert(g)
idn = list(range(size))
# TAB = list of entries (s, d, h) where h = _af_rmuln(d,g,s)
# for short, in the following d*g*s means _af_rmuln(d,g,s)
TAB = [(idn, idn, g)]
for i in range(size - 2):
b = i
testb = b in b_S and sgensx
if testb:
sgensx1 = [_af_new(_) for _ in sgensx]
deltab = _orbit(size, sgensx1, b)
else:
deltab = set([b])
# p1 = min(IMAGES) = min(Union D_p*h*deltab for h in TAB)
if all_metrics_with_sym:
md = _min_dummies(dumx, sym, indices)
else:
md = [min(_orbit(size, [_af_new(
ddx) for ddx in dsgsx], ii)) for ii in range(size - 2)]
p_i = min([min([md[h[x]] for x in deltab]) for s, d, h in TAB])
dsgsx1 = [_af_new(_) for _ in dsgsx]
Dxtrav = _orbit_transversal(size, dsgsx1, p_i, False, af=True) \
if dsgsx else None
if Dxtrav:
Dxtrav = [_af_invert(x) for x in Dxtrav]
# compute the orbit of p_i
for ii in range(num_types):
if p_i in dumx[ii]:
# the orbit is made by all the indices in dum[ii]
if sym[ii] is not None:
deltap = dumx[ii]
else:
# the orbit is made by all the even indices if p_i
# is even, by all the odd indices if p_i is odd
p_i_index = dumx[ii].index(p_i) % 2
deltap = dumx[ii][p_i_index::2]
break
else:
deltap = [p_i]
TAB1 = []
nTAB = len(TAB)
while TAB:
s, d, h = TAB.pop()
if min([md[h[x]] for x in deltab]) != p_i:
continue
deltab1 = [x for x in deltab if md[h[x]] == p_i]
# NEXT = s*deltab1 intersection (d*g)**-1*deltap
dg = _af_rmul(d, g)
dginv = _af_invert(dg)
sdeltab = [s[x] for x in deltab1]
gdeltap = [dginv[x] for x in deltap]
NEXT = [x for x in sdeltab if x in gdeltap]
# d, s satisfy
# d*g*s*base[i-1] = p_{i-1}; using the stabilizers
# d*g*s*S_{base[0],...,base[i-1]}*base[i-1] =
# D_{p_0,...,p_{i-1}}*p_{i-1}
# so that to find d1, s1 satisfying d1*g*s1*b = p_i
# one can look for dx in D_{p_0,...,p_{i-1}} and
# sx in S_{base[0],...,base[i-1]}
# d1 = dx*d; s1 = s*sx
# d1*g*s1*b = dx*d*g*s*sx*b = p_i
for j in NEXT:
if testb:
# solve s1*b = j with s1 = s*sx for some element sx
# of the stabilizer of ..., base[i-1]
# sx*b = s**-1*j; sx = _trace_S(s, j,...)
# s1 = s*trace_S(s**-1*j,...)
s1 = _trace_S(s, j, b, S_transversals)
if not s1:
continue
else:
s1 = [s[ix] for ix in s1]
else:
s1 = s
# assert s1[b] == j # invariant
# solve d1*g*j = p_i with d1 = dx*d for some element dg
# of the stabilizer of ..., p_{i-1}
# dx**-1*p_i = d*g*j; dx**-1 = trace_D(d*g*j,...)
# d1 = trace_D(d*g*j,...)**-1*d
# to save an inversion in the inner loop; notice we did
# Dxtrav = [perm_af_invert(x) for x in Dxtrav] out of the loop
if Dxtrav:
d1 = _trace_D(dg[j], p_i, Dxtrav)
if not d1:
continue
else:
if p_i != dg[j]:
continue
d1 = idn
assert d1[dg[j]] == p_i # invariant
d1 = [d1[ix] for ix in d]
h1 = [d1[g[ix]] for ix in s1]
# assert h1[b] == p_i # invariant
TAB1.append((s1, d1, h1))
# if TAB contains equal permutations, keep only one of them;
# if TAB contains equal permutations up to the sign, return 0
TAB1.sort(key=lambda x: x[-1])
nTAB1 = len(TAB1)
prev = [0] * size
while TAB1:
s, d, h = TAB1.pop()
if h[:-2] == prev[:-2]:
if h[-1] != prev[-1]:
return 0
else:
TAB.append((s, d, h))
prev = h
# stabilize the SGS
sgensx = [h for h in sgensx if h[b] == b]
if b in b_S:
b_S.remove(b)
_dumx_remove(dumx, dumx_flat, p_i)
dsgsx = []
for i in range(num_types):
dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies))
return TAB[0][-1]
def canonical_free(base, gens, g, num_free):
"""
canonicalization of a tensor with respect to free indices
choosing the minimum with respect to lexicographical ordering
in the free indices
``base``, ``gens`` BSGS for slot permutation group
``g`` permutation representing the tensor
``num_free`` number of free indices
The indices must be ordered with first the free indices
see explanation in double_coset_can_rep
The algorithm is a variation of the one given in [2].
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import canonical_free
>>> gens = [[1, 0, 2, 3, 5, 4], [2, 3, 0, 1, 4, 5],[0, 1, 3, 2, 5, 4]]
>>> gens = [Permutation(h) for h in gens]
>>> base = [0, 2]
>>> g = Permutation([2, 1, 0, 3, 4, 5])
>>> canonical_free(base, gens, g, 4)
[0, 3, 1, 2, 5, 4]
Consider the product of Riemann tensors
``T = R^{a}_{d0}^{d1,d2}*R_{d2,d1}^{d0,b}``
The order of the indices is ``[a, b, d0, -d0, d1, -d1, d2, -d2]``
The permutation corresponding to the tensor is
``g = [0, 3, 4, 6, 7, 5, 2, 1, 8, 9]``
In particular ``a`` is position ``0``, ``b`` is in position ``9``.
Use the slot symmetries to get `T` is a form which is the minimal
in lexicographic order in the free indices ``a`` and ``b``, e.g.
``-R^{a}_{d0}^{d1,d2}*R^{b,d0}_{d2,d1}`` corresponding to
``[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]``
>>> from sympy.combinatorics.tensor_can import riemann_bsgs, tensor_gens
>>> base, gens = riemann_bsgs
>>> size, sbase, sgens = tensor_gens(base, gens, [[], []], 0)
>>> g = Permutation([0, 3, 4, 6, 7, 5, 2, 1, 8, 9])
>>> canonical_free(sbase, [Permutation(h) for h in sgens], g, 2)
[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]
"""
g = g.array_form
size = len(g)
if not base:
return g[:]
transversals = get_transversals(base, gens)
m = len(base)
for x in sorted(g[:-2]):
if x not in base:
base.append(x)
h = g
for i, transv in enumerate(transversals):
b = base[i]
h_i = [size]*num_free
# find the element s in transversals[i] such that
# _af_rmul(h, s) has its free elements with the lowest position in h
s = None
for sk in transv.values():
h1 = _af_rmul(h, sk)
hi = [h1.index(ix) for ix in range(num_free)]
if hi < h_i:
h_i = hi
s = sk
if s:
h = _af_rmul(h, s)
return h
def _get_map_slots(size, fixed_slots):
res = list(range(size))
pos = 0
for i in range(size):
if i in fixed_slots:
continue
res[i] = pos
pos += 1
return res
def _lift_sgens(size, fixed_slots, free, s):
a = []
j = k = 0
fd = list(zip(fixed_slots, free))
fd = [y for x, y in sorted(fd)]
num_free = len(free)
for i in range(size):
if i in fixed_slots:
a.append(fd[k])
k += 1
else:
a.append(s[j] + num_free)
j += 1
return a
def canonicalize(g, dummies, msym, *v):
"""
canonicalize tensor formed by tensors
Parameters
==========
g : permutation representing the tensor
dummies : list representing the dummy indices
it can be a list of dummy indices of the same type
or a list of lists of dummy indices, one list for each
type of index;
the dummy indices must come after the free indices,
and put in order contravariant, covariant
[d0, -d0, d1,-d1,...]
msym : symmetry of the metric(s)
it can be an integer or a list;
in the first case it is the symmetry of the dummy index metric;
in the second case it is the list of the symmetries of the
index metric for each type
v : list, (base_i, gens_i, n_i, sym_i) for tensors of type `i`
base_i, gens_i : BSGS for tensors of this type.
The BSGS should have minimal base under lexicographic ordering;
if not, an attempt is made do get the minimal BSGS;
in case of failure,
canonicalize_naive is used, which is much slower.
n_i : number of tensors of type `i`.
sym_i : symmetry under exchange of component tensors of type `i`.
Both for msym and sym_i the cases are
* None no symmetry
* 0 commuting
* 1 anticommuting
Returns
=======
0 if the tensor is zero, else return the array form of
the permutation representing the canonical form of the tensor.
Algorithm
=========
First one uses canonical_free to get the minimum tensor under
lexicographic order, using only the slot symmetries.
If the component tensors have not minimal BSGS, it is attempted
to find it; if the attempt fails canonicalize_naive
is used instead.
Compute the residual slot symmetry keeping fixed the free indices
using tensor_gens(base, gens, list_free_indices, sym).
Reduce the problem eliminating the free indices.
Then use double_coset_can_rep and lift back the result reintroducing
the free indices.
Examples
========
one type of index with commuting metric;
`A_{a b}` and `B_{a b}` antisymmetric and commuting
`T = A_{d0 d1} * B^{d0}{}_{d2} * B^{d2 d1}`
`ord = [d0,-d0,d1,-d1,d2,-d2]` order of the indices
g = [1, 3, 0, 5, 4, 2, 6, 7]
`T_c = 0`
>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize, bsgs_direct_product
>>> from sympy.combinatorics import Permutation
>>> base2a, gens2a = get_symmetric_group_sgs(2, 1)
>>> t0 = (base2a, gens2a, 1, 0)
>>> t1 = (base2a, gens2a, 2, 0)
>>> g = Permutation([1, 3, 0, 5, 4, 2, 6, 7])
>>> canonicalize(g, range(6), 0, t0, t1)
0
same as above, but with `B_{a b}` anticommuting
`T_c = -A^{d0 d1} * B_{d0}{}^{d2} * B_{d1 d2}`
can = [0,2,1,4,3,5,7,6]
>>> t1 = (base2a, gens2a, 2, 1)
>>> canonicalize(g, range(6), 0, t0, t1)
[0, 2, 1, 4, 3, 5, 7, 6]
two types of indices `[a,b,c,d,e,f]` and `[m,n]`, in this order,
both with commuting metric
`f^{a b c}` antisymmetric, commuting
`A_{m a}` no symmetry, commuting
`T = f^c{}_{d a} * f^f{}_{e b} * A_m{}^d * A^{m b} * A_n{}^a * A^{n e}`
ord = [c,f,a,-a,b,-b,d,-d,e,-e,m,-m,n,-n]
g = [0,7,3, 1,9,5, 11,6, 10,4, 13,2, 12,8, 14,15]
The canonical tensor is
`T_c = -f^{c a b} * f^{f d e} * A^m{}_a * A_{m d} * A^n{}_b * A_{n e}`
can = [0,2,4, 1,6,8, 10,3, 11,7, 12,5, 13,9, 15,14]
>>> base_f, gens_f = get_symmetric_group_sgs(3, 1)
>>> base1, gens1 = get_symmetric_group_sgs(1)
>>> base_A, gens_A = bsgs_direct_product(base1, gens1, base1, gens1)
>>> t0 = (base_f, gens_f, 2, 0)
>>> t1 = (base_A, gens_A, 4, 0)
>>> dummies = [range(2, 10), range(10, 14)]
>>> g = Permutation([0, 7, 3, 1, 9, 5, 11, 6, 10, 4, 13, 2, 12, 8, 14, 15])
>>> canonicalize(g, dummies, [0, 0], t0, t1)
[0, 2, 4, 1, 6, 8, 10, 3, 11, 7, 12, 5, 13, 9, 15, 14]
"""
from sympy.combinatorics.testutil import canonicalize_naive
if not isinstance(msym, list):
if not msym in [0, 1, None]:
raise ValueError('msym must be 0, 1 or None')
num_types = 1
else:
num_types = len(msym)
if not all(msymx in [0, 1, None] for msymx in msym):
raise ValueError('msym entries must be 0, 1 or None')
if len(dummies) != num_types:
raise ValueError(
'dummies and msym must have the same number of elements')
size = g.size
num_tensors = 0
v1 = []
for i in range(len(v)):
base_i, gens_i, n_i, sym_i = v[i]
# check that the BSGS is minimal;
# this property is used in double_coset_can_rep;
# if it is not minimal use canonicalize_naive
if not _is_minimal_bsgs(base_i, gens_i):
mbsgs = get_minimal_bsgs(base_i, gens_i)
if not mbsgs:
can = canonicalize_naive(g, dummies, msym, *v)
return can
base_i, gens_i = mbsgs
v1.append((base_i, gens_i, [[]] * n_i, sym_i))
num_tensors += n_i
if num_types == 1 and not isinstance(msym, list):
dummies = [dummies]
msym = [msym]
flat_dummies = []
for dumx in dummies:
flat_dummies.extend(dumx)
if flat_dummies and flat_dummies != list(range(flat_dummies[0], flat_dummies[-1] + 1)):
raise ValueError('dummies is not valid')
# slot symmetry of the tensor
size1, sbase, sgens = gens_products(*v1)
if size != size1:
raise ValueError(
'g has size %d, generators have size %d' % (size, size1))
free = [i for i in range(size - 2) if i not in flat_dummies]
num_free = len(free)
# g1 minimal tensor under slot symmetry
g1 = canonical_free(sbase, sgens, g, num_free)
if not flat_dummies:
return g1
# save the sign of g1
sign = 0 if g1[-1] == size - 1 else 1
# the free indices are kept fixed.
# Determine free_i, the list of slots of tensors which are fixed
# since they are occupied by free indices, which are fixed.
start = 0
for i in range(len(v)):
free_i = []
base_i, gens_i, n_i, sym_i = v[i]
len_tens = gens_i[0].size - 2
# for each component tensor get a list od fixed islots
for j in range(n_i):
# get the elements corresponding to the component tensor
h = g1[start:(start + len_tens)]
fr = []
# get the positions of the fixed elements in h
for k in free:
if k in h:
fr.append(h.index(k))
free_i.append(fr)
start += len_tens
v1[i] = (base_i, gens_i, free_i, sym_i)
# BSGS of the tensor with fixed free indices
# if tensor_gens fails in gens_product, use canonicalize_naive
size, sbase, sgens = gens_products(*v1)
# reduce the permutations getting rid of the free indices
pos_dummies = [g1.index(x) for x in flat_dummies]
pos_free = [g1.index(x) for x in range(num_free)]
size_red = size - num_free
g1_red = [x - num_free for x in g1 if x in flat_dummies]
if sign:
g1_red.extend([size_red - 1, size_red - 2])
else:
g1_red.extend([size_red - 2, size_red - 1])
map_slots = _get_map_slots(size, pos_free)
sbase_red = [map_slots[i] for i in sbase if i not in pos_free]
sgens_red = [_af_new([map_slots[i] for i in y._array_form if i not in pos_free]) for y in sgens]
dummies_red = [[x - num_free for x in y] for y in dummies]
transv_red = get_transversals(sbase_red, sgens_red)
g1_red = _af_new(g1_red)
g2 = double_coset_can_rep(
dummies_red, msym, sbase_red, sgens_red, transv_red, g1_red)
if g2 == 0:
return 0
# lift to the case with the free indices
g3 = _lift_sgens(size, pos_free, free, g2)
return g3
def perm_af_direct_product(gens1, gens2, signed=True):
"""
direct products of the generators gens1 and gens2
Examples
========
>>> from sympy.combinatorics.tensor_can import perm_af_direct_product
>>> gens1 = [[1, 0, 2, 3], [0, 1, 3, 2]]
>>> gens2 = [[1, 0]]
>>> perm_af_direct_product(gens1, gens2, False)
[[1, 0, 2, 3, 4, 5], [0, 1, 3, 2, 4, 5], [0, 1, 2, 3, 5, 4]]
>>> gens1 = [[1, 0, 2, 3, 5, 4], [0, 1, 3, 2, 4, 5]]
>>> gens2 = [[1, 0, 2, 3]]
>>> perm_af_direct_product(gens1, gens2, True)
[[1, 0, 2, 3, 4, 5, 7, 6], [0, 1, 3, 2, 4, 5, 6, 7], [0, 1, 2, 3, 5, 4, 6, 7]]
"""
gens1 = [list(x) for x in gens1]
gens2 = [list(x) for x in gens2]
s = 2 if signed else 0
n1 = len(gens1[0]) - s
n2 = len(gens2[0]) - s
start = list(range(n1))
end = list(range(n1, n1 + n2))
if signed:
gens1 = [gen[:-2] + end + [gen[-2] + n2, gen[-1] + n2]
for gen in gens1]
gens2 = [start + [x + n1 for x in gen] for gen in gens2]
else:
gens1 = [gen + end for gen in gens1]
gens2 = [start + [x + n1 for x in gen] for gen in gens2]
res = gens1 + gens2
return res
def bsgs_direct_product(base1, gens1, base2, gens2, signed=True):
"""
direct product of two BSGS
base1 base of the first BSGS.
gens1 strong generating sequence of the first BSGS.
base2, gens2 similarly for the second BSGS.
signed flag for signed permutations.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import (get_symmetric_group_sgs, bsgs_direct_product)
>>> Permutation.print_cyclic = True
>>> base1, gens1 = get_symmetric_group_sgs(1)
>>> base2, gens2 = get_symmetric_group_sgs(2)
>>> bsgs_direct_product(base1, gens1, base2, gens2)
([1], [(4)(1 2)])
"""
s = 2 if signed else 0
n1 = gens1[0].size - s
base = list(base1)
base += [x + n1 for x in base2]
gens1 = [h._array_form for h in gens1]
gens2 = [h._array_form for h in gens2]
gens = perm_af_direct_product(gens1, gens2, signed)
size = len(gens[0])
id_af = list(range(size))
gens = [h for h in gens if h != id_af]
if not gens:
gens = [id_af]
return base, [_af_new(h) for h in gens]
def get_symmetric_group_sgs(n, antisym=False):
"""
Return base, gens of the minimal BSGS for (anti)symmetric tensor
``n`` rank of the tensor
``antisym = False`` symmetric tensor
``antisym = True`` antisymmetric tensor
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs
>>> Permutation.print_cyclic = True
>>> get_symmetric_group_sgs(3)
([0, 1], [(4)(0 1), (4)(1 2)])
"""
if n == 1:
return [], [_af_new(list(range(3)))]
gens = [Permutation(n - 1)(i, i + 1)._array_form for i in range(n - 1)]
if antisym == 0:
gens = [x + [n, n + 1] for x in gens]
else:
gens = [x + [n + 1, n] for x in gens]
base = list(range(n - 1))
return base, [_af_new(h) for h in gens]
riemann_bsgs = [0, 2], [Permutation(0, 1)(4, 5), Permutation(2, 3)(4, 5),
Permutation(5)(0, 2)(1, 3)]
def get_transversals(base, gens):
"""
Return transversals for the group with BSGS base, gens
"""
if not base:
return []
stabs = _distribute_gens_by_base(base, gens)
orbits, transversals = _orbits_transversals_from_bsgs(base, stabs)
transversals = [dict((x, h._array_form) for x, h in y.items()) for y in
transversals]
return transversals
def _is_minimal_bsgs(base, gens):
"""
Check if the BSGS has minimal base under lexigographic order.
base, gens BSGS
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import riemann_bsgs, _is_minimal_bsgs
>>> _is_minimal_bsgs(*riemann_bsgs)
True
>>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)]))
>>> _is_minimal_bsgs(*riemann_bsgs1)
False
"""
base1 = []
sgs1 = gens[:]
size = gens[0].size
for i in range(size):
if not all(h._array_form[i] == i for h in sgs1):
base1.append(i)
sgs1 = [h for h in sgs1 if h._array_form[i] == i]
return base1 == base
def get_minimal_bsgs(base, gens):
"""
Compute a minimal GSGS
base, gens BSGS
If base, gens is a minimal BSGS return it; else return a minimal BSGS
if it fails in finding one, it returns None
TODO: use baseswap in the case in which if it fails in finding a
minimal BSGS
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import get_minimal_bsgs
>>> Permutation.print_cyclic = True
>>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)]))
>>> get_minimal_bsgs(*riemann_bsgs1)
([0, 2], [(0 1)(4 5), (5)(0 2)(1 3), (2 3)(4 5)])
"""
G = PermutationGroup(gens)
base, gens = G.schreier_sims_incremental()
if not _is_minimal_bsgs(base, gens):
return None
return base, gens
def tensor_gens(base, gens, list_free_indices, sym=0):
"""
Returns size, res_base, res_gens BSGS for n tensors of the
same type
base, gens BSGS for tensors of this type
list_free_indices list of the slots occupied by fixed indices
for each of the tensors
sym symmetry under commutation of two tensors
sym None no symmetry
sym 0 commuting
sym 1 anticommuting
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import tensor_gens, get_symmetric_group_sgs
>>> Permutation.print_cyclic = True
two symmetric tensors with 3 indices without free indices
>>> base, gens = get_symmetric_group_sgs(3)
>>> tensor_gens(base, gens, [[], []])
(8, [0, 1, 3, 4], [(7)(0 1), (7)(1 2), (7)(3 4), (7)(4 5), (7)(0 3)(1 4)(2 5)])
two symmetric tensors with 3 indices with free indices in slot 1 and 0
>>> tensor_gens(base, gens, [[1], [0]])
(8, [0, 4], [(7)(0 2), (7)(4 5)])
four symmetric tensors with 3 indices, two of which with free indices
"""
def _get_bsgs(G, base, gens, free_indices):
"""
return the BSGS for G.pointwise_stabilizer(free_indices)
"""
if not free_indices:
return base[:], gens[:]
else:
H = G.pointwise_stabilizer(free_indices)
base, sgs = H.schreier_sims_incremental()
return base, sgs
# if not base there is no slot symmetry for the component tensors
# if list_free_indices.count([]) < 2 there is no commutation symmetry
# so there is no resulting slot symmetry
if not base and list_free_indices.count([]) < 2:
n = len(list_free_indices)
size = gens[0].size
size = n * (gens[0].size - 2) + 2
return size, [], [_af_new(list(range(size)))]
# if any(list_free_indices) one needs to compute the pointwise
# stabilizer, so G is needed
if any(list_free_indices):
G = PermutationGroup(gens)
else:
G = None
# no_free list of lists of indices for component tensors without fixed
# indices
no_free = []
size = gens[0].size
id_af = list(range(size))
num_indices = size - 2
if not list_free_indices[0]:
no_free.append(list(range(num_indices)))
res_base, res_gens = _get_bsgs(G, base, gens, list_free_indices[0])
for i in range(1, len(list_free_indices)):
base1, gens1 = _get_bsgs(G, base, gens, list_free_indices[i])
res_base, res_gens = bsgs_direct_product(res_base, res_gens,
base1, gens1, 1)
if not list_free_indices[i]:
no_free.append(list(range(size - 2, size - 2 + num_indices)))
size += num_indices
nr = size - 2
res_gens = [h for h in res_gens if h._array_form != id_af]
# if sym there are no commuting tensors stop here
if sym is None or not no_free:
if not res_gens:
res_gens = [_af_new(id_af)]
return size, res_base, res_gens
# if the component tensors have moinimal BSGS, so is their direct
# product P; the slot symmetry group is S = P*C, where C is the group
# to (anti)commute the component tensors with no free indices
# a stabilizer has the property S_i = P_i*C_i;
# the BSGS of P*C has SGS_P + SGS_C and the base is
# the ordered union of the bases of P and C.
# If P has minimal BSGS, so has S with this base.
base_comm = []
for i in range(len(no_free) - 1):
ind1 = no_free[i]
ind2 = no_free[i + 1]
a = list(range(ind1[0]))
a.extend(ind2)
a.extend(ind1)
base_comm.append(ind1[0])
a.extend(list(range(ind2[-1] + 1, nr)))
if sym == 0:
a.extend([nr, nr + 1])
else:
a.extend([nr + 1, nr])
res_gens.append(_af_new(a))
res_base = list(res_base)
# each base is ordered; order the union of the two bases
for i in base_comm:
if i not in res_base:
res_base.append(i)
res_base.sort()
if not res_gens:
res_gens = [_af_new(id_af)]
return size, res_base, res_gens
def gens_products(*v):
"""
Returns size, res_base, res_gens BSGS for n tensors of different types
v is a sequence of (base_i, gens_i, free_i, sym_i)
where
base_i, gens_i BSGS of tensor of type `i`
free_i list of the fixed slots for each of the tensors
of type `i`; if there are `n_i` tensors of type `i`
and none of them have fixed slots, `free = [[]]*n_i`
sym 0 (1) if the tensors of type `i` (anti)commute among themselves
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, gens_products
>>> Permutation.print_cyclic = True
>>> base, gens = get_symmetric_group_sgs(2)
>>> gens_products((base, gens, [[], []], 0))
(6, [0, 2], [(5)(0 1), (5)(2 3), (5)(0 2)(1 3)])
>>> gens_products((base, gens, [[1], []], 0))
(6, [2], [(5)(2 3)])
"""
res_size, res_base, res_gens = tensor_gens(*v[0])
for i in range(1, len(v)):
size, base, gens = tensor_gens(*v[i])
res_base, res_gens = bsgs_direct_product(res_base, res_gens, base,
gens, 1)
res_size = res_gens[0].size
id_af = list(range(res_size))
res_gens = [h for h in res_gens if h != id_af]
if not res_gens:
res_gens = [id_af]
return res_size, res_base, res_gens
| bsd-3-clause | 1,040,579,235,444,020,400 | 33.493682 | 109 | 0.557835 | false |
j5shi/Thruster | pylibs/idlelib/configSectionNameDialog.py | 2 | 4071 | """
Dialog that allows user to specify a new config file section name.
Used to get new highlight theme and keybinding set names.
The 'return value' for the dialog, used two placed in configDialog.py,
is the .result attribute set in the Ok and Cancel methods.
"""
from Tkinter import *
import tkMessageBox
class GetCfgSectionNameDialog(Toplevel):
def __init__(self, parent, title, message, used_names, _htest=False):
"""
message - string, informational message to display
used_names - string collection, names already in use for validity check
_htest - bool, change box location when running htest
"""
Toplevel.__init__(self, parent)
self.configure(borderwidth=5)
self.resizable(height=FALSE, width=FALSE)
self.title(title)
self.transient(parent)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.Cancel)
self.parent = parent
self.message = message
self.used_names = used_names
self.create_widgets()
self.withdraw() #hide while setting geometry
self.update_idletasks()
#needs to be done here so that the winfo_reqwidth is valid
self.messageInfo.config(width=self.frameMain.winfo_reqwidth())
self.geometry(
"+%d+%d" % (
parent.winfo_rootx() +
(parent.winfo_width()/2 - self.winfo_reqwidth()/2),
parent.winfo_rooty() +
((parent.winfo_height()/2 - self.winfo_reqheight()/2)
if not _htest else 100)
) ) #centre dialog over parent (or below htest box)
self.deiconify() #geometry set, unhide
self.wait_window()
def create_widgets(self):
self.name = StringVar(self.parent)
self.fontSize = StringVar(self.parent)
self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
self.messageInfo = Message(self.frameMain, anchor=W, justify=LEFT,
padx=5, pady=5, text=self.message) #,aspect=200)
entryName = Entry(self.frameMain, textvariable=self.name, width=30)
entryName.focus_set()
self.messageInfo.pack(padx=5, pady=5) #, expand=TRUE, fill=BOTH)
entryName.pack(padx=5, pady=5)
frameButtons = Frame(self, pady=2)
frameButtons.pack(side=BOTTOM)
self.buttonOk = Button(frameButtons, text='Ok',
width=8, command=self.Ok)
self.buttonOk.pack(side=LEFT, padx=5)
self.buttonCancel = Button(frameButtons, text='Cancel',
width=8, command=self.Cancel)
self.buttonCancel.pack(side=RIGHT, padx=5)
def name_ok(self):
''' After stripping entered name, check that it is a sensible
ConfigParser file section name. Return it if it is, '' if not.
'''
name = self.name.get().strip()
if not name: #no name specified
tkMessageBox.showerror(title='Name Error',
message='No name specified.', parent=self)
elif len(name)>30: #name too long
tkMessageBox.showerror(title='Name Error',
message='Name too long. It should be no more than '+
'30 characters.', parent=self)
name = ''
elif name in self.used_names:
tkMessageBox.showerror(title='Name Error',
message='This name is already in use.', parent=self)
name = ''
return name
def Ok(self, event=None):
name = self.name_ok()
if name:
self.result = name
self.destroy()
def Cancel(self, event=None):
self.result = ''
self.destroy()
if __name__ == '__main__':
import unittest
unittest.main('idlelib.idle_test.test_config_name', verbosity=2, exit=False)
from idlelib.idle_test.htest import run
run(GetCfgSectionNameDialog)
| gpl-2.0 | -296,595,226,079,826,750 | 42.25 | 80 | 0.588799 | false |
cszqwe/incubator-singa | tool/graph.py | 9 | 1398 | #/**
# * Copyright 2015 The Apache Software Foundation
# *
# * Licensed to the Apache Software Foundation (ASF) under one
# * or more contributor license agreements. See the NOTICE file
# * distributed with this work for additional information
# * regarding copyright ownership. The ASF licenses this file
# * to you under the Apache License, Version 2.0 (the
# * "License"); you may not use this file except in compliance
# * with the License. You may obtain a copy of the License at
# *
# * http://www.apache.org/licenses/LICENSE-2.0
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
# */
import sys
import pygraphviz
import networkx as nx
from networkx.readwrite import json_graph
import json
if __name__=='__main__':
print sys.argv
if len(sys.argv)<3:
print 'usage: draw the network graph\npython graph.py JSON_DAT FIG_FILE'
sys.exit()
with open(sys.argv[1]) as fd:
nodelink=json.load(fd)
G=json_graph.node_link_graph(nodelink)
A = nx.to_agraph(G)
A.layout('dot', args='-Nfontsize=10 -Nwidth=".2" -Nheight=".2" -Nmargin=0 \
-Gfontsize=8')
A.draw(sys.argv[2])
| apache-2.0 | 211,615,048,975,211,170 | 32.285714 | 79 | 0.706009 | false |
infosec-o4it/inventario | bia/admin.py | 1 | 2416 | # -*- coding: utf-8 -*-
from django.contrib import admin
from .models import ProcesoBia, CapitalTiempo, AplicacionesTiempo
from .models import PersonasTiempo, CanalesActividad, CanalesTiempo
from .models import DocumentosActividad, DocumentosTiempo, EquiposTIActividad
from .models import EquiposTiTiempo, EquiposNoTIActividad, EquiposNoTiTiempo
from .models import InstalacionesActividad, InstalacionesTiempo, PapelActividad
from .models import PapelTiempo, ServiciosExternosActividad, ServiciosTiempo
from .models import RyLImpacto, ServicioClienteImpacto, ImagenImpacto
from .models import IngresosImpacto, GastosImpacto, AplicacionesImpacto
from .models import DocumentoImpacto, PapelImpacto, Actividad
# Register your models here.
admin.site.register(ProcesoBia, ProcesoBia.Admin)
admin.site.register(CapitalTiempo, CapitalTiempo.Admin)
admin.site.register(AplicacionesTiempo, AplicacionesTiempo.Admin)
admin.site.register(PersonasTiempo, PersonasTiempo.Admin)
admin.site.register(CanalesActividad, CanalesActividad.Admin)
admin.site.register(CanalesTiempo, CanalesTiempo.Admin)
admin.site.register(DocumentosActividad, DocumentosActividad.Admin)
admin.site.register(DocumentosTiempo, DocumentosTiempo.Admin)
admin.site.register(EquiposTIActividad, EquiposTIActividad.Admin)
admin.site.register(EquiposTiTiempo, EquiposTiTiempo.Admin)
admin.site.register(EquiposNoTIActividad, EquiposNoTIActividad.Admin)
admin.site.register(EquiposNoTiTiempo, EquiposNoTiTiempo.Admin)
admin.site.register(InstalacionesActividad, InstalacionesActividad.Admin)
admin.site.register(InstalacionesTiempo, InstalacionesTiempo.Admin)
admin.site.register(PapelActividad, PapelActividad.Admin)
admin.site.register(PapelTiempo, PapelTiempo.Admin)
admin.site.register(ServiciosExternosActividad,
ServiciosExternosActividad.Admin)
admin.site.register(ServiciosTiempo, ServiciosTiempo.Admin)
admin.site.register(RyLImpacto, RyLImpacto.Admin)
admin.site.register(ServicioClienteImpacto, ServicioClienteImpacto.Admin)
admin.site.register(ImagenImpacto, ImagenImpacto.Admin)
admin.site.register(IngresosImpacto, IngresosImpacto.Admin)
admin.site.register(GastosImpacto, GastosImpacto.Admin)
admin.site.register(AplicacionesImpacto, AplicacionesImpacto.Admin)
admin.site.register(DocumentoImpacto, DocumentoImpacto.Admin)
admin.site.register(PapelImpacto, PapelImpacto.Admin)
admin.site.register(Actividad, Actividad.Admin)
| gpl-3.0 | 6,076,201,734,023,603,000 | 59.4 | 79 | 0.85803 | false |
trevor/calendarserver | twistedcaldav/directory/calendaruserproxyloader.py | 1 | 4355 | ##
# Copyright (c) 2009-2014 Apple 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.
##
"""
XML based calendar user proxy loader.
"""
__all__ = [
"XMLCalendarUserProxyLoader",
]
import types
from twisted.internet.defer import inlineCallbacks
from twext.python.log import Logger
from twistedcaldav.config import config, fullServerPath
from twistedcaldav.xmlutil import readXML
log = Logger()
ELEMENT_PROXIES = "proxies"
ELEMENT_RECORD = "record"
ELEMENT_GUID = "guid"
ELEMENT_WRITE_PROXIES = "write-proxies"
ELEMENT_READ_PROXIES = "read-proxies"
ELEMENT_MEMBER = "member"
ATTRIBUTE_REPEAT = "repeat"
class XMLCalendarUserProxyLoader(object):
"""
XML calendar user proxy configuration file parser and loader.
"""
def __repr__(self):
return "<%s %r>" % (self.__class__.__name__, self.xmlFile)
def __init__(self, xmlFile, service):
self.items = []
self.xmlFile = fullServerPath(config.DataRoot, xmlFile)
self.service = service
# Read in XML
try:
_ignore_tree, proxies_node = readXML(self.xmlFile, ELEMENT_PROXIES)
except ValueError:
log.failure("XML parse error for proxy data file {xmlfile}", xmlfile=self.xmlFile)
# FIXME: RuntimeError is dumb.
self._parseXML(proxies_node)
def _parseXML(self, rootnode):
"""
Parse the XML root node from the augments configuration document.
@param rootnode: the L{Element} to parse.
"""
for child in rootnode:
if child.tag != ELEMENT_RECORD:
raise RuntimeError("Unknown augment type: '%s' in augment file: '%s'" % (child.tag, self.xmlFile,))
repeat = int(child.get(ATTRIBUTE_REPEAT, "1"))
guid = None
write_proxies = set()
read_proxies = set()
for node in child:
if node.tag == ELEMENT_GUID:
guid = node.text
elif node.tag in (
ELEMENT_WRITE_PROXIES,
ELEMENT_READ_PROXIES,
):
self._parseMembers(node, write_proxies if node.tag == ELEMENT_WRITE_PROXIES else read_proxies)
else:
raise RuntimeError("Invalid element '%s' in proxies file: '%s'" % (node.tag, self.xmlFile,))
# Must have at least a guid
if not guid:
raise RuntimeError("Invalid record '%s' without a guid in proxies file: '%s'" % (child, self.xmlFile,))
if repeat > 1:
for i in xrange(1, repeat + 1):
self._buildRecord(guid, write_proxies, read_proxies, i)
else:
self._buildRecord(guid, write_proxies, read_proxies)
def _parseMembers(self, node, addto):
for child in node:
if child.tag == ELEMENT_MEMBER:
addto.add(child.text)
def _buildRecord(self, guid, write_proxies, read_proxies, count=None):
def expandCount(value, count):
if type(value) in types.StringTypes:
return value % (count,) if count and "%" in value else value
else:
return value
guid = expandCount(guid, count)
write_proxies = set([expandCount(member, count) for member in write_proxies])
read_proxies = set([expandCount(member, count) for member in read_proxies])
self.items.append((guid, write_proxies, read_proxies,))
@inlineCallbacks
def updateProxyDB(self):
db = self.service
for item in self.items:
guid, write_proxies, read_proxies = item
yield db.setGroupMembers("%s#%s" % (guid, "calendar-proxy-write"), write_proxies)
yield db.setGroupMembers("%s#%s" % (guid, "calendar-proxy-read"), read_proxies)
| apache-2.0 | 1,479,831,022,553,511,700 | 30.330935 | 119 | 0.61194 | false |
walbert947/ansible-modules-core | packaging/os/apt_repository.py | 16 | 19073 | #!/usr/bin/python
# encoding: utf-8
# (c) 2012, Matt Wright <[email protected]>
# (c) 2013, Alexander Saltanov <[email protected]>
# (c) 2014, Rutger Spiertz <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: apt_repository
short_description: Add and remove APT repositories
description:
- Add or remove an APT repositories in Ubuntu and Debian.
notes:
- This module works on Debian and Ubuntu and requires C(python-apt).
- This module supports Debian Squeeze (version 6) as well as its successors.
- This module treats Debian and Ubuntu distributions separately. So PPA could be installed only on Ubuntu machines.
options:
repo:
required: true
default: none
description:
- A source string for the repository.
state:
required: false
choices: [ "absent", "present" ]
default: "present"
description:
- A source string state.
mode:
required: false
default: 0644
description:
- The octal mode for newly created files in sources.list.d
version_added: "1.6"
update_cache:
description:
- Run the equivalent of C(apt-get update) when a change occurs. Cache updates are run after making changes.
required: false
default: "yes"
choices: [ "yes", "no" ]
validate_certs:
version_added: '1.8'
description:
- If C(no), SSL certificates for the target repo will not be validated. This should only be used
on personally controlled sites using self-signed certificates.
required: false
default: 'yes'
choices: ['yes', 'no']
filename:
version_added: '2.1'
description:
- Sets the name of the source list file in sources.list.d.
Defaults to a file name based on the repository source url.
The .list extension will be automatically added.
required: false
author: "Alexander Saltanov (@sashka)"
version_added: "0.7"
requirements: [ python-apt ]
'''
EXAMPLES = '''
# Add specified repository into sources list.
apt_repository: repo='deb http://archive.canonical.com/ubuntu hardy partner' state=present
# Add specified repository into sources list using specified filename.
apt_repository: repo='deb http://dl.google.com/linux/chrome/deb/ stable main' state=present filename='google-chrome'
# Add source repository into sources list.
apt_repository: repo='deb-src http://archive.canonical.com/ubuntu hardy partner' state=present
# Remove specified repository from sources list.
apt_repository: repo='deb http://archive.canonical.com/ubuntu hardy partner' state=absent
# On Ubuntu target: add nginx stable repository from PPA and install its signing key.
# On Debian target: adding PPA is not available, so it will fail immediately.
apt_repository: repo='ppa:nginx/stable'
'''
import glob
import os
import re
import tempfile
try:
import apt
import apt_pkg
import aptsources.distro as aptsources_distro
distro = aptsources_distro.get_distro()
HAVE_PYTHON_APT = True
except ImportError:
distro = None
HAVE_PYTHON_APT = False
VALID_SOURCE_TYPES = ('deb', 'deb-src')
def install_python_apt(module):
if not module.check_mode:
apt_get_path = module.get_bin_path('apt-get')
if apt_get_path:
rc, so, se = module.run_command([apt_get_path, 'update'])
if rc != 0:
module.fail_json(msg="Failed to auto-install python-apt. Error was: '%s'" % se.strip())
rc, so, se = module.run_command([apt_get_path, 'install', 'python-apt', '-y', '-q'])
if rc == 0:
global apt, apt_pkg, aptsources_distro, distro, HAVE_PYTHON_APT
import apt
import apt_pkg
import aptsources.distro as aptsources_distro
distro = aptsources_distro.get_distro()
HAVE_PYTHON_APT = True
else:
module.fail_json(msg="Failed to auto-install python-apt. Error was: '%s'" % se.strip())
else:
module.fail_json(msg="python-apt must be installed to use check mode")
class InvalidSource(Exception):
pass
# Simple version of aptsources.sourceslist.SourcesList.
# No advanced logic and no backups inside.
class SourcesList(object):
def __init__(self, module):
self.module = module
self.files = {} # group sources by file
# Repositories that we're adding -- used to implement mode param
self.new_repos = set()
self.default_file = self._apt_cfg_file('Dir::Etc::sourcelist')
# read sources.list if it exists
if os.path.isfile(self.default_file):
self.load(self.default_file)
# read sources.list.d
for file in glob.iglob('%s/*.list' % self._apt_cfg_dir('Dir::Etc::sourceparts')):
self.load(file)
def __iter__(self):
'''Simple iterator to go over all sources. Empty, non-source, and other not valid lines will be skipped.'''
for file, sources in self.files.items():
for n, valid, enabled, source, comment in sources:
if valid:
yield file, n, enabled, source, comment
raise StopIteration
def _expand_path(self, filename):
if '/' in filename:
return filename
else:
return os.path.abspath(os.path.join(self._apt_cfg_dir('Dir::Etc::sourceparts'), filename))
def _suggest_filename(self, line):
def _cleanup_filename(s):
filename = self.module.params['filename']
if filename is not None:
return filename
return '_'.join(re.sub('[^a-zA-Z0-9]', ' ', s).split())
def _strip_username_password(s):
if '@' in s:
s = s.split('@', 1)
s = s[-1]
return s
# Drop options and protocols.
line = re.sub('\[[^\]]+\]', '', line)
line = re.sub('\w+://', '', line)
# split line into valid keywords
parts = [part for part in line.split() if part not in VALID_SOURCE_TYPES]
# Drop usernames and passwords
parts[0] = _strip_username_password(parts[0])
return '%s.list' % _cleanup_filename(' '.join(parts[:1]))
def _parse(self, line, raise_if_invalid_or_disabled=False):
valid = False
enabled = True
source = ''
comment = ''
line = line.strip()
if line.startswith('#'):
enabled = False
line = line[1:]
# Check for another "#" in the line and treat a part after it as a comment.
i = line.find('#')
if i > 0:
comment = line[i+1:].strip()
line = line[:i]
# Split a source into substring to make sure that it is source spec.
# Duplicated whitespaces in a valid source spec will be removed.
source = line.strip()
if source:
chunks = source.split()
if chunks[0] in VALID_SOURCE_TYPES:
valid = True
source = ' '.join(chunks)
if raise_if_invalid_or_disabled and (not valid or not enabled):
raise InvalidSource(line)
return valid, enabled, source, comment
@staticmethod
def _apt_cfg_file(filespec):
'''
Wrapper for `apt_pkg` module for running with Python 2.5
'''
try:
result = apt_pkg.config.find_file(filespec)
except AttributeError:
result = apt_pkg.Config.FindFile(filespec)
return result
@staticmethod
def _apt_cfg_dir(dirspec):
'''
Wrapper for `apt_pkg` module for running with Python 2.5
'''
try:
result = apt_pkg.config.find_dir(dirspec)
except AttributeError:
result = apt_pkg.Config.FindDir(dirspec)
return result
def load(self, file):
group = []
f = open(file, 'r')
for n, line in enumerate(f):
valid, enabled, source, comment = self._parse(line)
group.append((n, valid, enabled, source, comment))
self.files[file] = group
def save(self):
for filename, sources in self.files.items():
if sources:
d, fn = os.path.split(filename)
fd, tmp_path = tempfile.mkstemp(prefix=".%s-" % fn, dir=d)
f = os.fdopen(fd, 'w')
for n, valid, enabled, source, comment in sources:
chunks = []
if not enabled:
chunks.append('# ')
chunks.append(source)
if comment:
chunks.append(' # ')
chunks.append(comment)
chunks.append('\n')
line = ''.join(chunks)
try:
f.write(line)
except IOError, err:
self.module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, unicode(err)))
self.module.atomic_move(tmp_path, filename)
# allow the user to override the default mode
if filename in self.new_repos:
this_mode = self.module.params['mode']
self.module.set_mode_if_different(filename, this_mode, False)
else:
del self.files[filename]
if os.path.exists(filename):
os.remove(filename)
def dump(self):
dumpstruct = {}
for filename, sources in self.files.items():
if sources:
lines = []
for n, valid, enabled, source, comment in sources:
chunks = []
if not enabled:
chunks.append('# ')
chunks.append(source)
if comment:
chunks.append(' # ')
chunks.append(comment)
chunks.append('\n')
lines.append(''.join(chunks))
dumpstruct[filename] = ''.join(lines)
return dumpstruct
def _choice(self, new, old):
if new is None:
return old
return new
def modify(self, file, n, enabled=None, source=None, comment=None):
'''
This function to be used with iterator, so we don't care of invalid sources.
If source, enabled, or comment is None, original value from line ``n`` will be preserved.
'''
valid, enabled_old, source_old, comment_old = self.files[file][n][1:]
self.files[file][n] = (n, valid, self._choice(enabled, enabled_old), self._choice(source, source_old), self._choice(comment, comment_old))
def _add_valid_source(self, source_new, comment_new, file):
# We'll try to reuse disabled source if we have it.
# If we have more than one entry, we will enable them all - no advanced logic, remember.
found = False
for filename, n, enabled, source, comment in self:
if source == source_new:
self.modify(filename, n, enabled=True)
found = True
if not found:
if file is None:
file = self.default_file
else:
file = self._expand_path(file)
if file not in self.files:
self.files[file] = []
files = self.files[file]
files.append((len(files), True, True, source_new, comment_new))
self.new_repos.add(file)
def add_source(self, line, comment='', file=None):
source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
# Prefer separate files for new sources.
self._add_valid_source(source, comment, file=file or self._suggest_filename(source))
def _remove_valid_source(self, source):
# If we have more than one entry, we will remove them all (not comment, remove!)
for filename, n, enabled, src, comment in self:
if source == src and enabled:
self.files[filename].pop(n)
def remove_source(self, line):
source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
self._remove_valid_source(source)
class UbuntuSourcesList(SourcesList):
LP_API = 'https://launchpad.net/api/1.0/~%s/+archive/%s'
def __init__(self, module, add_ppa_signing_keys_callback=None):
self.module = module
self.add_ppa_signing_keys_callback = add_ppa_signing_keys_callback
super(UbuntuSourcesList, self).__init__(module)
def _get_ppa_info(self, owner_name, ppa_name):
lp_api = self.LP_API % (owner_name, ppa_name)
headers = dict(Accept='application/json')
response, info = fetch_url(self.module, lp_api, headers=headers)
if info['status'] != 200:
self.module.fail_json(msg="failed to fetch PPA information, error was: %s" % info['msg'])
return json.load(response)
def _expand_ppa(self, path):
ppa = path.split(':')[1]
ppa_owner = ppa.split('/')[0]
try:
ppa_name = ppa.split('/')[1]
except IndexError:
ppa_name = 'ppa'
line = 'deb http://ppa.launchpad.net/%s/%s/ubuntu %s main' % (ppa_owner, ppa_name, distro.codename)
return line, ppa_owner, ppa_name
def _key_already_exists(self, key_fingerprint):
rc, out, err = self.module.run_command('apt-key export %s' % key_fingerprint, check_rc=True)
return len(err) == 0
def add_source(self, line, comment='', file=None):
if line.startswith('ppa:'):
source, ppa_owner, ppa_name = self._expand_ppa(line)
if source in self.repos_urls:
# repository already exists
return
if self.add_ppa_signing_keys_callback is not None:
info = self._get_ppa_info(ppa_owner, ppa_name)
if not self._key_already_exists(info['signing_key_fingerprint']):
command = ['apt-key', 'adv', '--recv-keys', '--keyserver', 'hkp://keyserver.ubuntu.com:80', info['signing_key_fingerprint']]
self.add_ppa_signing_keys_callback(command)
file = file or self._suggest_filename('%s_%s' % (line, distro.codename))
else:
source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
file = file or self._suggest_filename(source)
self._add_valid_source(source, comment, file)
def remove_source(self, line):
if line.startswith('ppa:'):
source = self._expand_ppa(line)[0]
else:
source = self._parse(line, raise_if_invalid_or_disabled=True)[2]
self._remove_valid_source(source)
@property
def repos_urls(self):
_repositories = []
for parsed_repos in self.files.values():
for parsed_repo in parsed_repos:
enabled = parsed_repo[1]
source_line = parsed_repo[3]
if not enabled:
continue
if source_line.startswith('ppa:'):
source, ppa_owner, ppa_name = self._expand_ppa(source_line)
_repositories.append(source)
else:
_repositories.append(source_line)
return _repositories
def get_add_ppa_signing_key_callback(module):
def _run_command(command):
module.run_command(command, check_rc=True)
if module.check_mode:
return None
else:
return _run_command
def main():
module = AnsibleModule(
argument_spec=dict(
repo=dict(required=True),
state=dict(choices=['present', 'absent'], default='present'),
mode=dict(required=False, default=0644),
update_cache = dict(aliases=['update-cache'], type='bool', default='yes'),
filename=dict(required=False, default=None),
# this should not be needed, but exists as a failsafe
install_python_apt=dict(required=False, default="yes", type='bool'),
validate_certs = dict(default='yes', type='bool'),
),
supports_check_mode=True,
)
params = module.params
repo = module.params['repo']
state = module.params['state']
update_cache = module.params['update_cache']
sourceslist = None
if not HAVE_PYTHON_APT:
if params['install_python_apt']:
install_python_apt(module)
else:
module.fail_json(msg='python-apt is not installed, and install_python_apt is False')
if isinstance(distro, aptsources_distro.UbuntuDistribution):
sourceslist = UbuntuSourcesList(module,
add_ppa_signing_keys_callback=get_add_ppa_signing_key_callback(module))
elif isinstance(distro, aptsources_distro.Distribution):
sourceslist = SourcesList(module)
else:
module.fail_json(msg='Module apt_repository supports only Debian and Ubuntu.')
sources_before = sourceslist.dump()
try:
if state == 'present':
sourceslist.add_source(repo)
elif state == 'absent':
sourceslist.remove_source(repo)
except InvalidSource, err:
module.fail_json(msg='Invalid repository string: %s' % unicode(err))
sources_after = sourceslist.dump()
changed = sources_before != sources_after
if changed and module._diff:
diff = []
for filename in set(sources_before.keys()).union(sources_after.keys()):
diff.append({'before': sources_before.get(filename, ''),
'after': sources_after.get(filename, ''),
'before_header': (filename, '/dev/null')[filename not in sources_before],
'after_header': (filename, '/dev/null')[filename not in sources_after]})
else:
diff = {}
if changed and not module.check_mode:
try:
sourceslist.save()
if update_cache:
cache = apt.Cache()
cache.update()
except OSError, err:
module.fail_json(msg=unicode(err))
module.exit_json(changed=changed, repo=repo, state=state, diff=diff)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
main()
| gpl-3.0 | -1,087,469,285,577,967,900 | 35.538314 | 146 | 0.58339 | false |
indico/indico | indico/core/oauth/util.py | 1 | 3398 | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import hashlib
from uuid import UUID
from authlib.oauth2.rfc6749 import list_to_scope, scope_to_list
from sqlalchemy.dialects.postgresql.array import ARRAY
from sqlalchemy.orm import joinedload
from indico.core.db import db
from indico.core.oauth.logger import logger
from indico.core.oauth.models.applications import OAuthApplication, OAuthApplicationUserLink
from indico.core.oauth.models.personal_tokens import PersonalToken
from indico.core.oauth.models.tokens import OAuthToken
# The maximum number of tokens to keep for any given app/user and scope combination
MAX_TOKENS_PER_SCOPE = 50
# The prefix for OAuth tokens
TOKEN_PREFIX_OAUTH = 'indo_'
# The prefix for personal tokens
TOKEN_PREFIX_PERSONAL = 'indp_'
def query_token(token_string, allow_personal=False):
token_hash = hashlib.sha256(token_string.encode()).hexdigest()
if token_string.startswith(TOKEN_PREFIX_PERSONAL):
if not allow_personal:
return None
return (PersonalToken.query
.filter_by(access_token_hash=token_hash)
.first())
# XXX: oauth tokens may be from pre-3.0 and thus not use a token prefix, so we simply
# assume that any token without another known prefix is an oauth token
# we always need the app link (which already loads the application) and the user
# since we need those to check if the token is still valid
return (OAuthToken.query
.filter_by(access_token_hash=token_hash)
.options(joinedload('app_user_link').joinedload('user'))
.first())
def query_client(client_id):
try:
UUID(hex=client_id)
except ValueError:
return None
return OAuthApplication.query.filter_by(client_id=client_id, is_enabled=True).first()
def save_token(token_data, request):
requested_scopes = set(scope_to_list(token_data.get('scope', '')))
application = OAuthApplication.query.filter_by(client_id=request.client.client_id).one()
link = OAuthApplicationUserLink.query.with_parent(application).with_parent(request.user).first()
if link is None:
link = OAuthApplicationUserLink(application=application, user=request.user, scopes=requested_scopes)
else:
if not requested_scopes:
# for already-authorized apps not specifying a scope uses all scopes the
# user previously granted to the app
requested_scopes = set(link.scopes)
token_data['scope'] = list_to_scope(requested_scopes)
new_scopes = requested_scopes - set(link.scopes)
if new_scopes:
logger.info('New scopes for %r: %s', link, new_scopes)
link.update_scopes(new_scopes)
link.tokens.append(OAuthToken(access_token=token_data['access_token'], scopes=requested_scopes))
# get rid of old tokens if there are too many
q = (db.session.query(OAuthToken.id)
.with_parent(link)
.filter_by(_scopes=db.cast(sorted(requested_scopes), ARRAY(db.String)))
.order_by(OAuthToken.created_dt.desc())
.offset(MAX_TOKENS_PER_SCOPE)
.scalar_subquery())
OAuthToken.query.filter(OAuthToken.id.in_(q)).delete(synchronize_session='fetch')
| mit | 7,706,720,988,045,286,000 | 38.511628 | 108 | 0.701589 | false |
jeremybanks/stack-suggestions-bot | src/stackexchange/site.py | 1 | 2184 | class Site(object):
def __init__(self, stack_exchange, site_data):
"""
Initializes the Site given a item from a /sites response.
The data must be complete; don't filter out any fields.
(The default behaviour is to include all fields.)
The Site objet will have all possible fields from the /sites
response as attributes. Omitted optional fields will either be
None, or an empty array (if a present value would be an array).
"""
self.se = stack_exchange
self._dict = site_data
self.name = site_data['name']
self.api_site_parameter = site_data['api_site_parameter']
self.site_url = site_data['site_url']
self.aliases = site_data.get('aliases') or []
self.audience = site_data['audience']
self.closed_beta_date = site_data.get('closed_beta_date')
self.favicon_url = site_data['favicon_url']
self.icon_url = site_data['icon_url']
self.high_resolution_icon_url = site_data.get('high_resolution_icon_url')
self.launch_date = site_data.get('launch_date')
self.logo_url = site_data['logo_url']
self.markdown_extensions = site_data.get('markdown_extensions') or []
self.open_beta_date = site_data.get('open_beta_date')
self.related_sites = site_data.get('related_sites') or []
self.site_state = site_data['site_state']
self.site_type = site_data['site_type']
self.styling = site_data['styling']
self.twitter_account = site_data.get('twitter_account')
def _request(self, path, object_hook=None, **kwargs):
return self.se._request(
path, self.api_site_parameter, object_hook, **kwargs)
def get_similar(self, title, preferred_tags=None, excluded_tags=None):
"""
Requests some questions similar to a title.
"""
params = {
'title': title,
'sort': 'relevance',
'page': 1,
'pagesize': 10,
'tagged': ';'.join(preferred_tags or []),
'nottagged': ';'.join(excluded_tags or [])
}
return self._request('similar', **params)
| mit | 2,115,681,325,751,210,500 | 40.207547 | 81 | 0.595696 | false |
mabhub/Geotrek | geotrek/core/widgets.py | 4 | 3323 | """
We distinguish two types of widgets : Geometry and Topology.
Geometry widgets receive a WKT string, deserialized by GEOS.
Leaflet.Draw is used for edition.
Topology widgets receive a JSON string, deserialized by Topology.deserialize().
Geotrek custom code is used for edition.
:notes:
The purpose of floppyforms is to use Django templates for widget rendering.
"""
import json
from django.template import loader
from django.utils import six
from mapentity.widgets import MapWidget
from .models import Topology
class SnappedLineStringWidget(MapWidget):
geometry_field_class = 'MapEntity.GeometryField.GeometryFieldSnap'
def serialize(self, value):
geojson = super(SnappedLineStringWidget, self).serialize(value)
snaplist = []
if value:
snaplist = [None for c in range(len(value.coords))]
value = {'geom': geojson, 'snap': snaplist}
return json.dumps(value)
def deserialize(self, value):
if isinstance(value, six.string_types) and value:
value = json.loads(value)
value = value['geom']
value = json.dumps(value)
return super(SnappedLineStringWidget, self).deserialize(value)
class BaseTopologyWidget(MapWidget):
""" A widget allowing to create topologies on a map.
"""
template_name = 'core/topology_widget_fragment.html'
geometry_field_class = 'MapEntity.GeometryField.TopologyField'
is_line_topology = False
is_point_topology = False
def serialize(self, value):
return value.serialize() if value else ''
def deserialize(self, value):
if isinstance(value, int):
return Topology.objects.get(pk=value)
try:
return Topology.deserialize(value)
except ValueError:
return None
def render(self, name, value, attrs=None):
"""Renders the fields. Parent class calls `serialize()` with the value.
"""
if isinstance(value, int):
value = Topology.objects.get(pk=value)
attrs = attrs or {}
attrs.update(is_line_topology=self.is_line_topology,
is_point_topology=self.is_point_topology)
return super(BaseTopologyWidget, self).render(name, value, attrs)
class LineTopologyWidget(BaseTopologyWidget):
""" A widget allowing to select a list of paths.
"""
is_line_topology = True
class PointTopologyWidget(BaseTopologyWidget):
""" A widget allowing to point a position with a marker.
"""
is_point_topology = True
class PointLineTopologyWidget(PointTopologyWidget, LineTopologyWidget):
""" A widget allowing to point a position with a marker or a list of paths.
"""
pass
class TopologyReadonlyWidget(BaseTopologyWidget):
template_name = "mapentity/mapgeometry_fragment.html"
def render(self, name, value, attrs=None):
"""
Completely bypass widget rendering, and just render a geometry.
"""
topology = value
if isinstance(topology, (six.string_types, int)):
topology = self.deserialize(topology)
geom = topology.geom if topology else None # if form invalid
context = {'object': geom, 'mapname': name}
return loader.render_to_string(self.template_name, context)
| bsd-2-clause | 3,893,293,936,703,938,600 | 30.647619 | 83 | 0.667469 | false |
BT-astauder/odoo | addons/purchase_requisition/purchase_requisition.py | 16 | 23485 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# 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 datetime import datetime
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT
import openerp.addons.decimal_precision as dp
class purchase_requisition(osv.osv):
_name = "purchase.requisition"
_description = "Purchase Requisition"
_inherit = ['mail.thread', 'ir.needaction_mixin']
def _get_po_line(self, cr, uid, ids, field_names, arg=None, context=None):
result = dict((res_id, []) for res_id in ids)
for element in self.browse(cr, uid, ids, context=context):
for po in element.purchase_ids:
result[element.id] += [po_line.id for po_line in po.order_line]
return result
_columns = {
'name': fields.char('Call for Bids Reference', required=True, copy=False),
'origin': fields.char('Source Document'),
'ordering_date': fields.date('Scheduled Ordering Date'),
'date_end': fields.datetime('Bid Submission Deadline'),
'schedule_date': fields.date('Scheduled Date', select=True, help="The expected and scheduled date where all the products are received"),
'user_id': fields.many2one('res.users', 'Responsible'),
'exclusive': fields.selection([('exclusive', 'Select only one RFQ (exclusive)'), ('multiple', 'Select multiple RFQ')], 'Bid Selection Type', required=True, help="Select only one RFQ (exclusive): On the confirmation of a purchase order, it cancels the remaining purchase order.\nSelect multiple RFQ: It allows to have multiple purchase orders.On confirmation of a purchase order it does not cancel the remaining orders"""),
'description': fields.text('Description'),
'company_id': fields.many2one('res.company', 'Company', required=True),
'purchase_ids': fields.one2many('purchase.order', 'requisition_id', 'Purchase Orders', states={'done': [('readonly', True)]}),
'po_line_ids': fields.function(_get_po_line, method=True, type='one2many', relation='purchase.order.line', string='Products by supplier'),
'line_ids': fields.one2many('purchase.requisition.line', 'requisition_id', 'Products to Purchase', states={'done': [('readonly', True)]}, copy=True),
'procurement_id': fields.many2one('procurement.order', 'Procurement', ondelete='set null', copy=False),
'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse'),
'state': fields.selection([('draft', 'Draft'), ('in_progress', 'Confirmed'),
('open', 'Bid Selection'), ('done', 'PO Created'),
('cancel', 'Cancelled')],
'Status', track_visibility='onchange', required=True,
copy=False),
'multiple_rfq_per_supplier': fields.boolean('Multiple RFQ per supplier'),
'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account'),
'picking_type_id': fields.many2one('stock.picking.type', 'Picking Type', required=True),
}
def _get_picking_in(self, cr, uid, context=None):
obj_data = self.pool.get('ir.model.data')
return obj_data.get_object_reference(cr, uid, 'stock', 'picking_type_in')[1]
_defaults = {
'state': 'draft',
'exclusive': 'multiple',
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'purchase.requisition', context=c),
'user_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).id,
'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'purchase.order.requisition'),
'picking_type_id': _get_picking_in,
}
def tender_cancel(self, cr, uid, ids, context=None):
purchase_order_obj = self.pool.get('purchase.order')
# try to set all associated quotations to cancel state
for tender in self.browse(cr, uid, ids, context=context):
for purchase_order in tender.purchase_ids:
purchase_order_obj.action_cancel(cr, uid, [purchase_order.id], context=context)
purchase_order_obj.message_post(cr, uid, [purchase_order.id], body=_('Cancelled by the tender associated to this quotation.'), context=context)
return self.write(cr, uid, ids, {'state': 'cancel'})
def tender_in_progress(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state': 'in_progress'}, context=context)
def tender_open(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state': 'open'}, context=context)
def tender_reset(self, cr, uid, ids, context=None):
self.write(cr, uid, ids, {'state': 'draft'})
for p_id in ids:
# Deleting the existing instance of workflow for PO
self.delete_workflow(cr, uid, [p_id])
self.create_workflow(cr, uid, [p_id])
return True
def tender_done(self, cr, uid, ids, context=None):
return self.write(cr, uid, ids, {'state': 'done'}, context=context)
def open_product_line(self, cr, uid, ids, context=None):
""" This opens product line view to view all lines from the different quotations, groupby default by product and partner to show comparaison
between supplier price
@return: the product line tree view
"""
if context is None:
context = {}
res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'purchase_requisition', 'purchase_line_tree', context=context)
res['context'] = context
po_lines = self.browse(cr, uid, ids, context=context)[0].po_line_ids
res['context'] = {
'search_default_groupby_product': True,
'search_default_hide_cancelled': True,
'tender_id': ids[0],
}
res['domain'] = [('id', 'in', [line.id for line in po_lines])]
return res
def open_rfq(self, cr, uid, ids, context=None):
""" This opens rfq view to view all quotations associated to the call for bids
@return: the RFQ tree view
"""
if context is None:
context = {}
res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'purchase', 'purchase_rfq', context=context)
res['context'] = context
po_ids = [po.id for po in self.browse(cr, uid, ids, context=context)[0].purchase_ids]
res['domain'] = [('id', 'in', po_ids)]
return res
def _prepare_purchase_order(self, cr, uid, requisition, supplier, context=None):
supplier_pricelist = supplier.property_product_pricelist_purchase
return {
'origin': requisition.name,
'date_order': requisition.date_end or fields.datetime.now(),
'partner_id': supplier.id,
'pricelist_id': supplier_pricelist.id,
'currency_id': supplier_pricelist and supplier_pricelist.currency_id.id or requisition.company_id.currency_id.id,
'location_id': requisition.procurement_id and requisition.procurement_id.location_id.id or requisition.picking_type_id.default_location_dest_id.id,
'company_id': requisition.company_id.id,
'fiscal_position': supplier.property_account_position and supplier.property_account_position.id or False,
'requisition_id': requisition.id,
'notes': requisition.description,
'picking_type_id': requisition.picking_type_id.id
}
def _prepare_purchase_order_line(self, cr, uid, requisition, requisition_line, purchase_id, supplier, context=None):
if context is None:
context = {}
po_line_obj = self.pool.get('purchase.order.line')
product_uom = self.pool.get('product.uom')
product = requisition_line.product_id
default_uom_po_id = product.uom_po_id.id
ctx = context.copy()
ctx['tz'] = requisition.user_id.tz
date_order = requisition.ordering_date and fields.date.date_to_datetime(self, cr, uid, requisition.ordering_date, context=ctx) or fields.datetime.now()
qty = product_uom._compute_qty(cr, uid, requisition_line.product_uom_id.id, requisition_line.product_qty, default_uom_po_id)
supplier_pricelist = supplier.property_product_pricelist_purchase and supplier.property_product_pricelist_purchase.id or False
vals = po_line_obj.onchange_product_id(
cr, uid, [], supplier_pricelist, product.id, qty, default_uom_po_id,
supplier.id, date_order=date_order,
fiscal_position_id=supplier.property_account_position,
date_planned=requisition_line.schedule_date,
name=False, price_unit=False, state='draft', context=context)['value']
vals.update({
'order_id': purchase_id,
'product_id': product.id,
'account_analytic_id': requisition_line.account_analytic_id.id,
})
return vals
def make_purchase_order(self, cr, uid, ids, partner_id, context=None):
"""
Create New RFQ for Supplier
"""
context = dict(context or {})
assert partner_id, 'Supplier should be specified'
purchase_order = self.pool.get('purchase.order')
purchase_order_line = self.pool.get('purchase.order.line')
res_partner = self.pool.get('res.partner')
supplier = res_partner.browse(cr, uid, partner_id, context=context)
res = {}
for requisition in self.browse(cr, uid, ids, context=context):
if not requisition.multiple_rfq_per_supplier and supplier.id in filter(lambda x: x, [rfq.state != 'cancel' and rfq.partner_id.id or None for rfq in requisition.purchase_ids]):
raise osv.except_osv(_('Warning!'), _('You have already one %s purchase order for this partner, you must cancel this purchase order to create a new quotation.') % rfq.state)
context.update({'mail_create_nolog': True})
purchase_id = purchase_order.create(cr, uid, self._prepare_purchase_order(cr, uid, requisition, supplier, context=context), context=context)
purchase_order.message_post(cr, uid, [purchase_id], body=_("RFQ created"), context=context)
res[requisition.id] = purchase_id
for line in requisition.line_ids:
purchase_order_line.create(cr, uid, self._prepare_purchase_order_line(cr, uid, requisition, line, purchase_id, supplier, context=context), context=context)
return res
def check_valid_quotation(self, cr, uid, quotation, context=None):
"""
Check if a quotation has all his order lines bid in order to confirm it if its the case
return True if all order line have been selected during bidding process, else return False
args : 'quotation' must be a browse record
"""
for line in quotation.order_line:
if line.state != 'confirmed' or line.product_qty != line.quantity_bid:
return False
return True
def _prepare_po_from_tender(self, cr, uid, tender, context=None):
""" Prepare the values to write in the purchase order
created from a tender.
:param tender: the source tender from which we generate a purchase order
"""
return {'order_line': [],
'requisition_id': tender.id,
'origin': tender.name}
def _prepare_po_line_from_tender(self, cr, uid, tender, line, purchase_id, context=None):
""" Prepare the values to write in the purchase order line
created from a line of the tender.
:param tender: the source tender from which we generate a purchase order
:param line: the source tender's line from which we generate a line
:param purchase_id: the id of the new purchase
"""
return {'product_qty': line.quantity_bid,
'order_id': purchase_id}
def generate_po(self, cr, uid, ids, context=None):
"""
Generate all purchase order based on selected lines, should only be called on one tender at a time
"""
po = self.pool.get('purchase.order')
poline = self.pool.get('purchase.order.line')
id_per_supplier = {}
for tender in self.browse(cr, uid, ids, context=context):
if tender.state == 'done':
raise osv.except_osv(_('Warning!'), _('You have already generate the purchase order(s).'))
confirm = False
#check that we have at least confirm one line
for po_line in tender.po_line_ids:
if po_line.state == 'confirmed':
confirm = True
break
if not confirm:
raise osv.except_osv(_('Warning!'), _('You have no line selected for buying.'))
#check for complete RFQ
for quotation in tender.purchase_ids:
if (self.check_valid_quotation(cr, uid, quotation, context=context)):
#use workflow to set PO state to confirm
po.signal_workflow(cr, uid, [quotation.id], 'purchase_confirm')
#get other confirmed lines per supplier
for po_line in tender.po_line_ids:
#only take into account confirmed line that does not belong to already confirmed purchase order
if po_line.state == 'confirmed' and po_line.order_id.state in ['draft', 'sent', 'bid']:
if id_per_supplier.get(po_line.partner_id.id):
id_per_supplier[po_line.partner_id.id].append(po_line)
else:
id_per_supplier[po_line.partner_id.id] = [po_line]
#generate po based on supplier and cancel all previous RFQ
ctx = dict(context or {}, force_requisition_id=True)
for supplier, product_line in id_per_supplier.items():
#copy a quotation for this supplier and change order_line then validate it
quotation_id = po.search(cr, uid, [('requisition_id', '=', tender.id), ('partner_id', '=', supplier)], limit=1)[0]
vals = self._prepare_po_from_tender(cr, uid, tender, context=context)
new_po = po.copy(cr, uid, quotation_id, default=vals, context=context)
#duplicate po_line and change product_qty if needed and associate them to newly created PO
for line in product_line:
vals = self._prepare_po_line_from_tender(cr, uid, tender, line, new_po, context=context)
poline.copy(cr, uid, line.id, default=vals, context=context)
#use workflow to set new PO state to confirm
po.signal_workflow(cr, uid, [new_po], 'purchase_confirm')
#cancel other orders
self.cancel_unconfirmed_quotations(cr, uid, tender, context=context)
#set tender to state done
self.signal_workflow(cr, uid, [tender.id], 'done')
return True
def cancel_unconfirmed_quotations(self, cr, uid, tender, context=None):
#cancel other orders
po = self.pool.get('purchase.order')
for quotation in tender.purchase_ids:
if quotation.state in ['draft', 'sent', 'bid']:
self.pool.get('purchase.order').signal_workflow(cr, uid, [quotation.id], 'purchase_cancel')
po.message_post(cr, uid, [quotation.id], body=_('Cancelled by the call for bids associated to this request for quotation.'), context=context)
return True
class purchase_requisition_line(osv.osv):
_name = "purchase.requisition.line"
_description = "Purchase Requisition Line"
_rec_name = 'product_id'
_columns = {
'product_id': fields.many2one('product.product', 'Product', domain=[('purchase_ok', '=', True)]),
'product_uom_id': fields.many2one('product.uom', 'Product Unit of Measure'),
'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure')),
'requisition_id': fields.many2one('purchase.requisition', 'Call for Bids', ondelete='cascade'),
'company_id': fields.related('requisition_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
'account_analytic_id': fields.many2one('account.analytic.account', 'Analytic Account',),
'schedule_date': fields.date('Scheduled Date'),
}
def onchange_product_id(self, cr, uid, ids, product_id, product_uom_id, parent_analytic_account, analytic_account, parent_date, date, context=None):
""" Changes UoM and name if product_id changes.
@param name: Name of the field
@param product_id: Changed product_id
@return: Dictionary of changed values
"""
value = {'product_uom_id': ''}
if product_id:
prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
value = {'product_uom_id': prod.uom_id.id, 'product_qty': 1.0}
if not analytic_account:
value.update({'account_analytic_id': parent_analytic_account})
if not date:
value.update({'schedule_date': parent_date})
return {'value': value}
_defaults = {
'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'purchase.requisition.line', context=c),
}
class purchase_order(osv.osv):
_inherit = "purchase.order"
_columns = {
'requisition_id': fields.many2one('purchase.requisition', 'Call for Bids', copy=False),
}
def wkf_confirm_order(self, cr, uid, ids, context=None):
res = super(purchase_order, self).wkf_confirm_order(cr, uid, ids, context=context)
proc_obj = self.pool.get('procurement.order')
for po in self.browse(cr, uid, ids, context=context):
if po.requisition_id and (po.requisition_id.exclusive == 'exclusive'):
for order in po.requisition_id.purchase_ids:
if order.id != po.id:
proc_ids = proc_obj.search(cr, uid, [('purchase_id', '=', order.id)])
if proc_ids and po.state == 'confirmed':
proc_obj.write(cr, uid, proc_ids, {'purchase_id': po.id})
order.signal_workflow('purchase_cancel')
po.requisition_id.tender_done(context=context)
return res
def _prepare_order_line_move(self, cr, uid, order, order_line, picking_id, group_id, context=None):
stock_move_lines = super(purchase_order, self)._prepare_order_line_move(cr, uid, order, order_line, picking_id, group_id, context=context)
if order.requisition_id and order.requisition_id.procurement_id and order.requisition_id.procurement_id.move_dest_id:
for i in range(0, len(stock_move_lines)):
stock_move_lines[i]['move_dest_id'] = order.requisition_id.procurement_id.move_dest_id.id
return stock_move_lines
class purchase_order_line(osv.osv):
_inherit = 'purchase.order.line'
_columns = {
'quantity_bid': fields.float('Quantity Bid', digits_compute=dp.get_precision('Product Unit of Measure'), help="Technical field for not loosing the initial information about the quantity proposed in the bid"),
}
def action_draft(self, cr, uid, ids, context=None):
self.write(cr, uid, ids, {'state': 'draft'}, context=context)
def action_confirm(self, cr, uid, ids, context=None):
super(purchase_order_line, self).action_confirm(cr, uid, ids, context=context)
for element in self.browse(cr, uid, ids, context=context):
if not element.quantity_bid:
self.write(cr, uid, ids, {'quantity_bid': element.product_qty}, context=context)
return True
def generate_po(self, cr, uid, tender_id, context=None):
#call generate_po from tender with active_id. Called from js widget
return self.pool.get('purchase.requisition').generate_po(cr, uid, [tender_id], context=context)
class product_template(osv.osv):
_inherit = 'product.template'
_columns = {
'purchase_requisition': fields.boolean('Call for Bids', help="Check this box to generate Call for Bids instead of generating requests for quotation from procurement.")
}
class procurement_order(osv.osv):
_inherit = 'procurement.order'
_columns = {
'requisition_id': fields.many2one('purchase.requisition', 'Latest Requisition')
}
def _run(self, cr, uid, procurement, context=None):
requisition_obj = self.pool.get('purchase.requisition')
warehouse_obj = self.pool.get('stock.warehouse')
if procurement.rule_id and procurement.rule_id.action == 'buy' and procurement.product_id.purchase_requisition:
warehouse_id = warehouse_obj.search(cr, uid, [('company_id', '=', procurement.company_id.id)], context=context)
requisition_id = requisition_obj.create(cr, uid, {
'origin': procurement.origin,
'date_end': procurement.date_planned,
'warehouse_id': warehouse_id and warehouse_id[0] or False,
'company_id': procurement.company_id.id,
'procurement_id': procurement.id,
'picking_type_id': procurement.rule_id.picking_type_id.id,
'line_ids': [(0, 0, {
'product_id': procurement.product_id.id,
'product_uom_id': procurement.product_uom.id,
'product_qty': procurement.product_qty
})],
})
self.message_post(cr, uid, [procurement.id], body=_("Purchase Requisition created"), context=context)
return self.write(cr, uid, [procurement.id], {'requisition_id': requisition_id}, context=context)
return super(procurement_order, self)._run(cr, uid, procurement, context=context)
def _check(self, cr, uid, procurement, context=None):
if procurement.rule_id and procurement.rule_id.action == 'buy' and procurement.product_id.purchase_requisition:
if procurement.requisition_id.state == 'done':
if any([purchase.shipped for purchase in procurement.requisition_id.purchase_ids]):
return True
return False
return super(procurement_order, self)._check(cr, uid, procurement, context=context)
| agpl-3.0 | 4,870,444,895,170,810,000 | 54.129108 | 432 | 0.6241 | false |
jjd27/xen-api | ocaml/idl/ocaml_backend/python/test_client.py | 29 | 1223 | #!/usr/bin/python
import getopt, sys, xmlrpclib
url = "http://dhcp108:70000" #default
parsed = getopt.getopt(sys.argv[1:], "u:url")
if len(parsed[0]) == 1:
url = parsed[0][0][1]
# Create an object to represent our server.
server = xmlrpclib.Server(url);
# Call the server and get our result.
print "Logging in... ",
session = server.Session.do_login_with_password("user", "passwd", "1.0", "xen-api-test-client.py")
print "OK"
print "Session ID: \""+session+"\""
vm_list = server.VM.do_list(session)
print "VM list = " + repr(vm_list)
for vm in vm_list:
print "VM ", vm, " in state: ", server.VM.get_power_state(session, vm)
first_vm = vm_list[0]
other = server.VM.get_otherConfig(session, first_vm)
print repr(other)
#state = server.VM.get_power_state(session, first_vm)
#if state == "Halted":
# print "Starting first VM... ",
# server.VM.do_start(session, first_vm, 1==0)
#elif state == "Suspended":
# print "Restoring first VM..."
# server.VM.do_unhibernate(session, first_vm, 1==0)
#elif state == "Running":
# print "Suspending first VM... ",
# server.VM.do_hibernate(session, first_vm, 1==1)
#print "OK"
print "Logging out... ",
server.Session.do_logout(session)
print "OK"
| lgpl-2.1 | -8,496,878,081,359,612,000 | 26.795455 | 98 | 0.654129 | false |
paplorinc/intellij-community | python/testData/inspections/PyCompatibilityInspection/stringLiteralExpression.py | 3 | 3306 | a = u"String"
# Python 3.6
a = <error descr="Python version 2.7 does not support a 'F' prefix"><warning descr="Python version 2.6, 3.4, 3.5 do not support a 'F' prefix">f</warning></error>""
a = <error descr="Python version 2.7 does not support a 'F' prefix"><warning descr="Python version 2.6, 3.4, 3.5 do not support a 'F' prefix">F</warning></error>""
a = <error descr="Python version 2.7 does not support a 'RF' prefix"><warning descr="Python version 2.6, 3.4, 3.5 do not support a 'RF' prefix">rf</warning></error>""
a = <error descr="Python version 2.7 does not support a 'FR' prefix"><warning descr="Python version 2.6, 3.4, 3.5 do not support a 'FR' prefix">fr</warning></error>""
a = <error descr="Python version 2.7 does not support a 'FU' prefix"><warning descr="Python version 2.6, 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'FU' prefix">fu</warning></error>""
a = <error descr="Python version 2.7 does not support a 'UF' prefix"><warning descr="Python version 2.6, 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'UF' prefix">uf</warning></error>""
a = <error descr="Python version 2.7 does not support a 'BF' prefix"><warning descr="Python version 2.6, 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'BF' prefix">bf</warning></error>""
a = <error descr="Python version 2.7 does not support a 'FB' prefix"><warning descr="Python version 2.6, 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'FB' prefix">fb</warning></error>""
a = <error descr="Python version 2.7 does not support a 'UFR' prefix"><warning descr="Python version 2.6, 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'UFR' prefix">ufr</warning></error>""
# python 3.3
a = u""
a = r""
a = b""
a = <error descr="Python version 2.7 does not support a 'RB' prefix"><warning descr="Python version 2.6 does not support a 'RB' prefix">rb</warning></error>""
a = br""
# python 3.2, 3.1
a = r""
a = b""
a = br""
# python 3.0
a = r""
a = b""
# python 2.7, 2.6
a = u""
a = r""
a = <warning descr="Python version 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'UR' prefix">ur</warning>""
a = b""
a = br""
# python 2.5
a = u""
a = r""
a = <warning descr="Python version 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'UR' prefix">ur</warning>""
# combined, PY-32321
b = <warning descr="Python version 3.4, 3.5, 3.6, 3.7, 3.8 do not allow to mix bytes and non-bytes literals">u"" b""</warning>
b = <warning descr="Python version 3.4, 3.5, 3.6, 3.7, 3.8 do not allow to mix bytes and non-bytes literals">r"" b""</warning>
b = <warning descr="Python version 3.4, 3.5, 3.6, 3.7, 3.8 do not allow to mix bytes and non-bytes literals"><error descr="Python version 2.7 does not support a 'F' prefix"><warning descr="Python version 2.6, 3.4, 3.5 do not support a 'F' prefix">f</warning></error>"" b""</warning>
# never was available
a = <error descr="Python version 2.7 does not support a 'RR' prefix"><warning descr="Python version 2.6, 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'RR' prefix">rr</warning></error>""
a = <error descr="Python version 2.7 does not support a 'BB' prefix"><warning descr="Python version 2.6, 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'BB' prefix">bb</warning></error>""
a = <error descr="Python version 2.7 does not support a 'UU' prefix"><warning descr="Python version 2.6, 3.4, 3.5, 3.6, 3.7, 3.8 do not support a 'UU' prefix">uu</warning></error>"" | apache-2.0 | -747,938,652,563,302,500 | 58.053571 | 282 | 0.65245 | false |
ismailsunni/geonode | geosafe/models.py | 1 | 6780 | from __future__ import absolute_import
import tempfile
import urlparse
from django.conf import settings
from django.core.files.base import File
from django.core.urlresolvers import reverse
from django.db import models
from celery.result import AsyncResult
from geonode.layers.models import Layer
from geonode.people.models import Profile
from geosafe.tasks.headless.analysis import filter_impact_function
# geosafe
# list of tags to get to the InaSAFE keywords.
# this is stored in a list so it can be easily used in a for loop
ISO_METADATA_KEYWORD_NESTING = [
'{http://www.isotc211.org/2005/gmd}identificationInfo',
'{http://www.isotc211.org/2005/gmd}MD_DataIdentification',
'{http://www.isotc211.org/2005/gmd}supplementalInformation',
'inasafe_keywords']
# flat xpath for the keyword container tag
ISO_METADATA_KEYWORD_TAG = '/'.join(ISO_METADATA_KEYWORD_NESTING)
class GeoSAFEException(BaseException):
pass
# Create your models here.
class Metadata(models.Model):
"""Represent metadata for a layer."""
layer = models.OneToOneField(Layer, primary_key=True,
related_name='metadata')
layer_purpose = models.CharField(
verbose_name='Purpose of the Layer',
max_length=20,
blank=True,
null=True,
default=''
)
category = models.CharField(
verbose_name='The category of layer purpose that describes a kind of'
'hazard or exposure this layer is',
max_length=30,
blank=True,
null=True,
default=''
)
class Analysis(models.Model):
"""Represent GeoSAFE analysis"""
HAZARD_EXPOSURE_CURRENT_VIEW_CODE = 1
HAZARD_EXPOSURE_CODE = 2
HAZARD_EXPOSURE_BBOX_CODE = 3
HAZARD_EXPOSURE_CURRENT_VIEW_TEXT = (
'Use intersection of hazard, exposure, and current view extent')
HAZARD_EXPOSURE_TEXT = 'Use intersection of hazard and exposure'
HAZARD_EXPOSURE_BBOX_TEXT = (
'Use intersection of hazard, exposure, and bounding box')
EXTENT_CHOICES = (
(HAZARD_EXPOSURE_CURRENT_VIEW_CODE, HAZARD_EXPOSURE_CURRENT_VIEW_TEXT),
(HAZARD_EXPOSURE_CODE, HAZARD_EXPOSURE_TEXT),
# Disable for now
# (HAZARD_EXPOSURE_BBOX_CODE, HAZARD_EXPOSURE_BBOX_TEXT),
)
class Meta:
verbose_name_plural = 'Analyses'
exposure_layer = models.ForeignKey(
Layer,
verbose_name='Exposure Layer',
help_text='Exposure layer for analysis.',
blank=False,
null=False,
related_name='exposure_layer'
)
hazard_layer = models.ForeignKey(
Layer,
verbose_name='Hazard Layer',
help_text='Hazard layer for analysis.',
blank=False,
null=False,
related_name='hazard_layer'
)
aggregation_layer = models.ForeignKey(
Layer,
verbose_name='Aggregation Layer',
help_text='Aggregation layer for analysis.',
blank=True,
null=True,
related_name='aggregation_layer'
)
impact_function_id = models.CharField(
max_length=100,
verbose_name='ID of Impact Function',
help_text='The ID of Impact Function used in the analysis.',
blank=False,
null=False
)
extent_option = models.IntegerField(
choices=EXTENT_CHOICES,
default=HAZARD_EXPOSURE_CODE,
verbose_name='Analysis extent',
help_text='Extent option for analysis.'
)
impact_layer = models.ForeignKey(
Layer,
verbose_name='Impact Layer',
help_text='Impact layer from this analysis.',
blank=True,
null=True,
related_name='impact_layer'
)
task_id = models.CharField(
max_length=40,
verbose_name='Task UUID',
help_text='Task UUID that runs analysis',
blank=True,
null=True
)
keep = models.BooleanField(
verbose_name='Keep impact result',
help_text='True if the impact will be kept',
blank=True,
default=False,
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
verbose_name='Author',
help_text='The author of the analysis',
blank=True,
null=True
)
report_map = models.FileField(
verbose_name='Report Map',
help_text='The map report of the analysis',
blank=True,
null=True,
upload_to='analysis/report/'
)
report_table = models.FileField(
verbose_name='Report Table',
help_text='The table report of the analysis',
blank=True,
null=True,
upload_to='analysis/report/'
)
def assign_report_map(self, filename):
try:
self.report_map.delete()
except:
pass
self.report_map = File(open(filename))
def assign_report_table(self, filename):
try:
self.report_table.delete()
except:
pass
self.report_table = File(open(filename))
def get_task_result(self):
return AsyncResult(self.task_id)
def get_label_class(self):
result = self.get_task_result()
if result.state == 'SUCCESS':
return 'success'
elif result.state == 'FAILURE':
return 'danger'
else:
return 'info'
def get_default_impact_title(self):
layer_name = '%s on %s' % (
self.hazard_layer.name,
self.exposure_layer.name
)
return layer_name
impact_function_list = filter_impact_function.delay().get()
def impact_function_name(self):
for i in self.impact_function_list:
if i['id'] == self.impact_function_id:
return i['name']
return ''
@classmethod
def get_layer_url(cls, layer):
layer_id = layer.id
layer_url = reverse(
'geosafe:layer-archive',
kwargs={'layer_id': layer_id})
layer_url = urlparse.urljoin(settings.GEONODE_BASE_URL, layer_url)
return layer_url
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None, run_analysis_flag=True):
super(Analysis, self).save(
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields)
def delete(self, using=None):
try:
self.report_map.delete()
except:
pass
try:
self.report_table.delete()
except:
pass
try:
self.impact_layer.delete()
except:
pass
super(Analysis, self).delete(using=using)
# needed to load signals
from geosafe import signals # noqa
| gpl-3.0 | 3,505,547,208,602,128,000 | 27.016529 | 79 | 0.605605 | false |
dragon788/powerline | powerline/lib/watcher/inotify.py | 35 | 7921 | # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import errno
import os
import ctypes
from threading import RLock
from powerline.lib.inotify import INotify
from powerline.lib.monotonic import monotonic
from powerline.lib.path import realpath
class INotifyFileWatcher(INotify):
def __init__(self, expire_time=10):
super(INotifyFileWatcher, self).__init__()
self.watches = {}
self.modified = {}
self.last_query = {}
self.lock = RLock()
self.expire_time = expire_time * 60
def expire_watches(self):
now = monotonic()
for path, last_query in tuple(self.last_query.items()):
if last_query - now > self.expire_time:
self.unwatch(path)
def process_event(self, wd, mask, cookie, name):
if wd == -1 and (mask & self.Q_OVERFLOW):
# We missed some INOTIFY events, so we dont
# know the state of any tracked files.
for path in tuple(self.modified):
if os.path.exists(path):
self.modified[path] = True
else:
self.watches.pop(path, None)
self.modified.pop(path, None)
self.last_query.pop(path, None)
return
for path, num in tuple(self.watches.items()):
if num == wd:
if mask & self.IGNORED:
self.watches.pop(path, None)
self.modified.pop(path, None)
self.last_query.pop(path, None)
else:
if mask & self.ATTRIB:
# The watched file could have had its inode changed, in
# which case we will not get any more events for this
# file, so re-register the watch. For example by some
# other file being renamed as this file.
try:
self.unwatch(path)
except OSError:
pass
try:
self.watch(path)
except OSError as e:
if getattr(e, 'errno', None) != errno.ENOENT:
raise
else:
self.modified[path] = True
else:
self.modified[path] = True
def unwatch(self, path):
''' Remove the watch for path. Raises an OSError if removing the watch
fails for some reason. '''
path = realpath(path)
with self.lock:
self.modified.pop(path, None)
self.last_query.pop(path, None)
wd = self.watches.pop(path, None)
if wd is not None:
if self._rm_watch(self._inotify_fd, wd) != 0:
self.handle_error()
def watch(self, path):
''' Register a watch for the file/directory named path. Raises an OSError if path
does not exist. '''
path = realpath(path)
with self.lock:
if path not in self.watches:
bpath = path if isinstance(path, bytes) else path.encode(self.fenc)
flags = self.MOVE_SELF | self.DELETE_SELF
buf = ctypes.c_char_p(bpath)
# Try watching path as a directory
wd = self._add_watch(self._inotify_fd, buf, flags | self.ONLYDIR)
if wd == -1:
eno = ctypes.get_errno()
if eno != errno.ENOTDIR:
self.handle_error()
# Try watching path as a file
flags |= (self.MODIFY | self.ATTRIB)
wd = self._add_watch(self._inotify_fd, buf, flags)
if wd == -1:
self.handle_error()
self.watches[path] = wd
self.modified[path] = False
def is_watching(self, path):
with self.lock:
return realpath(path) in self.watches
def __call__(self, path):
''' Return True if path has been modified since the last call. Can
raise OSError if the path does not exist. '''
path = realpath(path)
with self.lock:
self.last_query[path] = monotonic()
self.expire_watches()
if path not in self.watches:
# Try to re-add the watch, it will fail if the file does not
# exist/you dont have permission
self.watch(path)
return True
self.read(get_name=False)
if path not in self.modified:
# An ignored event was received which means the path has been
# automatically unwatched
return True
ans = self.modified[path]
if ans:
self.modified[path] = False
return ans
def close(self):
with self.lock:
for path in tuple(self.watches):
try:
self.unwatch(path)
except OSError:
pass
super(INotifyFileWatcher, self).close()
class NoSuchDir(ValueError):
pass
class BaseDirChanged(ValueError):
pass
class DirTooLarge(ValueError):
def __init__(self, bdir):
ValueError.__init__(self, 'The directory {0} is too large to monitor. Try increasing the value in /proc/sys/fs/inotify/max_user_watches'.format(bdir))
class INotifyTreeWatcher(INotify):
is_dummy = False
def __init__(self, basedir, ignore_event=None):
super(INotifyTreeWatcher, self).__init__()
self.basedir = realpath(basedir)
self.watch_tree()
self.modified = True
self.ignore_event = (lambda path, name: False) if ignore_event is None else ignore_event
def watch_tree(self):
self.watched_dirs = {}
self.watched_rmap = {}
try:
self.add_watches(self.basedir)
except OSError as e:
if e.errno == errno.ENOSPC:
raise DirTooLarge(self.basedir)
def add_watches(self, base, top_level=True):
''' Add watches for this directory and all its descendant directories,
recursively. '''
base = realpath(base)
# There may exist a link which leads to an endless
# add_watches loop or to maximum recursion depth exceeded
if not top_level and base in self.watched_dirs:
return
try:
is_dir = self.add_watch(base)
except OSError as e:
if e.errno == errno.ENOENT:
# The entry could have been deleted between listdir() and
# add_watch().
if top_level:
raise NoSuchDir('The dir {0} does not exist'.format(base))
return
if e.errno == errno.EACCES:
# We silently ignore entries for which we dont have permission,
# unless they are the top level dir
if top_level:
raise NoSuchDir('You do not have permission to monitor {0}'.format(base))
return
raise
else:
if is_dir:
try:
files = os.listdir(base)
except OSError as e:
if e.errno in (errno.ENOTDIR, errno.ENOENT):
# The dir was deleted/replaced between the add_watch()
# and listdir()
if top_level:
raise NoSuchDir('The dir {0} does not exist'.format(base))
return
raise
for x in files:
self.add_watches(os.path.join(base, x), top_level=False)
elif top_level:
# The top level dir is a file, not good.
raise NoSuchDir('The dir {0} does not exist'.format(base))
def add_watch(self, path):
bpath = path if isinstance(path, bytes) else path.encode(self.fenc)
wd = self._add_watch(
self._inotify_fd,
ctypes.c_char_p(bpath),
# Ignore symlinks and watch only directories
self.DONT_FOLLOW | self.ONLYDIR |
self.MODIFY | self.CREATE | self.DELETE |
self.MOVE_SELF | self.MOVED_FROM | self.MOVED_TO |
self.ATTRIB | self.DELETE_SELF
)
if wd == -1:
eno = ctypes.get_errno()
if eno == errno.ENOTDIR:
return False
raise OSError(eno, 'Failed to add watch for: {0}: {1}'.format(path, self.os.strerror(eno)))
self.watched_dirs[path] = wd
self.watched_rmap[wd] = path
return True
def process_event(self, wd, mask, cookie, name):
if wd == -1 and (mask & self.Q_OVERFLOW):
# We missed some INOTIFY events, so we dont
# know the state of any tracked dirs.
self.watch_tree()
self.modified = True
return
path = self.watched_rmap.get(wd, None)
if path is not None:
if not self.ignore_event(path, name):
self.modified = True
if mask & self.CREATE:
# A new sub-directory might have been created, monitor it.
try:
if not isinstance(path, bytes):
name = name.decode(self.fenc)
self.add_watch(os.path.join(path, name))
except OSError as e:
if e.errno == errno.ENOENT:
# Deleted before add_watch()
pass
elif e.errno == errno.ENOSPC:
raise DirTooLarge(self.basedir)
else:
raise
if (mask & self.DELETE_SELF or mask & self.MOVE_SELF) and path == self.basedir:
raise BaseDirChanged('The directory %s was moved/deleted' % path)
def __call__(self):
self.read()
ret = self.modified
self.modified = False
return ret
| mit | 403,453,236,594,433,200 | 28.55597 | 152 | 0.66229 | false |
F5Networks/f5-ansible | ansible_collections/f5networks/f5_modules/plugins/modules/bigip_monitor_snmp_dca.py | 1 | 23355 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# 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
DOCUMENTATION = r'''
---
module: bigip_monitor_snmp_dca
short_description: Manages BIG-IP SNMP data collecting agent (DCA) monitors
description:
- The BIG-IP has an SNMP data collecting agent (DCA) that can query remote
SNMP agents of various types, including the UC Davis agent (UCD) and the
Windows 2000 Server agent (WIN2000).
version_added: "1.0.0"
options:
name:
description:
- Monitor name.
type: str
required: True
description:
description:
- Specifies descriptive text that identifies the monitor.
type: str
parent:
description:
- The parent template of this monitor template. Once this value has
been set, it cannot be changed. By default, this value is the C(snmp_dca)
parent on the C(Common) partition.
type: str
default: "/Common/snmp_dca"
interval:
description:
- Specifies the frequency, in seconds, at which the system issues the
monitor check when either the resource is down or the status of the
resource is unknown. When creating a new monitor, the default is C(10).
type: int
timeout:
description:
- Specifies the number of seconds the target has in which to respond to
the monitor request. When creating a new monitor, the default is C(30)
seconds. If the target responds within the set time period, it is
considered 'up'. If the target does not respond within the set time
period, it is considered 'down'. When this value is set to 0 (zero),
the system uses the interval from the parent monitor. Note that
C(timeout) and C(time_until_up) combine to control when a resource is
set to up.
type: int
time_until_up:
description:
- Specifies the number of seconds to wait after a resource first responds
correctly to the monitor before setting the resource to 'up'. During the
interval, all responses from the resource must be correct. When the
interval expires, the resource is marked 'up'. A value of 0, means
that the resource is marked up immediately upon receipt of the first
correct response. When creating a new monitor, the default is C(0).
type: int
community:
description:
- Specifies the community name the system must use to authenticate
with the host server through SNMP. When creating a new monitor, the
default value is C(public). This value is case sensitive.
type: str
version:
description:
- Specifies the version of SNMP the host server uses. When creating
a new monitor, the default is C(v1). When C(v1), specifies the
host server uses SNMP version 1. When C(v2c), specifies that the host
server uses SNMP version 2c.
type: str
choices:
- v1
- v2c
agent_type:
description:
- Specifies the SNMP agent running on the monitored server. When creating
a new monitor, the default is C(UCD) (UC-Davis).
type: str
choices:
- UCD
- WIN2000
- GENERIC
cpu_coefficient:
description:
- Specifies the coefficient the system uses to calculate the weight
of the CPU threshold in the dynamic ratio load balancing algorithm.
When creating a new monitor, the default is C(1.5).
type: str
cpu_threshold:
description:
- Specifies the maximum acceptable CPU usage on the target server. When
creating a new monitor, the default is C(80) percent.
type: int
memory_coefficient:
description:
- Specifies the coefficient the system uses to calculate the weight
of the memory threshold in the dynamic ratio load balancing algorithm.
When creating a new monitor, the default is C(1.0).
type: str
memory_threshold:
description:
- Specifies the maximum acceptable memory usage on the target server.
When creating a new monitor, the default is C(70) percent.
type: int
disk_coefficient:
description:
- Specifies the coefficient the system uses to calculate the weight
of the disk threshold in the dynamic ratio load balancing algorithm.
When creating a new monitor, the default is C(2.0).
type: str
disk_threshold:
description:
- Specifies the maximum acceptable disk usage on the target server. When
creating a new monitor, the default is C(90) percent.
type: int
partition:
description:
- Device partition to manage resources on.
type: str
default: Common
state:
description:
- When C(present), ensures the monitor exists.
- When C(absent), ensures the monitor is removed.
type: str
choices:
- present
- absent
default: present
notes:
- Requires BIG-IP software version >= 12
- This module does not support the C(variables) option because it
is broken in the REST API and does not function correctly in C(tmsh); for
example you cannot remove user-defined params. Therefore, there is no way
to automatically configure it.
extends_documentation_fragment: f5networks.f5_modules.f5
author:
- Tim Rupp (@caphrim007)
- Wojciech Wypior (@wojtek0806)
'''
EXAMPLES = r'''
- name: Create SNMP DCS monitor
bigip_monitor_snmp_dca:
name: my_monitor
state: present
provider:
server: lb.mydomain.com
user: admin
password: secret
delegate_to: localhost
- name: Remove TCP Echo Monitor
bigip_monitor_snmp_dca:
name: my_monitor
state: absent
provider:
server: lb.mydomain.com
user: admin
password: secret
delegate_to: localhost
'''
RETURN = r'''
parent:
description: New parent template of the monitor.
returned: changed
type: str
sample: snmp_dca
description:
description: The description of the monitor.
returned: changed
type: str
sample: Important Monitor
interval:
description: The new interval at which to run the monitor check.
returned: changed
type: int
sample: 2
timeout:
description: The new timeout in which the remote system must respond to the monitor.
returned: changed
type: int
sample: 10
time_until_up:
description: The new time in which to mark a system as up after first successful response.
returned: changed
type: int
sample: 2
community:
description: The new community for the monitor.
returned: changed
type: str
sample: foobar
version:
description: The new new SNMP version to be used by the monitor.
returned: changed
type: str
sample: v2c
agent_type:
description: The new agent type to be used by the monitor.
returned: changed
type: str
sample: UCD
cpu_coefficient:
description: The new CPU coefficient.
returned: changed
type: float
sample: 2.4
cpu_threshold:
description: The new CPU threshold.
returned: changed
type: int
sample: 85
memory_coefficient:
description: The new memory coefficient.
returned: changed
type: float
sample: 6.4
memory_threshold:
description: The new memory threshold.
returned: changed
type: int
sample: 50
disk_coefficient:
description: The new disk coefficient.
returned: changed
type: float
sample: 10.2
disk_threshold:
description: The new disk threshold.
returned: changed
type: int
sample: 34
'''
from datetime import datetime
from ansible.module_utils.basic import (
AnsibleModule, env_fallback
)
from ..module_utils.bigip import F5RestClient
from ..module_utils.common import (
F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
)
from ..module_utils.compare import cmp_str_with_none
from ..module_utils.icontrol import tmos_version
from ..module_utils.teem import send_teem
class Parameters(AnsibleF5Parameters):
api_map = {
'timeUntilUp': 'time_until_up',
'defaultsFrom': 'parent',
'agentType': 'agent_type',
'cpuCoefficient': 'cpu_coefficient',
'cpuThreshold': 'cpu_threshold',
'memoryCoefficient': 'memory_coefficient',
'memoryThreshold': 'memory_threshold',
'diskCoefficient': 'disk_coefficient',
'diskThreshold': 'disk_threshold',
}
api_attributes = [
'timeUntilUp',
'defaultsFrom',
'interval',
'timeout',
'destination',
'community',
'version',
'agentType',
'cpuCoefficient',
'cpuThreshold',
'memoryCoefficient',
'memoryThreshold',
'diskCoefficient',
'diskThreshold',
'description',
]
returnables = [
'parent',
'ip',
'interval',
'timeout',
'time_until_up',
'description',
'community',
'version',
'agent_type',
'cpu_coefficient',
'cpu_threshold',
'memory_coefficient',
'memory_threshold',
'disk_coefficient',
'disk_threshold',
]
updatables = [
'ip',
'interval',
'timeout',
'time_until_up',
'description',
'community',
'version',
'agent_type',
'cpu_coefficient',
'cpu_threshold',
'memory_coefficient',
'memory_threshold',
'disk_coefficient',
'disk_threshold',
]
@property
def interval(self):
if self._values['interval'] is None:
return None
if 1 > int(self._values['interval']) > 86400:
raise F5ModuleError(
"Interval value must be between 1 and 86400"
)
return int(self._values['interval'])
@property
def timeout(self):
if self._values['timeout'] is None:
return None
return int(self._values['timeout'])
@property
def time_until_up(self):
if self._values['time_until_up'] is None:
return None
return int(self._values['time_until_up'])
@property
def parent(self):
if self._values['parent'] is None:
return None
result = fq_name(self.partition, self._values['parent'])
return result
@property
def cpu_coefficient(self):
result = self._get_numeric_property('cpu_coefficient')
return result
@property
def cpu_threshold(self):
result = self._get_numeric_property('cpu_threshold')
return result
@property
def memory_coefficient(self):
result = self._get_numeric_property('memory_coefficient')
return result
@property
def memory_threshold(self):
result = self._get_numeric_property('memory_threshold')
return result
@property
def disk_coefficient(self):
result = self._get_numeric_property('disk_coefficient')
return result
@property
def disk_threshold(self):
result = self._get_numeric_property('disk_threshold')
return result
def _get_numeric_property(self, property):
if self._values[property] is None:
return None
try:
fvar = float(self._values[property])
except ValueError:
raise F5ModuleError(
"Provided {0} must be a valid number".format(property)
)
return fvar
@property
def type(self):
return 'snmp_dca'
class ApiParameters(Parameters):
@property
def description(self):
if self._values['description'] in [None, 'none']:
return None
return self._values['description']
class ModuleParameters(Parameters):
@property
def description(self):
if self._values['description'] is None:
return None
elif self._values['description'] in ['none', '']:
return ''
return self._values['description']
class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
raise
return result
class UsableChanges(Changes):
pass
class ReportableChanges(Changes):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
result = self.__default(param)
return result
@property
def parent(self):
if self.want.parent != self.have.parent:
raise F5ModuleError(
"The parent monitor cannot be changed"
)
@property
def interval(self):
if self.want.timeout is not None and self.want.interval is not None:
if self.want.interval >= self.want.timeout:
raise F5ModuleError(
"Parameter 'interval' must be less than 'timeout'."
)
elif self.want.timeout is not None:
if self.have.interval >= self.want.timeout:
raise F5ModuleError(
"Parameter 'interval' must be less than 'timeout'."
)
elif self.want.interval is not None:
if self.want.interval >= self.have.timeout:
raise F5ModuleError(
"Parameter 'interval' must be less than 'timeout'."
)
if self.want.interval != self.have.interval:
return self.want.interval
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
@property
def description(self):
return cmp_str_with_none(self.want.description, self.have.description)
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = F5RestClient(**self.module.params)
self.want = ModuleParameters(params=self.module.params)
self.have = ApiParameters()
self.changes = UsableChanges()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def exec_module(self):
start = datetime.now().isoformat()
version = tmos_version(self.client)
changed = False
result = dict()
state = self.want.state
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
send_teem(start, self.client, self.module, version)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def exists(self):
uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/snmp-dca/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if resp.status == 404 or 'code' in response and response['code'] == 404:
return False
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
return True
errors = [401, 403, 409, 500, 501, 502, 503, 504]
if resp.status in errors or 'code' in response and response['code'] in errors:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def remove(self):
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource.")
return True
def create(self):
self._set_changed_options()
self._set_default_creation_values()
if self.module.check_mode:
return True
self.create_on_device()
return True
def _set_default_creation_values(self):
if self.want.timeout is None:
self.want.update({'timeout': 30})
if self.want.interval is None:
self.want.update({'interval': 10})
if self.want.time_until_up is None:
self.want.update({'time_until_up': 0})
if self.want.community is None:
self.want.update({'community': 'public'})
if self.want.version is None:
self.want.update({'version': 'v1'})
if self.want.agent_type is None:
self.want.update({'agent_type': 'UCD'})
if self.want.cpu_coefficient is None:
self.want.update({'cpu_coefficient': '1.5'})
if self.want.cpu_threshold is None:
self.want.update({'cpu_threshold': '80'})
if self.want.memory_coefficient is None:
self.want.update({'memory_coefficient': '1.0'})
if self.want.memory_threshold is None:
self.want.update({'memory_threshold': '70'})
if self.want.disk_coefficient is None:
self.want.update({'disk_coefficient': '2.0'})
if self.want.disk_threshold is None:
self.want.update({'disk_threshold': '90'})
def create_on_device(self):
params = self.changes.api_params()
params['name'] = self.want.name
params['partition'] = self.want.partition
uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/snmp-dca/".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
return True
raise F5ModuleError(resp.content)
def update_on_device(self):
params = self.changes.api_params()
uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/snmp-dca/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.patch(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
return True
raise F5ModuleError(resp.content)
def absent(self):
if self.exists():
return self.remove()
return False
def remove_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/snmp-dca/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.delete(uri)
if resp.status == 200:
return True
def read_current_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/ltm/monitor/snmp-dca/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
return ApiParameters(params=response)
raise F5ModuleError(resp.content)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
name=dict(required=True),
description=dict(),
parent=dict(default='/Common/snmp_dca'),
interval=dict(type='int'),
timeout=dict(type='int'),
time_until_up=dict(type='int'),
community=dict(),
version=dict(choices=['v1', 'v2c']),
agent_type=dict(
choices=['UCD', 'WIN2000', 'GENERIC']
),
cpu_coefficient=dict(),
cpu_threshold=dict(type='int'),
memory_coefficient=dict(),
memory_threshold=dict(type='int'),
disk_coefficient=dict(),
disk_threshold=dict(type='int'),
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
)
try:
mm = ModuleManager(module=module)
results = mm.exec_module()
module.exit_json(**results)
except F5ModuleError as ex:
module.fail_json(msg=str(ex))
if __name__ == '__main__':
main()
| gpl-3.0 | 8,502,129,284,505,672,000 | 29.852048 | 94 | 0.603939 | false |
shakamunyi/tensorflow | tensorflow/contrib/distributions/python/ops/gaussian.py | 2 | 8079 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""The Normal (Gaussian) distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.contrib.framework.python.framework import tensor_util as contrib_tensor_util # pylint: disable=line-too-long
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import constant_op
from tensorflow.python.ops import logging_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
# TODO(ebrevdo): Use asserts contrib module when ready
def _assert_all_positive(x):
return logging_ops.Assert(
math_ops.reduce_all(x > 0),
["Tensor %s should contain only positive values: " % x.name, x])
class Gaussian(object):
"""The scalar Gaussian distribution with mean and stddev parameters mu, sigma.
#### Mathematical details
The PDF of this distribution is:
```f(x) = sqrt(1/(2*pi*sigma^2)) exp(-(x-mu)^2/(2*sigma^2))```
#### Examples
Examples of initialization of one or a batch of distributions.
```python
# Define a single scalar Gaussian distribution.
dist = tf.contrib.distributions.Gaussian(mu=0, sigma=3)
# Evaluate the cdf at 1, returning a scalar.
dist.cdf(1)
# Define a batch of two scalar valued Gaussians.
# The first has mean 1 and standard deviation 11, the second 2 and 22.
dist = tf.contrib.distributions.Gaussian(mu=[1, 2.], sigma=[11, 22.])
# Evaluate the pdf of the first distribution on 0, and the second on 1.5,
# returning a length two tensor.
dist.pdf([0, 1.5])
# Get 3 samples, returning a 3 x 2 tensor.
dist.sample(3)
```
Arguments are broadcast when possible.
```python
# Define a batch of two scalar valued Gaussians.
# Both have mean 1, but different standard deviations.
dist = tf.contrib.distributions.Gaussian(mu=1, sigma=[11, 22.])
# Evaluate the pdf of both distributions on the same point, 3.0,
# returning a length 2 tensor.
dist.pdf(3.0)
```
"""
def __init__(self, mu, sigma, name=None):
"""Construct Gaussian distributions with mean and stddev `mu` and `sigma`.
The parameters `mu` and `sigma` must be shaped in a way that supports
broadcasting (e.g. `mu + sigma` is a valid operation).
Args:
mu: `float` or `double` tensor, the means of the distribution(s).
sigma: `float` or `double` tensor, the stddevs of the distribution(s).
sigma must contain only positive values.
name: The name to give Ops created by the initializer.
Raises:
TypeError: if mu and sigma are different dtypes.
"""
with ops.op_scope([mu, sigma], name, "Gaussian"):
mu = ops.convert_to_tensor(mu)
sigma = ops.convert_to_tensor(sigma)
with ops.control_dependencies([_assert_all_positive(sigma)]):
self._mu = array_ops.identity(mu, name="mu")
self._sigma = array_ops.identity(sigma, name="sigma")
contrib_tensor_util.assert_same_float_dtype((mu, sigma))
@property
def dtype(self):
return self._mu.dtype
@property
def mu(self):
return self._mu
@property
def sigma(self):
return self._sigma
@property
def mean(self):
return self._mu * array_ops.ones_like(self._sigma)
def log_pdf(self, x, name=None):
"""Log pdf of observations in `x` under these Gaussian distribution(s).
Args:
x: tensor of dtype `dtype`, must be broadcastable with `mu` and `sigma`.
name: The name to give this op.
Returns:
log_pdf: tensor of dtype `dtype`, the log-PDFs of `x`.
"""
with ops.op_scope([self._mu, self._sigma, x], name, "GaussianLogPdf"):
x = ops.convert_to_tensor(x)
if x.dtype != self.dtype:
raise TypeError("Input x dtype does not match dtype: %s vs. %s"
% (x.dtype, self.dtype))
log_2_pi = constant_op.constant(math.log(2 * math.pi), dtype=self.dtype)
return (-0.5*log_2_pi - math_ops.log(self._sigma)
-0.5*math_ops.square((x - self._mu) / self._sigma))
def cdf(self, x, name=None):
"""CDF of observations in `x` under these Gaussian distribution(s).
Args:
x: tensor of dtype `dtype`, must be broadcastable with `mu` and `sigma`.
name: The name to give this op.
Returns:
cdf: tensor of dtype `dtype`, the CDFs of `x`.
"""
with ops.op_scope([self._mu, self._sigma, x], name, "GaussianCdf"):
x = ops.convert_to_tensor(x)
if x.dtype != self.dtype:
raise TypeError("Input x dtype does not match dtype: %s vs. %s"
% (x.dtype, self.dtype))
return (0.5 + 0.5*math_ops.erf(
1.0/(math.sqrt(2.0) * self._sigma)*(x - self._mu)))
def log_cdf(self, x, name=None):
"""Log CDF of observations `x` under these Gaussian distribution(s).
Args:
x: tensor of dtype `dtype`, must be broadcastable with `mu` and `sigma`.
name: The name to give this op.
Returns:
log_cdf: tensor of dtype `dtype`, the log-CDFs of `x`.
"""
with ops.op_scope([self._mu, self._sigma, x], name, "GaussianLogCdf"):
return math_ops.log(self.cdf(x))
def pdf(self, x, name=None):
"""The PDF of observations in `x` under these Gaussian distribution(s).
Args:
x: tensor of dtype `dtype`, must be broadcastable with `mu` and `sigma`.
name: The name to give this op.
Returns:
pdf: tensor of dtype `dtype`, the pdf values of `x`.
"""
with ops.op_scope([self._mu, self._sigma, x], name, "GaussianPdf"):
return math_ops.exp(self.log_pdf(x))
def entropy(self, name=None):
"""The entropy of Gaussian distribution(s).
Args:
name: The name to give this op.
Returns:
entropy: tensor of dtype `dtype`, the entropy.
"""
with ops.op_scope([self._mu, self._sigma], name, "GaussianEntropy"):
two_pi_e1 = constant_op.constant(
2 * math.pi * math.exp(1), dtype=self.dtype)
# Use broadcasting rules to calculate the full broadcast sigma.
sigma = self._sigma * array_ops.ones_like(self._mu)
return 0.5 * math_ops.log(two_pi_e1 * math_ops.square(sigma))
def sample(self, n, seed=None, name=None):
"""Sample `n` observations from the Gaussian Distributions.
Args:
n: `Scalar`, type int32, the number of observations to sample.
seed: Python integer, the random seed.
name: The name to give this op.
Returns:
samples: `[n, ...]`, a `Tensor` of `n` samples for each
of the distributions determined by broadcasting the hyperparameters.
"""
with ops.op_scope([self._mu, self._sigma, n], name, "GaussianSample"):
broadcast_shape = (self._mu + self._sigma).get_shape()
n = ops.convert_to_tensor(n)
shape = array_ops.concat(
0, [array_ops.pack([n]), array_ops.shape(self.mean)])
sampled = random_ops.random_normal(
shape=shape, mean=0, stddev=1, dtype=self._mu.dtype, seed=seed)
# Provide some hints to shape inference
n_val = tensor_util.constant_value(n)
final_shape = tensor_shape.vector(n_val).concatenate(broadcast_shape)
sampled.set_shape(final_shape)
return sampled * self._sigma + self._mu
@property
def is_reparameterized(self):
return True
| apache-2.0 | -2,743,043,769,153,469,400 | 33.378723 | 125 | 0.652308 | false |
JordanReiter/python-oauth2 | oauth2/__init__.py | 6 | 24905 | """
The MIT License
Copyright (c) 2007-2010 Leah Culver, Joe Stump, Mark Paschal, Vic Fryzel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import urllib
import time
import random
import urlparse
import hmac
import binascii
import httplib2
try:
from urlparse import parse_qs, parse_qsl
except ImportError:
from cgi import parse_qs, parse_qsl
VERSION = '1.0' # Hi Blaine!
HTTP_METHOD = 'GET'
SIGNATURE_METHOD = 'PLAINTEXT'
class Error(RuntimeError):
"""Generic exception class."""
def __init__(self, message='OAuth error occurred.'):
self._message = message
@property
def message(self):
"""A hack to get around the deprecation errors in 2.6."""
return self._message
def __str__(self):
return self._message
class MissingSignature(Error):
pass
def build_authenticate_header(realm=''):
"""Optional WWW-Authenticate header (401 error)"""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def build_xoauth_string(url, consumer, token=None):
"""Build an XOAUTH string for use in SMTP/IMPA authentication."""
request = Request.from_consumer_and_token(consumer, token,
"GET", url)
signing_method = SignatureMethod_HMAC_SHA1()
request.sign_request(signing_method, consumer, token)
params = []
for k, v in sorted(request.iteritems()):
if v is not None:
params.append('%s="%s"' % (k, escape(v)))
return "%s %s %s" % ("GET", url, ','.join(params))
def escape(s):
"""Escape a URL including any /."""
return urllib.quote(s, safe='~')
def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
def generate_nonce(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
def generate_verifier(length=8):
"""Generate pseudorandom number."""
return ''.join([str(random.randint(0, 9)) for i in range(length)])
class Consumer(object):
"""A consumer of OAuth-protected services.
The OAuth consumer is a "third-party" service that wants to access
protected resources from an OAuth service provider on behalf of an end
user. It's kind of the OAuth client.
Usually a consumer must be registered with the service provider by the
developer of the consumer software. As part of that process, the service
provider gives the consumer a *key* and a *secret* with which the consumer
software can identify itself to the service. The consumer will include its
key in each request to identify itself, but will use its secret only when
signing requests, to prove that the request is from that particular
registered consumer.
Once registered, the consumer can then use its consumer credentials to ask
the service provider for a request token, kicking off the OAuth
authorization process.
"""
key = None
secret = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def __str__(self):
data = {'oauth_consumer_key': self.key,
'oauth_consumer_secret': self.secret}
return urllib.urlencode(data)
class Token(object):
"""An OAuth credential used to request authorization or a protected
resource.
Tokens in OAuth comprise a *key* and a *secret*. The key is included in
requests to identify the token being used, but the secret is used only in
the signature, to prove that the requester is who the server gave the
token to.
When first negotiating the authorization, the consumer asks for a *request
token* that the live user authorizes with the service provider. The
consumer then exchanges the request token for an *access token* that can
be used to access protected resources.
"""
key = None
secret = None
callback = None
callback_confirmed = None
verifier = None
def __init__(self, key, secret):
self.key = key
self.secret = secret
if self.key is None or self.secret is None:
raise ValueError("Key and secret must be set.")
def set_callback(self, callback):
self.callback = callback
self.callback_confirmed = 'true'
def set_verifier(self, verifier=None):
if verifier is not None:
self.verifier = verifier
else:
self.verifier = generate_verifier()
def get_callback_url(self):
if self.callback and self.verifier:
# Append the oauth_verifier.
parts = urlparse.urlparse(self.callback)
scheme, netloc, path, params, query, fragment = parts[:6]
if query:
query = '%s&oauth_verifier=%s' % (query, self.verifier)
else:
query = 'oauth_verifier=%s' % self.verifier
return urlparse.urlunparse((scheme, netloc, path, params,
query, fragment))
return self.callback
def to_string(self):
"""Returns this token as a plain string, suitable for storage.
The resulting string includes the token's secret, so you should never
send or store this string where a third party can read it.
"""
data = {
'oauth_token': self.key,
'oauth_token_secret': self.secret,
}
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
@staticmethod
def from_string(s):
"""Deserializes a token from a string like one returned by
`to_string()`."""
if not len(s):
raise ValueError("Invalid parameter string.")
params = parse_qs(s, keep_blank_values=False)
if not len(params):
raise ValueError("Invalid parameter string.")
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oauth_token' not found in OAuth request.")
try:
secret = params['oauth_token_secret'][0]
except Exception:
raise ValueError("'oauth_token_secret' not found in "
"OAuth request.")
token = Token(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except KeyError:
pass # 1.0, no callback confirmed.
return token
def __str__(self):
return self.to_string()
def setter(attr):
name = attr.__name__
def getter(self):
try:
return self.__dict__[name]
except KeyError:
raise AttributeError(name)
def deleter(self):
del self.__dict__[name]
return property(getter, attr, deleter)
class Request(dict):
"""The parameters and information for an HTTP request, suitable for
authorizing with OAuth credentials.
When a consumer wants to access a service's protected resources, it does
so using a signed HTTP request identifying itself (the consumer) with its
key, and providing an access token authorized by the end user to access
those resources.
"""
version = VERSION
def __init__(self, method=HTTP_METHOD, url=None, parameters=None):
self.method = method
self.url = url
if parameters is not None:
self.update(parameters)
@setter
def url(self, value):
self.__dict__['url'] = value
if value is not None:
scheme, netloc, path, params, query, fragment = urlparse.urlparse(value)
# Exclude default port numbers.
if scheme == 'http' and netloc[-3:] == ':80':
netloc = netloc[:-3]
elif scheme == 'https' and netloc[-4:] == ':443':
netloc = netloc[:-4]
if scheme not in ('http', 'https'):
raise ValueError("Unsupported URL %s (%s)." % (value, scheme))
# Normalized URL excludes params, query, and fragment.
self.normalized_url = urlparse.urlunparse((scheme, netloc, path, None, None, None))
else:
self.normalized_url = None
self.__dict__['url'] = None
@setter
def method(self, value):
self.__dict__['method'] = value.upper()
def _get_timestamp_nonce(self):
return self['oauth_timestamp'], self['oauth_nonce']
def get_nonoauth_parameters(self):
"""Get any non-OAuth parameters."""
return dict([(k, v) for k, v in self.iteritems()
if not k.startswith('oauth_')])
def to_header(self, realm=''):
"""Serialize as a header for an HTTPAuth request."""
oauth_params = ((k, v) for k, v in self.items()
if k.startswith('oauth_'))
stringy_params = ((k, escape(str(v))) for k, v in oauth_params)
header_params = ('%s="%s"' % (k, v) for k, v in stringy_params)
params_header = ', '.join(header_params)
auth_header = 'OAuth realm="%s"' % realm
if params_header:
auth_header = "%s, %s" % (auth_header, params_header)
return {'Authorization': auth_header}
def to_postdata(self):
"""Serialize as post data for a POST request."""
# tell urlencode to deal with sequence values and map them correctly
# to resulting querystring. for example self["k"] = ["v1", "v2"] will
# result in 'k=v1&k=v2' and not k=%5B%27v1%27%2C+%27v2%27%5D
return urllib.urlencode(self, True)
def to_url(self):
"""Serialize as a URL for a GET request."""
base_url = urlparse.urlparse(self.url)
query = parse_qs(base_url.query)
for k, v in self.items():
query.setdefault(k, []).append(v)
url = (base_url.scheme, base_url.netloc, base_url.path, base_url.params,
urllib.urlencode(query, True), base_url.fragment)
return urlparse.urlunparse(url)
def get_parameter(self, parameter):
ret = self.get(parameter)
if ret is None:
raise Error('Parameter not found: %s' % parameter)
return ret
def get_normalized_parameters(self):
"""Return a string that contains the parameters that must be signed."""
items = []
for key, value in self.iteritems():
if key == 'oauth_signature':
continue
# 1.0a/9.1.1 states that kvp must be sorted by key, then by value,
# so we unpack sequence values into multiple items for sorting.
if hasattr(value, '__iter__'):
items.extend((key, item) for item in value)
else:
items.append((key, value))
# Include any query string parameters from the provided URL
query = urlparse.urlparse(self.url)[4]
items.extend(self._split_url_string(query).items())
encoded_str = urllib.urlencode(sorted(items))
# Encode signature parameters per Oauth Core 1.0 protocol
# spec draft 7, section 3.6
# (http://tools.ietf.org/html/draft-hammer-oauth-07#section-3.6)
# Spaces must be encoded with "%20" instead of "+"
return encoded_str.replace('+', '%20')
def sign_request(self, signature_method, consumer, token):
"""Set the signature parameter to the result of sign."""
if 'oauth_consumer_key' not in self:
self['oauth_consumer_key'] = consumer.key
if token and 'oauth_token' not in self:
self['oauth_token'] = token.key
self['oauth_signature_method'] = signature_method.name
self['oauth_signature'] = signature_method.sign(self, consumer, token)
@classmethod
def make_timestamp(cls):
"""Get seconds since epoch (UTC)."""
return str(int(time.time()))
@classmethod
def make_nonce(cls):
"""Generate pseudorandom number."""
return str(random.randint(0, 100000000))
@classmethod
def from_request(cls, http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers and 'Authorization' in headers:
auth_header = headers['Authorization']
# Check that the authorization header is OAuth.
if auth_header[:6] == 'OAuth ':
auth_header = auth_header[6:]
try:
# Get the parameters from the header.
header_params = cls._split_header(auth_header)
parameters.update(header_params)
except:
raise Error('Unable to parse OAuth parameters from '
'Authorization header.')
# GET or POST query string.
if query_string:
query_params = cls._split_url_string(query_string)
parameters.update(query_params)
# URL parameters.
param_str = urlparse.urlparse(http_url)[4] # query
url_params = cls._split_url_string(param_str)
parameters.update(url_params)
if parameters:
return cls(http_method, http_url, parameters)
return None
@classmethod
def from_consumer_and_token(cls, consumer, token=None,
http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
defaults = {
'oauth_consumer_key': consumer.key,
'oauth_timestamp': cls.make_timestamp(),
'oauth_nonce': cls.make_nonce(),
'oauth_version': cls.version,
}
defaults.update(parameters)
parameters = defaults
if token:
parameters['oauth_token'] = token.key
if token.verifier:
parameters['oauth_verifier'] = token.verifier
return Request(http_method, http_url, parameters)
@classmethod
def from_token_and_callback(cls, token, callback=None,
http_method=HTTP_METHOD, http_url=None, parameters=None):
if not parameters:
parameters = {}
parameters['oauth_token'] = token.key
if callback:
parameters['oauth_callback'] = callback
return cls(http_method, http_url, parameters)
@staticmethod
def _split_header(header):
"""Turn Authorization: header into parameters."""
params = {}
parts = header.split(',')
for param in parts:
# Ignore realm parameter.
if param.find('realm') > -1:
continue
# Remove whitespace.
param = param.strip()
# Split key-value.
param_parts = param.split('=', 1)
# Remove quotes and unescape the value.
params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"'))
return params
@staticmethod
def _split_url_string(param_str):
"""Turn URL string into parameters."""
parameters = parse_qs(param_str, keep_blank_values=False)
for k, v in parameters.iteritems():
parameters[k] = urllib.unquote(v[0])
return parameters
class Client(httplib2.Http):
"""OAuthClient is a worker to attempt to execute a request."""
def __init__(self, consumer, token=None, cache=None, timeout=None,
proxy_info=None):
if consumer is not None and not isinstance(consumer, Consumer):
raise ValueError("Invalid consumer.")
if token is not None and not isinstance(token, Token):
raise ValueError("Invalid token.")
self.consumer = consumer
self.token = token
self.method = SignatureMethod_HMAC_SHA1()
httplib2.Http.__init__(self, cache=cache, timeout=timeout,
proxy_info=proxy_info)
def set_signature_method(self, method):
if not isinstance(method, SignatureMethod):
raise ValueError("Invalid signature method.")
self.method = method
def request(self, uri, method="GET", body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None):
DEFAULT_CONTENT_TYPE = 'application/x-www-form-urlencoded'
if not isinstance(headers, dict):
headers = {}
is_multipart = method == 'POST' and headers.get('Content-Type',
DEFAULT_CONTENT_TYPE) != DEFAULT_CONTENT_TYPE
if body and method == "POST" and not is_multipart:
parameters = dict(parse_qsl(body))
else:
parameters = None
req = Request.from_consumer_and_token(self.consumer,
token=self.token, http_method=method, http_url=uri,
parameters=parameters)
req.sign_request(self.method, self.consumer, self.token)
if method == "POST":
headers['Content-Type'] = headers.get('Content-Type',
DEFAULT_CONTENT_TYPE)
if is_multipart:
headers.update(req.to_header())
else:
body = req.to_postdata()
elif method == "GET":
uri = req.to_url()
else:
headers.update(req.to_header())
return httplib2.Http.request(self, uri, method=method, body=body,
headers=headers, redirections=redirections,
connection_type=connection_type)
class Server(object):
"""A skeletal implementation of a service provider, providing protected
resources to requests from authorized consumers.
This class implements the logic to check requests for authorization. You
can use it with your web server or web framework to protect certain
resources with OAuth.
"""
timestamp_threshold = 300 # In seconds, five minutes.
version = VERSION
signature_methods = None
def __init__(self, signature_methods=None):
self.signature_methods = signature_methods or {}
def add_signature_method(self, signature_method):
self.signature_methods[signature_method.name] = signature_method
return self.signature_methods
def verify_request(self, request, consumer, token):
"""Verifies an api call and checks all the parameters."""
version = self._get_version(request)
self._check_signature(request, consumer, token)
parameters = request.get_nonoauth_parameters()
return parameters
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
def _get_version(self, request):
"""Verify the correct version request for this server."""
try:
version = request.get_parameter('oauth_version')
except:
version = VERSION
if version and version != self.version:
raise Error('OAuth version %s not supported.' % str(version))
return version
def _get_signature_method(self, request):
"""Figure out the signature with some defaults."""
try:
signature_method = request.get_parameter('oauth_signature_method')
except:
signature_method = SIGNATURE_METHOD
try:
# Get the signature method object.
signature_method = self.signature_methods[signature_method]
except:
signature_method_names = ', '.join(self.signature_methods.keys())
raise Error('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names))
return signature_method
def _get_verifier(self, request):
return request.get_parameter('oauth_verifier')
def _check_signature(self, request, consumer, token):
timestamp, nonce = request._get_timestamp_nonce()
self._check_timestamp(timestamp)
signature_method = self._get_signature_method(request)
try:
signature = request.get_parameter('oauth_signature')
except:
raise MissingSignature('Missing oauth_signature.')
# Validate the signature.
valid = signature_method.check(request, consumer, token, signature)
if not valid:
key, base = signature_method.signing_base(request, consumer, token)
raise Error('Invalid signature. Expected signature base '
'string: %s' % base)
built = signature_method.sign(request, consumer, token)
def _check_timestamp(self, timestamp):
"""Verify that timestamp is recentish."""
timestamp = int(timestamp)
now = int(time.time())
lapsed = now - timestamp
if lapsed > self.timestamp_threshold:
raise Error('Expired timestamp: given %d and now %s has a '
'greater difference than threshold %d' % (timestamp, now,
self.timestamp_threshold))
class SignatureMethod(object):
"""A way of signing requests.
The OAuth protocol lets consumers and service providers pick a way to sign
requests. This interface shows the methods expected by the other `oauth`
modules for signing requests. Subclass it and implement its methods to
provide a new way to sign requests.
"""
def signing_base(self, request, consumer, token):
"""Calculates the string that needs to be signed.
This method returns a 2-tuple containing the starting key for the
signing and the message to be signed. The latter may be used in error
messages to help clients debug their software.
"""
raise NotImplementedError
def sign(self, request, consumer, token):
"""Returns the signature for the given request, based on the consumer
and token also provided.
You should use your implementation of `signing_base()` to build the
message to sign. Otherwise it may be less useful for debugging.
"""
raise NotImplementedError
def check(self, request, consumer, token, signature):
"""Returns whether the given signature is the correct signature for
the given consumer and token signing the given request."""
built = self.sign(request, consumer, token)
return built == signature
class SignatureMethod_HMAC_SHA1(SignatureMethod):
name = 'HMAC-SHA1'
def signing_base(self, request, consumer, token):
if request.normalized_url is None:
raise ValueError("Base URL for request is not set.")
sig = (
escape(request.method),
escape(request.normalized_url),
escape(request.get_normalized_parameters()),
)
key = '%s&' % escape(consumer.secret)
if token:
key += escape(token.secret)
raw = '&'.join(sig)
return key, raw
def sign(self, request, consumer, token):
"""Builds the base signature string."""
key, raw = self.signing_base(request, consumer, token)
# HMAC object.
try:
from hashlib import sha1 as sha
except ImportError:
import sha # Deprecated
hashed = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
class SignatureMethod_PLAINTEXT(SignatureMethod):
name = 'PLAINTEXT'
def signing_base(self, request, consumer, token):
"""Concatenates the consumer key and secret with the token's
secret."""
sig = '%s&' % escape(consumer.secret)
if token:
sig = sig + escape(token.secret)
return sig, sig
def sign(self, request, consumer, token):
key, raw = self.signing_base(request, consumer, token)
return raw
| mit | -5,290,430,773,135,147,000 | 32.884354 | 134 | 0.617105 | false |
zofuthan/airmozilla | airmozilla/main/context_processors.py | 5 | 11943 | import datetime
from django.conf import settings
from django.db.models import Q
from django.utils import timezone
from django.core.cache import cache
from funfactory.urlresolvers import reverse
from airmozilla.main.models import (
Event,
Channel,
EventHitStats,
most_recent_event
)
from airmozilla.main.views import is_contributor
from airmozilla.search.forms import SearchForm
from airmozilla.staticpages.models import StaticPage
def nav_bar(request):
def get_nav_bar():
items = [
('Home', reverse('main:home'), 'home', ''),
('About', '/about/', 'about', ''),
('Channels', reverse('main:channels'), 'channels', ''),
('Calendar', reverse('main:calendar'), 'calendar', ''),
]
if not request.user.is_staff:
items.append(
('Tag Cloud', reverse('main:tag_cloud'), 'tag_cloud', '')
)
items.append(
('Starred', reverse('starred:home'), 'starred', '')
)
unfinished_events = 0
if request.user.is_active:
unfinished_events = Event.objects.filter(
creator=request.user,
status=Event.STATUS_INITIATED,
upload__isnull=False,
).count()
if settings.USE_NEW_UPLOADER:
items.append(
('New/Upload', reverse('new:home'), 'new', ''),
)
else:
items.append(
('Requests', reverse('suggest:start'), 'suggest', ''),
)
if request.user.is_staff:
items.append(
('Management', reverse('manage:events'), '', ''),
)
if not settings.BROWSERID_DISABLED:
items.append(
('Sign out', '/browserid/logout/', '', 'browserid-logout'),
)
return {'items': items, 'unfinished_events': unfinished_events}
# The reason for making this a closure is because this stuff is not
# needed on every single template render. Only the main pages where
# there is a nav bar at all.
return {'nav_bar': get_nav_bar}
def dev(request):
return {
'DEV': settings.DEV,
'DEBUG': settings.DEBUG,
'BROWSERID_DISABLED': settings.BROWSERID_DISABLED,
}
def search_form(request):
return {'search_form': SearchForm(request.GET)}
def base(request):
def get_feed_data():
feed_privacy = _get_feed_privacy(request.user)
if getattr(request, 'channels', None):
channels = request.channels
else:
channels = Channel.objects.filter(
slug=settings.DEFAULT_CHANNEL_SLUG
)
if settings.DEFAULT_CHANNEL_SLUG in [x.slug for x in channels]:
title = 'Air Mozilla RSS'
url = reverse('main:feed', args=(feed_privacy,))
else:
_channel = channels[0]
title = 'Air Mozilla - %s - RSS' % _channel.name
url = reverse(
'main:channel_feed',
args=(_channel.slug, feed_privacy)
)
return {
'title': title,
'url': url,
}
return {
# used for things like {% if event.attr == Event.ATTR1 %}
'Event': Event,
'get_feed_data': get_feed_data,
}
def sidebar(request):
# none of this is relevant if you're in certain URLs
def get_sidebar():
data = {}
if not getattr(request, 'show_sidebar', True):
return data
# if viewing a specific page is limited by channel, apply that
# filtering here too
if getattr(request, 'channels', None):
channels = request.channels
else:
channels = Channel.objects.filter(
slug=settings.DEFAULT_CHANNEL_SLUG
)
if settings.DEFAULT_CHANNEL_SLUG in [x.slug for x in channels]:
sidebar_channel = settings.DEFAULT_CHANNEL_SLUG
else:
_channel = channels[0]
sidebar_channel = _channel.slug
data['upcoming'] = get_upcoming_events(channels, request.user)
data['featured'] = get_featured_events(channels, request.user)
data['sidebar_top'] = None
data['sidebar_bottom'] = None
sidebar_urls_q = (
Q(url='sidebar_top_%s' % sidebar_channel) |
Q(url='sidebar_bottom_%s' % sidebar_channel) |
Q(url='sidebar_top_*') |
Q(url='sidebar_bottom_*')
)
# to avoid having to do 2 queries, make a combined one
# set it up with an iterator
for page in StaticPage.objects.filter(sidebar_urls_q):
if page.url.startswith('sidebar_top_'):
data['sidebar_top'] = page
elif page.url.startswith('sidebar_bottom_'):
data['sidebar_bottom'] = page
return data
# Make this context processor return a closure so it's explicit
# from the template if you need its data.
return {'get_sidebar': get_sidebar}
def get_upcoming_events(channels, user,
length=settings.UPCOMING_SIDEBAR_COUNT):
"""return a queryset of upcoming events"""
anonymous = True
contributor = False
if user.is_active:
anonymous = False
if is_contributor(user):
contributor = True
cache_key = 'upcoming_events_%s_%s' % (int(anonymous), int(contributor))
cache_key += ','.join(str(x.id) for x in channels)
event = most_recent_event()
if event:
cache_key += str(event.modified.microsecond)
upcoming = cache.get(cache_key)
if upcoming is None:
upcoming = _get_upcoming_events(channels, anonymous, contributor)
upcoming = upcoming[:length]
cache.set(cache_key, upcoming, 60 * 60)
return upcoming
def _get_upcoming_events(channels, anonymous, contributor):
"""do the heavy lifting of getting the featured events"""
upcoming = Event.objects.upcoming().order_by('start_time')
upcoming = upcoming.filter(channels__in=channels).distinct()
upcoming = upcoming.select_related('picture')
if anonymous:
upcoming = upcoming.exclude(privacy=Event.PRIVACY_COMPANY)
elif contributor:
upcoming = upcoming.filter(privacy=Event.PRIVACY_PUBLIC)
return upcoming
def get_featured_events(
channels,
user,
length=settings.FEATURED_SIDEBAR_COUNT
):
"""return a list of events that are sorted by their score"""
anonymous = True
contributor = False
if user.is_active:
anonymous = False
if is_contributor(user):
contributor = True
cache_key = 'featured_events_%s_%s' % (int(anonymous), int(contributor))
if channels:
cache_key += ','.join(str(x.id) for x in channels)
event = most_recent_event()
if event:
cache_key += str(event.modified.microsecond)
featured = cache.get(cache_key)
if featured is None:
featured = _get_featured_events(channels, anonymous, contributor)
featured = featured[:length]
cache.set(cache_key, featured, 60 * 60)
# Sadly, in Django when you do a left outer join on a many-to-many
# table you get repeats and you can't fix that by adding a simple
# `distinct` on the first field.
# In django, if you do `myqueryset.distinct('id')` it requires
# that that's also something you order by.
# In pure Postgresql you can do this:
# SELECT
# DISTINCT main_eventhitstats.id as id,
# (some formula) AS score,
# ...
# FROM ...
# INNER JOIN ...
# INNER JOIN ...
# ORDER BY score DESC
# LIMIT 5;
#
# But you can't do that with Django.
# So we have to manually de-dupe. Hopefully we can alleviate this
# problem altogether when we start doing aggregates where you have
# many repeated EventHitStats *per* event and you need to look at
# their total score across multiple vidly shortcodes.
events = []
for each in featured:
if each.event not in events:
events.append(each.event)
return events
def _get_featured_events(channels, anonymous, contributor):
"""do the heavy lifting of getting the featured events"""
now = timezone.now()
yesterday = now - datetime.timedelta(days=1)
# subtract one second to not accidentally tip it
yesterday -= datetime.timedelta(seconds=1)
featured = (
EventHitStats.objects
.exclude(event__archive_time__isnull=True)
.filter(event__archive_time__lt=yesterday)
.exclude(event__channels__exclude_from_trending=True)
.extra(
select={
# being 'featured' pretends the event has twice as
# many hits as actually does
'score': '(featured::int + 1) * total_hits'
'/ extract(days from (now() - archive_time)) ^ 1.8',
}
)
.select_related('event')
.order_by('-score')
)
if channels:
featured = featured.filter(event__channels__in=channels)
if anonymous:
featured = featured.filter(event__privacy=Event.PRIVACY_PUBLIC)
elif contributor:
featured = featured.exclude(event__privacy=Event.PRIVACY_COMPANY)
featured = featured.select_related('event__picture')
return featured
def analytics(request):
# unless specified, the analytics is include if DEBUG = False
if request.path_info.startswith('/manage/'):
include = False
else:
include = getattr(
settings,
'INCLUDE_ANALYTICS',
not settings.DEBUG
)
return {'include_analytics': include}
def _get_feed_privacy(user):
"""return 'public', 'contributors' or 'company' depending on the user
profile.
Because this is used very frequently and because it's expensive to
pull out the entire user profile every time, we use cache to remember
if the user is a contributor or not (applicable only if logged in)
"""
if user.is_active:
if is_contributor(user):
return 'contributors'
return 'company'
return 'public'
def browserid(request):
# by making this a function, it means we only need to run this
# when ``redirect_next()`` is called
def redirect_next():
next = request.GET.get('next')
if next:
if '://' in next:
return reverse('main:home')
return next
url = request.META['PATH_INFO']
if url in (reverse('main:login'), reverse('main:login_failure')):
# can't have that!
url = reverse('main:home')
return url
return {'redirect_next': redirect_next}
def faux_i18n(request):
"""We don't do I18N but we also don't want to necessarily delete
all the hard work on using `_('English')` in templates because
maybe one day we'll start doing I18N and then it might be good
to keep these annotations in the templates."""
def _(*args, **kwargs):
return args[0]
return {'_': _}
def autocompeter(request):
"""We need to tell the Autocompeter service which groups the current
user should be able to view."""
key = getattr(settings, 'AUTOCOMPETER_KEY', None)
if not key:
return {}
groups = []
if request.user and request.user.is_active:
groups.append(Event.PRIVACY_CONTRIBUTORS)
if not is_contributor(request.user):
groups.append(Event.PRIVACY_COMPANY)
url = getattr(settings, 'AUTOCOMPETER_URL', '')
domain = getattr(settings, 'AUTOCOMPETER_DOMAIN', '')
enabled = getattr(settings, 'AUTOCOMPETER_ENABLED', True)
return {
'include_autocompeter': enabled,
'autocompeter_domain': domain,
'autocompeter_groups': ','.join(groups),
'autocompeter_url': url,
}
| bsd-3-clause | 3,431,418,118,143,389,700 | 31.991713 | 79 | 0.59449 | false |
Distrotech/libreoffice | testtools/source/bridgetest/pyuno/core.py | 7 | 17619 | #
# This file is part of the LibreOffice project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# This file incorporates work covered by the following license notice:
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed
# with this work for additional information regarding copyright
# ownership. The ASF licenses this file to you under the Apache
# License, Version 2.0 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0 .
#
import pyuno
import uno
import unittest
import exceptions
import types
def suite(ctx):
suite = unittest.TestSuite()
suite.addTest(TestCase("testErrors",ctx))
suite.addTest(TestCase("testBaseTypes",ctx))
suite.addTest(TestCase("testOutparam",ctx))
suite.addTest(TestCase("testStruct",ctx))
suite.addTest(TestCase("testType",ctx))
suite.addTest(TestCase("testEnum",ctx))
suite.addTest(TestCase("testBool",ctx))
suite.addTest(TestCase("testChar",ctx))
suite.addTest(TestCase("testUnicode",ctx))
suite.addTest(TestCase("testConstant",ctx))
suite.addTest(TestCase("testExceptions",ctx))
suite.addTest(TestCase("testInterface",ctx))
suite.addTest(TestCase("testByteSequence",ctx))
suite.addTest(TestCase("testInvoke",ctx))
return suite
def equalsEps( a,b,eps ):
if a - eps <= b and a+eps >= b:
return 1
return 0
def assign( rData, bBool, cChar, nByte, nShort, nUShort, nLong, nULong, nHyper,\
nUHyper, fFloat, fDouble, eEnum, rStr, xTest, rAny ):
rData.Bool = bBool;
rData.Char = cChar;
rData.Byte = nByte;
rData.Short = nShort;
rData.UShort = nUShort;
rData.Long = nLong;
rData.ULong = nULong;
rData.Hyper = nHyper;
rData.UHyper = nUHyper;
rData.Float = fFloat;
rData.Double = fDouble;
rData.Enum = eEnum;
rData.String = rStr;
rData.Interface = xTest;
rData.Any = rAny;
class PythonTransporter:
def __init__( self ):
pass
def transportAny( self, arg ):
return arg
class TestCase( unittest.TestCase):
def __init__(self,method,ctx):
unittest.TestCase.__init__(self,method)
self.ctx = ctx
def setUp(self):
# the testcomponent from the testtools project
self.tobj = self.ctx.ServiceManager.createInstanceWithContext(
'com.sun.star.test.bridge.CppTestObject' , self.ctx )
self.tobj.Bool = 1
self.tobj.Char = 'h'
self.tobj.Byte = 43
self.tobj.Short = -42
self.tobj.UShort = 44
self.tobj.Long = 42
self.tobj.ULong = 41
self.tobj.Hyper = 46
self.tobj.UHyper = 47
self.tobj.Float = 4.3
self.tobj.Double = 4.2
self.tobj.Enum = 4
self.tobj.String = "yabadabadoo"
self.tobj.Interface = self.ctx
self.tobj.Any = self.tobj.String
mystruct = uno.createUnoStruct( "test.testtools.bridgetest.TestData" )
assign( mystruct, 1, 'h', 43, -42,44,42,41,46,47,4.3,4.2,4,"yabadabadoo",self.ctx,"yabadabadoo")
self.tobj.Struct = mystruct
self.testElement = uno.createUnoStruct( "test.testtools.bridgetest.TestElement" )
self.testElement.String = "foo"
self.testElement2 = uno.createUnoStruct( "test.testtools.bridgetest.TestElement" )
self.testElement2.String = "42"
self.tobj.Sequence = (self.testElement,self.testElement2)
def testBaseTypes(self):
self.failUnless( 42 == self.tobj.Long , "Long attribute" )
self.failUnless( 41 == self.tobj.ULong , "ULong attribute" )
self.failUnless( 43 == self.tobj.Byte , "Byte attribute" )
self.failUnless( 44 == self.tobj.UShort , "UShort attribute" )
self.failUnless( -42 == self.tobj.Short , "Short attribute" )
self.failUnless( 46 == self.tobj.Hyper , "Hyper attribute" )
self.failUnless( 47 == self.tobj.UHyper , "UHyper attribute" )
self.failUnless( self.tobj.Bool , "Bool attribute2" )
self.failUnless( "yabadabadoo" == self.tobj.String , "String attribute" )
self.failUnless( self.tobj.Sequence[0] == self.testElement , "Sequence test")
self.failUnless( self.tobj.Sequence[1] == self.testElement2 , "Sequence2 test")
self.failUnless( equalsEps( 4.3,self.tobj.Float,0.0001) , "float test" )
self.failUnless( 4.2 == self.tobj.Double , "double test" )
self.failUnless( self.ctx == self.tobj.Interface ,
"object identity test with C++ object" )
self.failUnless( not self.ctx == self.tobj , "object not identical test " )
self.failUnless( 42 == self.tobj.transportAny( 42 ), "transportAny long" )
self.failUnless( "woo, this is python" == self.tobj.transportAny( "woo, this is python" ), \
"string roundtrip via any test" )
def testEnum( self ):
e1 = uno.Enum( "com.sun.star.uno.TypeClass" , "LONG" )
e2 = uno.Enum( "com.sun.star.uno.TypeClass" , "LONG" )
e3 = uno.Enum( "com.sun.star.uno.TypeClass" , "UNSIGNED_LONG" )
e4 = uno.Enum( "test.testtools.bridgetest.TestEnum" , "TWO" )
self.failUnless( e1 == e2 , "equal enum test" )
self.failUnless( not (e1 == e3) , "different enums test" )
self.failUnless( self.tobj.transportAny( e3 ) == e3, "enum roundtrip test" )
self.tobj.Enum = e4
self.failUnless( e4 == self.tobj.Enum , "enum assignment failed" )
def testType(self ):
t1 = uno.getTypeByName( "com.sun.star.lang.XComponent" )
t2 = uno.getTypeByName( "com.sun.star.lang.XComponent" )
t3 = uno.getTypeByName( "com.sun.star.lang.EventObject" )
self.failUnless( t1.typeClass == \
uno.Enum( "com.sun.star.uno.TypeClass", "INTERFACE" ), "typeclass of type test" )
self.failUnless( t3.typeClass == \
uno.Enum( "com.sun.star.uno.TypeClass", "STRUCT" ), "typeclass of type test")
self.failUnless( t1 == t2 , "equal type test" )
self.failUnless( t1 == t2 , "equal type test" )
self.failUnless( t1 == self.tobj.transportAny( t1 ), "type rountrip test" )
def testBool( self ):
self.failUnless( uno.Bool(1) , "uno.Bool true test" )
self.failUnless( not uno.Bool(0) , "uno.Bool false test" )
self.failUnless( uno.Bool( "true") , "uno.Bool true1 test" )
self.failUnless( not uno.Bool( "false") , "uno.Bool true1 test" )
self.tobj.Bool = uno.Bool(1)
self.failUnless( self.tobj.Bool , "bool true attribute test" )
self.tobj.Bool = uno.Bool(0)
self.failUnless( not self.tobj.Bool , "bool true attribute test" )
# new boolean semantic
self.failUnless( id( self.tobj.transportAny( True ) ) == id(True) , "boolean preserve test")
self.failUnless( id( self.tobj.transportAny( False ) ) == id(False) , "boolean preserve test" )
self.failUnless( id( self.tobj.transportAny(1) ) != id( True ), "boolean preserve test" )
self.failUnless( id( self.tobj.transportAny(0) ) != id( False ), "boolean preserve test" )
def testChar( self ):
self.tobj.Char = uno.Char( u'h' )
self.failUnless( self.tobj.Char == uno.Char( u'h' ), "char type test" )
self.failUnless( isinstance( self.tobj.transportAny( uno.Char(u'h') ),uno.Char),"char preserve test" )
def testStruct( self ):
mystruct = uno.createUnoStruct( "test.testtools.bridgetest.TestData" )
assign( mystruct, 1, 'h', 43, -42,44,42,41,46,47,4.3,4.2,4,"yabadabadoo",self.ctx,"yabadabadoo")
self.tobj.Struct = mystruct
aSecondStruct = self.tobj.Struct
self.failUnless( self.tobj.Struct == mystruct, "struct roundtrip for equality test" )
self.failUnless( aSecondStruct == mystruct, "struct roundtrip for equality test2" )
aSecondStruct.Short = 720
self.failUnless( not aSecondStruct == mystruct , "different structs equality test" )
self.failUnless( not self.ctx == mystruct , "object is not equal to struct test" )
self.failUnless( mystruct == self.tobj.transportAny( mystruct ), "struct roundtrip with any test" )
my2ndstruct = uno.createUnoStruct( "test.testtools.bridgetest.TestData", \
1, 'h', 43, -42,44,42,41,46,47,4.3,4.2,4,"yabadabadoo",self.ctx,"yabadabadoo",())
self.failUnless( my2ndstruct == mystruct, "struct non-default ctor test" )
def testUnicode( self ):
uni = u'\0148'
self.tobj.String = uni
self.failUnless( uni == self.tobj.String )
self.tobj.String = u'dubidu'
self.failUnless( u'dubidu' == self.tobj.String , "unicode comparison test")
self.failUnless( 'dubidu' == self.tobj.String , "unicode vs. string comparison test" )
def testConstant( self ):
self.failUnless( uno.getConstantByName( "com.sun.star.beans.PropertyConcept.ATTRIBUTES" ) == 4,\
"constant retrieval test" )
def testExceptions( self ):
unoExc = uno.getClass( "com.sun.star.uno.Exception" )
ioExc = uno.getClass( "com.sun.star.io.IOException" )
dispExc = uno.getClass( "com.sun.star.lang.DisposedException" )
wasHere = 0
try:
raise ioExc( "huhuh" , self.tobj )
except unoExc , instance:
wasHere = 1
self.failUnless( wasHere , "exceptiont test 1" )
wasHere = 0
try:
raise ioExc
except ioExc:
wasHere = 1
else:
self.failUnless( wasHere, "exception test 2" )
wasHere = 0
try:
raise dispExc
except ioExc:
pass
except unoExc:
wasHere = 1
self.failUnless(wasHere, "exception test 3")
illegalArg = uno.getClass( "com.sun.star.lang.IllegalArgumentException" )
wasHere = 0
try:
self.tobj.raiseException( 1 , "foo" , self.tobj )
self.failUnless( 0 , "exception test 5a" )
except ioExc:
self.failUnless( 0 , "exception test 5b" )
except illegalArg, i:
self.failUnless( 1 == i.ArgumentPosition , "exception member test" )
self.failUnless( "foo" == i.Message , "exception member test 2 " )
wasHere = 1
else:
self.failUnless( 0, "except test 5c" )
self.failUnless( wasHere, "illegal argument exception test failed" )
def testInterface(self):
clazz = uno.getClass( "com.sun.star.lang.XComponent" )
self.failUnless( "com.sun.star.lang.XComponent" == clazz.__pyunointerface__ )
self.failUnless( issubclass( clazz, uno.getClass( "com.sun.star.uno.XInterface" ) ) )
self.tobj.Interface = None
def testOutparam( self):
# outparameter
struct, mybool,mychar,mybyte,myshort,myushort,mylong,myulong,myhyper,myuhyper,myfloat, \
mydouble,myenum,mystring,myinterface,myany,myseq,my2ndstruct = self.tobj.getValues( \
None,None,None,None,None,None,None,None,None,None, \
None,None,None,None,None,None,None)
self.failUnless(struct == self.tobj.Struct, "outparam 1 test")
self.failUnless(self.tobj.Bool, "outparam 2 test")
self.failUnless(mychar == self.tobj.Char, "outparam 3 test")
self.failUnless(mybyte == self.tobj.Byte, "outparam 4 test")
self.failUnless(myshort == self.tobj.Short, "outparam 5 test")
self.failUnless(myushort == self.tobj.UShort, "outparam 6 test")
self.failUnless(mylong == self.tobj.Long, "outparam 7 test")
self.failUnless(myulong == self.tobj.ULong, "outparam 8 test")
self.failUnless(myhyper == self.tobj.Hyper, "outparam 9 test")
self.failUnless(myuhyper == self.tobj.UHyper, "outparam 10 test")
self.failUnless(myfloat == self.tobj.Float, "outparam 11 test")
self.failUnless(mydouble == self.tobj.Double, "outparam 12 test")
self.failUnless(myenum == self.tobj.Enum, "outparam 13 test")
self.failUnless(mystring == self.tobj.String, "outparam 14 test")
self.failUnless(myinterface == self.tobj.Interface, "outparam 15 test")
self.failUnless(myany == self.tobj.Any, "outparam 16 test")
self.failUnless(myseq == self.tobj.Sequence, "outparam 17 test")
self.failUnless(my2ndstruct == struct, "outparam 18 test")
# should work, debug on windows, why not
# struct, mybool,mychar,mybyte,myshort,myushort,mylong,myulong,myhyper,myuhyper,myfloat,\
# mydouble,myenum,mystring,myinterface,myany,myseq,my2ndstruct = self.tobj.setValues2( \
# mybool,mychar,mybyte,myshort,myushort,mylong,myulong,myhyper,myuhyper,myfloat,\
# mydouble,myenum,mystring,myinterface,myany,myseq,my2ndstruct)
# self.failUnless(struct == self.tobj.Struct, "outparam 1 test")
# self.failUnless( mybool and self.tobj.Bool, "outparam 2 test")
# self.failUnless(mychar == self.tobj.Char, "outparam 3 test")
# self.failUnless(mybyte == self.tobj.Byte, "outparam 4 test")
# self.failUnless(myshort == self.tobj.Short, "outparam 5 test")
# self.failUnless(myushort == self.tobj.UShort, "outparam 6 test")
# self.failUnless(mylong == self.tobj.Long, "outparam 7 test")
# self.failUnless(myulong == self.tobj.ULong, "outparam 8 test")
# self.failUnless(myhyper == self.tobj.Hyper, "outparam 9 test")
# self.failUnless(myuhyper == self.tobj.UHyper, "outparam 10 test")
# self.failUnless(myfloat == self.tobj.Float, "outparam 11 test")
# self.failUnless(mydouble == self.tobj.Double, "outparam 12 test")
# self.failUnless(myenum == self.tobj.Enum, "outparam 13 test")
# self.failUnless(mystring == self.tobj.String, "outparam 14 test")
# self.failUnless(myinterface == self.tobj.Interface, "outparam 15 test")
# self.failUnless(myany == self.tobj.Any, "outparam 16 test")
# self.failUnless(myseq == self.tobj.Sequence, "outparam 17 test")
# self.failUnless(my2ndstruct == struct, "outparam 18 test")
def testErrors( self ):
wasHere = 0
try:
self.tobj.a = 5
self.fail("attribute a shouldn't exist")
except AttributeError:
wasHere = 1
except IllegalArgumentException:
wasHere = 1
self.failUnless( wasHere, "wrong attribute test" )
IllegalArgumentException = uno.getClass("com.sun.star.lang.IllegalArgumentException" )
RuntimeException = uno.getClass("com.sun.star.uno.RuntimeException" )
# TODO: Remove this once it is done
# wrong number of arguments bug !?
self.failUnlessRaises( IllegalArgumentException, self.tobj.transportAny, 42, 43 )
self.failUnlessRaises( IllegalArgumentException, self.tobj.transportAny )
self.failUnlessRaises( RuntimeException, uno.getClass, "a.b" )
self.failUnlessRaises( RuntimeException, uno.getClass, "com.sun.star.uno.TypeClass" )
self.failUnlessRaises( RuntimeException, uno.Enum, "a" , "b" )
self.failUnlessRaises( RuntimeException, uno.Enum, "com.sun.star.uno.TypeClass" , "b" )
self.failUnlessRaises( RuntimeException, uno.Enum, "com.sun.star.uno.XInterface" , "b" )
tcInterface =uno.Enum( "com.sun.star.uno.TypeClass" , "INTERFACE" )
self.failUnlessRaises( RuntimeException, uno.Type, "a", tcInterface )
self.failUnlessRaises( RuntimeException, uno.Type, "com.sun.star.uno.Exception", tcInterface )
self.failUnlessRaises( (RuntimeException,exceptions.RuntimeError), uno.getTypeByName, "a" )
self.failUnlessRaises( (RuntimeException), uno.getConstantByName, "a" )
self.failUnlessRaises( (RuntimeException), uno.getConstantByName, "com.sun.star.uno.XInterface" )
def testByteSequence( self ):
s = uno.ByteSequence( "ab" )
self.failUnless( s == uno.ByteSequence( "ab" ) )
self.failUnless( uno.ByteSequence( "abc" ) == s + uno.ByteSequence( "c" ) )
self.failUnless( uno.ByteSequence( "abc" ) == s + "c" )
self.failUnless( s + "c" == "abc" )
self.failUnless( s == uno.ByteSequence( s ) )
self.failUnless( s[0] == 'a' )
self.failUnless( s[1] == 'b' )
def testInvoke( self ):
self.failUnless( 5 == uno.invoke( self.tobj , "transportAny" , (uno.Any("byte", 5),) ) )
self.failUnless( 5 == uno.invoke(
PythonTransporter(), "transportAny" , (uno.Any( "byte", 5 ),) ) )
t = uno.getTypeByName( "long" )
mystruct = uno.createUnoStruct(
"com.sun.star.beans.PropertyValue", "foo",0,uno.Any(t,2),0 )
mystruct.Value = uno.Any(t, 1)
| gpl-3.0 | -6,889,867,776,256,954,000 | 48.215084 | 118 | 0.615131 | false |
neerja28/Tempest | tempest/api/compute/volumes/test_volumes_get.py | 5 | 3024 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest_lib.common.utils import data_utils
from testtools import matchers
from tempest.api.compute import base
from tempest import config
from tempest import test
CONF = config.CONF
class VolumesGetTestJSON(base.BaseV2ComputeTest):
@classmethod
def skip_checks(cls):
super(VolumesGetTestJSON, cls).skip_checks()
if not CONF.service_available.cinder:
skip_msg = ("%s skipped as Cinder is not available" % cls.__name__)
raise cls.skipException(skip_msg)
@classmethod
def setup_clients(cls):
super(VolumesGetTestJSON, cls).setup_clients()
cls.client = cls.volumes_extensions_client
@test.idempotent_id('f10f25eb-9775-4d9d-9cbe-1cf54dae9d5f')
def test_volume_create_get_delete(self):
# CREATE, GET, DELETE Volume
volume = None
v_name = data_utils.rand_name('Volume')
metadata = {'Type': 'work'}
# Create volume
volume = self.client.create_volume(display_name=v_name,
metadata=metadata)
self.addCleanup(self.delete_volume, volume['id'])
self.assertIn('id', volume)
self.assertIn('displayName', volume)
self.assertEqual(volume['displayName'], v_name,
"The created volume name is not equal "
"to the requested name")
self.assertTrue(volume['id'] is not None,
"Field volume id is empty or not found.")
# Wait for Volume status to become ACTIVE
self.client.wait_for_volume_status(volume['id'], 'available')
# GET Volume
fetched_volume = self.client.get_volume(volume['id'])
# Verification of details of fetched Volume
self.assertEqual(v_name,
fetched_volume['displayName'],
'The fetched Volume is different '
'from the created Volume')
self.assertEqual(volume['id'],
fetched_volume['id'],
'The fetched Volume is different '
'from the created Volume')
self.assertThat(fetched_volume['metadata'].items(),
matchers.ContainsAll(metadata.items()),
'The fetched Volume metadata misses data '
'from the created Volume')
| apache-2.0 | 8,277,674,554,553,515,000 | 39.864865 | 79 | 0.614749 | false |
sssllliang/silverberry | lib/google/protobuf/internal/descriptor_pool_test.py | 19 | 35436 | #! /usr/bin/env python
#
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# 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.
"""Tests for google.protobuf.descriptor_pool."""
__author__ = '[email protected] (Matt Toia)'
import os
import sys
try:
import unittest2 as unittest #PY26
except ImportError:
import unittest
from google.protobuf import unittest_import_pb2
from google.protobuf import unittest_import_public_pb2
from google.protobuf import unittest_pb2
from google.protobuf import descriptor_pb2
from google.protobuf.internal import api_implementation
from google.protobuf.internal import descriptor_pool_test1_pb2
from google.protobuf.internal import descriptor_pool_test2_pb2
from google.protobuf.internal import factory_test1_pb2
from google.protobuf.internal import factory_test2_pb2
from google.protobuf.internal import file_options_test_pb2
from google.protobuf.internal import more_messages_pb2
from google.protobuf import descriptor
from google.protobuf import descriptor_database
from google.protobuf import descriptor_pool
from google.protobuf import message_factory
from google.protobuf import symbol_database
class DescriptorPoolTest(unittest.TestCase):
def setUp(self):
self.pool = descriptor_pool.DescriptorPool()
self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test1_pb2.DESCRIPTOR.serialized_pb)
self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test2_pb2.DESCRIPTOR.serialized_pb)
self.pool.Add(self.factory_test1_fd)
self.pool.Add(self.factory_test2_fd)
def testFindFileByName(self):
name1 = 'google/protobuf/internal/factory_test1.proto'
file_desc1 = self.pool.FindFileByName(name1)
self.assertIsInstance(file_desc1, descriptor.FileDescriptor)
self.assertEqual(name1, file_desc1.name)
self.assertEqual('google.protobuf.python.internal', file_desc1.package)
self.assertIn('Factory1Message', file_desc1.message_types_by_name)
name2 = 'google/protobuf/internal/factory_test2.proto'
file_desc2 = self.pool.FindFileByName(name2)
self.assertIsInstance(file_desc2, descriptor.FileDescriptor)
self.assertEqual(name2, file_desc2.name)
self.assertEqual('google.protobuf.python.internal', file_desc2.package)
self.assertIn('Factory2Message', file_desc2.message_types_by_name)
def testFindFileByNameFailure(self):
with self.assertRaises(KeyError):
self.pool.FindFileByName('Does not exist')
def testFindFileContainingSymbol(self):
file_desc1 = self.pool.FindFileContainingSymbol(
'google.protobuf.python.internal.Factory1Message')
self.assertIsInstance(file_desc1, descriptor.FileDescriptor)
self.assertEqual('google/protobuf/internal/factory_test1.proto',
file_desc1.name)
self.assertEqual('google.protobuf.python.internal', file_desc1.package)
self.assertIn('Factory1Message', file_desc1.message_types_by_name)
file_desc2 = self.pool.FindFileContainingSymbol(
'google.protobuf.python.internal.Factory2Message')
self.assertIsInstance(file_desc2, descriptor.FileDescriptor)
self.assertEqual('google/protobuf/internal/factory_test2.proto',
file_desc2.name)
self.assertEqual('google.protobuf.python.internal', file_desc2.package)
self.assertIn('Factory2Message', file_desc2.message_types_by_name)
def testFindFileContainingSymbolFailure(self):
with self.assertRaises(KeyError):
self.pool.FindFileContainingSymbol('Does not exist')
def testFindMessageTypeByName(self):
msg1 = self.pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory1Message')
self.assertIsInstance(msg1, descriptor.Descriptor)
self.assertEqual('Factory1Message', msg1.name)
self.assertEqual('google.protobuf.python.internal.Factory1Message',
msg1.full_name)
self.assertEqual(None, msg1.containing_type)
self.assertFalse(msg1.has_options)
nested_msg1 = msg1.nested_types[0]
self.assertEqual('NestedFactory1Message', nested_msg1.name)
self.assertEqual(msg1, nested_msg1.containing_type)
nested_enum1 = msg1.enum_types[0]
self.assertEqual('NestedFactory1Enum', nested_enum1.name)
self.assertEqual(msg1, nested_enum1.containing_type)
self.assertEqual(nested_msg1, msg1.fields_by_name[
'nested_factory_1_message'].message_type)
self.assertEqual(nested_enum1, msg1.fields_by_name[
'nested_factory_1_enum'].enum_type)
msg2 = self.pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory2Message')
self.assertIsInstance(msg2, descriptor.Descriptor)
self.assertEqual('Factory2Message', msg2.name)
self.assertEqual('google.protobuf.python.internal.Factory2Message',
msg2.full_name)
self.assertIsNone(msg2.containing_type)
nested_msg2 = msg2.nested_types[0]
self.assertEqual('NestedFactory2Message', nested_msg2.name)
self.assertEqual(msg2, nested_msg2.containing_type)
nested_enum2 = msg2.enum_types[0]
self.assertEqual('NestedFactory2Enum', nested_enum2.name)
self.assertEqual(msg2, nested_enum2.containing_type)
self.assertEqual(nested_msg2, msg2.fields_by_name[
'nested_factory_2_message'].message_type)
self.assertEqual(nested_enum2, msg2.fields_by_name[
'nested_factory_2_enum'].enum_type)
self.assertTrue(msg2.fields_by_name['int_with_default'].has_default_value)
self.assertEqual(
1776, msg2.fields_by_name['int_with_default'].default_value)
self.assertTrue(
msg2.fields_by_name['double_with_default'].has_default_value)
self.assertEqual(
9.99, msg2.fields_by_name['double_with_default'].default_value)
self.assertTrue(
msg2.fields_by_name['string_with_default'].has_default_value)
self.assertEqual(
'hello world', msg2.fields_by_name['string_with_default'].default_value)
self.assertTrue(msg2.fields_by_name['bool_with_default'].has_default_value)
self.assertFalse(msg2.fields_by_name['bool_with_default'].default_value)
self.assertTrue(msg2.fields_by_name['enum_with_default'].has_default_value)
self.assertEqual(
1, msg2.fields_by_name['enum_with_default'].default_value)
msg3 = self.pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory2Message.NestedFactory2Message')
self.assertEqual(nested_msg2, msg3)
self.assertTrue(msg2.fields_by_name['bytes_with_default'].has_default_value)
self.assertEqual(
b'a\xfb\x00c',
msg2.fields_by_name['bytes_with_default'].default_value)
self.assertEqual(1, len(msg2.oneofs))
self.assertEqual(1, len(msg2.oneofs_by_name))
self.assertEqual(2, len(msg2.oneofs[0].fields))
for name in ['oneof_int', 'oneof_string']:
self.assertEqual(msg2.oneofs[0],
msg2.fields_by_name[name].containing_oneof)
self.assertIn(msg2.fields_by_name[name], msg2.oneofs[0].fields)
def testFindMessageTypeByNameFailure(self):
with self.assertRaises(KeyError):
self.pool.FindMessageTypeByName('Does not exist')
def testFindEnumTypeByName(self):
enum1 = self.pool.FindEnumTypeByName(
'google.protobuf.python.internal.Factory1Enum')
self.assertIsInstance(enum1, descriptor.EnumDescriptor)
self.assertEqual(0, enum1.values_by_name['FACTORY_1_VALUE_0'].number)
self.assertEqual(1, enum1.values_by_name['FACTORY_1_VALUE_1'].number)
self.assertFalse(enum1.has_options)
nested_enum1 = self.pool.FindEnumTypeByName(
'google.protobuf.python.internal.Factory1Message.NestedFactory1Enum')
self.assertIsInstance(nested_enum1, descriptor.EnumDescriptor)
self.assertEqual(
0, nested_enum1.values_by_name['NESTED_FACTORY_1_VALUE_0'].number)
self.assertEqual(
1, nested_enum1.values_by_name['NESTED_FACTORY_1_VALUE_1'].number)
enum2 = self.pool.FindEnumTypeByName(
'google.protobuf.python.internal.Factory2Enum')
self.assertIsInstance(enum2, descriptor.EnumDescriptor)
self.assertEqual(0, enum2.values_by_name['FACTORY_2_VALUE_0'].number)
self.assertEqual(1, enum2.values_by_name['FACTORY_2_VALUE_1'].number)
nested_enum2 = self.pool.FindEnumTypeByName(
'google.protobuf.python.internal.Factory2Message.NestedFactory2Enum')
self.assertIsInstance(nested_enum2, descriptor.EnumDescriptor)
self.assertEqual(
0, nested_enum2.values_by_name['NESTED_FACTORY_2_VALUE_0'].number)
self.assertEqual(
1, nested_enum2.values_by_name['NESTED_FACTORY_2_VALUE_1'].number)
def testFindEnumTypeByNameFailure(self):
with self.assertRaises(KeyError):
self.pool.FindEnumTypeByName('Does not exist')
def testFindFieldByName(self):
field = self.pool.FindFieldByName(
'google.protobuf.python.internal.Factory1Message.list_value')
self.assertEqual(field.name, 'list_value')
self.assertEqual(field.label, field.LABEL_REPEATED)
self.assertFalse(field.has_options)
with self.assertRaises(KeyError):
self.pool.FindFieldByName('Does not exist')
def testFindExtensionByName(self):
# An extension defined in a message.
extension = self.pool.FindExtensionByName(
'google.protobuf.python.internal.Factory2Message.one_more_field')
self.assertEqual(extension.name, 'one_more_field')
# An extension defined at file scope.
extension = self.pool.FindExtensionByName(
'google.protobuf.python.internal.another_field')
self.assertEqual(extension.name, 'another_field')
self.assertEqual(extension.number, 1002)
with self.assertRaises(KeyError):
self.pool.FindFieldByName('Does not exist')
def testFindAllExtensions(self):
factory1_message = self.pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory1Message')
factory2_message = self.pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory2Message')
# An extension defined in a message.
one_more_field = factory2_message.extensions_by_name['one_more_field']
self.pool.AddExtensionDescriptor(one_more_field)
# An extension defined at file scope.
factory_test2 = self.pool.FindFileByName(
'google/protobuf/internal/factory_test2.proto')
another_field = factory_test2.extensions_by_name['another_field']
self.pool.AddExtensionDescriptor(another_field)
extensions = self.pool.FindAllExtensions(factory1_message)
expected_extension_numbers = set([one_more_field, another_field])
self.assertEqual(expected_extension_numbers, set(extensions))
# Verify that mutating the returned list does not affect the pool.
extensions.append('unexpected_element')
# Get the extensions again, the returned value does not contain the
# 'unexpected_element'.
extensions = self.pool.FindAllExtensions(factory1_message)
self.assertEqual(expected_extension_numbers, set(extensions))
def testFindExtensionByNumber(self):
factory1_message = self.pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory1Message')
factory2_message = self.pool.FindMessageTypeByName(
'google.protobuf.python.internal.Factory2Message')
# An extension defined in a message.
one_more_field = factory2_message.extensions_by_name['one_more_field']
self.pool.AddExtensionDescriptor(one_more_field)
# An extension defined at file scope.
factory_test2 = self.pool.FindFileByName(
'google/protobuf/internal/factory_test2.proto')
another_field = factory_test2.extensions_by_name['another_field']
self.pool.AddExtensionDescriptor(another_field)
# An extension defined in a message.
extension = self.pool.FindExtensionByNumber(factory1_message, 1001)
self.assertEqual(extension.name, 'one_more_field')
# An extension defined at file scope.
extension = self.pool.FindExtensionByNumber(factory1_message, 1002)
self.assertEqual(extension.name, 'another_field')
with self.assertRaises(KeyError):
extension = self.pool.FindExtensionByNumber(factory1_message, 1234567)
def testExtensionsAreNotFields(self):
with self.assertRaises(KeyError):
self.pool.FindFieldByName('google.protobuf.python.internal.another_field')
with self.assertRaises(KeyError):
self.pool.FindFieldByName(
'google.protobuf.python.internal.Factory2Message.one_more_field')
with self.assertRaises(KeyError):
self.pool.FindExtensionByName(
'google.protobuf.python.internal.Factory1Message.list_value')
def testUserDefinedDB(self):
db = descriptor_database.DescriptorDatabase()
self.pool = descriptor_pool.DescriptorPool(db)
db.Add(self.factory_test1_fd)
db.Add(self.factory_test2_fd)
self.testFindMessageTypeByName()
def testAddSerializedFile(self):
self.pool = descriptor_pool.DescriptorPool()
self.pool.AddSerializedFile(self.factory_test1_fd.SerializeToString())
self.pool.AddSerializedFile(self.factory_test2_fd.SerializeToString())
self.testFindMessageTypeByName()
def testComplexNesting(self):
more_messages_desc = descriptor_pb2.FileDescriptorProto.FromString(
more_messages_pb2.DESCRIPTOR.serialized_pb)
test1_desc = descriptor_pb2.FileDescriptorProto.FromString(
descriptor_pool_test1_pb2.DESCRIPTOR.serialized_pb)
test2_desc = descriptor_pb2.FileDescriptorProto.FromString(
descriptor_pool_test2_pb2.DESCRIPTOR.serialized_pb)
self.pool.Add(more_messages_desc)
self.pool.Add(test1_desc)
self.pool.Add(test2_desc)
TEST1_FILE.CheckFile(self, self.pool)
TEST2_FILE.CheckFile(self, self.pool)
def testEnumDefaultValue(self):
"""Test the default value of enums which don't start at zero."""
def _CheckDefaultValue(file_descriptor):
default_value = (file_descriptor
.message_types_by_name['DescriptorPoolTest1']
.fields_by_name['nested_enum']
.default_value)
self.assertEqual(default_value,
descriptor_pool_test1_pb2.DescriptorPoolTest1.BETA)
# First check what the generated descriptor contains.
_CheckDefaultValue(descriptor_pool_test1_pb2.DESCRIPTOR)
# Then check the generated pool. Normally this is the same descriptor.
file_descriptor = symbol_database.Default().pool.FindFileByName(
'google/protobuf/internal/descriptor_pool_test1.proto')
self.assertIs(file_descriptor, descriptor_pool_test1_pb2.DESCRIPTOR)
_CheckDefaultValue(file_descriptor)
# Then check the dynamic pool and its internal DescriptorDatabase.
descriptor_proto = descriptor_pb2.FileDescriptorProto.FromString(
descriptor_pool_test1_pb2.DESCRIPTOR.serialized_pb)
self.pool.Add(descriptor_proto)
# And do the same check as above
file_descriptor = self.pool.FindFileByName(
'google/protobuf/internal/descriptor_pool_test1.proto')
_CheckDefaultValue(file_descriptor)
def testDefaultValueForCustomMessages(self):
"""Check the value returned by non-existent fields."""
def _CheckValueAndType(value, expected_value, expected_type):
self.assertEqual(value, expected_value)
self.assertIsInstance(value, expected_type)
def _CheckDefaultValues(msg):
try:
int64 = long
except NameError: # Python3
int64 = int
try:
unicode_type = unicode
except NameError: # Python3
unicode_type = str
_CheckValueAndType(msg.optional_int32, 0, int)
_CheckValueAndType(msg.optional_uint64, 0, (int64, int))
_CheckValueAndType(msg.optional_float, 0, (float, int))
_CheckValueAndType(msg.optional_double, 0, (float, int))
_CheckValueAndType(msg.optional_bool, False, bool)
_CheckValueAndType(msg.optional_string, u'', unicode_type)
_CheckValueAndType(msg.optional_bytes, b'', bytes)
_CheckValueAndType(msg.optional_nested_enum, msg.FOO, int)
# First for the generated message
_CheckDefaultValues(unittest_pb2.TestAllTypes())
# Then for a message built with from the DescriptorPool.
pool = descriptor_pool.DescriptorPool()
pool.Add(descriptor_pb2.FileDescriptorProto.FromString(
unittest_import_public_pb2.DESCRIPTOR.serialized_pb))
pool.Add(descriptor_pb2.FileDescriptorProto.FromString(
unittest_import_pb2.DESCRIPTOR.serialized_pb))
pool.Add(descriptor_pb2.FileDescriptorProto.FromString(
unittest_pb2.DESCRIPTOR.serialized_pb))
message_class = message_factory.MessageFactory(pool).GetPrototype(
pool.FindMessageTypeByName(
unittest_pb2.TestAllTypes.DESCRIPTOR.full_name))
_CheckDefaultValues(message_class())
class ProtoFile(object):
def __init__(self, name, package, messages, dependencies=None,
public_dependencies=None):
self.name = name
self.package = package
self.messages = messages
self.dependencies = dependencies or []
self.public_dependencies = public_dependencies or []
def CheckFile(self, test, pool):
file_desc = pool.FindFileByName(self.name)
test.assertEqual(self.name, file_desc.name)
test.assertEqual(self.package, file_desc.package)
dependencies_names = [f.name for f in file_desc.dependencies]
test.assertEqual(self.dependencies, dependencies_names)
public_dependencies_names = [f.name for f in file_desc.public_dependencies]
test.assertEqual(self.public_dependencies, public_dependencies_names)
for name, msg_type in self.messages.items():
msg_type.CheckType(test, None, name, file_desc)
class EnumType(object):
def __init__(self, values):
self.values = values
def CheckType(self, test, msg_desc, name, file_desc):
enum_desc = msg_desc.enum_types_by_name[name]
test.assertEqual(name, enum_desc.name)
expected_enum_full_name = '.'.join([msg_desc.full_name, name])
test.assertEqual(expected_enum_full_name, enum_desc.full_name)
test.assertEqual(msg_desc, enum_desc.containing_type)
test.assertEqual(file_desc, enum_desc.file)
for index, (value, number) in enumerate(self.values):
value_desc = enum_desc.values_by_name[value]
test.assertEqual(value, value_desc.name)
test.assertEqual(index, value_desc.index)
test.assertEqual(number, value_desc.number)
test.assertEqual(enum_desc, value_desc.type)
test.assertIn(value, msg_desc.enum_values_by_name)
class MessageType(object):
def __init__(self, type_dict, field_list, is_extendable=False,
extensions=None):
self.type_dict = type_dict
self.field_list = field_list
self.is_extendable = is_extendable
self.extensions = extensions or []
def CheckType(self, test, containing_type_desc, name, file_desc):
if containing_type_desc is None:
desc = file_desc.message_types_by_name[name]
expected_full_name = '.'.join([file_desc.package, name])
else:
desc = containing_type_desc.nested_types_by_name[name]
expected_full_name = '.'.join([containing_type_desc.full_name, name])
test.assertEqual(name, desc.name)
test.assertEqual(expected_full_name, desc.full_name)
test.assertEqual(containing_type_desc, desc.containing_type)
test.assertEqual(desc.file, file_desc)
test.assertEqual(self.is_extendable, desc.is_extendable)
for name, subtype in self.type_dict.items():
subtype.CheckType(test, desc, name, file_desc)
for index, (name, field) in enumerate(self.field_list):
field.CheckField(test, desc, name, index)
for index, (name, field) in enumerate(self.extensions):
field.CheckField(test, desc, name, index)
class EnumField(object):
def __init__(self, number, type_name, default_value):
self.number = number
self.type_name = type_name
self.default_value = default_value
def CheckField(self, test, msg_desc, name, index):
field_desc = msg_desc.fields_by_name[name]
enum_desc = msg_desc.enum_types_by_name[self.type_name]
test.assertEqual(name, field_desc.name)
expected_field_full_name = '.'.join([msg_desc.full_name, name])
test.assertEqual(expected_field_full_name, field_desc.full_name)
test.assertEqual(index, field_desc.index)
test.assertEqual(self.number, field_desc.number)
test.assertEqual(descriptor.FieldDescriptor.TYPE_ENUM, field_desc.type)
test.assertEqual(descriptor.FieldDescriptor.CPPTYPE_ENUM,
field_desc.cpp_type)
test.assertTrue(field_desc.has_default_value)
test.assertEqual(enum_desc.values_by_name[self.default_value].number,
field_desc.default_value)
test.assertFalse(enum_desc.values_by_name[self.default_value].has_options)
test.assertEqual(msg_desc, field_desc.containing_type)
test.assertEqual(enum_desc, field_desc.enum_type)
class MessageField(object):
def __init__(self, number, type_name):
self.number = number
self.type_name = type_name
def CheckField(self, test, msg_desc, name, index):
field_desc = msg_desc.fields_by_name[name]
field_type_desc = msg_desc.nested_types_by_name[self.type_name]
test.assertEqual(name, field_desc.name)
expected_field_full_name = '.'.join([msg_desc.full_name, name])
test.assertEqual(expected_field_full_name, field_desc.full_name)
test.assertEqual(index, field_desc.index)
test.assertEqual(self.number, field_desc.number)
test.assertEqual(descriptor.FieldDescriptor.TYPE_MESSAGE, field_desc.type)
test.assertEqual(descriptor.FieldDescriptor.CPPTYPE_MESSAGE,
field_desc.cpp_type)
test.assertFalse(field_desc.has_default_value)
test.assertEqual(msg_desc, field_desc.containing_type)
test.assertEqual(field_type_desc, field_desc.message_type)
class StringField(object):
def __init__(self, number, default_value):
self.number = number
self.default_value = default_value
def CheckField(self, test, msg_desc, name, index):
field_desc = msg_desc.fields_by_name[name]
test.assertEqual(name, field_desc.name)
expected_field_full_name = '.'.join([msg_desc.full_name, name])
test.assertEqual(expected_field_full_name, field_desc.full_name)
test.assertEqual(index, field_desc.index)
test.assertEqual(self.number, field_desc.number)
test.assertEqual(descriptor.FieldDescriptor.TYPE_STRING, field_desc.type)
test.assertEqual(descriptor.FieldDescriptor.CPPTYPE_STRING,
field_desc.cpp_type)
test.assertTrue(field_desc.has_default_value)
test.assertEqual(self.default_value, field_desc.default_value)
class ExtensionField(object):
def __init__(self, number, extended_type):
self.number = number
self.extended_type = extended_type
def CheckField(self, test, msg_desc, name, index):
field_desc = msg_desc.extensions_by_name[name]
test.assertEqual(name, field_desc.name)
expected_field_full_name = '.'.join([msg_desc.full_name, name])
test.assertEqual(expected_field_full_name, field_desc.full_name)
test.assertEqual(self.number, field_desc.number)
test.assertEqual(index, field_desc.index)
test.assertEqual(descriptor.FieldDescriptor.TYPE_MESSAGE, field_desc.type)
test.assertEqual(descriptor.FieldDescriptor.CPPTYPE_MESSAGE,
field_desc.cpp_type)
test.assertFalse(field_desc.has_default_value)
test.assertTrue(field_desc.is_extension)
test.assertEqual(msg_desc, field_desc.extension_scope)
test.assertEqual(msg_desc, field_desc.message_type)
test.assertEqual(self.extended_type, field_desc.containing_type.name)
class AddDescriptorTest(unittest.TestCase):
def _TestMessage(self, prefix):
pool = descriptor_pool.DescriptorPool()
pool.AddDescriptor(unittest_pb2.TestAllTypes.DESCRIPTOR)
self.assertEqual(
'protobuf_unittest.TestAllTypes',
pool.FindMessageTypeByName(
prefix + 'protobuf_unittest.TestAllTypes').full_name)
# AddDescriptor is not recursive.
with self.assertRaises(KeyError):
pool.FindMessageTypeByName(
prefix + 'protobuf_unittest.TestAllTypes.NestedMessage')
pool.AddDescriptor(unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR)
self.assertEqual(
'protobuf_unittest.TestAllTypes.NestedMessage',
pool.FindMessageTypeByName(
prefix + 'protobuf_unittest.TestAllTypes.NestedMessage').full_name)
# Files are implicitly also indexed when messages are added.
self.assertEqual(
'google/protobuf/unittest.proto',
pool.FindFileByName(
'google/protobuf/unittest.proto').name)
self.assertEqual(
'google/protobuf/unittest.proto',
pool.FindFileContainingSymbol(
prefix + 'protobuf_unittest.TestAllTypes.NestedMessage').name)
@unittest.skipIf(api_implementation.Type() == 'cpp',
'With the cpp implementation, Add() must be called first')
def testMessage(self):
self._TestMessage('')
self._TestMessage('.')
def _TestEnum(self, prefix):
pool = descriptor_pool.DescriptorPool()
pool.AddEnumDescriptor(unittest_pb2.ForeignEnum.DESCRIPTOR)
self.assertEqual(
'protobuf_unittest.ForeignEnum',
pool.FindEnumTypeByName(
prefix + 'protobuf_unittest.ForeignEnum').full_name)
# AddEnumDescriptor is not recursive.
with self.assertRaises(KeyError):
pool.FindEnumTypeByName(
prefix + 'protobuf_unittest.ForeignEnum.NestedEnum')
pool.AddEnumDescriptor(unittest_pb2.TestAllTypes.NestedEnum.DESCRIPTOR)
self.assertEqual(
'protobuf_unittest.TestAllTypes.NestedEnum',
pool.FindEnumTypeByName(
prefix + 'protobuf_unittest.TestAllTypes.NestedEnum').full_name)
# Files are implicitly also indexed when enums are added.
self.assertEqual(
'google/protobuf/unittest.proto',
pool.FindFileByName(
'google/protobuf/unittest.proto').name)
self.assertEqual(
'google/protobuf/unittest.proto',
pool.FindFileContainingSymbol(
prefix + 'protobuf_unittest.TestAllTypes.NestedEnum').name)
@unittest.skipIf(api_implementation.Type() == 'cpp',
'With the cpp implementation, Add() must be called first')
def testEnum(self):
self._TestEnum('')
self._TestEnum('.')
@unittest.skipIf(api_implementation.Type() == 'cpp',
'With the cpp implementation, Add() must be called first')
def testFile(self):
pool = descriptor_pool.DescriptorPool()
pool.AddFileDescriptor(unittest_pb2.DESCRIPTOR)
self.assertEqual(
'google/protobuf/unittest.proto',
pool.FindFileByName(
'google/protobuf/unittest.proto').name)
# AddFileDescriptor is not recursive; messages and enums within files must
# be explicitly registered.
with self.assertRaises(KeyError):
pool.FindFileContainingSymbol(
'protobuf_unittest.TestAllTypes')
def testEmptyDescriptorPool(self):
# Check that an empty DescriptorPool() contains no messages.
pool = descriptor_pool.DescriptorPool()
proto_file_name = descriptor_pb2.DESCRIPTOR.name
self.assertRaises(KeyError, pool.FindFileByName, proto_file_name)
# Add the above file to the pool
file_descriptor = descriptor_pb2.FileDescriptorProto()
descriptor_pb2.DESCRIPTOR.CopyToProto(file_descriptor)
pool.Add(file_descriptor)
# Now it exists.
self.assertTrue(pool.FindFileByName(proto_file_name))
def testCustomDescriptorPool(self):
# Create a new pool, and add a file descriptor.
pool = descriptor_pool.DescriptorPool()
file_desc = descriptor_pb2.FileDescriptorProto(
name='some/file.proto', package='package')
file_desc.message_type.add(name='Message')
pool.Add(file_desc)
self.assertEqual(pool.FindFileByName('some/file.proto').name,
'some/file.proto')
self.assertEqual(pool.FindMessageTypeByName('package.Message').name,
'Message')
def testFileDescriptorOptionsWithCustomDescriptorPool(self):
# Create a descriptor pool, and add a new FileDescriptorProto to it.
pool = descriptor_pool.DescriptorPool()
file_name = 'file_descriptor_options_with_custom_descriptor_pool.proto'
file_descriptor_proto = descriptor_pb2.FileDescriptorProto(name=file_name)
extension_id = file_options_test_pb2.foo_options
file_descriptor_proto.options.Extensions[extension_id].foo_name = 'foo'
pool.Add(file_descriptor_proto)
# The options set on the FileDescriptorProto should be available in the
# descriptor even if they contain extensions that cannot be deserialized
# using the pool.
file_descriptor = pool.FindFileByName(file_name)
options = file_descriptor.GetOptions()
self.assertEqual('foo', options.Extensions[extension_id].foo_name)
# The object returned by GetOptions() is cached.
self.assertIs(options, file_descriptor.GetOptions())
@unittest.skipIf(
api_implementation.Type() != 'cpp',
'default_pool is only supported by the C++ implementation')
class DefaultPoolTest(unittest.TestCase):
def testFindMethods(self):
# pylint: disable=g-import-not-at-top
from google.protobuf.pyext import _message
pool = _message.default_pool
self.assertIs(
pool.FindFileByName('google/protobuf/unittest.proto'),
unittest_pb2.DESCRIPTOR)
self.assertIs(
pool.FindMessageTypeByName('protobuf_unittest.TestAllTypes'),
unittest_pb2.TestAllTypes.DESCRIPTOR)
self.assertIs(
pool.FindFieldByName('protobuf_unittest.TestAllTypes.optional_int32'),
unittest_pb2.TestAllTypes.DESCRIPTOR.fields_by_name['optional_int32'])
self.assertIs(
pool.FindExtensionByName('protobuf_unittest.optional_int32_extension'),
unittest_pb2.DESCRIPTOR.extensions_by_name['optional_int32_extension'])
self.assertIs(
pool.FindEnumTypeByName('protobuf_unittest.ForeignEnum'),
unittest_pb2.ForeignEnum.DESCRIPTOR)
self.assertIs(
pool.FindOneofByName('protobuf_unittest.TestAllTypes.oneof_field'),
unittest_pb2.TestAllTypes.DESCRIPTOR.oneofs_by_name['oneof_field'])
def testAddFileDescriptor(self):
# pylint: disable=g-import-not-at-top
from google.protobuf.pyext import _message
pool = _message.default_pool
file_desc = descriptor_pb2.FileDescriptorProto(name='some/file.proto')
pool.Add(file_desc)
pool.AddSerializedFile(file_desc.SerializeToString())
TEST1_FILE = ProtoFile(
'google/protobuf/internal/descriptor_pool_test1.proto',
'google.protobuf.python.internal',
{
'DescriptorPoolTest1': MessageType({
'NestedEnum': EnumType([('ALPHA', 1), ('BETA', 2)]),
'NestedMessage': MessageType({
'NestedEnum': EnumType([('EPSILON', 5), ('ZETA', 6)]),
'DeepNestedMessage': MessageType({
'NestedEnum': EnumType([('ETA', 7), ('THETA', 8)]),
}, [
('nested_enum', EnumField(1, 'NestedEnum', 'ETA')),
('nested_field', StringField(2, 'theta')),
]),
}, [
('nested_enum', EnumField(1, 'NestedEnum', 'ZETA')),
('nested_field', StringField(2, 'beta')),
('deep_nested_message', MessageField(3, 'DeepNestedMessage')),
])
}, [
('nested_enum', EnumField(1, 'NestedEnum', 'BETA')),
('nested_message', MessageField(2, 'NestedMessage')),
], is_extendable=True),
'DescriptorPoolTest2': MessageType({
'NestedEnum': EnumType([('GAMMA', 3), ('DELTA', 4)]),
'NestedMessage': MessageType({
'NestedEnum': EnumType([('IOTA', 9), ('KAPPA', 10)]),
'DeepNestedMessage': MessageType({
'NestedEnum': EnumType([('LAMBDA', 11), ('MU', 12)]),
}, [
('nested_enum', EnumField(1, 'NestedEnum', 'MU')),
('nested_field', StringField(2, 'lambda')),
]),
}, [
('nested_enum', EnumField(1, 'NestedEnum', 'IOTA')),
('nested_field', StringField(2, 'delta')),
('deep_nested_message', MessageField(3, 'DeepNestedMessage')),
])
}, [
('nested_enum', EnumField(1, 'NestedEnum', 'GAMMA')),
('nested_message', MessageField(2, 'NestedMessage')),
]),
})
TEST2_FILE = ProtoFile(
'google/protobuf/internal/descriptor_pool_test2.proto',
'google.protobuf.python.internal',
{
'DescriptorPoolTest3': MessageType({
'NestedEnum': EnumType([('NU', 13), ('XI', 14)]),
'NestedMessage': MessageType({
'NestedEnum': EnumType([('OMICRON', 15), ('PI', 16)]),
'DeepNestedMessage': MessageType({
'NestedEnum': EnumType([('RHO', 17), ('SIGMA', 18)]),
}, [
('nested_enum', EnumField(1, 'NestedEnum', 'RHO')),
('nested_field', StringField(2, 'sigma')),
]),
}, [
('nested_enum', EnumField(1, 'NestedEnum', 'PI')),
('nested_field', StringField(2, 'nu')),
('deep_nested_message', MessageField(3, 'DeepNestedMessage')),
])
}, [
('nested_enum', EnumField(1, 'NestedEnum', 'XI')),
('nested_message', MessageField(2, 'NestedMessage')),
], extensions=[
('descriptor_pool_test',
ExtensionField(1001, 'DescriptorPoolTest1')),
]),
},
dependencies=['google/protobuf/internal/descriptor_pool_test1.proto',
'google/protobuf/internal/more_messages.proto'],
public_dependencies=['google/protobuf/internal/more_messages.proto'])
if __name__ == '__main__':
unittest.main()
| apache-2.0 | 5,672,402,507,135,217,000 | 42.214634 | 80 | 0.703155 | false |
iotile/coretools | iotilesensorgraph/iotile/sg/parser/scopes/trigger_scope.py | 1 | 2303 | from .scope import Scope
from ...node import InputTrigger
from ...exceptions import SensorGraphSemanticError
from ...stream import DataStream
class TriggerScope(Scope):
"""A scope that implements trigger_chain but cannot provide a clock.
Args:
sensor_graph (SensorGraph): The sensor graph we are working on.
scope_stack (list(Scope)): The stack of already allocated scopes.
trigger_input ((DataStream, InputTrigger): The input trigger stream
and condition. The input trigger must already be attached.
"""
def __init__(self, sensor_graph, scope_stack, trigger_input):
parent = scope_stack[-1]
alloc = parent.allocator
sensor_graph = parent.sensor_graph
super(TriggerScope, self).__init__(u"Trigger Scope", sensor_graph, alloc, parent)
# Create our own node to create our triggering chain
# this will be optimized out if it turned out not to be needed
# after all nodes have been allocated. Since we can trigger on a root
# node, make sure we don't try to make our output a root input.
stream_type = trigger_input[0].stream_type
if stream_type == DataStream.InputType:
stream_type = DataStream.UnbufferedType
stream = alloc.allocate_stream(stream_type)
sensor_graph.add_node(u'({} {}) => {} using copy_latest_a'.format(trigger_input[0], trigger_input[1], stream))
self.trigger_stream = stream
self.trigger_cond = InputTrigger(u'count', '==', 1)
def trigger_chain(self):
"""Return a NodeInput tuple for creating a node.
Returns:
(StreamIdentifier, InputTrigger)
"""
trigger_stream = self.allocator.attach_stream(self.trigger_stream)
return (trigger_stream, self.trigger_cond)
def clock(self, interval, basis):
"""Return a NodeInput tuple for triggering an event every interval.
We request each distinct type of clock at most once and combine it with our
latch stream each time it is requested.
Args:
interval (int): The interval (in seconds) at which this input should
trigger.
"""
raise SensorGraphSemanticError("TriggerScope does not provide a clock output that can be used.")
| gpl-3.0 | 5,710,999,682,054,407,000 | 39.403509 | 118 | 0.65914 | false |
ichbinder23/mailsend | Mailer.py | 1 | 1917 | '''
Created on 15.10.2014
@author: jakob
'''
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os.path
class Mailer(object):
def __init__(self, imailoption):
assert isinstance(imailoption.get_receiver(), list)#, "receiver parameter ist not a list"
self.__imailoption = imailoption
def sendmail(self):
msg = MIMEMultipart()
msg['From'] = self.__imailoption.get_transmitter()
msg['To'] = COMMASPACE.join(self.__imailoption.get_receiver())
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = self.__imailoption.get_subject()
msg.attach( MIMEText(self.__imailoption.get_message()) )
if self.__imailoption.get_attachments() != None:
for am in self.__imailoption.get_attachments():
if os.path.isfile(am):
part = MIMEBase('application', "octet-stream")
part.set_payload( open(am,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(am))
msg.attach(part)
else:
print "File dont not exists: %s" % (am)
smtp = smtplib.SMTP(self.__imailoption.get_SMTP_Server_URL(),
self.__imailoption.get_SMTP_Server_Prot())
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(self.__imailoption.get_loginname(),
self.__imailoption.get_password())
smtp.sendmail(self.__imailoption.get_transmitter(),
self.__imailoption.get_receiver(),
msg.as_string())
smtp.close()
| gpl-2.0 | 4,603,037,186,639,711,700 | 35.884615 | 110 | 0.577465 | false |
edquist/autopyfactory | attic/jsd3.py | 3 | 4287 | #! /usr/bin/env python
#
# Job submission-related code.
#
#
# Copyright (C) 2011 Jose Caballero
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging
import os
class JSDDirective(object):
def __init__(self, value):
self.log = logging.getLogger("main.jsddirective")
self.content= value
self.log.info('JSDDirective: Object initialized.')
def __str__(self):
return self.content
def __repr__(self):
return self.content
class JSDDirectiveKeyValue(object):
def __init__(self, key, value):
self.log = logging.getLogger("main.jsddirective")
self.key = key
self.value = value
self.log.info('JSDDirectiveKeyValue: Object initialized.')
def __str__(self):
return '%s = %s' %(self.key, self.value)
def __repr__(self):
return '%s = %s' %(self.key, self.value)
class JSDDirectiveHandler(object):
def __init__(self):
self.directives = []
def add(self, value):
directive = JSDDirective(value)
self.directives.append(directive)
def get(self):
# return a list of strings
return [dir for dir in self.directives]
class JSDDirectiveKeyValueHandler(object):
def __init__(self):
# directives = {}
# -- key is the directive key
# -- value is the entire JSDDirectiveKeyValue object
self.directives = {}
def add(self, key, value):
directive = JSDDirectiveKeyValue(key, value)
self.directives[key] = directive
def get(self):
# return a list of strings
return [dir for dir in self.directives.values()]
class JSDFile(object):
def __init__(self):
self.log = logging.getLogger("main.jsdfile")
self.handlers = []
self.log.info('JSDFile: Object initialized.')
def add(self, handler):
self.log.debug('add: Starting.')
self.handlers.append(handler)
self.log.debug('add: Leaving.')
def write(self, path, filename):
'''
Dumps the whole content of the JSDFile object into a disk file
'''
self.log.debug('writeJSD: Starting.')
if not os.access(path, os.F_OK):
try:
os.makedirs(path)
self.log.debug('writeJSD: Created directory %s', path)
except OSError, (errno, errMsg):
self.log.error('writeJSD: Failed to create directory %s (error %d): %s', path, errno, errMsg)
return
jsdfilename = os.path.join(path, filename)
self._dump(jsdfilename)
self.log.debug('writeJSD: the submit file content is\n %s ' %self)
self.log.debug('writeJSD: Leaving.')
return jsdfilename
def _dump(self, jsdfilename):
self.log.debug('_dump: Starting.')
jsdfile = open(jsdfilename, 'w')
for handler in self.handlers:
for line in handler.get():
print >> jsdfile, line
jsdfile.close()
self.log.debug('_dump: Leaving.')
# ==============================================================================
if __name__ == '__main__':
jsd = JSDFile()
lh1 = JSDDirectiveHandler()
lh2 = JSDDirectiveHandler()
dh1 = JSDDirectiveKeyValueHandler()
dh2 = JSDDirectiveKeyValueHandler()
jsd.add(lh1)
jsd.add(dh1)
jsd.add(lh2)
jsd.add(dh2)
lh1.add('linea 1')
lh1.add('linea 2')
dh1.add('key1', 'value1')
dh1.add('key2', 'value2')
lh2.add('linea 3')
lh2.add('linea 4')
dh2.add('key3', 'value3')
dh2.add('key4', 'value4')
dh2.add('key4', 'VALUE4')
jsd.write('/tmp/jsd', 'out')
| gpl-3.0 | 347,834,638,143,927,900 | 24.825301 | 109 | 0.594588 | false |
torbjoernk/easybuild-easyblocks | easybuild/easyblocks/s/slepc.py | 10 | 5767 | ##
# Copyright 2009-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (http://www.herculesstichting.be/in_English)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild 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 v2.
#
# EasyBuild 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 EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBuild support for SLEPc, implemented as an easyblock
@author: Kenneth Hoste (Ghent University)
"""
import os
import re
from distutils.version import LooseVersion
import easybuild.tools.environment as env
from easybuild.easyblocks.generic.configuremake import ConfigureMake
from easybuild.framework.easyconfig import BUILD, CUSTOM
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.modules import get_software_root
from easybuild.tools.run import run_cmd
class EB_SLEPc(ConfigureMake):
"""Support for building and installing SLEPc"""
@staticmethod
def extra_options():
"""Add extra config options specific to SLEPc."""
extra_vars = {
'runtest': ['test', "Make target to test build", BUILD],
'petsc_arch': [None, "PETSc architecture to use (value for $PETSC_ARCH)", CUSTOM],
'sourceinstall': [False, "Indicates whether a source installation should be performed", CUSTOM],
}
return ConfigureMake.extra_options(extra_vars)
def __init__(self, *args, **kwargs):
"""Initialize SLEPc custom variables."""
super(EB_SLEPc, self).__init__(*args, **kwargs)
self.slepc_subdir = ''
def make_builddir(self):
"""Decide whether or not to build in install dir before creating build dir."""
if self.cfg['sourceinstall']:
self.build_in_installdir = True
super(EB_SLEPc, self).make_builddir()
def configure_step(self):
"""Configure SLEPc by setting configure options and running configure script."""
# check PETSc dependency
if not get_software_root("PETSc"):
raise EasyBuildError("PETSc module not loaded?")
# set SLEPC_DIR environment variable
env.setvar('SLEPC_DIR', self.cfg['start_dir'])
self.log.debug('SLEPC_DIR: %s' % os.getenv('SLEPC_DIR'))
# optional dependencies
depfilter = self.cfg.builddependencies() + ["PETSc"]
deps = [dep['name'] for dep in self.cfg.dependencies() if not dep['name'] in depfilter]
for dep in deps:
deproot = get_software_root(dep)
if deproot:
withdep = "--with-%s" % dep.lower()
self.cfg.update('configopts', '%s=1 %s-dir=%s' % (withdep, withdep, deproot))
if self.cfg['sourceinstall']:
# run configure without --prefix (required)
cmd = "%s ./configure %s" % (self.cfg['preconfigopts'], self.cfg['configopts'])
(out, _) = run_cmd(cmd, log_all=True, simple=False)
else:
# regular './configure --prefix=X' for non-source install
# make sure old install dir is removed first
self.make_installdir(dontcreate=True)
out = super(EB_SLEPc, self).configure_step()
# check for errors in configure
error_regexp = re.compile("ERROR")
if error_regexp.search(out):
raise EasyBuildError("Error(s) detected in configure output!")
# define $PETSC_ARCH
petsc_arch = self.cfg['petsc_arch']
if self.cfg['petsc_arch'] is None:
petsc_arch = 'arch-installed-petsc'
env.setvar('PETSC_ARCH', petsc_arch)
if self.cfg['sourceinstall']:
self.slepc_subdir = os.path.join('%s-%s' % (self.name.lower(), self.version), petsc_arch)
# SLEPc > 3.5, make does not accept -j
if LooseVersion(self.version) >= LooseVersion("3.5"):
self.cfg['parallel'] = None
def make_module_req_guess(self):
"""Specify correct LD_LIBRARY_PATH and CPATH for SLEPc installation."""
guesses = super(EB_SLEPc, self).make_module_req_guess()
guesses.update({
'CPATH': [os.path.join(self.slepc_subdir, "include")],
'LD_LIBRARY_PATH': [os.path.join(self.slepc_subdir, "lib")],
})
return guesses
def make_module_extra(self):
"""Set SLEPc specific environment variables (SLEPC_DIR)."""
txt = super(EB_SLEPc, self).make_module_extra()
if self.cfg['sourceinstall']:
subdir = '%s-%s' % (self.name.lower(), self.version)
txt += self.module_generator.set_environment('SLEPC_DIR', os.path.join(self.installdir, subdir))
else:
txt += self.module_generator.set_environment('SLEPC_DIR', self.installdir)
return txt
def sanity_check_step(self):
"""Custom sanity check for SLEPc"""
custom_paths = {
'files': [],
'dirs': [os.path.join(self.slepc_subdir, x) for x in ["conf", "include", "lib"]],
}
super(EB_SLEPc, self).sanity_check_step(custom_paths=custom_paths)
| gpl-2.0 | -1,552,919,844,008,710,700 | 37.446667 | 108 | 0.638113 | false |
noba3/KoTos | addons/plugin.video.rtl2-now.de/resources/lib/kodion/items/video_item.py | 16 | 4457 | import re
import datetime
from .base_item import BaseItem
__RE_IMDB__ = re.compile(r'(http(s)?://)?www.imdb.(com|de)/title/(?P<imdbid>[t0-9]+)(/)?')
class VideoItem(BaseItem):
def __init__(self, name, uri, image=u'', fanart=u''):
BaseItem.__init__(self, name, uri, image, fanart)
self._genre = None
self._aired = None
self._duration = None
self._director = None
self._premiered = None
self._episode = None
self._season = None
self._year = None
self._plot = None
self._title = name
self._imdb_id = None
self._cast = None
self._rating = None
self._track_number = None
self._studio = None
self._artist = None
self._play_count = None
pass
def set_play_count(self, play_count):
self._play_count = int(play_count)
pass
def get_play_count(self):
return self._play_count
def add_artist(self, artist):
if self._artist is None:
self._artist = []
pass
self._artist.append(unicode(artist))
pass
def get_artist(self):
return self._artist
def set_studio(self, studio):
self._studio = unicode(studio)
pass
def get_studio(self):
return self._studio
def set_title(self, title):
self._title = unicode(title)
self._name = self._title
pass
def get_title(self):
return self._title
def set_track_number(self, track_number):
self._track_number = int(track_number)
pass
def get_track_number(self):
return self._track_number
def set_year(self, year):
self._year = int(year)
pass
def set_year_from_datetime(self, date_time):
self.set_year(date_time.year)
pass
def get_year(self):
return self._year
def set_premiered(self, year, month, day):
date = datetime.date(year, month, day)
self._premiered = date.isoformat()
pass
def set_premiered_from_datetime(self, date_time):
self.set_premiered(year=date_time.year, month=date_time.month, day=date_time.day)
pass
def get_premiered(self):
return self._premiered
def set_plot(self, plot):
self._plot = unicode(plot)
pass
def get_plot(self):
return self._plot
def set_rating(self, rating):
self._rating = float(rating)
pass
def get_rating(self):
return self._rating
def set_director(self, director_name):
self._director = unicode(director_name)
pass
def get_director(self):
return self._director
def add_cast(self, cast):
if self._cast is None:
self._cast = []
pass
self._cast.append(cast)
pass
def get_cast(self):
return self._cast
def set_imdb_id(self, url_or_id):
re_match = __RE_IMDB__.match(url_or_id)
if re_match:
self._imdb_id = re_match.group('imdbid')
else:
self._imdb_id = url_or_id
pass
def get_imdb_id(self):
return self._imdb_id
def set_episode(self, episode):
self._episode = int(episode)
pass
def get_episode(self):
return self._episode
def set_season(self, season):
self._season = int(season)
pass
def get_season(self):
return self._season
def set_duration(self, hours, minutes, seconds=0):
_seconds = seconds
_seconds += minutes * 60
_seconds += hours * 60 * 60
self.set_duration_from_seconds(_seconds)
pass
def set_duration_from_minutes(self, minutes):
self.set_duration_from_seconds(int(minutes) * 60)
pass
def set_duration_from_seconds(self, seconds):
self._duration = int(seconds)
pass
def get_duration(self):
return self._duration
def set_aired(self, year, month, day):
date = datetime.date(year, month, day)
self._aired = date.isoformat()
pass
def set_aired_from_datetime(self, date_time):
self.set_aired(year=date_time.year, month=date_time.month, day=date_time.day)
pass
def get_aired(self):
return self._aired
def set_genre(self, genre):
self._genre = unicode(genre)
pass
def get_genre(self):
return self._genre
pass | gpl-2.0 | 4,031,269,859,424,774,000 | 22.967742 | 90 | 0.565178 | false |
ChinaQuants/zipline | setup.py | 1 | 6383 | #!/usr/bin/env python
#
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import re
import sys
from operator import lt, gt, eq, le, ge
from os.path import (
abspath,
dirname,
join,
)
from distutils.version import StrictVersion
from setuptools import (
Extension,
find_packages,
setup,
)
class LazyCythonizingList(list):
cythonized = False
def lazy_cythonize(self):
if self.cythonized:
return
self.cythonized = True
from Cython.Build import cythonize
from numpy import get_include
self[:] = cythonize(
[
Extension(*ext_args, include_dirs=[get_include()])
for ext_args in self
]
)
def __iter__(self):
self.lazy_cythonize()
return super(LazyCythonizingList, self).__iter__()
def __getitem__(self, num):
self.lazy_cythonize()
return super(LazyCythonizingList, self).__getitem__(num)
ext_modules = LazyCythonizingList([
('zipline.assets._assets', ['zipline/assets/_assets.pyx']),
('zipline.lib.adjusted_array', ['zipline/lib/adjusted_array.pyx']),
('zipline.lib.adjustment', ['zipline/lib/adjustment.pyx']),
('zipline.lib.rank', ['zipline/lib/rank.pyx']),
(
'zipline.data._equities',
['zipline/data/_equities.pyx'],
),
(
'zipline.data._adjustments',
['zipline/data/_adjustments.pyx'],
),
])
STR_TO_CMP = {
'<': lt,
'<=': le,
'=': eq,
'==': eq,
'>': gt,
'>=': ge,
}
def _filter_requirements(lines_iter):
for line in lines_iter:
line = line.strip()
if not line or line.startswith('#'):
continue
# pip install -r understands line with ;python_version<'3.0', but
# whatever happens inside extras_requires doesn't. Parse the line
# manually and conditionally add it if needed.
if ';' not in line:
yield line
continue
requirement, version_spec = line.split(';')
try:
groups = re.match(
"(python_version)([<>=]{1,2})(')([0-9\.]+)(')(.*)",
version_spec,
).groups()
comp = STR_TO_CMP[groups[1]]
version_spec = StrictVersion(groups[3])
except Exception as e:
# My kingdom for a 'raise from'!
raise AssertionError(
"Couldn't parse requirement line; '%s'\n"
"Error was:\n"
"%r" % (line, e)
)
sys_version = '.'.join(list(map(str, sys.version_info[:3])))
if comp(sys_version, version_spec):
yield requirement
def read_requirements(path):
"""
Read a requirements.txt file, expressed as a path relative to Zipline root.
"""
real_path = join(dirname(abspath(__file__)), path)
with open(real_path) as f:
return list(_filter_requirements(f.readlines()))
def install_requires():
return read_requirements('etc/requirements.txt')
def extras_requires():
dev_reqs = read_requirements('etc/requirements_dev.txt')
talib_reqs = ['TA-Lib==0.4.9']
return {
'dev': dev_reqs,
'talib': talib_reqs,
'all': dev_reqs + talib_reqs,
}
def module_requirements(requirements_path, module_names):
module_names = set(module_names)
found = set()
module_lines = []
parser = re.compile("([^=<>]+)([<=>]{1,2})(.*)")
for line in read_requirements(requirements_path):
match = parser.match(line)
if match is None:
raise AssertionError("Could not parse requirement: '%s'" % line)
groups = match.groups()
name = groups[0]
if name in module_names:
found.add(name)
module_lines.append(line)
if found != module_names:
raise AssertionError(
"No requirements found for %s." % module_names - found
)
return module_lines
def pre_setup():
if not set(sys.argv) & {'install', 'develop', 'egg_info', 'bdist_wheel'}:
return
try:
import pip
if StrictVersion(pip.__version__) < StrictVersion('7.1.0'):
raise AssertionError(
"Zipline installation requires pip>=7.1.0, but your pip "
"version is {version}. \n"
"You can upgrade your pip with "
"'pip install --upgrade pip'.".format(
version=pip.__version__,
)
)
except ImportError:
raise AssertionError("Zipline installation requires pip")
required = ('Cython', 'numpy')
for line in module_requirements('etc/requirements.txt', required):
pip.main(['install', line])
pre_setup()
setup(
name='zipline',
version='0.8.0rc1',
description='A backtester for financial algorithms.',
author='Quantopian Inc.',
author_email='[email protected]',
packages=find_packages('.', include=['zipline', 'zipline.*']),
ext_modules=ext_modules,
scripts=['scripts/run_algo.py'],
include_package_data=True,
license='Apache 2.0',
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Operating System :: OS Independent',
'Intended Audience :: Science/Research',
'Topic :: Office/Business :: Financial',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: System :: Distributed Computing',
],
install_requires=install_requires(),
extras_require=extras_requires(),
url="http://zipline.io"
)
| apache-2.0 | 6,638,006,999,681,160,000 | 28.013636 | 79 | 0.586088 | false |
sensysnetworks/uClinux | user/python/Lib/distutils/cmd.py | 4 | 19410 | """distutils.cmd
Provides the Command class, the base class for the command classes
in the distutils.command package.
"""
# created 2000/04/03, Greg Ward
# (extricated from core.py; actually dates back to the beginning)
__revision__ = "$Id: cmd.py,v 1.25 2000/09/26 02:12:31 gward Exp $"
import sys, os, string, re
from types import *
from distutils.errors import *
from distutils import util, dir_util, file_util, archive_util, dep_util
class Command:
"""Abstract base class for defining command classes, the "worker bees"
of the Distutils. A useful analogy for command classes is to think of
them as subroutines with local variables called "options". The options
are "declared" in 'initialize_options()' and "defined" (given their
final values, aka "finalized") in 'finalize_options()', both of which
must be defined by every command class. The distinction between the
two is necessary because option values might come from the outside
world (command line, config file, ...), and any options dependent on
other options must be computed *after* these outside influences have
been processed -- hence 'finalize_options()'. The "body" of the
subroutine, where it does all its work based on the values of its
options, is the 'run()' method, which must also be implemented by every
command class.
"""
# 'sub_commands' formalizes the notion of a "family" of commands,
# eg. "install" as the parent with sub-commands "install_lib",
# "install_headers", etc. The parent of a family of commands
# defines 'sub_commands' as a class attribute; it's a list of
# (command_name : string, predicate : unbound_method | string | None)
# tuples, where 'predicate' is a method of the parent command that
# determines whether the corresponding command is applicable in the
# current situation. (Eg. we "install_headers" is only applicable if
# we have any C header files to install.) If 'predicate' is None,
# that command is always applicable.
#
# 'sub_commands' is usually defined at the *end* of a class, because
# predicates can be unbound methods, so they must already have been
# defined. The canonical example is the "install" command.
sub_commands = []
# -- Creation/initialization methods -------------------------------
def __init__ (self, dist):
"""Create and initialize a new Command object. Most importantly,
invokes the 'initialize_options()' method, which is the real
initializer and depends on the actual command being
instantiated.
"""
# late import because of mutual dependence between these classes
from distutils.dist import Distribution
if not isinstance(dist, Distribution):
raise TypeError, "dist must be a Distribution instance"
if self.__class__ is Command:
raise RuntimeError, "Command is an abstract class"
self.distribution = dist
self.initialize_options()
# Per-command versions of the global flags, so that the user can
# customize Distutils' behaviour command-by-command and let some
# commands fallback on the Distribution's behaviour. None means
# "not defined, check self.distribution's copy", while 0 or 1 mean
# false and true (duh). Note that this means figuring out the real
# value of each flag is a touch complicated -- hence "self.verbose"
# (etc.) will be handled by __getattr__, below.
self._verbose = None
self._dry_run = None
# Some commands define a 'self.force' option to ignore file
# timestamps, but methods defined *here* assume that
# 'self.force' exists for all commands. So define it here
# just to be safe.
self.force = None
# The 'help' flag is just used for command-line parsing, so
# none of that complicated bureaucracy is needed.
self.help = 0
# 'finalized' records whether or not 'finalize_options()' has been
# called. 'finalize_options()' itself should not pay attention to
# this flag: it is the business of 'ensure_finalized()', which
# always calls 'finalize_options()', to respect/update it.
self.finalized = 0
# __init__ ()
def __getattr__ (self, attr):
if attr in ('verbose', 'dry_run'):
myval = getattr(self, "_" + attr)
if myval is None:
return getattr(self.distribution, attr)
else:
return myval
else:
raise AttributeError, attr
def ensure_finalized (self):
if not self.finalized:
self.finalize_options()
self.finalized = 1
# Subclasses must define:
# initialize_options()
# provide default values for all options; may be customized by
# setup script, by options from config file(s), or by command-line
# options
# finalize_options()
# decide on the final values for all options; this is called
# after all possible intervention from the outside world
# (command-line, option file, etc.) has been processed
# run()
# run the command: do whatever it is we're here to do,
# controlled by the command's various option values
def initialize_options (self):
"""Set default values for all the options that this command
supports. Note that these defaults may be overridden by other
commands, by the setup script, by config files, or by the
command-line. Thus, this is not the place to code dependencies
between options; generally, 'initialize_options()' implementations
are just a bunch of "self.foo = None" assignments.
This method must be implemented by all command classes.
"""
raise RuntimeError, \
"abstract method -- subclass %s must override" % self.__class__
def finalize_options (self):
"""Set final values for all the options that this command supports.
This is always called as late as possible, ie. after any option
assignments from the command-line or from other commands have been
done. Thus, this is the place to to code option dependencies: if
'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as
long as 'foo' still has the same value it was assigned in
'initialize_options()'.
This method must be implemented by all command classes.
"""
raise RuntimeError, \
"abstract method -- subclass %s must override" % self.__class__
def dump_options (self, header=None, indent=""):
from distutils.fancy_getopt import longopt_xlate
if header is None:
header = "command options for '%s':" % self.get_command_name()
print indent + header
indent = indent + " "
for (option, _, _) in self.user_options:
option = string.translate(option, longopt_xlate)
if option[-1] == "=":
option = option[:-1]
value = getattr(self, option)
print indent + "%s = %s" % (option, value)
def run (self):
"""A command's raison d'etre: carry out the action it exists to
perform, controlled by the options initialized in
'initialize_options()', customized by other commands, the setup
script, the command-line, and config files, and finalized in
'finalize_options()'. All terminal output and filesystem
interaction should be done by 'run()'.
This method must be implemented by all command classes.
"""
raise RuntimeError, \
"abstract method -- subclass %s must override" % self.__class__
def announce (self, msg, level=1):
"""If the current verbosity level is of greater than or equal to
'level' print 'msg' to stdout.
"""
if self.verbose >= level:
print msg
def debug_print (self, msg):
"""Print 'msg' to stdout if the global DEBUG (taken from the
DISTUTILS_DEBUG environment variable) flag is true.
"""
from distutils.core import DEBUG
if DEBUG:
print msg
# -- Option validation methods -------------------------------------
# (these are very handy in writing the 'finalize_options()' method)
#
# NB. the general philosophy here is to ensure that a particular option
# value meets certain type and value constraints. If not, we try to
# force it into conformance (eg. if we expect a list but have a string,
# split the string on comma and/or whitespace). If we can't force the
# option into conformance, raise DistutilsOptionError. Thus, command
# classes need do nothing more than (eg.)
# self.ensure_string_list('foo')
# and they can be guaranteed that thereafter, self.foo will be
# a list of strings.
def _ensure_stringlike (self, option, what, default=None):
val = getattr(self, option)
if val is None:
setattr(self, option, default)
return default
elif type(val) is not StringType:
raise DistutilsOptionError, \
"'%s' must be a %s (got `%s`)" % (option, what, val)
return val
def ensure_string (self, option, default=None):
"""Ensure that 'option' is a string; if not defined, set it to
'default'.
"""
self._ensure_stringlike(option, "string", default)
def ensure_string_list (self, option):
"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
"""
val = getattr(self, option)
if val is None:
return
elif type(val) is StringType:
setattr(self, option, re.split(r',\s*|\s+', val))
else:
if type(val) is ListType:
types = map(type, val)
ok = (types == [StringType] * len(val))
else:
ok = 0
if not ok:
raise DistutilsOptionError, \
"'%s' must be a list of strings (got %s)" % \
(option, `val`)
def _ensure_tested_string (self, option, tester,
what, error_fmt, default=None):
val = self._ensure_stringlike(option, what, default)
if val is not None and not tester(val):
raise DistutilsOptionError, \
("error in '%s' option: " + error_fmt) % (option, val)
def ensure_filename (self, option):
"""Ensure that 'option' is the name of an existing file."""
self._ensure_tested_string(option, os.path.isfile,
"filename",
"'%s' does not exist or is not a file")
def ensure_dirname (self, option):
self._ensure_tested_string(option, os.path.isdir,
"directory name",
"'%s' does not exist or is not a directory")
# -- Convenience methods for commands ------------------------------
def get_command_name (self):
if hasattr(self, 'command_name'):
return self.command_name
else:
return self.__class__.__name__
def set_undefined_options (self, src_cmd, *option_pairs):
"""Set the values of any "undefined" options from corresponding
option values in some other command object. "Undefined" here means
"is None", which is the convention used to indicate that an option
has not been changed between 'initialize_options()' and
'finalize_options()'. Usually called from 'finalize_options()' for
options that depend on some other command rather than another
option of the same command. 'src_cmd' is the other command from
which option values will be taken (a command object will be created
for it if necessary); the remaining arguments are
'(src_option,dst_option)' tuples which mean "take the value of
'src_option' in the 'src_cmd' command object, and copy it to
'dst_option' in the current command object".
"""
# Option_pairs: list of (src_option, dst_option) tuples
src_cmd_obj = self.distribution.get_command_obj(src_cmd)
src_cmd_obj.ensure_finalized()
for (src_option, dst_option) in option_pairs:
if getattr(self, dst_option) is None:
setattr(self, dst_option,
getattr(src_cmd_obj, src_option))
def get_finalized_command (self, command, create=1):
"""Wrapper around Distribution's 'get_command_obj()' method: find
(create if necessary and 'create' is true) the command object for
'command', call its 'ensure_finalized()' method, and return the
finalized command object.
"""
cmd_obj = self.distribution.get_command_obj(command, create)
cmd_obj.ensure_finalized()
return cmd_obj
# XXX rename to 'get_reinitialized_command()'? (should do the
# same in dist.py, if so)
def reinitialize_command (self, command, reinit_subcommands=0):
return self.distribution.reinitialize_command(
command, reinit_subcommands)
def run_command (self, command):
"""Run some other command: uses the 'run_command()' method of
Distribution, which creates and finalizes the command object if
necessary and then invokes its 'run()' method.
"""
self.distribution.run_command(command)
def get_sub_commands (self):
"""Determine the sub-commands that are relevant in the current
distribution (ie., that need to be run). This is based on the
'sub_commands' class attribute: each tuple in that list may include
a method that we call to determine if the subcommand needs to be
run for the current distribution. Return a list of command names.
"""
commands = []
for (cmd_name, method) in self.sub_commands:
if method is None or method(self):
commands.append(cmd_name)
return commands
# -- External world manipulation -----------------------------------
def warn (self, msg):
sys.stderr.write("warning: %s: %s\n" %
(self.get_command_name(), msg))
def execute (self, func, args, msg=None, level=1):
util.execute(func, args, msg, self.verbose >= level, self.dry_run)
def mkpath (self, name, mode=0777):
dir_util.mkpath(name, mode,
self.verbose, self.dry_run)
def copy_file (self, infile, outfile,
preserve_mode=1, preserve_times=1, link=None, level=1):
"""Copy a file respecting verbose, dry-run and force flags. (The
former two default to whatever is in the Distribution object, and
the latter defaults to false for commands that don't define it.)"""
return file_util.copy_file(
infile, outfile,
preserve_mode, preserve_times,
not self.force,
link,
self.verbose >= level,
self.dry_run)
def copy_tree (self, infile, outfile,
preserve_mode=1, preserve_times=1, preserve_symlinks=0,
level=1):
"""Copy an entire directory tree respecting verbose, dry-run,
and force flags.
"""
return dir_util.copy_tree(
infile, outfile,
preserve_mode,preserve_times,preserve_symlinks,
not self.force,
self.verbose >= level,
self.dry_run)
def move_file (self, src, dst, level=1):
"""Move a file respecting verbose and dry-run flags."""
return file_util.move_file(src, dst,
self.verbose >= level,
self.dry_run)
def spawn (self, cmd, search_path=1, level=1):
"""Spawn an external command respecting verbose and dry-run flags."""
from distutils.spawn import spawn
spawn(cmd, search_path,
self.verbose >= level,
self.dry_run)
def make_archive (self, base_name, format,
root_dir=None, base_dir=None):
return archive_util.make_archive(
base_name, format, root_dir, base_dir,
self.verbose, self.dry_run)
def make_file (self, infiles, outfile, func, args,
exec_msg=None, skip_msg=None, level=1):
"""Special case of 'execute()' for operations that process one or
more input files and generate one output file. Works just like
'execute()', except the operation is skipped and a different
message printed if 'outfile' already exists and is newer than all
files listed in 'infiles'. If the command defined 'self.force',
and it is true, then the command is unconditionally run -- does no
timestamp checks.
"""
if exec_msg is None:
exec_msg = "generating %s from %s" % \
(outfile, string.join(infiles, ', '))
if skip_msg is None:
skip_msg = "skipping %s (inputs unchanged)" % outfile
# Allow 'infiles' to be a single string
if type(infiles) is StringType:
infiles = (infiles,)
elif type(infiles) not in (ListType, TupleType):
raise TypeError, \
"'infiles' must be a string, or a list or tuple of strings"
# If 'outfile' must be regenerated (either because it doesn't
# exist, is out-of-date, or the 'force' flag is true) then
# perform the action that presumably regenerates it
if self.force or dep_util.newer_group (infiles, outfile):
self.execute(func, args, exec_msg, level)
# Otherwise, print the "skip" message
else:
self.announce(skip_msg, level)
# make_file ()
# class Command
# XXX 'install_misc' class not currently used -- it was the base class for
# both 'install_scripts' and 'install_data', but they outgrew it. It might
# still be useful for 'install_headers', though, so I'm keeping it around
# for the time being.
class install_misc (Command):
"""Common base class for installing some files in a subdirectory.
Currently used by install_data and install_scripts.
"""
user_options = [('install-dir=', 'd', "directory to install the files to")]
def initialize_options (self):
self.install_dir = None
self.outfiles = []
def _install_dir_from (self, dirname):
self.set_undefined_options('install', (dirname, 'install_dir'))
def _copy_files (self, filelist):
self.outfiles = []
if not filelist:
return
self.mkpath(self.install_dir)
for f in filelist:
self.copy_file(f, self.install_dir)
self.outfiles.append(os.path.join(self.install_dir, f))
def get_outputs (self):
return self.outfiles
if __name__ == "__main__":
print "ok"
| gpl-2.0 | 4,063,554,653,729,518,000 | 39.103306 | 79 | 0.604225 | false |
midma101/AndIWasJustGoingToBed | .venv/lib/python2.7/site-packages/paramiko/agent.py | 7 | 12321 | # Copyright (C) 2003-2007 John Rochester <[email protected]>
#
# This file is part of paramiko.
#
# Paramiko 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.
#
# Paramiko 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 Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
"""
SSH Agent interface for Unix clients.
"""
import os
import socket
import struct
import sys
import threading
import time
import tempfile
import stat
from select import select
from paramiko.ssh_exception import SSHException
from paramiko.message import Message
from paramiko.pkey import PKey
from paramiko.channel import Channel
from paramiko.common import io_sleep
from paramiko.util import retry_on_signal
SSH2_AGENTC_REQUEST_IDENTITIES, SSH2_AGENT_IDENTITIES_ANSWER, \
SSH2_AGENTC_SIGN_REQUEST, SSH2_AGENT_SIGN_RESPONSE = range(11, 15)
class AgentSSH(object):
"""
Client interface for using private keys from an SSH agent running on the
local machine. If an SSH agent is running, this class can be used to
connect to it and retreive L{PKey} objects which can be used when
attempting to authenticate to remote SSH servers.
Because the SSH agent protocol uses environment variables and unix-domain
sockets, this probably doesn't work on Windows. It does work on most
posix platforms though (Linux and MacOS X, for example).
"""
def __init__(self):
self._conn = None
self._keys = ()
def get_keys(self):
"""
Return the list of keys available through the SSH agent, if any. If
no SSH agent was running (or it couldn't be contacted), an empty list
will be returned.
@return: a list of keys available on the SSH agent
@rtype: tuple of L{AgentKey}
"""
return self._keys
def _connect(self, conn):
self._conn = conn
ptype, result = self._send_message(chr(SSH2_AGENTC_REQUEST_IDENTITIES))
if ptype != SSH2_AGENT_IDENTITIES_ANSWER:
raise SSHException('could not get keys from ssh-agent')
keys = []
for i in range(result.get_int()):
keys.append(AgentKey(self, result.get_string()))
result.get_string()
self._keys = tuple(keys)
def _close(self):
#self._conn.close()
self._conn = None
self._keys = ()
def _send_message(self, msg):
msg = str(msg)
self._conn.send(struct.pack('>I', len(msg)) + msg)
l = self._read_all(4)
msg = Message(self._read_all(struct.unpack('>I', l)[0]))
return ord(msg.get_byte()), msg
def _read_all(self, wanted):
result = self._conn.recv(wanted)
while len(result) < wanted:
if len(result) == 0:
raise SSHException('lost ssh-agent')
extra = self._conn.recv(wanted - len(result))
if len(extra) == 0:
raise SSHException('lost ssh-agent')
result += extra
return result
class AgentProxyThread(threading.Thread):
""" Class in charge of communication between two chan """
def __init__(self, agent):
threading.Thread.__init__(self, target=self.run)
self._agent = agent
self._exit = False
def run(self):
try:
(r,addr) = self.get_connection()
self.__inr = r
self.__addr = addr
self._agent.connect()
self._communicate()
except:
#XXX Not sure what to do here ... raise or pass ?
raise
def _communicate(self):
import fcntl
oldflags = fcntl.fcntl(self.__inr, fcntl.F_GETFL)
fcntl.fcntl(self.__inr, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
while not self._exit:
events = select([self._agent._conn, self.__inr], [], [], 0.5)
for fd in events[0]:
if self._agent._conn == fd:
data = self._agent._conn.recv(512)
if len(data) != 0:
self.__inr.send(data)
else:
self._close()
break
elif self.__inr == fd:
data = self.__inr.recv(512)
if len(data) != 0:
self._agent._conn.send(data)
else:
self._close()
break
time.sleep(io_sleep)
def _close(self):
self._exit = True
self.__inr.close()
self._agent._conn.close()
class AgentLocalProxy(AgentProxyThread):
"""
Class to be used when wanting to ask a local SSH Agent being
asked from a remote fake agent (so use a unix socket for ex.)
"""
def __init__(self, agent):
AgentProxyThread.__init__(self, agent)
def get_connection(self):
""" Return a pair of socket object and string address
May Block !
"""
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
conn.bind(self._agent._get_filename())
conn.listen(1)
(r,addr) = conn.accept()
return (r, addr)
except:
raise
return None
class AgentRemoteProxy(AgentProxyThread):
"""
Class to be used when wanting to ask a remote SSH Agent
"""
def __init__(self, agent, chan):
AgentProxyThread.__init__(self, agent)
self.__chan = chan
def get_connection(self):
"""
Class to be used when wanting to ask a local SSH Agent being
asked from a remote fake agent (so use a unix socket for ex.)
"""
return (self.__chan, None)
class AgentClientProxy(object):
"""
Class proxying request as a client:
-> client ask for a request_forward_agent()
-> server creates a proxy and a fake SSH Agent
-> server ask for establishing a connection when needed,
calling the forward_agent_handler at client side.
-> the forward_agent_handler launch a thread for connecting
the remote fake agent and the local agent
-> Communication occurs ...
"""
def __init__(self, chanRemote):
self._conn = None
self.__chanR = chanRemote
self.thread = AgentRemoteProxy(self, chanRemote)
self.thread.start()
def __del__(self):
self.close()
def connect(self):
"""
Method automatically called by the run() method of the AgentProxyThread
"""
if ('SSH_AUTH_SOCK' in os.environ) and (sys.platform != 'win32'):
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
retry_on_signal(lambda: conn.connect(os.environ['SSH_AUTH_SOCK']))
except:
# probably a dangling env var: the ssh agent is gone
return
elif sys.platform == 'win32':
import win_pageant
if win_pageant.can_talk_to_agent():
conn = win_pageant.PageantConnection()
else:
return
else:
# no agent support
return
self._conn = conn
def close(self):
"""
Close the current connection and terminate the agent
Should be called manually
"""
if hasattr(self, "thread"):
self.thread._exit = True
self.thread.join(1000)
if self._conn is not None:
self._conn.close()
class AgentServerProxy(AgentSSH):
"""
@param t : transport used for the Forward for SSH Agent communication
@raise SSHException: mostly if we lost the agent
"""
def __init__(self, t):
AgentSSH.__init__(self)
self.__t = t
self._dir = tempfile.mkdtemp('sshproxy')
os.chmod(self._dir, stat.S_IRWXU)
self._file = self._dir + '/sshproxy.ssh'
self.thread = AgentLocalProxy(self)
self.thread.start()
def __del__(self):
self.close()
def connect(self):
conn_sock = self.__t.open_forward_agent_channel()
if conn_sock is None:
raise SSHException('lost ssh-agent')
conn_sock.set_name('auth-agent')
self._connect(conn_sock)
def close(self):
"""
Terminate the agent, clean the files, close connections
Should be called manually
"""
os.remove(self._file)
os.rmdir(self._dir)
self.thread._exit = True
self.thread.join(1000)
self._close()
def get_env(self):
"""
Helper for the environnement under unix
@return: the SSH_AUTH_SOCK Environnement variables
@rtype: dict
"""
env = {}
env['SSH_AUTH_SOCK'] = self._get_filename()
return env
def _get_filename(self):
return self._file
class AgentRequestHandler(object):
def __init__(self, chanClient):
self._conn = None
self.__chanC = chanClient
chanClient.request_forward_agent(self._forward_agent_handler)
self.__clientProxys = []
def _forward_agent_handler(self, chanRemote):
self.__clientProxys.append(AgentClientProxy(chanRemote))
def __del__(self):
self.close()
def close(self):
for p in self.__clientProxys:
p.close()
class Agent(AgentSSH):
"""
Client interface for using private keys from an SSH agent running on the
local machine. If an SSH agent is running, this class can be used to
connect to it and retreive L{PKey} objects which can be used when
attempting to authenticate to remote SSH servers.
Because the SSH agent protocol uses environment variables and unix-domain
sockets, this probably doesn't work on Windows. It does work on most
posix platforms though (Linux and MacOS X, for example).
"""
def __init__(self):
"""
Open a session with the local machine's SSH agent, if one is running.
If no agent is running, initialization will succeed, but L{get_keys}
will return an empty tuple.
@raise SSHException: if an SSH agent is found, but speaks an
incompatible protocol
"""
AgentSSH.__init__(self)
if ('SSH_AUTH_SOCK' in os.environ) and (sys.platform != 'win32'):
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
conn.connect(os.environ['SSH_AUTH_SOCK'])
except:
# probably a dangling env var: the ssh agent is gone
return
elif sys.platform == 'win32':
import win_pageant
if win_pageant.can_talk_to_agent():
conn = win_pageant.PageantConnection()
else:
return
else:
# no agent support
return
self._connect(conn)
def close(self):
"""
Close the SSH agent connection.
"""
self._close()
class AgentKey(PKey):
"""
Private key held in a local SSH agent. This type of key can be used for
authenticating to a remote server (signing). Most other key operations
work as expected.
"""
def __init__(self, agent, blob):
self.agent = agent
self.blob = blob
self.name = Message(blob).get_string()
def __str__(self):
return self.blob
def get_name(self):
return self.name
def sign_ssh_data(self, rng, data):
msg = Message()
msg.add_byte(chr(SSH2_AGENTC_SIGN_REQUEST))
msg.add_string(self.blob)
msg.add_string(data)
msg.add_int(0)
ptype, result = self.agent._send_message(msg)
if ptype != SSH2_AGENT_SIGN_RESPONSE:
raise SSHException('key cannot be used for signing')
return result.get_string()
| mit | 1,747,289,928,490,454,800 | 31.423684 | 82 | 0.586073 | false |
yanchen036/tensorflow | tensorflow/contrib/distributions/python/ops/bijectors/affine_scalar.py | 3 | 4227 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Affine bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops.distributions import bijector
__all__ = [
"AffineScalar",
]
class AffineScalar(bijector.Bijector):
"""Compute `Y = g(X; shift, scale) = scale * X + shift`.
Examples:
```python
# Y = X
b = AffineScalar()
# Y = X + shift
b = AffineScalar(shift=[1., 2, 3])
# Y = 2 * X + shift
b = AffineScalar(
shift=[1., 2, 3],
scale=2.)
```
"""
def __init__(self,
shift=None,
scale=None,
validate_args=False,
name="affine_scalar"):
"""Instantiates the `AffineScalar` bijector.
This `Bijector` is initialized with `shift` `Tensor` and `scale` arguments,
giving the forward operation:
```none
Y = g(X) = scale * X + shift
```
if `scale` is not specified, then the bijector has the semantics of
`scale = 1.`. Similarly, if `shift` is not specified, then the bijector
has the semantics of `shift = 0.`.
Args:
shift: Floating-point `Tensor`. If this is set to `None`, no shift is
applied.
scale: Floating-point `Tensor`. If this is set to `None`, no scale is
applied.
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.
"""
self._graph_parents = []
self._name = name
self._validate_args = validate_args
with self._name_scope("init", values=[scale, shift]):
self._shift = shift
self._scale = scale
if self._shift is not None:
self._shift = ops.convert_to_tensor(shift, name="shift")
if self._scale is not None:
self._scale = ops.convert_to_tensor(self._scale, name="scale")
if validate_args:
self._scale = control_flow_ops.with_dependencies(
[check_ops.assert_none_equal(
self._scale,
array_ops.zeros([], dtype=self._scale.dtype))],
self._scale)
super(AffineScalar, self).__init__(
forward_min_event_ndims=0,
is_constant_jacobian=True,
validate_args=validate_args,
name=name)
@property
def shift(self):
"""The `shift` `Tensor` in `Y = scale @ X + shift`."""
return self._shift
@property
def scale(self):
"""The `scale` `LinearOperator` in `Y = scale @ X + shift`."""
return self._scale
def _forward(self, x):
y = array_ops.identity(x)
if self.scale is not None:
y *= self.scale
if self.shift is not None:
y += self.shift
return y
def _inverse(self, y):
x = array_ops.identity(y)
if self.shift is not None:
x -= self.shift
if self.scale is not None:
x /= self.scale
return x
def _forward_log_det_jacobian(self, x):
# is_constant_jacobian = True for this bijector, hence the
# `log_det_jacobian` need only be specified for a single input, as this will
# be tiled to match `event_ndims`.
if self.scale is None:
return constant_op.constant(0., dtype=x.dtype.base_dtype)
return math_ops.log(math_ops.abs(self.scale))
| apache-2.0 | -6,396,973,251,379,227,000 | 28.978723 | 80 | 0.625739 | false |
strogo/djpcms | djpcms/migrations/0003_auto__add_field_blockcontent_for_not_authenticated.py | 1 | 10859 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'BlockContent.for_not_authenticated'
db.add_column('djpcms_blockcontent', 'for_not_authenticated', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False)
def backwards(self, orm):
# Deleting field 'BlockContent.for_not_authenticated'
db.delete_column('djpcms_blockcontent', 'for_not_authenticated')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'djpcms.additionalpagedata': {
'Meta': {'object_name': 'AdditionalPageData'},
'body': ('django.db.models.fields.TextField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'additionaldata'", 'to': "orm['djpcms.Page']"}),
'where': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'})
},
'djpcms.blockcontent': {
'Meta': {'ordering': "('page', 'block', 'position')", 'unique_together': "(('page', 'block', 'position'),)", 'object_name': 'BlockContent'},
'arguments': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'block': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),
'container_type': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
'for_not_authenticated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'page': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'blockcontents'", 'to': "orm['djpcms.Page']"}),
'plugin_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'position': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'})
},
'djpcms.csspageinfo': {
'Meta': {'object_name': 'CssPageInfo'},
'body_class_name': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}),
'container_class_name': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'fixed': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'gridsize': ('django.db.models.fields.PositiveIntegerField', [], {'default': '12'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
},
'djpcms.innertemplate': {
'Meta': {'object_name': 'InnerTemplate'},
'blocks': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'template': ('django.db.models.fields.TextField', [], {'blank': 'True'})
},
'djpcms.page': {
'Meta': {'object_name': 'Page'},
'application': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
'code_object': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'cssinfo': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['djpcms.CssPageInfo']", 'null': 'True', 'blank': 'True'}),
'doctype': ('django.db.models.fields.PositiveIntegerField', [], {'default': '4'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_navigation': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}),
'inner_template': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['djpcms.InnerTemplate']", 'null': 'True', 'blank': 'True'}),
'insitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'level': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'link': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['djpcms.Page']"}),
'redirect_to': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'redirected_from'", 'null': 'True', 'to': "orm['djpcms.Page']"}),
'requires_login': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'soft_root': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'template': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '60', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'max_length': '1000'}),
'url_pattern': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
},
'djpcms.sitecontent': {
'Meta': {'ordering': "('code',)", 'object_name': 'SiteContent'},
'body': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'code': ('djpcms.fields.SlugCode', [], {'unique': 'True', 'max_length': '64'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'markup': ('django.db.models.fields.CharField', [], {'max_length': '3', 'blank': 'True'}),
'user_last': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
},
'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
}
}
complete_apps = ['djpcms']
| bsd-3-clause | 461,357,308,424,885,440 | 76.014184 | 182 | 0.551064 | false |
user-none/calibre | src/calibre/gui2/preferences/ignored_devices.py | 14 | 3695 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:fdm=marker:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import (QLabel, QVBoxLayout, QListWidget, QListWidgetItem, Qt,
QIcon)
from calibre.customize.ui import enable_plugin
from calibre.gui2.preferences import ConfigWidgetBase, test_widget
class ConfigWidget(ConfigWidgetBase):
restart_critical = False
def genesis(self, gui):
self.gui = gui
self.l = l = QVBoxLayout()
self.setLayout(l)
self.la = la = QLabel(_(
'The list of devices that you have asked calibre to ignore. '
'Uncheck a device to have calibre stop ignoring it.'))
la.setWordWrap(True)
l.addWidget(la)
self.devices = f = QListWidget(self)
l.addWidget(f)
f.itemChanged.connect(self.changed_signal)
f.itemDoubleClicked.connect(self.toggle_item)
self.la2 = la = QLabel(_(
'The list of device plugins you have disabled. Uncheck an entry '
'to enable the plugin. calibre cannot detect devices that are '
'managed by disabled plugins.'))
la.setWordWrap(True)
l.addWidget(la)
self.device_plugins = f = QListWidget(f)
l.addWidget(f)
f.itemChanged.connect(self.changed_signal)
f.itemDoubleClicked.connect(self.toggle_item)
def toggle_item(self, item):
item.setCheckState(Qt.Checked if item.checkState() == Qt.Unchecked else
Qt.Unchecked)
def initialize(self):
self.devices.blockSignals(True)
self.devices.clear()
for dev in self.gui.device_manager.devices:
for d, name in dev.get_user_blacklisted_devices().iteritems():
item = QListWidgetItem('%s [%s]'%(name, d), self.devices)
item.setData(Qt.UserRole, (dev, d))
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
item.setCheckState(Qt.Checked)
self.devices.blockSignals(False)
self.device_plugins.blockSignals(True)
for dev in self.gui.device_manager.disabled_device_plugins:
n = dev.get_gui_name()
item = QListWidgetItem(n, self.device_plugins)
item.setData(Qt.UserRole, dev)
item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable|Qt.ItemIsSelectable)
item.setCheckState(Qt.Checked)
item.setIcon(QIcon(I('plugins.png')))
self.device_plugins.sortItems()
self.device_plugins.blockSignals(False)
def restore_defaults(self):
if self.devices.count() > 0:
self.devices.clear()
def commit(self):
devs = {}
for i in xrange(0, self.devices.count()):
e = self.devices.item(i)
dev, uid = e.data(Qt.UserRole)
if dev not in devs:
devs[dev] = []
if e.checkState() == Qt.Checked:
devs[dev].append(uid)
for dev, bl in devs.iteritems():
dev.set_user_blacklisted_devices(bl)
for i in xrange(self.device_plugins.count()):
e = self.device_plugins.item(i)
dev = e.data(Qt.UserRole)
if e.checkState() == Qt.Unchecked:
enable_plugin(dev)
return True # Restart required
if __name__ == '__main__':
from PyQt5.Qt import QApplication
app = QApplication([])
test_widget('Sharing', 'Ignored Devices')
| gpl-3.0 | -6,033,297,496,390,095,000 | 34.873786 | 90 | 0.606225 | false |
lao605/product-definition-center | pdc/apps/changeset/tests.py | 4 | 5753 | #
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
from mock import Mock, call, patch
from django.test import TestCase
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from .middleware import ChangesetMiddleware
from .middleware import logger as changeset_logger
class ChangesetMiddlewareTestCase(TestCase):
def setUp(self):
self.cm = ChangesetMiddleware()
self.request = Mock()
setattr(self.request, "method", "POST")
def test_passing_arguments(self):
self.request.user.is_authenticated = lambda: False
self.request.META.get = lambda x, y: y
func = Mock()
func.__name__ = "Mock"
func.return_value = 123
with patch("pdc.apps.changeset.models.Changeset") as changeset:
ret = self.cm.process_view(self.request, func, [1, 2, 3], {'arg': 'val'})
self.assertTrue(func.called)
self.assertEqual(ret, 123)
self.assertEqual(func.call_args, call(self.request, 1, 2, 3, arg='val'))
self.assertEqual(changeset.mock_calls, [call(author=None, comment=None), call().commit()])
def test_no_commit_with_exception(self):
self.request.user.is_authenticated = lambda: False
self.request.META.get = lambda x, y: y
func = Mock()
func.__name__ = "Mock"
func.side_effect = Exception("Boom!")
changeset_logger.error = Mock()
with patch("pdc.apps.changeset.models.Changeset") as changeset:
self.assertRaises(Exception, self.cm.process_view, self.request, func, [], {})
self.assertTrue(func.called)
self.assertEqual(changeset.mock_calls, [call(author=None, comment=None)])
self.assertTrue(changeset_logger.error.called)
class ChangesetRESTTestCase(APITestCase):
fixtures = ['pdc/apps/changeset/fixtures/tests/changeset.json',
"pdc/apps/component/fixtures/tests/bugzilla_component.json"]
def test_get(self):
url = reverse('changeset-detail', args=[1])
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data.get('changes')), 2)
self.assertEqual(response.data.get("id"), 1)
def test_list_order(self):
url = reverse('changeset-list')
response = self.client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
results = response.data.get('results')
self.assertTrue(results[0].get('committed_on') > results[1].get('committed_on'))
def test_query(self):
url = reverse('changeset-list')
response = self.client.get(url + '?resource=contact', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['count'], 1)
def test_query_with_multiple_values(self):
url = reverse('changeset-list')
response = self.client.get(url + '?resource=contact&resource=person', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['count'], 2)
def test_query_with_wrong_resource(self):
url = reverse('changeset-list')
response = self.client.get(url + '?resource=nonexists', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['count'], 0)
def test_query_with_correct_datetimeformat(self):
url = reverse('changeset-list')
response = self.client.get(url + '?changed_since=2015-02-03T02:55:18', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['count'], 1)
def test_query_with_incorrect_datetimeformat(self):
url = reverse('changeset-list')
response = self.client.get(url + '?changed_since=20150203T02:55:18', format='json')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_query_with_pdc_change_comment(self):
url = reverse('changeset-list')
response = self.client.get(url + '?comment=change', format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['count'], 1)
def test_create_with_pdc_change_comment(self):
url = reverse('bugzillacomponent-list')
data = {'name': 'bin', 'parent_pk': 1}
extra = {'HTTP_PDC_CHANGE_COMMENT': 'New bugzilla component'}
response = self.client.post(url, data, format='json', **extra)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
url1 = reverse('changeset-list')
response1 = self.client.get(url1 + '?comment=new', format='json')
self.assertEqual(response1.status_code, status.HTTP_200_OK)
self.assertEqual(response1.data['count'], 1)
def test_bulk_create_with_pdc_change_comment(self):
url = reverse('bugzillacomponent-list')
data = [{'name': 'bin', 'parent_pk': 1}, {'name': 'bin1', 'parent_pk': 2}]
extra = {'HTTP_PDC_CHANGE_COMMENT': 'New bugzilla components'}
response = self.client.post(url, data, format='json', **extra)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
url1 = reverse('changeset-list')
response1 = self.client.get(url1 + '?comment=components', format='json')
self.assertEqual(response1.status_code, status.HTTP_200_OK)
self.assertEqual(response1.data['count'], 1)
self.assertEqual(len(response1.data.get('results')[0].get('changes')), 2)
| mit | -2,710,370,780,748,330,000 | 41.614815 | 102 | 0.654267 | false |
google/llvm-propeller | llvm/utils/lit/lit/TestRunner.py | 3 | 61152 | from __future__ import absolute_import
import errno
import io
import itertools
import getopt
import os, signal, subprocess, sys
import re
import stat
import platform
import shutil
import tempfile
import threading
import io
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from lit.ShCommands import GlobItem, Command
import lit.ShUtil as ShUtil
import lit.Test as Test
import lit.util
from lit.util import to_bytes, to_string, to_unicode
from lit.BooleanExpression import BooleanExpression
class InternalShellError(Exception):
def __init__(self, command, message):
self.command = command
self.message = message
kIsWindows = platform.system() == 'Windows'
# Don't use close_fds on Windows.
kUseCloseFDs = not kIsWindows
# Use temporary files to replace /dev/null on Windows.
kAvoidDevNull = kIsWindows
kDevNull = "/dev/null"
# A regex that matches %dbg(ARG), which lit inserts at the beginning of each
# run command pipeline such that ARG specifies the pipeline's source line
# number. lit later expands each %dbg(ARG) to a command that behaves as a null
# command in the target shell so that the line number is seen in lit's verbose
# mode.
#
# This regex captures ARG. ARG must not contain a right parenthesis, which
# terminates %dbg. ARG must not contain quotes, in which ARG might be enclosed
# during expansion.
kPdbgRegex = '%dbg\\(([^)\'"]*)\\)'
class ShellEnvironment(object):
"""Mutable shell environment containing things like CWD and env vars.
Environment variables are not implemented, but cwd tracking is.
"""
def __init__(self, cwd, env):
self.cwd = cwd
self.env = dict(env)
class TimeoutHelper(object):
"""
Object used to helper manage enforcing a timeout in
_executeShCmd(). It is passed through recursive calls
to collect processes that have been executed so that when
the timeout happens they can be killed.
"""
def __init__(self, timeout):
self.timeout = timeout
self._procs = []
self._timeoutReached = False
self._doneKillPass = False
# This lock will be used to protect concurrent access
# to _procs and _doneKillPass
self._lock = None
self._timer = None
def cancel(self):
if not self.active():
return
self._timer.cancel()
def active(self):
return self.timeout > 0
def addProcess(self, proc):
if not self.active():
return
needToRunKill = False
with self._lock:
self._procs.append(proc)
# Avoid re-entering the lock by finding out if kill needs to be run
# again here but call it if necessary once we have left the lock.
# We could use a reentrant lock here instead but this code seems
# clearer to me.
needToRunKill = self._doneKillPass
# The initial call to _kill() from the timer thread already happened so
# we need to call it again from this thread, otherwise this process
# will be left to run even though the timeout was already hit
if needToRunKill:
assert self.timeoutReached()
self._kill()
def startTimer(self):
if not self.active():
return
# Do some late initialisation that's only needed
# if there is a timeout set
self._lock = threading.Lock()
self._timer = threading.Timer(self.timeout, self._handleTimeoutReached)
self._timer.start()
def _handleTimeoutReached(self):
self._timeoutReached = True
self._kill()
def timeoutReached(self):
return self._timeoutReached
def _kill(self):
"""
This method may be called multiple times as we might get unlucky
and be in the middle of creating a new process in _executeShCmd()
which won't yet be in ``self._procs``. By locking here and in
addProcess() we should be able to kill processes launched after
the initial call to _kill()
"""
with self._lock:
for p in self._procs:
lit.util.killProcessAndChildren(p.pid)
# Empty the list and note that we've done a pass over the list
self._procs = [] # Python2 doesn't have list.clear()
self._doneKillPass = True
class ShellCommandResult(object):
"""Captures the result of an individual command."""
def __init__(self, command, stdout, stderr, exitCode, timeoutReached,
outputFiles = []):
self.command = command
self.stdout = stdout
self.stderr = stderr
self.exitCode = exitCode
self.timeoutReached = timeoutReached
self.outputFiles = list(outputFiles)
def executeShCmd(cmd, shenv, results, timeout=0):
"""
Wrapper around _executeShCmd that handles
timeout
"""
# Use the helper even when no timeout is required to make
# other code simpler (i.e. avoid bunch of ``!= None`` checks)
timeoutHelper = TimeoutHelper(timeout)
if timeout > 0:
timeoutHelper.startTimer()
finalExitCode = _executeShCmd(cmd, shenv, results, timeoutHelper)
timeoutHelper.cancel()
timeoutInfo = None
if timeoutHelper.timeoutReached():
timeoutInfo = 'Reached timeout of {} seconds'.format(timeout)
return (finalExitCode, timeoutInfo)
def expand_glob(arg, cwd):
if isinstance(arg, GlobItem):
return sorted(arg.resolve(cwd))
return [arg]
def expand_glob_expressions(args, cwd):
result = [args[0]]
for arg in args[1:]:
result.extend(expand_glob(arg, cwd))
return result
def quote_windows_command(seq):
"""
Reimplement Python's private subprocess.list2cmdline for MSys compatibility
Based on CPython implementation here:
https://hg.python.org/cpython/file/849826a900d2/Lib/subprocess.py#l422
Some core util distributions (MSys) don't tokenize command line arguments
the same way that MSVC CRT does. Lit rolls its own quoting logic similar to
the stock CPython logic to paper over these quoting and tokenization rule
differences.
We use the same algorithm from MSDN as CPython
(http://msdn.microsoft.com/en-us/library/17w5ykft.aspx), but we treat more
characters as needing quoting, such as double quotes themselves.
"""
result = []
needquote = False
for arg in seq:
bs_buf = []
# Add a space to separate this argument from the others
if result:
result.append(' ')
# This logic differs from upstream list2cmdline.
needquote = (" " in arg) or ("\t" in arg) or ("\"" in arg) or not arg
if needquote:
result.append('"')
for c in arg:
if c == '\\':
# Don't know if we need to double yet.
bs_buf.append(c)
elif c == '"':
# Double backslashes.
result.append('\\' * len(bs_buf)*2)
bs_buf = []
result.append('\\"')
else:
# Normal char
if bs_buf:
result.extend(bs_buf)
bs_buf = []
result.append(c)
# Add remaining backslashes, if any.
if bs_buf:
result.extend(bs_buf)
if needquote:
result.extend(bs_buf)
result.append('"')
return ''.join(result)
# args are from 'export' or 'env' command.
# Skips the command, and parses its arguments.
# Modifies env accordingly.
# Returns copy of args without the command or its arguments.
def updateEnv(env, args):
arg_idx_next = len(args)
unset_next_env_var = False
for arg_idx, arg in enumerate(args[1:]):
# Support for the -u flag (unsetting) for env command
# e.g., env -u FOO -u BAR will remove both FOO and BAR
# from the environment.
if arg == '-u':
unset_next_env_var = True
continue
if unset_next_env_var:
unset_next_env_var = False
if arg in env.env:
del env.env[arg]
continue
# Partition the string into KEY=VALUE.
key, eq, val = arg.partition('=')
# Stop if there was no equals.
if eq == '':
arg_idx_next = arg_idx + 1
break
env.env[key] = val
return args[arg_idx_next:]
def executeBuiltinCd(cmd, shenv):
"""executeBuiltinCd - Change the current directory."""
if len(cmd.args) != 2:
raise InternalShellError("'cd' supports only one argument")
newdir = cmd.args[1]
# Update the cwd in the parent environment.
if os.path.isabs(newdir):
shenv.cwd = newdir
else:
shenv.cwd = os.path.realpath(os.path.join(shenv.cwd, newdir))
# The cd builtin always succeeds. If the directory does not exist, the
# following Popen calls will fail instead.
return ShellCommandResult(cmd, "", "", 0, False)
def executeBuiltinExport(cmd, shenv):
"""executeBuiltinExport - Set an environment variable."""
if len(cmd.args) != 2:
raise InternalShellError("'export' supports only one argument")
updateEnv(shenv, cmd.args)
return ShellCommandResult(cmd, "", "", 0, False)
def executeBuiltinEcho(cmd, shenv):
"""Interpret a redirected echo command"""
opened_files = []
stdin, stdout, stderr = processRedirects(cmd, subprocess.PIPE, shenv,
opened_files)
if stdin != subprocess.PIPE or stderr != subprocess.PIPE:
raise InternalShellError(
cmd, "stdin and stderr redirects not supported for echo")
# Some tests have un-redirected echo commands to help debug test failures.
# Buffer our output and return it to the caller.
is_redirected = True
encode = lambda x : x
if stdout == subprocess.PIPE:
is_redirected = False
stdout = StringIO()
elif kIsWindows:
# Reopen stdout in binary mode to avoid CRLF translation. The versions
# of echo we are replacing on Windows all emit plain LF, and the LLVM
# tests now depend on this.
# When we open as binary, however, this also means that we have to write
# 'bytes' objects to stdout instead of 'str' objects.
encode = lit.util.to_bytes
stdout = open(stdout.name, stdout.mode + 'b')
opened_files.append((None, None, stdout, None))
# Implement echo flags. We only support -e and -n, and not yet in
# combination. We have to ignore unknown flags, because `echo "-D FOO"`
# prints the dash.
args = cmd.args[1:]
interpret_escapes = False
write_newline = True
while len(args) >= 1 and args[0] in ('-e', '-n'):
flag = args[0]
args = args[1:]
if flag == '-e':
interpret_escapes = True
elif flag == '-n':
write_newline = False
def maybeUnescape(arg):
if not interpret_escapes:
return arg
arg = lit.util.to_bytes(arg)
codec = 'string_escape' if sys.version_info < (3,0) else 'unicode_escape'
return arg.decode(codec)
if args:
for arg in args[:-1]:
stdout.write(encode(maybeUnescape(arg)))
stdout.write(encode(' '))
stdout.write(encode(maybeUnescape(args[-1])))
if write_newline:
stdout.write(encode('\n'))
for (name, mode, f, path) in opened_files:
f.close()
output = "" if is_redirected else stdout.getvalue()
return ShellCommandResult(cmd, output, "", 0, False)
def executeBuiltinMkdir(cmd, cmd_shenv):
"""executeBuiltinMkdir - Create new directories."""
args = expand_glob_expressions(cmd.args, cmd_shenv.cwd)[1:]
try:
opts, args = getopt.gnu_getopt(args, 'p')
except getopt.GetoptError as err:
raise InternalShellError(cmd, "Unsupported: 'mkdir': %s" % str(err))
parent = False
for o, a in opts:
if o == "-p":
parent = True
else:
assert False, "unhandled option"
if len(args) == 0:
raise InternalShellError(cmd, "Error: 'mkdir' is missing an operand")
stderr = StringIO()
exitCode = 0
for dir in args:
cwd = cmd_shenv.cwd
dir = to_unicode(dir) if kIsWindows else to_bytes(dir)
cwd = to_unicode(cwd) if kIsWindows else to_bytes(cwd)
if not os.path.isabs(dir):
dir = os.path.realpath(os.path.join(cwd, dir))
if parent:
lit.util.mkdir_p(dir)
else:
try:
lit.util.mkdir(dir)
except OSError as err:
stderr.write("Error: 'mkdir' command failed, %s\n" % str(err))
exitCode = 1
return ShellCommandResult(cmd, "", stderr.getvalue(), exitCode, False)
def executeBuiltinRm(cmd, cmd_shenv):
"""executeBuiltinRm - Removes (deletes) files or directories."""
args = expand_glob_expressions(cmd.args, cmd_shenv.cwd)[1:]
try:
opts, args = getopt.gnu_getopt(args, "frR", ["--recursive"])
except getopt.GetoptError as err:
raise InternalShellError(cmd, "Unsupported: 'rm': %s" % str(err))
force = False
recursive = False
for o, a in opts:
if o == "-f":
force = True
elif o in ("-r", "-R", "--recursive"):
recursive = True
else:
assert False, "unhandled option"
if len(args) == 0:
raise InternalShellError(cmd, "Error: 'rm' is missing an operand")
def on_rm_error(func, path, exc_info):
# path contains the path of the file that couldn't be removed
# let's just assume that it's read-only and remove it.
os.chmod(path, stat.S_IMODE( os.stat(path).st_mode) | stat.S_IWRITE)
os.remove(path)
stderr = StringIO()
exitCode = 0
for path in args:
cwd = cmd_shenv.cwd
path = to_unicode(path) if kIsWindows else to_bytes(path)
cwd = to_unicode(cwd) if kIsWindows else to_bytes(cwd)
if not os.path.isabs(path):
path = os.path.realpath(os.path.join(cwd, path))
if force and not os.path.exists(path):
continue
try:
if os.path.isdir(path):
if not recursive:
stderr.write("Error: %s is a directory\n" % path)
exitCode = 1
if platform.system() == 'Windows':
# NOTE: use ctypes to access `SHFileOperationsW` on Windows to
# use the NT style path to get access to long file paths which
# cannot be removed otherwise.
from ctypes.wintypes import BOOL, HWND, LPCWSTR, UINT, WORD
from ctypes import addressof, byref, c_void_p, create_unicode_buffer
from ctypes import Structure
from ctypes import windll, WinError, POINTER
class SHFILEOPSTRUCTW(Structure):
_fields_ = [
('hWnd', HWND),
('wFunc', UINT),
('pFrom', LPCWSTR),
('pTo', LPCWSTR),
('fFlags', WORD),
('fAnyOperationsAborted', BOOL),
('hNameMappings', c_void_p),
('lpszProgressTitle', LPCWSTR),
]
FO_MOVE, FO_COPY, FO_DELETE, FO_RENAME = range(1, 5)
FOF_SILENT = 4
FOF_NOCONFIRMATION = 16
FOF_NOCONFIRMMKDIR = 512
FOF_NOERRORUI = 1024
FOF_NO_UI = FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR
SHFileOperationW = windll.shell32.SHFileOperationW
SHFileOperationW.argtypes = [POINTER(SHFILEOPSTRUCTW)]
path = os.path.abspath(path)
pFrom = create_unicode_buffer(path, len(path) + 2)
pFrom[len(path)] = pFrom[len(path) + 1] = '\0'
operation = SHFILEOPSTRUCTW(wFunc=UINT(FO_DELETE),
pFrom=LPCWSTR(addressof(pFrom)),
fFlags=FOF_NO_UI)
result = SHFileOperationW(byref(operation))
if result:
raise WinError(result)
else:
shutil.rmtree(path, onerror = on_rm_error if force else None)
else:
if force and not os.access(path, os.W_OK):
os.chmod(path,
stat.S_IMODE(os.stat(path).st_mode) | stat.S_IWRITE)
os.remove(path)
except OSError as err:
stderr.write("Error: 'rm' command failed, %s" % str(err))
exitCode = 1
return ShellCommandResult(cmd, "", stderr.getvalue(), exitCode, False)
def executeBuiltinColon(cmd, cmd_shenv):
"""executeBuiltinColon - Discard arguments and exit with status 0."""
return ShellCommandResult(cmd, "", "", 0, False)
def processRedirects(cmd, stdin_source, cmd_shenv, opened_files):
"""Return the standard fds for cmd after applying redirects
Returns the three standard file descriptors for the new child process. Each
fd may be an open, writable file object or a sentinel value from the
subprocess module.
"""
# Apply the redirections, we use (N,) as a sentinel to indicate stdin,
# stdout, stderr for N equal to 0, 1, or 2 respectively. Redirects to or
# from a file are represented with a list [file, mode, file-object]
# where file-object is initially None.
redirects = [(0,), (1,), (2,)]
for (op, filename) in cmd.redirects:
if op == ('>',2):
redirects[2] = [filename, 'w', None]
elif op == ('>>',2):
redirects[2] = [filename, 'a', None]
elif op == ('>&',2) and filename in '012':
redirects[2] = redirects[int(filename)]
elif op == ('>&',) or op == ('&>',):
redirects[1] = redirects[2] = [filename, 'w', None]
elif op == ('>',):
redirects[1] = [filename, 'w', None]
elif op == ('>>',):
redirects[1] = [filename, 'a', None]
elif op == ('<',):
redirects[0] = [filename, 'r', None]
else:
raise InternalShellError(cmd, "Unsupported redirect: %r" % ((op, filename),))
# Open file descriptors in a second pass.
std_fds = [None, None, None]
for (index, r) in enumerate(redirects):
# Handle the sentinel values for defaults up front.
if isinstance(r, tuple):
if r == (0,):
fd = stdin_source
elif r == (1,):
if index == 0:
raise InternalShellError(cmd, "Unsupported redirect for stdin")
elif index == 1:
fd = subprocess.PIPE
else:
fd = subprocess.STDOUT
elif r == (2,):
if index != 2:
raise InternalShellError(cmd, "Unsupported redirect on stdout")
fd = subprocess.PIPE
else:
raise InternalShellError(cmd, "Bad redirect")
std_fds[index] = fd
continue
(filename, mode, fd) = r
# Check if we already have an open fd. This can happen if stdout and
# stderr go to the same place.
if fd is not None:
std_fds[index] = fd
continue
redir_filename = None
name = expand_glob(filename, cmd_shenv.cwd)
if len(name) != 1:
raise InternalShellError(cmd, "Unsupported: glob in "
"redirect expanded to multiple files")
name = name[0]
if kAvoidDevNull and name == kDevNull:
fd = tempfile.TemporaryFile(mode=mode)
elif kIsWindows and name == '/dev/tty':
# Simulate /dev/tty on Windows.
# "CON" is a special filename for the console.
fd = open("CON", mode)
else:
# Make sure relative paths are relative to the cwd.
redir_filename = os.path.join(cmd_shenv.cwd, name)
redir_filename = to_unicode(redir_filename) \
if kIsWindows else to_bytes(redir_filename)
fd = open(redir_filename, mode)
# Workaround a Win32 and/or subprocess bug when appending.
#
# FIXME: Actually, this is probably an instance of PR6753.
if mode == 'a':
fd.seek(0, 2)
# Mutate the underlying redirect list so that we can redirect stdout
# and stderr to the same place without opening the file twice.
r[2] = fd
opened_files.append((filename, mode, fd) + (redir_filename,))
std_fds[index] = fd
return std_fds
def _executeShCmd(cmd, shenv, results, timeoutHelper):
if timeoutHelper.timeoutReached():
# Prevent further recursion if the timeout has been hit
# as we should try avoid launching more processes.
return None
if isinstance(cmd, ShUtil.Seq):
if cmd.op == ';':
res = _executeShCmd(cmd.lhs, shenv, results, timeoutHelper)
return _executeShCmd(cmd.rhs, shenv, results, timeoutHelper)
if cmd.op == '&':
raise InternalShellError(cmd,"unsupported shell operator: '&'")
if cmd.op == '||':
res = _executeShCmd(cmd.lhs, shenv, results, timeoutHelper)
if res != 0:
res = _executeShCmd(cmd.rhs, shenv, results, timeoutHelper)
return res
if cmd.op == '&&':
res = _executeShCmd(cmd.lhs, shenv, results, timeoutHelper)
if res is None:
return res
if res == 0:
res = _executeShCmd(cmd.rhs, shenv, results, timeoutHelper)
return res
raise ValueError('Unknown shell command: %r' % cmd.op)
assert isinstance(cmd, ShUtil.Pipeline)
procs = []
default_stdin = subprocess.PIPE
stderrTempFiles = []
opened_files = []
named_temp_files = []
builtin_commands = set(['cat', 'diff'])
builtin_commands_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "builtin_commands")
inproc_builtins = {'cd': executeBuiltinCd,
'export': executeBuiltinExport,
'echo': executeBuiltinEcho,
'mkdir': executeBuiltinMkdir,
'rm': executeBuiltinRm,
':': executeBuiltinColon}
# To avoid deadlock, we use a single stderr stream for piped
# output. This is null until we have seen some output using
# stderr.
for i,j in enumerate(cmd.commands):
# Reference the global environment by default.
cmd_shenv = shenv
args = list(j.args)
not_args = []
not_count = 0
not_crash = False
while True:
if args[0] == 'env':
# Create a copy of the global environment and modify it for
# this one command. There might be multiple envs in a pipeline,
# and there might be multiple envs in a command (usually when
# one comes from a substitution):
# env FOO=1 llc < %s | env BAR=2 llvm-mc | FileCheck %s
# env FOO=1 %{another_env_plus_cmd} | FileCheck %s
if cmd_shenv is shenv:
cmd_shenv = ShellEnvironment(shenv.cwd, shenv.env)
args = updateEnv(cmd_shenv, args)
if not args:
raise InternalShellError(j, "Error: 'env' requires a"
" subcommand")
elif args[0] == 'not':
not_args.append(args.pop(0))
not_count += 1
if args and args[0] == '--crash':
not_args.append(args.pop(0))
not_crash = True
if not args:
raise InternalShellError(j, "Error: 'not' requires a"
" subcommand")
else:
break
# Handle in-process builtins.
#
# Handle "echo" as a builtin if it is not part of a pipeline. This
# greatly speeds up tests that construct input files by repeatedly
# echo-appending to a file.
# FIXME: Standardize on the builtin echo implementation. We can use a
# temporary file to sidestep blocking pipe write issues.
inproc_builtin = inproc_builtins.get(args[0], None)
if inproc_builtin and (args[0] != 'echo' or len(cmd.commands) == 1):
# env calling an in-process builtin is useless, so we take the safe
# approach of complaining.
if not cmd_shenv is shenv:
raise InternalShellError(j, "Error: 'env' cannot call '{}'"
.format(args[0]))
if not_crash:
raise InternalShellError(j, "Error: 'not --crash' cannot call"
" '{}'".format(args[0]))
if len(cmd.commands) != 1:
raise InternalShellError(j, "Unsupported: '{}' cannot be part"
" of a pipeline".format(args[0]))
result = inproc_builtin(Command(args, j.redirects), cmd_shenv)
if not_count % 2:
result.exitCode = int(not result.exitCode)
result.command.args = j.args;
results.append(result)
return result.exitCode
# Resolve any out-of-process builtin command before adding back 'not'
# commands.
if args[0] in builtin_commands:
args.insert(0, sys.executable)
cmd_shenv.env['PYTHONPATH'] = \
os.path.dirname(os.path.abspath(__file__))
args[1] = os.path.join(builtin_commands_dir, args[1] + ".py")
# We had to search through the 'not' commands to find all the 'env'
# commands and any other in-process builtin command. We don't want to
# reimplement 'not' and its '--crash' here, so just push all 'not'
# commands back to be called as external commands. Because this
# approach effectively moves all 'env' commands up front, it relies on
# the assumptions that (1) environment variables are not intended to be
# relevant to 'not' commands and (2) the 'env' command should always
# blindly pass along the status it receives from any command it calls.
args = not_args + args
stdin, stdout, stderr = processRedirects(j, default_stdin, cmd_shenv,
opened_files)
# If stderr wants to come from stdout, but stdout isn't a pipe, then put
# stderr on a pipe and treat it as stdout.
if (stderr == subprocess.STDOUT and stdout != subprocess.PIPE):
stderr = subprocess.PIPE
stderrIsStdout = True
else:
stderrIsStdout = False
# Don't allow stderr on a PIPE except for the last
# process, this could deadlock.
#
# FIXME: This is slow, but so is deadlock.
if stderr == subprocess.PIPE and j != cmd.commands[-1]:
stderr = tempfile.TemporaryFile(mode='w+b')
stderrTempFiles.append((i, stderr))
# Resolve the executable path ourselves.
executable = None
# For paths relative to cwd, use the cwd of the shell environment.
if args[0].startswith('.'):
exe_in_cwd = os.path.join(cmd_shenv.cwd, args[0])
if os.path.isfile(exe_in_cwd):
executable = exe_in_cwd
if not executable:
executable = lit.util.which(args[0], cmd_shenv.env['PATH'])
if not executable:
raise InternalShellError(j, '%r: command not found' % args[0])
# Replace uses of /dev/null with temporary files.
if kAvoidDevNull:
# In Python 2.x, basestring is the base class for all string (including unicode)
# In Python 3.x, basestring no longer exist and str is always unicode
try:
str_type = basestring
except NameError:
str_type = str
for i,arg in enumerate(args):
if isinstance(arg, str_type) and kDevNull in arg:
f = tempfile.NamedTemporaryFile(delete=False)
f.close()
named_temp_files.append(f.name)
args[i] = arg.replace(kDevNull, f.name)
# Expand all glob expressions
args = expand_glob_expressions(args, cmd_shenv.cwd)
# On Windows, do our own command line quoting for better compatibility
# with some core utility distributions.
if kIsWindows:
args = quote_windows_command(args)
try:
procs.append(subprocess.Popen(args, cwd=cmd_shenv.cwd,
executable = executable,
stdin = stdin,
stdout = stdout,
stderr = stderr,
env = cmd_shenv.env,
close_fds = kUseCloseFDs))
# Let the helper know about this process
timeoutHelper.addProcess(procs[-1])
except OSError as e:
raise InternalShellError(j, 'Could not create process ({}) due to {}'.format(executable, e))
# Immediately close stdin for any process taking stdin from us.
if stdin == subprocess.PIPE:
procs[-1].stdin.close()
procs[-1].stdin = None
# Update the current stdin source.
if stdout == subprocess.PIPE:
default_stdin = procs[-1].stdout
elif stderrIsStdout:
default_stdin = procs[-1].stderr
else:
default_stdin = subprocess.PIPE
# Explicitly close any redirected files. We need to do this now because we
# need to release any handles we may have on the temporary files (important
# on Win32, for example). Since we have already spawned the subprocess, our
# handles have already been transferred so we do not need them anymore.
for (name, mode, f, path) in opened_files:
f.close()
# FIXME: There is probably still deadlock potential here. Yawn.
procData = [None] * len(procs)
procData[-1] = procs[-1].communicate()
for i in range(len(procs) - 1):
if procs[i].stdout is not None:
out = procs[i].stdout.read()
else:
out = ''
if procs[i].stderr is not None:
err = procs[i].stderr.read()
else:
err = ''
procData[i] = (out,err)
# Read stderr out of the temp files.
for i,f in stderrTempFiles:
f.seek(0, 0)
procData[i] = (procData[i][0], f.read())
f.close()
exitCode = None
for i,(out,err) in enumerate(procData):
res = procs[i].wait()
# Detect Ctrl-C in subprocess.
if res == -signal.SIGINT:
raise KeyboardInterrupt
# Ensure the resulting output is always of string type.
try:
if out is None:
out = ''
else:
out = to_string(out.decode('utf-8', errors='replace'))
except:
out = str(out)
try:
if err is None:
err = ''
else:
err = to_string(err.decode('utf-8', errors='replace'))
except:
err = str(err)
# Gather the redirected output files for failed commands.
output_files = []
if res != 0:
for (name, mode, f, path) in sorted(opened_files):
if path is not None and mode in ('w', 'a'):
try:
with open(path, 'rb') as f:
data = f.read()
except:
data = None
if data is not None:
output_files.append((name, path, data))
results.append(ShellCommandResult(
cmd.commands[i], out, err, res, timeoutHelper.timeoutReached(),
output_files))
if cmd.pipe_err:
# Take the last failing exit code from the pipeline.
if not exitCode or res != 0:
exitCode = res
else:
exitCode = res
# Remove any named temporary files we created.
for f in named_temp_files:
try:
os.remove(f)
except OSError:
pass
if cmd.negate:
exitCode = not exitCode
return exitCode
def executeScriptInternal(test, litConfig, tmpBase, commands, cwd):
cmds = []
for i, ln in enumerate(commands):
ln = commands[i] = re.sub(kPdbgRegex, ": '\\1'; ", ln)
try:
cmds.append(ShUtil.ShParser(ln, litConfig.isWindows,
test.config.pipefail).parse())
except:
return lit.Test.Result(Test.FAIL, "shell parser error on: %r" % ln)
cmd = cmds[0]
for c in cmds[1:]:
cmd = ShUtil.Seq(cmd, '&&', c)
results = []
timeoutInfo = None
try:
shenv = ShellEnvironment(cwd, test.config.environment)
exitCode, timeoutInfo = executeShCmd(cmd, shenv, results, timeout=litConfig.maxIndividualTestTime)
except InternalShellError:
e = sys.exc_info()[1]
exitCode = 127
results.append(
ShellCommandResult(e.command, '', e.message, exitCode, False))
out = err = ''
for i,result in enumerate(results):
# Write the command line run.
out += '$ %s\n' % (' '.join('"%s"' % s
for s in result.command.args),)
# If nothing interesting happened, move on.
if litConfig.maxIndividualTestTime == 0 and \
result.exitCode == 0 and \
not result.stdout.strip() and not result.stderr.strip():
continue
# Otherwise, something failed or was printed, show it.
# Add the command output, if redirected.
for (name, path, data) in result.outputFiles:
if data.strip():
out += "# redirected output from %r:\n" % (name,)
data = to_string(data.decode('utf-8', errors='replace'))
if len(data) > 1024:
out += data[:1024] + "\n...\n"
out += "note: data was truncated\n"
else:
out += data
out += "\n"
if result.stdout.strip():
out += '# command output:\n%s\n' % (result.stdout,)
if result.stderr.strip():
out += '# command stderr:\n%s\n' % (result.stderr,)
if not result.stdout.strip() and not result.stderr.strip():
out += "note: command had no output on stdout or stderr\n"
# Show the error conditions:
if result.exitCode != 0:
# On Windows, a negative exit code indicates a signal, and those are
# easier to recognize or look up if we print them in hex.
if litConfig.isWindows and result.exitCode < 0:
codeStr = hex(int(result.exitCode & 0xFFFFFFFF)).rstrip("L")
else:
codeStr = str(result.exitCode)
out += "error: command failed with exit status: %s\n" % (
codeStr,)
if litConfig.maxIndividualTestTime > 0 and result.timeoutReached:
out += 'error: command reached timeout: %s\n' % (
str(result.timeoutReached),)
return out, err, exitCode, timeoutInfo
def executeScript(test, litConfig, tmpBase, commands, cwd):
bashPath = litConfig.getBashPath()
isWin32CMDEXE = (litConfig.isWindows and not bashPath)
script = tmpBase + '.script'
if isWin32CMDEXE:
script += '.bat'
# Write script file
mode = 'w'
open_kwargs = {}
if litConfig.isWindows and not isWin32CMDEXE:
mode += 'b' # Avoid CRLFs when writing bash scripts.
elif sys.version_info > (3,0):
open_kwargs['encoding'] = 'utf-8'
f = open(script, mode, **open_kwargs)
if isWin32CMDEXE:
for i, ln in enumerate(commands):
commands[i] = re.sub(kPdbgRegex, "echo '\\1' > nul && ", ln)
if litConfig.echo_all_commands:
f.write('@echo on\n')
else:
f.write('@echo off\n')
f.write('\n@if %ERRORLEVEL% NEQ 0 EXIT\n'.join(commands))
else:
for i, ln in enumerate(commands):
commands[i] = re.sub(kPdbgRegex, ": '\\1'; ", ln)
if test.config.pipefail:
f.write(b'set -o pipefail;' if mode == 'wb' else 'set -o pipefail;')
if litConfig.echo_all_commands:
f.write(b'set -x;' if mode == 'wb' else 'set -x;')
if sys.version_info > (3,0) and mode == 'wb':
f.write(bytes('{ ' + '; } &&\n{ '.join(commands) + '; }', 'utf-8'))
else:
f.write('{ ' + '; } &&\n{ '.join(commands) + '; }')
f.write(b'\n' if mode == 'wb' else '\n')
f.close()
if isWin32CMDEXE:
command = ['cmd','/c', script]
else:
if bashPath:
command = [bashPath, script]
else:
command = ['/bin/sh', script]
if litConfig.useValgrind:
# FIXME: Running valgrind on sh is overkill. We probably could just
# run on clang with no real loss.
command = litConfig.valgrindArgs + command
try:
out, err, exitCode = lit.util.executeCommand(command, cwd=cwd,
env=test.config.environment,
timeout=litConfig.maxIndividualTestTime)
return (out, err, exitCode, None)
except lit.util.ExecuteCommandTimeoutException as e:
return (e.out, e.err, e.exitCode, e.msg)
def parseIntegratedTestScriptCommands(source_path, keywords):
"""
parseIntegratedTestScriptCommands(source_path) -> commands
Parse the commands in an integrated test script file into a list of
(line_number, command_type, line).
"""
# This code is carefully written to be dual compatible with Python 2.5+ and
# Python 3 without requiring input files to always have valid codings. The
# trick we use is to open the file in binary mode and use the regular
# expression library to find the commands, with it scanning strings in
# Python2 and bytes in Python3.
#
# Once we find a match, we do require each script line to be decodable to
# UTF-8, so we convert the outputs to UTF-8 before returning. This way the
# remaining code can work with "strings" agnostic of the executing Python
# version.
keywords_re = re.compile(
to_bytes("(%s)(.*)\n" % ("|".join(re.escape(k) for k in keywords),)))
f = open(source_path, 'rb')
try:
# Read the entire file contents.
data = f.read()
# Ensure the data ends with a newline.
if not data.endswith(to_bytes('\n')):
data = data + to_bytes('\n')
# Iterate over the matches.
line_number = 1
last_match_position = 0
for match in keywords_re.finditer(data):
# Compute the updated line number by counting the intervening
# newlines.
match_position = match.start()
line_number += data.count(to_bytes('\n'), last_match_position,
match_position)
last_match_position = match_position
# Convert the keyword and line to UTF-8 strings and yield the
# command. Note that we take care to return regular strings in
# Python 2, to avoid other code having to differentiate between the
# str and unicode types.
#
# Opening the file in binary mode prevented Windows \r newline
# characters from being converted to Unix \n newlines, so manually
# strip those from the yielded lines.
keyword,ln = match.groups()
yield (line_number, to_string(keyword.decode('utf-8')),
to_string(ln.decode('utf-8').rstrip('\r')))
finally:
f.close()
def getTempPaths(test):
"""Get the temporary location, this is always relative to the test suite
root, not test source root."""
execpath = test.getExecPath()
execdir,execbase = os.path.split(execpath)
tmpDir = os.path.join(execdir, 'Output')
tmpBase = os.path.join(tmpDir, execbase)
return tmpDir, tmpBase
def colonNormalizePath(path):
if kIsWindows:
return re.sub(r'^(.):', r'\1', path.replace('\\', '/'))
else:
assert path[0] == '/'
return path[1:]
def getDefaultSubstitutions(test, tmpDir, tmpBase, normalize_slashes=False):
sourcepath = test.getSourcePath()
sourcedir = os.path.dirname(sourcepath)
# Normalize slashes, if requested.
if normalize_slashes:
sourcepath = sourcepath.replace('\\', '/')
sourcedir = sourcedir.replace('\\', '/')
tmpDir = tmpDir.replace('\\', '/')
tmpBase = tmpBase.replace('\\', '/')
substitutions = []
substitutions.extend(test.config.substitutions)
tmpName = tmpBase + '.tmp'
baseName = os.path.basename(tmpBase)
substitutions.extend([('%s', sourcepath),
('%S', sourcedir),
('%p', sourcedir),
('%{pathsep}', os.pathsep),
('%t', tmpName),
('%basename_t', baseName),
('%T', tmpDir)])
# "%/[STpst]" should be normalized.
substitutions.extend([
('%/s', sourcepath.replace('\\', '/')),
('%/S', sourcedir.replace('\\', '/')),
('%/p', sourcedir.replace('\\', '/')),
('%/t', tmpBase.replace('\\', '/') + '.tmp'),
('%/T', tmpDir.replace('\\', '/')),
])
# "%{/[STpst]:regex_replacement}" should be normalized like "%/[STpst]" but we're
# also in a regex replacement context of a s@@@ regex.
def regex_escape(s):
s = s.replace('@', '\@')
s = s.replace('&', '\&')
return s
substitutions.extend([
('%{/s:regex_replacement}',
regex_escape(sourcepath.replace('\\', '/'))),
('%{/S:regex_replacement}',
regex_escape(sourcedir.replace('\\', '/'))),
('%{/p:regex_replacement}',
regex_escape(sourcedir.replace('\\', '/'))),
('%{/t:regex_replacement}',
regex_escape(tmpBase.replace('\\', '/')) + '.tmp'),
('%{/T:regex_replacement}',
regex_escape(tmpDir.replace('\\', '/'))),
])
# "%:[STpst]" are normalized paths without colons and without a leading
# slash.
substitutions.extend([
('%:s', colonNormalizePath(sourcepath)),
('%:S', colonNormalizePath(sourcedir)),
('%:p', colonNormalizePath(sourcedir)),
('%:t', colonNormalizePath(tmpBase + '.tmp')),
('%:T', colonNormalizePath(tmpDir)),
])
return substitutions
def _memoize(f):
cache = {} # Intentionally unbounded, see applySubstitutions()
def memoized(x):
if x not in cache:
cache[x] = f(x)
return cache[x]
return memoized
@_memoize
def _caching_re_compile(r):
return re.compile(r)
def applySubstitutions(script, substitutions, recursion_limit=None):
"""
Apply substitutions to the script. Allow full regular expression syntax.
Replace each matching occurrence of regular expression pattern a with
substitution b in line ln.
If a substitution expands into another substitution, it is expanded
recursively until the line has no more expandable substitutions. If
the line can still can be substituted after being substituted
`recursion_limit` times, it is an error. If the `recursion_limit` is
`None` (the default), no recursive substitution is performed at all.
"""
# We use #_MARKER_# to hide %% while we do the other substitutions.
def escape(ln):
return _caching_re_compile('%%').sub('#_MARKER_#', ln)
def unescape(ln):
return _caching_re_compile('#_MARKER_#').sub('%', ln)
def processLine(ln):
# Apply substitutions
for a,b in substitutions:
if kIsWindows:
b = b.replace("\\","\\\\")
# re.compile() has a built-in LRU cache with 512 entries. In some
# test suites lit ends up thrashing that cache, which made e.g.
# check-llvm run 50% slower. Use an explicit, unbounded cache
# to prevent that from happening. Since lit is fairly
# short-lived, since the set of substitutions is fairly small, and
# since thrashing has such bad consequences, not bounding the cache
# seems reasonable.
ln = _caching_re_compile(a).sub(str(b), escape(ln))
# Strip the trailing newline and any extra whitespace.
return ln.strip()
def processLineToFixedPoint(ln):
assert isinstance(recursion_limit, int) and recursion_limit >= 0
origLine = ln
steps = 0
processed = processLine(ln)
while processed != ln and steps < recursion_limit:
ln = processed
processed = processLine(ln)
steps += 1
if processed != ln:
raise ValueError("Recursive substitution of '%s' did not complete "
"in the provided recursion limit (%s)" % \
(origLine, recursion_limit))
return processed
process = processLine if recursion_limit is None else processLineToFixedPoint
return [unescape(process(ln)) for ln in script]
class ParserKind(object):
"""
An enumeration representing the style of an integrated test keyword or
command.
TAG: A keyword taking no value. Ex 'END.'
COMMAND: A keyword taking a list of shell commands. Ex 'RUN:'
LIST: A keyword taking a comma-separated list of values.
BOOLEAN_EXPR: A keyword taking a comma-separated list of
boolean expressions. Ex 'XFAIL:'
INTEGER: A keyword taking a single integer. Ex 'ALLOW_RETRIES:'
CUSTOM: A keyword with custom parsing semantics.
"""
TAG = 0
COMMAND = 1
LIST = 2
BOOLEAN_EXPR = 3
INTEGER = 4
CUSTOM = 5
@staticmethod
def allowedKeywordSuffixes(value):
return { ParserKind.TAG: ['.'],
ParserKind.COMMAND: [':'],
ParserKind.LIST: [':'],
ParserKind.BOOLEAN_EXPR: [':'],
ParserKind.INTEGER: [':'],
ParserKind.CUSTOM: [':', '.']
} [value]
@staticmethod
def str(value):
return { ParserKind.TAG: 'TAG',
ParserKind.COMMAND: 'COMMAND',
ParserKind.LIST: 'LIST',
ParserKind.BOOLEAN_EXPR: 'BOOLEAN_EXPR',
ParserKind.INTEGER: 'INTEGER',
ParserKind.CUSTOM: 'CUSTOM'
} [value]
class IntegratedTestKeywordParser(object):
"""A parser for LLVM/Clang style integrated test scripts.
keyword: The keyword to parse for. It must end in either '.' or ':'.
kind: An value of ParserKind.
parser: A custom parser. This value may only be specified with
ParserKind.CUSTOM.
"""
def __init__(self, keyword, kind, parser=None, initial_value=None):
allowedSuffixes = ParserKind.allowedKeywordSuffixes(kind)
if len(keyword) == 0 or keyword[-1] not in allowedSuffixes:
if len(allowedSuffixes) == 1:
raise ValueError("Keyword '%s' of kind '%s' must end in '%s'"
% (keyword, ParserKind.str(kind),
allowedSuffixes[0]))
else:
raise ValueError("Keyword '%s' of kind '%s' must end in "
" one of '%s'"
% (keyword, ParserKind.str(kind),
' '.join(allowedSuffixes)))
if parser is not None and kind != ParserKind.CUSTOM:
raise ValueError("custom parsers can only be specified with "
"ParserKind.CUSTOM")
self.keyword = keyword
self.kind = kind
self.parsed_lines = []
self.value = initial_value
self.parser = parser
if kind == ParserKind.COMMAND:
self.parser = lambda line_number, line, output: \
self._handleCommand(line_number, line, output,
self.keyword)
elif kind == ParserKind.LIST:
self.parser = self._handleList
elif kind == ParserKind.BOOLEAN_EXPR:
self.parser = self._handleBooleanExpr
elif kind == ParserKind.INTEGER:
self.parser = self._handleSingleInteger
elif kind == ParserKind.TAG:
self.parser = self._handleTag
elif kind == ParserKind.CUSTOM:
if parser is None:
raise ValueError("ParserKind.CUSTOM requires a custom parser")
self.parser = parser
else:
raise ValueError("Unknown kind '%s'" % kind)
def parseLine(self, line_number, line):
try:
self.parsed_lines += [(line_number, line)]
self.value = self.parser(line_number, line, self.value)
except ValueError as e:
raise ValueError(str(e) + ("\nin %s directive on test line %d" %
(self.keyword, line_number)))
def getValue(self):
return self.value
@staticmethod
def _handleTag(line_number, line, output):
"""A helper for parsing TAG type keywords"""
return (not line.strip() or output)
@staticmethod
def _handleCommand(line_number, line, output, keyword):
"""A helper for parsing COMMAND type keywords"""
# Trim trailing whitespace.
line = line.rstrip()
# Substitute line number expressions
line = re.sub(r'%\(line\)', str(line_number), line)
def replace_line_number(match):
if match.group(1) == '+':
return str(line_number + int(match.group(2)))
if match.group(1) == '-':
return str(line_number - int(match.group(2)))
line = re.sub(r'%\(line *([\+-]) *(\d+)\)', replace_line_number, line)
# Collapse lines with trailing '\\'.
if output and output[-1][-1] == '\\':
output[-1] = output[-1][:-1] + line
else:
if output is None:
output = []
pdbg = "%dbg({keyword} at line {line_number})".format(
keyword=keyword,
line_number=line_number)
assert re.match(kPdbgRegex + "$", pdbg), \
"kPdbgRegex expected to match actual %dbg usage"
line = "{pdbg} {real_command}".format(
pdbg=pdbg,
real_command=line)
output.append(line)
return output
@staticmethod
def _handleList(line_number, line, output):
"""A parser for LIST type keywords"""
if output is None:
output = []
output.extend([s.strip() for s in line.split(',')])
return output
@staticmethod
def _handleSingleInteger(line_number, line, output):
"""A parser for INTEGER type keywords"""
if output is None:
output = []
try:
n = int(line)
except ValueError:
raise ValueError("INTEGER parser requires the input to be an integer (got {})".format(line))
output.append(n)
return output
@staticmethod
def _handleBooleanExpr(line_number, line, output):
"""A parser for BOOLEAN_EXPR type keywords"""
parts = [s.strip() for s in line.split(',') if s.strip() != '']
if output and output[-1][-1] == '\\':
output[-1] = output[-1][:-1] + parts[0]
del parts[0]
if output is None:
output = []
output.extend(parts)
# Evaluate each expression to verify syntax.
# We don't want any results, just the raised ValueError.
for s in output:
if s != '*' and not s.endswith('\\'):
BooleanExpression.evaluate(s, [])
return output
def _parseKeywords(sourcepath, additional_parsers=[],
require_script=True):
"""_parseKeywords
Scan an LLVM/Clang style integrated test script and extract all the lines
pertaining to a special parser. This includes 'RUN', 'XFAIL', 'REQUIRES',
'UNSUPPORTED' and 'ALLOW_RETRIES', as well as other specified custom
parsers.
Returns a dictionary mapping each custom parser to its value after
parsing the test.
"""
# Install the built-in keyword parsers.
script = []
builtin_parsers = [
IntegratedTestKeywordParser('RUN:', ParserKind.COMMAND, initial_value=script),
IntegratedTestKeywordParser('XFAIL:', ParserKind.BOOLEAN_EXPR),
IntegratedTestKeywordParser('REQUIRES:', ParserKind.BOOLEAN_EXPR),
IntegratedTestKeywordParser('UNSUPPORTED:', ParserKind.BOOLEAN_EXPR),
IntegratedTestKeywordParser('ALLOW_RETRIES:', ParserKind.INTEGER),
IntegratedTestKeywordParser('END.', ParserKind.TAG)
]
keyword_parsers = {p.keyword: p for p in builtin_parsers}
# Install user-defined additional parsers.
for parser in additional_parsers:
if not isinstance(parser, IntegratedTestKeywordParser):
raise ValueError('Additional parser must be an instance of '
'IntegratedTestKeywordParser')
if parser.keyword in keyword_parsers:
raise ValueError("Parser for keyword '%s' already exists"
% parser.keyword)
keyword_parsers[parser.keyword] = parser
# Collect the test lines from the script.
for line_number, command_type, ln in \
parseIntegratedTestScriptCommands(sourcepath,
keyword_parsers.keys()):
parser = keyword_parsers[command_type]
parser.parseLine(line_number, ln)
if command_type == 'END.' and parser.getValue() is True:
break
# Verify the script contains a run line.
if require_script and not script:
raise ValueError("Test has no 'RUN:' line")
# Check for unterminated run lines.
if script and script[-1][-1] == '\\':
raise ValueError("Test has unterminated 'RUN:' lines (with '\\')")
# Check boolean expressions for unterminated lines.
for key in keyword_parsers:
kp = keyword_parsers[key]
if kp.kind != ParserKind.BOOLEAN_EXPR:
continue
value = kp.getValue()
if value and value[-1][-1] == '\\':
raise ValueError("Test has unterminated '{key}' lines (with '\\')"
.format(key=key))
# Make sure there's at most one ALLOW_RETRIES: line
allowed_retries = keyword_parsers['ALLOW_RETRIES:'].getValue()
if allowed_retries and len(allowed_retries) > 1:
raise ValueError("Test has more than one ALLOW_RETRIES lines")
return {p.keyword: p.getValue() for p in keyword_parsers.values()}
def parseIntegratedTestScript(test, additional_parsers=[],
require_script=True):
"""parseIntegratedTestScript - Scan an LLVM/Clang style integrated test
script and extract the lines to 'RUN' as well as 'XFAIL', 'REQUIRES',
'UNSUPPORTED' and 'ALLOW_RETRIES' information into the given test.
If additional parsers are specified then the test is also scanned for the
keywords they specify and all matches are passed to the custom parser.
If 'require_script' is False an empty script
may be returned. This can be used for test formats where the actual script
is optional or ignored.
"""
# Parse the test sources and extract test properties
try:
parsed = _parseKeywords(test.getSourcePath(), additional_parsers,
require_script)
except ValueError as e:
return lit.Test.Result(Test.UNRESOLVED, str(e))
script = parsed['RUN:'] or []
test.xfails += parsed['XFAIL:'] or []
test.requires += parsed['REQUIRES:'] or []
test.unsupported += parsed['UNSUPPORTED:'] or []
if parsed['ALLOW_RETRIES:']:
test.allowed_retries = parsed['ALLOW_RETRIES:'][0]
# Enforce REQUIRES:
missing_required_features = test.getMissingRequiredFeatures()
if missing_required_features:
msg = ', '.join(missing_required_features)
return lit.Test.Result(Test.UNSUPPORTED,
"Test requires the following unavailable "
"features: %s" % msg)
# Enforce UNSUPPORTED:
unsupported_features = test.getUnsupportedFeatures()
if unsupported_features:
msg = ', '.join(unsupported_features)
return lit.Test.Result(
Test.UNSUPPORTED,
"Test does not support the following features "
"and/or targets: %s" % msg)
# Enforce limit_to_features.
if not test.isWithinFeatureLimits():
msg = ', '.join(test.config.limit_to_features)
return lit.Test.Result(Test.UNSUPPORTED,
"Test does not require any of the features "
"specified in limit_to_features: %s" % msg)
return script
def _runShTest(test, litConfig, useExternalSh, script, tmpBase):
def runOnce(execdir):
if useExternalSh:
res = executeScript(test, litConfig, tmpBase, script, execdir)
else:
res = executeScriptInternal(test, litConfig, tmpBase, script, execdir)
if isinstance(res, lit.Test.Result):
return res
out,err,exitCode,timeoutInfo = res
if exitCode == 0:
status = Test.PASS
else:
if timeoutInfo is None:
status = Test.FAIL
else:
status = Test.TIMEOUT
return out,err,exitCode,timeoutInfo,status
# Create the output directory if it does not already exist.
lit.util.mkdir_p(os.path.dirname(tmpBase))
# Re-run failed tests up to test.allowed_retries times.
execdir = os.path.dirname(test.getExecPath())
attempts = test.allowed_retries + 1
for i in range(attempts):
res = runOnce(execdir)
if isinstance(res, lit.Test.Result):
return res
out,err,exitCode,timeoutInfo,status = res
if status != Test.FAIL:
break
# If we had to run the test more than once, count it as a flaky pass. These
# will be printed separately in the test summary.
if i > 0 and status == Test.PASS:
status = Test.FLAKYPASS
# Form the output log.
output = """Script:\n--\n%s\n--\nExit Code: %d\n""" % (
'\n'.join(script), exitCode)
if timeoutInfo is not None:
output += """Timeout: %s\n""" % (timeoutInfo,)
output += "\n"
# Append the outputs, if present.
if out:
output += """Command Output (stdout):\n--\n%s\n--\n""" % (out,)
if err:
output += """Command Output (stderr):\n--\n%s\n--\n""" % (err,)
return lit.Test.Result(status, output)
def executeShTest(test, litConfig, useExternalSh,
extra_substitutions=[],
preamble_commands=[]):
if test.config.unsupported:
return lit.Test.Result(Test.UNSUPPORTED, 'Test is unsupported')
script = list(preamble_commands)
parsed = parseIntegratedTestScript(test, require_script=not script)
if isinstance(parsed, lit.Test.Result):
return parsed
script += parsed
if litConfig.noExecute:
return lit.Test.Result(Test.PASS)
tmpDir, tmpBase = getTempPaths(test)
substitutions = list(extra_substitutions)
substitutions += getDefaultSubstitutions(test, tmpDir, tmpBase,
normalize_slashes=useExternalSh)
script = applySubstitutions(script, substitutions,
recursion_limit=test.config.recursiveExpansionLimit)
return _runShTest(test, litConfig, useExternalSh, script, tmpBase)
| apache-2.0 | -7,036,055,583,136,992,000 | 37.679317 | 106 | 0.567766 | false |
jojurajan/asplusquiz | problem_2/country_ip.py | 1 | 2718 | import csv
class CountryIp(object):
'''
Find the country to which the given IP is allocated
'''
ip_map = None
ip_ranges = None
def __init__(self):
self._set_ip_country_map()
def _set_ip_country_map(self):
'''
* Load data from IpToCountry.csv into a mapping of the following structure:
ip_identifier_range: country_name
* Set the ip_identifier_range values into a list for each access
'''
with open('IpToCountry.csv', 'r') as f:
csv_file = csv.reader(f)
self.ip_map = {}
self.ip_ranges = []
for x in csv_file:
if x[0][0] != '#':
map_key = (int(x[0]), int(x[1]))
self.ip_map[map_key] = x[6]
self.ip_ranges.append(map_key)
def search(self, ip_addr):
'''
Search for the country which matches the specified ip address.
* The ip address is validated.
* The ip_identifier is calculated to check in the generated ip mapping
* The ip_identifier is checked against the mapping.
- If match is found, it returns country name
- Else, returns None
'''
self._validate(ip_addr)
ip_identifier = self._calculate_id(ip_addr)
for ip_range in self.ip_ranges:
if ip_identifier >= ip_range[0] and ip_identifier <= ip_range[1]:
return self.ip_map[ip_range]
def _calculate_id(self, ip_addr):
'''
Calculates the identifier for the passed ip address.
* The ip is split into sections, for each octet
* The identifier is calculated as follows:
- e.g. for 1.2.3.4, identifier would be calculated as
1*(256*256*256) + 2*(256*256) + 3*(256) + 4*(1)
'''
multiplier = 1
result = 0
ip_addr = ip_addr.split('.')
ip_addr.reverse()
for section in ip_addr:
result += int(section) * multiplier
multiplier *= 256
return result
def _validate(self, ip_addr):
'''
Validates the passed ip address string.
* Checks by typecasting each octet section into int
* Checks for each section to be greater than -1 and less than 255
'''
try:
for section in ip_addr.split('.'):
section = int(section)
if section < 0 or section > 255:
raise Exception('Invalid ip')
except:
raise Exception('Invalid ip')
if __name__ == '__main__':
ip_addr = raw_input('IP -> ')
print CountryIp().search(ip_addr)
| mit | -2,149,022,767,538,018,300 | 33.405063 | 83 | 0.528698 | false |
enthought/traitsgui | enthought/pyface/workbench/action/reset_all_perspectives_action.py | 1 | 1179 | """ An action that resets *all* perspectives. """
# Enthought library imports.
from enthought.pyface.api import YES
# Local imports.
from workbench_action import WorkbenchAction
# The message used when confirming the action.
MESSAGE = 'Do you want to reset ALL perspectives to their defaults?'
class ResetAllPerspectivesAction(WorkbenchAction):
""" An action that resets *all* perspectives. """
#### 'Action' interface ###################################################
# The action's unique identifier (may be None).
id = 'enthought.pyface.workbench.action.reset_all_perspectives'
# The action's name (displayed on menus/tool bar tools etc).
name = 'Reset All Perspectives'
###########################################################################
# 'Action' interface.
###########################################################################
def perform(self, event):
""" Perform the action. """
window = self.window
if window.confirm(MESSAGE) == YES:
window.reset_all_perspectives()
return
#### EOF ######################################################################
| bsd-3-clause | -6,225,161,870,719,519,000 | 28.475 | 79 | 0.513147 | false |
jirikuncar/invenio-previewer | invenio_previewer/version.py | 2 | 1143 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""Version information for Invenio-Previewer.
This file is imported by ``invenio_previewer.__init__``,
and parsed by ``setup.py``.
"""
__version__ = "0.1.0.dev20150000"
| gpl-2.0 | 1,392,125,906,243,515,100 | 35.870968 | 76 | 0.743657 | false |
CyrusBiotechnology/dj-bioinformatics-protein | dj_bioinformatics_protein/models.py | 1 | 10977 | import logging
import hashlib
import os
import re
from django.db import models
from django.conf import settings
from .fields import AminoAcidSequenceField, AminoAcidSequenceTextField, AminoAcidAlignmentField, AminoAcidAlignmentTextField
logger = logging.getLogger('dj_bioinformatics_protein.' + __name__)
FORMATS_SETTINGS = {
"MAX_DESCRIPTION_LENGTH": 1000,
"MAX_SEQUENCE_LENGTH": 5000,
"ALIGNMENT": {
'PDB_CODE_LENGTH': 4,
'PDB_CHAIN_LENGTH': 1,
}
}
try:
FORMATS_SETTINGS.update(settings.FORMATS)
except AttributeError:
pass
class FASTA(models.Model):
""" To the client, this is usually represented with the __str__ method; the entire
file. However, there are lots of advantages to storing the FASTA file as 4 different
fields in the database, or storing the sequence on disk and the remaining three in
the database. Since the hash of the sequence should be unique, we can look up FASTAs
either locally or on remote systems with this unique hash, to be sure we aren't
storing two of the same sequence. This also allows us to do should also do some
higher-level checks to make sure that that two jobs are not run with the same
sequence against the same database. With deterministic applications, we will get the
same result.
"""
# SHA 256 hash is generated on the fly, to enforce uniqueness of sequence field
sha256 = models.CharField(unique=True, editable=False, blank=True, max_length=255)
# FASTA body fields
description = models.CharField(max_length=FORMATS_SETTINGS['MAX_DESCRIPTION_LENGTH'])
comments = models.TextField(null=True)
sequence = AminoAcidSequenceField(
max_length=FORMATS_SETTINGS['MAX_SEQUENCE_LENGTH']
)
def header(self, allow_comments=False):
""" Generate the header string
:param allow_comments: Choose to allow comments to be printed in the output
:return: Properly formatted header string
"""
if allow_comments and self.comments:
header = ';' + str(self.description)
header += os.linesep.join(['; ' + comment for comment in self.comments.split('\n')])
else:
header = '>' + str(self.description)
return header
def body(self, line_length=80):
""" Break the sequence in to lines of line_length
:param line_length: int; break lines to this length
:return: formatted body
"""
sequence = str(self.sequence)
parsed = [sequence[i:i + line_length] for i in range(0, len(sequence), line_length)]
return os.linesep.join(parsed)
@property
def formatted(self):
fasta = self.header()
fasta += os.linesep
fasta += self.body()
return str(fasta)
@property
def hash(self):
return hashlib.sha256(self.sequence).hexdigest()
@staticmethod
def clean_sequence(sequence):
_sequence = ''.join(re.findall('(\w+)', sequence))
return _sequence.upper()
def save(self, *args, **kwargs):
if not self.sha256:
self.sha256 = self.hash
self.description.strip()
self.description.lstrip('>;')
self.sequence = self.clean_sequence(self.sequence)
super(FASTA, self).save(*args, **kwargs)
@classmethod
def from_fasta(cls, fasta):
""" Builds a FASTA object from a FASTA file. We use this during deserialization
of objects to turn the FASTA passed as a string into a FASTA instance in the db.
PLEASE NOTE, this function doesn't persist FASTA objects! You must run .save()
on instances returned by this function!
:param fasta: FASTA file (entire file as a string with newlines)
:return: a single populated FASTA object
"""
fasta_object = cls()
fasta_object.description = ''
fasta_object.comments = ''
fasta_object.sequence = ''
split = []
for l in [l for l in fasta.split('\\n')]:
split += l.split('\n')
for i, line in enumerate(split):
_line = line.rstrip()
if _line.startswith('>') and i == 0:
fasta_object.description = _line[1:]
elif _line.startswith(';') and i == 0:
fasta_object.description = _line[1:]
elif _line.startswith(';') and i != 1:
fasta_object.comments += _line[1:] + '\n'
else:
fasta_object.sequence += _line
if not fasta_object.sequence:
raise Exception(("No FASTA sequence given. Make sure your FASTA is"
" formatted properly and try again"))
return fasta_object
def __str__(self):
return str(self.formatted)
try:
""" Maximum FASTA length is limited to the sum of all field limits by
default, but this may be overridden by adding the following setting in
settings.py:
FORMATS = {
'FASTA': {
'MAX_FASTA_FILE_LENGTH': <integer>
}
}
It's also possible to override the length of a single field (which will
affect the total length automatically) by providing that field instead:
FORMATS = {
'FASTA': {
'MAX_DESCRIPTION_LENGTH': 255,
'MAX_COMMENTS_LENGTH': 2000,
'MAX_SEQUENCE_LENGTH': 5000,
}
}
"""
MAX_FASTA_FILE_LENGTH = settings.FORMATS['MAX_SEQUENCE_LENGTH']
except (AttributeError, IndexError, KeyError):
""" Failing to get FASTA length from settings, we can infer the maximum
FASTA length we should accept by summing the max_length of all the fields
of the FASTA object. This is an imperfect solution, since we could
potentially have a single field that is too long, but we assume we've
chosen sane limits on our side. We also assume that the client app does
some checking before sending data and is able to handle 4XX & 5XX errors in
a sane way, notifying the end user. """
MAX_FASTA_FILE_LENGTH = FASTA._meta.get_field('description').max_length
try:
MAX_FASTA_FILE_LENGTH += FASTA._meta.get_field('comments').max_length
except TypeError:
pass
MAX_FASTA_FILE_LENGTH += FORMATS_SETTINGS['MAX_SEQUENCE_LENGTH']
class Alignment(models.Model):
""" Represents one alignment
"""
JSON_FIELDS = [
"alignment_method",
"rank",
"query_description",
"target_description",
"target_pdb_code",
"target_pdb_chain",
"query_start",
"query_aln_seq",
"target_start",
"target_aln_seq",
"score_line",
"p_correct",
"threaded_template"
]
ALIGNMENT_SETTINGS = FORMATS_SETTINGS['ALIGNMENT']
ALIGN_METHOD_CHOICES = [
('H', 'hhsearch'),
('S', 'sparksX'),
('U', 'user'),
]
user_template = False # search for pdb database or user defined files
full_query_sequence = AminoAcidSequenceField(
max_length=FORMATS_SETTINGS['MAX_SEQUENCE_LENGTH']
)
query_aln_seq = AminoAcidAlignmentTextField( #disk
max_length=FORMATS_SETTINGS['MAX_SEQUENCE_LENGTH']
)
alignment_method = models.CharField(max_length=1, choices=ALIGN_METHOD_CHOICES)
rank = models.IntegerField()
active = models.BooleanField(default=True)
# modeled sequence information
query_start = models.IntegerField() # 1 based
query_description = models.CharField(max_length=FORMATS_SETTINGS['MAX_DESCRIPTION_LENGTH'], null=True)
modified_query_aln_seq = AminoAcidAlignmentTextField(
max_length=FORMATS_SETTINGS['MAX_SEQUENCE_LENGTH'],
null=True
)
# template information
target_start = models.IntegerField() # 1 based
target_description = models.TextField(max_length=FORMATS_SETTINGS['MAX_DESCRIPTION_LENGTH'], null=True)
target_pdb_code = models.CharField(max_length=ALIGNMENT_SETTINGS['PDB_CODE_LENGTH'])
target_pdb_chain = models.CharField(max_length=ALIGNMENT_SETTINGS['PDB_CHAIN_LENGTH'])
target_aln_seq = AminoAcidAlignmentTextField(
max_length=FORMATS_SETTINGS['MAX_SEQUENCE_LENGTH'])
modified_target_aln_seq = AminoAcidAlignmentTextField(
max_length=FORMATS_SETTINGS['MAX_SEQUENCE_LENGTH'],
null=True
)
p_correct = models.FloatField() # current using Robetta p_correct calculator. to be improved using alignment score
threaded_template = models.TextField(blank=True, null=True)
@property
def target_grishin_tag(self):
if self.alignment_method == 'H':
tag = "%s%s_%3d" % (self.target_pdb_code, self.target_pdb_chain, self.rank + 200)
elif self.alignment_method == 'S':
tag = "%s%s_%3d" % (self.target_pdb_code, self.target_pdb_chain, self.rank + 300)
else:
tag = "%s%s_%3d" % (self.target_pdb_code, self.target_pdb_chain, self.rank + 400)
return str(tag)
@property
def grishin_lines(self):
outlines = "## %s %s\n" % (self.query_description, self.target_grishin_tag)
outlines += "# \n"
outlines += "scores_from_program: 0\n"
outlines += "%d %s\n" % (self.query_start - 1, self.query_aln_seq)
outlines += "%d %s\n" % (self.target_start - 1, self.target_aln_seq)
outlines += "--\n\n"
return str(outlines)
@property
def hash(self):
return hashlib.sha256(self.grishin_lines).hexdigest()
def load_data(self, data_in):
for attr in self.JSON_FIELDS:
if attr in data_in.keys():
if attr == 'alignment_method':
if data_in[attr] == "hhsearch":
self.alignment_method = 'H'
elif data_in[attr] == "sparksX":
self.alignment_method = 'S'
else:
logger.warning("Currently user input alignment not supported")
self.alignment_method = 'U'
else:
self.__dict__[attr] = data_in[attr]
def dump_data(self):
aln = {}
for attr in self.JSON_FIELDS:
if attr not in self.__dict__.keys():
logger.warning("Missing data for %s in the alignment." % attr)
if attr in self.__dict__.keys() and self.__dict__[attr] is not None:
if attr == "alignment_method":
if self.alignment_method == 'H':
aln[attr] = "hhsearch"
elif self.alignment_method == 'S':
aln[attr] = "sparksX"
else:
aln[attr] = "user"
else:
aln[attr] = self.__dict__[attr]
aln['FASTA'] = self.full_query_sequence.formatted
aln['target_grishin_tag'] = self.target_grishin_tag
aln['grishin_lines'] = self.grishin_lines
return aln
def __str__(self):
return self.grishin_lines
| mit | 6,637,823,392,020,612,000 | 35.347682 | 124 | 0.610914 | false |
agoravoting/agora-ciudadana | agora_site/misc/utils.py | 2 | 16239 | """
taken from
http://www.djangosnippets.org/snippets/377/
"""
from django.core.urlresolvers import resolve, Resolver404
from django.http import HttpRequest
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.utils.datastructures import DictWrapper
from django.utils import datetime_safe
from django.core import mail as django_mail
from django.core.mail import (EmailMultiAlternatives, EmailMessage, send_mail,
send_mass_mail, get_connection)
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.db.models import signals
import json
from django.views.generic import CreateView
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django.shortcuts import _get_queryset
from django.forms.fields import Field, DateTimeField
from django.forms.util import ValidationError
import datetime
import pygeoip
from actstream.signals import action
from jsonfield import JSONField as JSONField2
from tastypie.fields import ApiField
from tastypie.serializers import Serializer
from guardian.core import ObjectPermissionChecker
from guardian.models import UserObjectPermission, GroupObjectPermission
from guardian.utils import get_identity
import html2text
class FormRequestMixin(object):
'''
Adds self.request to the form constructor arguments
'''
def get_form_kwargs(self):
"""
Returns the keyword arguments for instanciating the form.
"""
kwargs = super(FormRequestMixin, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs
class RequestCreateView(FormRequestMixin, CreateView):
pass
class JSONApiField(ApiField):
'''
Json Tastypie api field.
'''
dehydrated_type = 'dict'
help_text = "JSON data. Ex: {'prices': [26.73, 34], 'name': 'Daniel'}"
def dehydrate(self, bundle):
if self.attribute and hasattr(bundle.obj, self.attribute):
return getattr(bundle.obj, self.attribute)
else:
return None
class JSONFormField(Field):
def clean(self, value):
if not value and not self.required:
return None
value = super(JSONFormField, self).clean(value)
if isinstance(value, basestring):
try:
json.loads(value)
except ValueError:
raise ValidationError(_("Enter valid JSON"))
return value
class ISODateTimeFormField(DateTimeField):
def strptime(self, value, format):
from dateutil.parser import parse
return parse(value)
class JSONField(models.TextField):
"""
JSONField is a generic textfield that neatly serializes/unserializes
JSON objects seamlessly.
deserialization_params added on 2011-01-09 to provide additional hints at deserialization time
"""
# Used so to_python() is called
__metaclass__ = models.SubfieldBase
def __init__(self, name=None, json_type=None, deserialization_params=None, **kwargs):
self.json_type = json_type
self.deserialization_params = deserialization_params
super(JSONField, self).__init__(name, **kwargs)
def to_python(self, value):
"""Convert our string value to JSON after we load it from the DB"""
if self.json_type:
if isinstance(value, self.json_type):
return value
if isinstance(value, dict) or isinstance(value, list):
return value
if (type(value)==unicode and len(value.strip()) == 0) or value == None:
return None
try:
parsed_value = json.loads(value)
except:
return None
if self.json_type and parsed_value:
parsed_value = self.json_type.fromJSONDict(parsed_value, **self.deserialization_params)
return parsed_value
# we should never look up by JSON field anyways.
# def get_prep_lookup(self, lookup_type, value)
def get_prep_value(self, value):
"""Convert our JSON object to a string before we save"""
if isinstance(value, basestring):
return value
if value == None:
return None
if self.json_type and isinstance(value, self.json_type):
the_dict = value.toJSONDict()
else:
the_dict = value
return json.dumps(the_dict, cls=DjangoJSONEncoder)
def get_internal_type(self):
return 'JSONField'
def db_type(self, connection):
"""
Returns the database column data type for this field, for the provided
connection.
"""
# The default implementation of this method looks at the
# backend-specific DATA_TYPES dictionary, looking up the field by its
# "internal type".
#
# A Field class can implement the get_internal_type() method to specify
# which *preexisting* Django Field class it's most similar to -- i.e.,
# a custom field might be represented by a TEXT column type, which is
# the same as the TextField Django field type, which means the custom
# field's get_internal_type() returns 'TextField'.
#
# But the limitation of the get_internal_type() / data_types approach
# is that it cannot handle database column types that aren't already
# mapped to one of the built-in Django field types. In this case, you
# can implement db_type() instead of get_internal_type() to specify
# exactly which wacky database column type you want to use.
data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_")
real_internal_type = super(JSONField, self).get_internal_type()
try:
return (connection.creation.data_types[real_internal_type]
% data)
except KeyError:
return None
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
##
## for schema migration, we have to tell South about JSONField
## basically that it's the same as its parent class
##
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^agora_site\.misc\.utils\.JSONField"])
GEOIP = None
def geolocate_ip(ip_addr):
'''
Given an ip address, geolocates it, returning a tuple(latitude, longitude)
'''
global GEOIP
try:
if not GEOIP:
GEOIP = pygeoip.GeoIP(settings.GEOIP_DB_PATH)
data = GEOIP.record_by_addr(ip_addr)
return [data["latitude"], data["longitude"]]
except Exception, e:
return [0, 0]
def get_protocol(request):
'''
Given the request object, returns either 'https' or 'http' appropiately
'''
if request is None:
return 'https' if settings.AGORA_USE_HTTPS else 'http'
if request.is_secure():
return 'https'
else:
return 'http'
def validate_email(email):
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
try:
validate_email(email)
return True
except ValidationError:
return False
def get_base_email_context(request=None):
'''
Returns a basic email context
'''
if request is None:
return dict(
cancel_emails_url=reverse('cancel-email-updates'),
site=Site.objects.all()[0],
protocol=get_protocol(request)
)
return dict(
cancel_emails_url=reverse('cancel-email-updates'),
site=Site.objects.get_current(),
protocol=get_protocol(request)
)
def send_action(user, verb, request, action_object=None, target=None):
if request is None:
ipaddr = ''
geolocation = '[0,0]'
else:
ipaddr=request.META.get('REMOTE_ADDR')
geolocation=json.dumps(geolocate_ip(request.META.get('REMOTE_ADDR')))
action.send(user, verb=verb, action_object=action_object, target=target,
ipaddr=ipaddr, geolocation=geolocation)
def get_base_email_context_task(is_secure, site_id):
'''
Returns a basic email context for tasks
'''
return dict(
cancel_emails_url=reverse('cancel-email-updates'),
site=Site.objects.get(pk=site_id),
protocol=is_secure and 'https' or 'http'
)
def send_mass_html_mail(datatuple, fail_silently=True, user=None, password=None,
connection=None):
"""
Given a datatuple of (subject, text_content, html_content, from_email,
recipient_list), sends each message to each recipient list. Returns the
number of emails sent.
If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
If auth_user and auth_password are set, they're used to log in.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
"""
connection = connection or get_connection(
username=user, password=password, fail_silently=fail_silently
)
messages = []
for subject, text, html, from_email, recipient in datatuple:
message = EmailMultiAlternatives(subject, text, from_email, recipient)
message.attach_alternative(html, 'text/html')
messages.append(message)
return connection.send_messages(messages)
def get_users_with_perm(obj, perm_codename):
ctype = ContentType.objects.get_for_model(obj)
qset = Q(
userobjectpermission__content_type=ctype,
userobjectpermission__object_pk=obj.pk,
userobjectpermission__permission__codename=perm_codename,
userobjectpermission__permission__content_type=ctype,)
return User.objects.filter(qset).distinct()
def list_contains_all(l1, l2):
'''
return True if l2 contains all the elements in l1, False otherwise
'''
for el in l1:
if el not in l2:
return False
return True
from functools import partial
from tastypie import fields
from tastypie.resources import Resource
from tastypie.exceptions import ApiFieldError
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from tastypie.contrib.contenttypes.resources import GenericResource
class GenericForeignKeyField(fields.ToOneField):
"""
Provides access to GenericForeignKey objects from the django content_types
framework.
"""
def __init__(self, to, attribute, **kwargs):
if not isinstance(to, dict):
raise ValueError('to field must be a dictionary in GenericForeignKeyField')
if len(to) <= 0:
raise ValueError('to field must have some values')
for k, v in to.iteritems():
if not issubclass(k, models.Model) or not issubclass(v, Resource):
raise ValueError('to field must map django models to tastypie resources')
super(GenericForeignKeyField, self).__init__(to, attribute, **kwargs)
def get_related_resource(self, related_instance):
self._to_class = self.to.get(type(related_instance), None)
if self._to_class is None and not self.null:
raise TypeError('no resource for model %s' % type(related_instance))
return super(GenericForeignKeyField, self).get_related_resource(related_instance)
@property
def to_class(self):
if self._to_class and not issubclass(GenericResource, self._to_class):
return self._to_class
return partial(GenericResource, resources=self.to.values())
def resource_from_uri(self, fk_resource, uri, request=None, related_obj=None, related_name=None):
try:
obj = fk_resource.get_via_uri(uri, request=request)
fk_resource = self.get_related_resource(obj)
return super(GenericForeignKeyField, self).resource_from_uri(fk_resource, uri, request, related_obj, related_name)
except ObjectDoesNotExist:
raise ApiFieldError("Could not find the provided object via resource URI '%s'." % uri)
def build_related_resource(self, *args, **kwargs):
self._to_class = None
return super(GenericForeignKeyField, self).build_related_resource(*args, **kwargs)
class customstr(str):
def get(k, d=None):
return ""
# the following is from
# http://gdorn.circuitlocution.com/blog/2012/11/21/using-tastypie-inside-django.html
def rest(path, query={}, data={}, headers={}, method="GET", request=None):
"""
Converts a RPC-like call to something like a HttpRequest, passes it
to the right view function (via django's url resolver) and returns
the result.
Args:
path: a uri-like string representing an API endpoint. e.g. /resource/27.
/api/v2/ is automatically prepended to the path.
query: dictionary of GET-like query parameters to pass to view
data: dictionary of POST-like parameters to pass to view
headers: dictionary of extra headers to pass to view (will end up in request.META)
method: HTTP verb for the emulated request
Returns:
a tuple of (status, content):
status: integer representing an HTTP response code
content: string, body of response; may be empty
"""
#adjust for lack of trailing slash, just in case
if path[-1] != '/':
path += '/'
hreq = FakeHttpRequest()
hreq.path = '/api/v1' + path
hreq.GET = query
if isinstance(data, basestring):
hreq.POST = customstr(data)
else:
hreq.POST = customstr(json.dumps(data))
hreq.META = headers
hreq.method = method
if request:
hreq.user = request.user
try:
view = resolve(hreq.path)
res = view.func(hreq, *view.args, **view.kwargs)
except Resolver404:
return (404, '')
#container is the untouched content before HttpResponse mangles it
return (res.status_code, res._container)
class CustomNoneSerializer(Serializer):
"""
A custom serializer for TastyPie allowing "none" as an encoding type.
Resources need to specify this serializer as Meta.serializer.
See http://django-tastypie.readthedocs.org/en/latest/serialization.html
@todo: Is there a better way to tell TastyPie to not do any serialization per-request
(without breaking a hypothetical HTTP REST service)?
"""
formats = Serializer.formats + ['none']
content_types = Serializer.content_types
content_types['none'] = 'none/none'
def to_none(self, data, options=None):
"""
Outbound 'serializer'.
"""
#If the object is a tastypie bundle containing a dict, just return the dict.
if hasattr(data, 'data'):
return data.data
elif isinstance(data, dict):
if 'objects' in data:
data['objects'] = [foo.data for foo in data['objects']]
return data
def from_none(self, data, options=None):
return data
class FakeHttpRequest(HttpRequest):
"""
Custom version of Django's HttpRequest to minimize unnecessary work
for in-process requests.
"""
_read_started = False
@property
def raw_post_data(self):
"""
Instead of providing a file-like object representing the body
of the request, just return the internal dict; tastypie copes with
this just fine.
"""
return self.POST
@property
def encoding(self):
"""
We're passing python native types around and not encoding anything,
so all FakeHttpRequests are encoded as 'none/none'.
"""
return 'none/none'
def clean_html(text, to_plaintext=False):
if isinstance(text, str):
text = unicode(text, 'utf-8')
text = text.strip()
if not len(text):
return text
import bleach
ALLOWED_TAGS = bleach.ALLOWED_TAGS
ALLOWED_TAGS.append('p')
html = bleach.clean(text, tags=ALLOWED_TAGS, strip=True)
from lxml.html import html5parser
doc = html5parser.fromstring(html)
plaintext = doc.xpath("string()")
if plaintext == text:
return plaintext
return html
| agpl-3.0 | 1,330,964,010,952,777,500 | 32.07332 | 126 | 0.660755 | false |
janezkranjc/clowdflows | streams/models.py | 2 | 7040 | from django.db import models
from django.contrib.auth.models import User
import workflows.library
from picklefield.fields import PickledObjectField
import workflows
class HaltStream(Exception):
pass
# Create your models here.
class Stream(models.Model):
user = models.ForeignKey(User,related_name="streams")
workflow = models.OneToOneField(workflows.models.Workflow, related_name="stream")
last_executed = models.DateTimeField(auto_now_add=True)
period = models.IntegerField(default=60)
active = models.BooleanField(default=False)
@models.permalink
def get_absolute_url(self):
return ('stream', [str(self.id)])
def stream_visualization_widgets(self):
return self.workflow.widgets.all().exclude(abstract_widget__streaming_visualization_view='')
def reset(self):
self.widget_data.all().delete()
def execute(self,workflow=None,outputs={}):
if workflow is None:
workflow = self.workflow
ready_to_run = []
widgets = workflow.widgets.all()
#get unfinished
if workflow.is_for_loop():
fi = workflow.widgets.filter(type='for_input')[0]
fo = workflow.widgets.filter(type='for_output')[0]
outer_output = fo.inputs.all()[0].outer_output
outputs[outer_output.pk]=(outer_output.variable,[])
input_list = []
try:
if fi.outputs.all()[0].outer_input.connections.count() > 0:
input_list = outputs[fi.outputs.all()[0].outer_input.connections.all()[0].output.pk][1]
except:
input_list = []
else:
input_list = [0]
#print input_list
for for_input in input_list:
#print for_input
finished = []
unfinished_list = []
halted = []
loop = True
while loop:
for w in unfinished_list:
# prepare all the inputs for this widget
input_dict = {}
output_dict = {}
finish = True
for i in w.inputs.all():
#gremo pogledat ce obstaja povezava in ce obstaja gremo value prebrat iz outputa
if not i.parameter:
if i.connections.count() > 0:
#preberemo value iz output_dicta
i.value = outputs[i.connections.all()[0].output.pk][1]
else:
i.value = None
if i.multi_id == 0:
input_dict[i.variable]=i.value
else:
if not i.variable in input_dict:
input_dict[i.variable]=[]
if not i.value==None:
input_dict[i.variable].append(i.value)
if w.type == 'regular':
function_to_call = getattr(workflows.library,w.abstract_widget.action)
if w.abstract_widget.wsdl != '':
input_dict['wsdl']=w.abstract_widget.wsdl
input_dict['wsdl_method']=w.abstract_widget.wsdl_method
try:
if w.abstract_widget.has_progress_bar:
output_dict = function_to_call(input_dict,w)
elif w.abstract_widget.is_streaming:
output_dict = function_to_call(input_dict,w,self)
else:
output_dict = function_to_call(input_dict)
except HaltStream:
halted.append(w)
finish=False
if w.type == 'subprocess':
new_outputs = self.execute(workflow=w.workflow_link,outputs=outputs)
for o in w.outputs.all():
try:
outputs[o.pk]=new_outputs[o.pk]
except:
outputs[o.pk]=(o.variable,None)
if w.type == 'for_input':
for o in w.outputs.all():
outputs[o.pk]=(o.variable,for_input)
#print outputs[o.pk]
output_dict[o.variable]=for_input
if w.type == 'for_output':
for i in w.inputs.all():
outputs[i.outer_output.pk][1].append(input_dict[i.variable])
output_dict[i.variable]=input_dict[i.variable]
if w.type == 'input':
for o in w.outputs.all():
value = None
try:
if o.outer_input.connections.count() > 0:
value = outputs[o.outer_input.connections.all()[0].output.pk][1]
except:
value = None
output_dict[o.variable]=value
if finish:
if w.type == 'output':
for i in w.inputs.all():
outputs[i.outer_output.pk]=(i.outer_output.variable,input_dict[i.variable])
if w.type != 'subprocess':
for o in w.outputs.all():
outputs[o.pk]=(o.variable,output_dict[o.variable])
finished.append(w.pk)
unfinished_list = []
for w in widgets:
if not w.pk in finished:
ready_to_run = True
connections = workflow.connections.filter(input__widget=w)
for c in connections:
if c.output.widget.pk not in finished:
ready_to_run = False
break
if ready_to_run:
if w not in halted:
unfinished_list.append(w)
if len(unfinished_list)==0:
loop = False
return outputs
def __unicode__(self):
try:
return unicode(self.workflow)+' stream'
except:
return 'Unknown stream'
class StreamWidgetData(models.Model):
stream = models.ForeignKey(Stream, related_name="widget_data")
widget = models.ForeignKey(workflows.models.Widget, related_name="stream_data")
value = PickledObjectField(null=True)
class StreamWidgetState(models.Model):
stream = models.ForeignKey(Stream, related_name="widget_state")
widget = models.ForeignKey(workflows.models.Widget, related_name="stream_state")
state = PickledObjectField(null=True)
| gpl-3.0 | -1,379,623,310,772,043,000 | 39.693642 | 107 | 0.47429 | false |
nearai/program_synthesis | program_synthesis/naps/uast/uast_watcher.py | 1 | 5298 | # Watcher is a way to monitor Executor activity
# Example cases:
# - collect execution traces
# - collect information about data flowing through statements to later find blocks
# with the same behaviour across different solutions to the same problem
#
# The current set of events is tailored towards the use cases above.
def tuplify(x):
if isinstance(x, list):
return tuple([tuplify(_) for _ in x])
elif isinstance(x, dict):
return tuple(x.items())
return x
class WatcherEvent(object):
def __init__(self, event_type, executor, context, *args):
super(WatcherEvent, self).__init__()
self.context = context
self.executor = executor
self.event_type = event_type
self.args = args
class Watcher(object):
def __init__(self):
super(Watcher, self).__init__()
def watch(self, event):
if event.event_type == 'before_expression':
self.on_before_expression(event.executor, event.context, *event.args)
elif event.event_type == 'after_expression':
self.on_after_expression(event.executor, event.context, *event.args)
elif event.event_type == 'before_ternary_expression':
self.on_before_ternary_expression(event.executor, event.context, *event.args)
elif event.event_type == 'after_ternary_expression':
self.on_after_ternary_expression(event.executor, event.context, *event.args)
elif event.event_type == 'before_statement':
self.on_before_statement(event.executor, event.context, *event.args)
elif event.event_type == 'after_statement':
self.on_after_statement(event.executor, event.context, *event.args)
elif event.event_type == 'before_block':
self.on_before_block(event.executor, event.context, *event.args)
elif event.event_type == 'after_block':
self.on_after_block(event.executor, event.context, *event.args)
elif event.event_type == 'before_if_block':
self.on_before_if_block(event.executor, event.context, *event.args)
elif event.event_type == 'after_if_block':
self.on_after_if_block(event.executor, event.context, *event.args)
elif event.event_type == 'before_foreach_block':
self.on_before_foreach_block(event.executor, event.context, *event.args)
elif event.event_type == 'after_foreach_block':
self.on_after_foreach_block(event.executor, event.context, *event.args)
elif event.event_type == 'before_while_block':
self.on_before_while_block(event.executor, event.context, *event.args)
elif event.event_type == 'after_while_block':
self.on_after_while_block(event.executor, event.context, *event.args)
elif event.event_type == 'before_func_block':
self.on_before_func_block(event.executor, event.context, *event.args)
elif event.event_type == 'after_func_block':
self.on_after_func_block(event.executor, event.context, *event.args)
elif event.event_type == 'before_func':
self.on_before_func(event.executor, event.context, *event.args)
elif event.event_type == 'after_func':
self.on_after_func(event.executor, event.context, *event.args)
elif event.event_type == 'read':
self.on_read(event.executor, event.context, *event.args)
elif event.event_type == 'write':
self.on_write(event.executor, event.context, *event.args)
def on_before_expression(self, executor, context, expr, is_lhs=False):
pass
def on_after_expression(self, executor, context, ret, expr, is_lhs=False):
pass
def on_before_ternary_expression(self, executor, context, pred_expr, expr, is_lhs=False):
pass
def on_after_ternary_expression(self, executor, context, ret, pred_expr, expr, is_lhs=False):
pass
def on_before_statement(self, executor, context, stmt):
pass
def on_after_statement(self, executor, context, ret, stmt):
pass
def on_before_block(self, executor, context, block):
pass
def on_after_block(self, executor, context, ret, block):
pass
def on_before_if_block(self, executor, context, expr, block):
pass
def on_after_if_block(self, executor, context, ret, expr, block):
pass
def on_before_foreach_block(self, executor, context, expr, block):
pass
def on_after_foreach_block(self, executor, context, ret, expr, block):
pass
def on_before_while_block(self, executor, context, expr, block):
pass
def on_after_while_block(self, executor, context, ret, expr, block):
pass
def on_before_func_block(self, executor, context, func_name, func_vars, func_args, args_vals, expressions, block):
pass
def on_after_func_block(self, executor, context, ret, func_name, func_vars, func_args, args_vals, expressions, block):
pass
def on_before_func(self, executor, context, func, args):
pass
def on_after_func(self, executor, context, ret, func, args):
pass
def on_read(self, executor, context, args):
pass
def on_write(self, executor, context, args):
pass
| apache-2.0 | 5,210,443,456,277,423,000 | 33.402597 | 122 | 0.642695 | false |
BT-ojossen/connector | connector/queue/queue.py | 28 | 1459 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from __future__ import absolute_import
from Queue import PriorityQueue
class JobsQueue(object):
""" Holds the jobs planned for execution in memory.
The Jobs are sorted, the higher the priority is,
the earlier the jobs are dequeued.
"""
def __init__(self):
self._queue = PriorityQueue()
def enqueue(self, job):
self._queue.put_nowait(job)
def dequeue(self):
""" Take the first job according to its priority
and return it"""
return self._queue.get()
| agpl-3.0 | 9,191,123,347,857,750,000 | 34.585366 | 78 | 0.612748 | false |
dwighthubbard/ipython_embedded_notebooks | intro/range_finder.py | 1 | 3017 | #!/usr/bin/python3
import RPi.GPIO as GPIO
import time
import sys
# Set our pin to output mode
#GPIO.setmode(GPIO.BOARD)
#GPIO.setup(12, GPIO.OUT)
# Set the PWM frequency in Hz (cycles per second)
#p = GPIO.PWM(12, 60) # channel=12 frequency=60Hz
# Start doing PWM
#p.start(0)
class RangeFinder(object):
model = 'HC_SR04'
GPIO_TRIGGER = 23
GPIO_ECHO = 24
MAX_INCH = 180
def __init__(self, samples=3):
# Use BCM instead of physical pin numbering:
self.samples = samples
GPIO.setmode(GPIO.BCM)
# Set trigger and echo pins as output and input
GPIO.setup(self.GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(self.GPIO_ECHO, GPIO.IN)
# Initialize trigger to low:
GPIO.output(self.GPIO_TRIGGER, False)
@property
def distance_cm(self):
"""
Measure a single distance, in cemtimeters.
"""
GPIO.output(self.GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(self.GPIO_TRIGGER, False)
start = time.time()
stop = time.time()
while GPIO.input(self.GPIO_ECHO) == 0:
start = time.time()
while GPIO.input(self.GPIO_ECHO) == 1:
stop = time.time()
# Convert to inches:
return ((stop - start) * 34300)/2
@property
def distance_inch(self):
"""Measure a single distance, in inches.
"""
GPIO.output(self.GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(self.GPIO_TRIGGER, False)
start = time.time()
stop = time.time()
while GPIO.input(self.GPIO_ECHO) == 0:
start = time.time()
while GPIO.input(self.GPIO_ECHO) == 1:
stop = time.time()
# Convert to inches:
return (((stop - start) * 34300)/2)*0.393701
@property
def average_distance_feet(self):
return self.average_distance(unit='feet')
@property
def average_distance_inch(self):
return self.average_distance(unit='inch')
@property
def average_distance_cm(self):
return self.average_distance(unit='cm')
@property
def average_distance_percent(self):
return self.average_distance(unit='percent')
def average_distance(self, unit='inch'):
tot = 0.0
for i in range(self.samples):
if unit == 'cm':
tot += self.distance_cm
elif unit == 'inch':
tot += self.distance_inch
elif unit == 'percent':
percent = self.MAX_INCH * (self.distance_inch/self.MAX_INCH)
if percent > 100:
percent = 100
tot += percent
else:
tot += self.distance_inch/12.0
time.sleep(0.1)
return tot / self.samples
if __name__ == '__main__':
sensor = RangeFinder()
print('Running main')
while True:
percent = sensor.average_distance_percent
print(100-percent)
time.sleep(.1) | mit | -3,249,227,595,914,577,000 | 24.15 | 76 | 0.563474 | false |
tensorflow/tensorflow | tensorflow/python/kernel_tests/distributions/student_t_test.py | 6 | 19442 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Student t distribution."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import importlib
import math
import numpy as np
from tensorflow.python.eager import backprop
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import test_util
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops.distributions import student_t
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging
def try_import(name): # pylint: disable=invalid-name
module = None
try:
module = importlib.import_module(name)
except ImportError as e:
tf_logging.warning("Could not import %s: %s" % (name, str(e)))
return module
stats = try_import("scipy.stats")
@test_util.run_all_in_graph_and_eager_modes
class StudentTTest(test.TestCase):
def testStudentPDFAndLogPDF(self):
batch_size = 6
df = constant_op.constant([3.] * batch_size)
mu = constant_op.constant([7.] * batch_size)
sigma = constant_op.constant([8.] * batch_size)
df_v = 3.
mu_v = 7.
sigma_v = 8.
t = np.array([-2.5, 2.5, 8., 0., -1., 2.], dtype=np.float32)
student = student_t.StudentT(df, loc=mu, scale=-sigma) # pylint: disable=invalid-unary-operand-type
log_pdf = student.log_prob(t)
self.assertEqual(log_pdf.get_shape(), (6,))
log_pdf_values = self.evaluate(log_pdf)
pdf = student.prob(t)
self.assertEqual(pdf.get_shape(), (6,))
pdf_values = self.evaluate(pdf)
if not stats:
return
expected_log_pdf = stats.t.logpdf(t, df_v, loc=mu_v, scale=sigma_v)
expected_pdf = stats.t.pdf(t, df_v, loc=mu_v, scale=sigma_v)
self.assertAllClose(expected_log_pdf, log_pdf_values)
self.assertAllClose(np.log(expected_pdf), log_pdf_values)
self.assertAllClose(expected_pdf, pdf_values)
self.assertAllClose(np.exp(expected_log_pdf), pdf_values)
def testStudentLogPDFMultidimensional(self):
batch_size = 6
df = constant_op.constant([[1.5, 7.2]] * batch_size)
mu = constant_op.constant([[3., -3.]] * batch_size)
sigma = constant_op.constant(
[[-math.sqrt(10.), math.sqrt(15.)]] * batch_size)
df_v = np.array([1.5, 7.2])
mu_v = np.array([3., -3.])
sigma_v = np.array([np.sqrt(10.), np.sqrt(15.)])
t = np.array([[-2.5, 2.5, 4., 0., -1., 2.]], dtype=np.float32).T
student = student_t.StudentT(df, loc=mu, scale=sigma)
log_pdf = student.log_prob(t)
log_pdf_values = self.evaluate(log_pdf)
self.assertEqual(log_pdf.get_shape(), (6, 2))
pdf = student.prob(t)
pdf_values = self.evaluate(pdf)
self.assertEqual(pdf.get_shape(), (6, 2))
if not stats:
return
expected_log_pdf = stats.t.logpdf(t, df_v, loc=mu_v, scale=sigma_v)
expected_pdf = stats.t.pdf(t, df_v, loc=mu_v, scale=sigma_v)
self.assertAllClose(expected_log_pdf, log_pdf_values)
self.assertAllClose(np.log(expected_pdf), log_pdf_values)
self.assertAllClose(expected_pdf, pdf_values)
self.assertAllClose(np.exp(expected_log_pdf), pdf_values)
def testStudentCDFAndLogCDF(self):
batch_size = 6
df = constant_op.constant([3.] * batch_size)
mu = constant_op.constant([7.] * batch_size)
sigma = constant_op.constant([-8.] * batch_size)
df_v = 3.
mu_v = 7.
sigma_v = 8.
t = np.array([-2.5, 2.5, 8., 0., -1., 2.], dtype=np.float32)
student = student_t.StudentT(df, loc=mu, scale=sigma)
log_cdf = student.log_cdf(t)
self.assertEqual(log_cdf.get_shape(), (6,))
log_cdf_values = self.evaluate(log_cdf)
cdf = student.cdf(t)
self.assertEqual(cdf.get_shape(), (6,))
cdf_values = self.evaluate(cdf)
if not stats:
return
expected_log_cdf = stats.t.logcdf(t, df_v, loc=mu_v, scale=sigma_v)
expected_cdf = stats.t.cdf(t, df_v, loc=mu_v, scale=sigma_v)
self.assertAllClose(expected_log_cdf, log_cdf_values, atol=0., rtol=1e-5)
self.assertAllClose(
np.log(expected_cdf), log_cdf_values, atol=0., rtol=1e-5)
self.assertAllClose(expected_cdf, cdf_values, atol=0., rtol=1e-5)
self.assertAllClose(
np.exp(expected_log_cdf), cdf_values, atol=0., rtol=1e-5)
def testStudentEntropy(self):
df_v = np.array([[2., 3., 7.]]) # 1x3
mu_v = np.array([[1., -1, 0]]) # 1x3
sigma_v = np.array([[1., -2., 3.]]).T # transposed => 3x1
student = student_t.StudentT(df=df_v, loc=mu_v, scale=sigma_v)
ent = student.entropy()
ent_values = self.evaluate(ent)
# Help scipy broadcast to 3x3
ones = np.array([[1, 1, 1]])
sigma_bc = np.abs(sigma_v) * ones
mu_bc = ones.T * mu_v
df_bc = ones.T * df_v
if not stats:
return
expected_entropy = stats.t.entropy(
np.reshape(df_bc, [-1]),
loc=np.reshape(mu_bc, [-1]),
scale=np.reshape(sigma_bc, [-1]))
expected_entropy = np.reshape(expected_entropy, df_bc.shape)
self.assertAllClose(expected_entropy, ent_values)
def testStudentSample(self):
df = constant_op.constant(4.)
mu = constant_op.constant(3.)
sigma = constant_op.constant(-math.sqrt(10.))
df_v = 4.
mu_v = 3.
sigma_v = np.sqrt(10.)
n = constant_op.constant(200000)
student = student_t.StudentT(df=df, loc=mu, scale=sigma)
samples = student.sample(n, seed=123456)
sample_values = self.evaluate(samples)
n_val = 200000
self.assertEqual(sample_values.shape, (n_val,))
self.assertAllClose(sample_values.mean(), mu_v, rtol=0.1, atol=0)
self.assertAllClose(
sample_values.var(), sigma_v**2 * df_v / (df_v - 2), rtol=0.1, atol=0)
self._checkKLApprox(df_v, mu_v, sigma_v, sample_values)
# Test that sampling with the same seed twice gives the same results.
def testStudentSampleMultipleTimes(self):
df = constant_op.constant(4.)
mu = constant_op.constant(3.)
sigma = constant_op.constant(math.sqrt(10.))
n = constant_op.constant(100)
random_seed.set_random_seed(654321)
student = student_t.StudentT(df=df, loc=mu, scale=sigma, name="student_t1")
samples1 = self.evaluate(student.sample(n, seed=123456))
random_seed.set_random_seed(654321)
student2 = student_t.StudentT(df=df, loc=mu, scale=sigma, name="student_t2")
samples2 = self.evaluate(student2.sample(n, seed=123456))
self.assertAllClose(samples1, samples2)
def testStudentSampleSmallDfNoNan(self):
df_v = [1e-1, 1e-5, 1e-10, 1e-20]
df = constant_op.constant(df_v)
n = constant_op.constant(200000)
student = student_t.StudentT(df=df, loc=1., scale=1.)
samples = student.sample(n, seed=123456)
sample_values = self.evaluate(samples)
n_val = 200000
self.assertEqual(sample_values.shape, (n_val, 4))
self.assertTrue(np.all(np.logical_not(np.isnan(sample_values))))
def testStudentSampleMultiDimensional(self):
batch_size = 7
df = constant_op.constant([[5., 7.]] * batch_size)
mu = constant_op.constant([[3., -3.]] * batch_size)
sigma = constant_op.constant(
[[math.sqrt(10.), math.sqrt(15.)]] * batch_size)
df_v = [5., 7.]
mu_v = [3., -3.]
sigma_v = [np.sqrt(10.), np.sqrt(15.)]
n = constant_op.constant(200000)
student = student_t.StudentT(df=df, loc=mu, scale=sigma)
samples = student.sample(n, seed=123456)
sample_values = self.evaluate(samples)
self.assertEqual(samples.get_shape(), (200000, batch_size, 2))
self.assertAllClose(
sample_values[:, 0, 0].mean(), mu_v[0], rtol=0.1, atol=0)
self.assertAllClose(
sample_values[:, 0, 0].var(),
sigma_v[0]**2 * df_v[0] / (df_v[0] - 2),
rtol=0.2,
atol=0)
self._checkKLApprox(df_v[0], mu_v[0], sigma_v[0], sample_values[:, 0, 0])
self.assertAllClose(
sample_values[:, 0, 1].mean(), mu_v[1], rtol=0.1, atol=0)
self.assertAllClose(
sample_values[:, 0, 1].var(),
sigma_v[1]**2 * df_v[1] / (df_v[1] - 2),
rtol=0.2,
atol=0)
self._checkKLApprox(df_v[1], mu_v[1], sigma_v[1], sample_values[:, 0, 1])
def _checkKLApprox(self, df, mu, sigma, samples):
n = samples.size
np.random.seed(137)
if not stats:
return
sample_scipy = stats.t.rvs(df, loc=mu, scale=sigma, size=n)
covg = 0.99
r = stats.t.interval(covg, df, loc=mu, scale=sigma)
bins = 100
hist, _ = np.histogram(samples, bins=bins, range=r)
hist_scipy, _ = np.histogram(sample_scipy, bins=bins, range=r)
self.assertGreater(hist.sum(), n * (covg - .01))
self.assertGreater(hist_scipy.sum(), n * (covg - .01))
hist_min1 = hist + 1. # put at least one item in each bucket
hist_norm = hist_min1 / hist_min1.sum()
hist_scipy_min1 = hist_scipy + 1. # put at least one item in each bucket
hist_scipy_norm = hist_scipy_min1 / hist_scipy_min1.sum()
kl_appx = np.sum(np.log(hist_scipy_norm / hist_norm) * hist_scipy_norm)
self.assertLess(kl_appx, 1)
def testBroadcastingParams(self):
def _check(student):
self.assertEqual(student.mean().get_shape(), (3,))
self.assertEqual(student.variance().get_shape(), (3,))
self.assertEqual(student.entropy().get_shape(), (3,))
self.assertEqual(student.log_prob(2.).get_shape(), (3,))
self.assertEqual(student.prob(2.).get_shape(), (3,))
self.assertEqual(student.sample(37).get_shape(), (37, 3,))
_check(student_t.StudentT(df=[2., 3., 4.,], loc=2., scale=1.))
_check(student_t.StudentT(df=7., loc=[2., 3., 4.,], scale=1.))
_check(student_t.StudentT(df=7., loc=3., scale=[2., 3., 4.,]))
def testBroadcastingPdfArgs(self):
def _assert_shape(student, arg, shape):
self.assertEqual(student.log_prob(arg).get_shape(), shape)
self.assertEqual(student.prob(arg).get_shape(), shape)
def _check(student):
_assert_shape(student, 2., (3,))
xs = np.array([2., 3., 4.], dtype=np.float32)
_assert_shape(student, xs, (3,))
xs = np.array([xs])
_assert_shape(student, xs, (1, 3))
xs = xs.T
_assert_shape(student, xs, (3, 3))
_check(student_t.StudentT(df=[2., 3., 4.,], loc=2., scale=1.))
_check(student_t.StudentT(df=7., loc=[2., 3., 4.,], scale=1.))
_check(student_t.StudentT(df=7., loc=3., scale=[2., 3., 4.,]))
def _check2d(student):
_assert_shape(student, 2., (1, 3))
xs = np.array([2., 3., 4.], dtype=np.float32)
_assert_shape(student, xs, (1, 3))
xs = np.array([xs])
_assert_shape(student, xs, (1, 3))
xs = xs.T
_assert_shape(student, xs, (3, 3))
_check2d(student_t.StudentT(df=[[2., 3., 4.,]], loc=2., scale=1.))
_check2d(student_t.StudentT(df=7., loc=[[2., 3., 4.,]], scale=1.))
_check2d(student_t.StudentT(df=7., loc=3., scale=[[2., 3., 4.,]]))
def _check2d_rows(student):
_assert_shape(student, 2., (3, 1))
xs = np.array([2., 3., 4.], dtype=np.float32) # (3,)
_assert_shape(student, xs, (3, 3))
xs = np.array([xs]) # (1,3)
_assert_shape(student, xs, (3, 3))
xs = xs.T # (3,1)
_assert_shape(student, xs, (3, 1))
_check2d_rows(student_t.StudentT(df=[[2.], [3.], [4.]], loc=2., scale=1.))
_check2d_rows(student_t.StudentT(df=7., loc=[[2.], [3.], [4.]], scale=1.))
_check2d_rows(student_t.StudentT(df=7., loc=3., scale=[[2.], [3.], [4.]]))
def testMeanAllowNanStatsIsFalseWorksWhenAllBatchMembersAreDefined(self):
mu = [1., 3.3, 4.4]
student = student_t.StudentT(df=[3., 5., 7.], loc=mu, scale=[3., 2., 1.])
mean = self.evaluate(student.mean())
self.assertAllClose([1., 3.3, 4.4], mean)
def testMeanAllowNanStatsIsFalseRaisesWhenBatchMemberIsUndefined(self):
mu = [1., 3.3, 4.4]
student = student_t.StudentT(
df=[0.5, 5., 7.], loc=mu, scale=[3., 2., 1.], allow_nan_stats=False)
with self.assertRaisesOpError("x < y"):
self.evaluate(student.mean())
def testMeanAllowNanStatsIsTrueReturnsNaNForUndefinedBatchMembers(self):
mu = [-2, 0., 1., 3.3, 4.4]
sigma = [5., 4., 3., 2., 1.]
student = student_t.StudentT(
df=[0.5, 1., 3., 5., 7.], loc=mu, scale=sigma, allow_nan_stats=True)
mean = self.evaluate(student.mean())
self.assertAllClose([np.nan, np.nan, 1., 3.3, 4.4], mean)
def testVarianceAllowNanStatsTrueReturnsNaNforUndefinedBatchMembers(self):
# df = 0.5 ==> undefined mean ==> undefined variance.
# df = 1.5 ==> infinite variance.
df = [0.5, 1.5, 3., 5., 7.]
mu = [-2, 0., 1., 3.3, 4.4]
sigma = [5., 4., 3., 2., 1.]
student = student_t.StudentT(
df=df, loc=mu, scale=sigma, allow_nan_stats=True)
var = self.evaluate(student.variance())
if not stats:
return
expected_var = [
stats.t.var(d, loc=m, scale=s) for (d, m, s) in zip(df, mu, sigma)
]
# Slicing off first element due to nan/inf mismatch in different SciPy
# versions.
self.assertAllClose(expected_var[1:], var[1:])
def testVarianceAllowNanStatsFalseGivesCorrectValueForDefinedBatchMembers(
self):
# df = 1.5 ==> infinite variance.
df = [1.5, 3., 5., 7.]
mu = [0., 1., 3.3, 4.4]
sigma = [4., 3., 2., 1.]
student = student_t.StudentT(df=df, loc=mu, scale=sigma)
var = self.evaluate(student.variance())
if not stats:
return
expected_var = [
stats.t.var(d, loc=m, scale=s) for (d, m, s) in zip(df, mu, sigma)
]
self.assertAllClose(expected_var, var)
def testVarianceAllowNanStatsFalseRaisesForUndefinedBatchMembers(self):
# df <= 1 ==> variance not defined
student = student_t.StudentT(df=1., loc=0., scale=1., allow_nan_stats=False)
with self.assertRaisesOpError("x < y"):
self.evaluate(student.variance())
# df <= 1 ==> variance not defined
student = student_t.StudentT(
df=0.5, loc=0., scale=1., allow_nan_stats=False)
with self.assertRaisesOpError("x < y"):
self.evaluate(student.variance())
def testStd(self):
# Defined for all batch members.
df = [3.5, 5., 3., 5., 7.]
mu = [-2.2]
sigma = [5., 4., 3., 2., 1.]
student = student_t.StudentT(df=df, loc=mu, scale=sigma)
# Test broadcast of mu across shape of df/sigma
stddev = self.evaluate(student.stddev())
mu *= len(df)
if not stats:
return
expected_stddev = [
stats.t.std(d, loc=m, scale=s) for (d, m, s) in zip(df, mu, sigma)
]
self.assertAllClose(expected_stddev, stddev)
def testMode(self):
df = [0.5, 1., 3]
mu = [-1, 0., 1]
sigma = [5., 4., 3.]
student = student_t.StudentT(df=df, loc=mu, scale=sigma)
# Test broadcast of mu across shape of df/sigma
mode = self.evaluate(student.mode())
self.assertAllClose([-1., 0, 1], mode)
def testPdfOfSample(self):
student = student_t.StudentT(df=3., loc=np.pi, scale=1.)
num = 20000
samples = student.sample(num, seed=123456)
pdfs = student.prob(samples)
mean = student.mean()
mean_pdf = student.prob(student.mean())
sample_vals, pdf_vals, mean_val, mean_pdf_val = self.evaluate(
[samples, pdfs, student.mean(), mean_pdf])
self.assertEqual(samples.get_shape(), (num,))
self.assertEqual(pdfs.get_shape(), (num,))
self.assertEqual(mean.get_shape(), ())
self.assertNear(np.pi, np.mean(sample_vals), err=0.1)
self.assertNear(np.pi, mean_val, err=1e-6)
# Verify integral over sample*pdf ~= 1.
# Tolerance increased since eager was getting a value of 1.002041.
self._assertIntegral(sample_vals, pdf_vals, err=5e-2)
if not stats:
return
self.assertNear(stats.t.pdf(np.pi, 3., loc=np.pi), mean_pdf_val, err=1e-6)
def testFullyReparameterized(self):
df = constant_op.constant(2.0)
mu = constant_op.constant(1.0)
sigma = constant_op.constant(3.0)
with backprop.GradientTape() as tape:
tape.watch(df)
tape.watch(mu)
tape.watch(sigma)
student = student_t.StudentT(df=df, loc=mu, scale=sigma)
samples = student.sample(100)
grad_df, grad_mu, grad_sigma = tape.gradient(samples, [df, mu, sigma])
self.assertIsNotNone(grad_df)
self.assertIsNotNone(grad_mu)
self.assertIsNotNone(grad_sigma)
def testPdfOfSampleMultiDims(self):
student = student_t.StudentT(df=[7., 11.], loc=[[5.], [6.]], scale=3.)
self.assertAllEqual([], student.event_shape)
self.assertAllEqual([], self.evaluate(student.event_shape_tensor()))
self.assertAllEqual([2, 2], student.batch_shape)
self.assertAllEqual([2, 2], self.evaluate(student.batch_shape_tensor()))
num = 50000
samples = student.sample(num, seed=123456)
pdfs = student.prob(samples)
sample_vals, pdf_vals = self.evaluate([samples, pdfs])
self.assertEqual(samples.get_shape(), (num, 2, 2))
self.assertEqual(pdfs.get_shape(), (num, 2, 2))
self.assertNear(5., np.mean(sample_vals[:, 0, :]), err=0.1)
self.assertNear(6., np.mean(sample_vals[:, 1, :]), err=0.1)
self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0, 0], err=0.05)
self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0, 1], err=0.05)
self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1, 0], err=0.05)
self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1, 1], err=0.05)
if not stats:
return
self.assertNear(
stats.t.var(7., loc=0., scale=3.), # loc d.n. effect var
np.var(sample_vals[:, :, 0]),
err=1.0)
self.assertNear(
stats.t.var(11., loc=0., scale=3.), # loc d.n. effect var
np.var(sample_vals[:, :, 1]),
err=1.0)
def _assertIntegral(self, sample_vals, pdf_vals, err=1.5e-3):
s_p = zip(sample_vals, pdf_vals)
prev = (sample_vals.min() - 1000, 0)
total = 0
for k in sorted(s_p, key=lambda x: x[0]):
pair_pdf = (k[1] + prev[1]) / 2
total += (k[0] - prev[0]) * pair_pdf
prev = k
self.assertNear(1., total, err=err)
def testNegativeDofFails(self):
with self.assertRaisesOpError(r"Condition x > 0 did not hold"):
student = student_t.StudentT(
df=[2, -5.], loc=0., scale=1., validate_args=True, name="S")
self.evaluate(student.mean())
def testStudentTWithAbsDfSoftplusScale(self):
df = constant_op.constant([-3.2, -4.6])
mu = constant_op.constant([-4.2, 3.4])
sigma = constant_op.constant([-6.4, -8.8])
student = student_t.StudentTWithAbsDfSoftplusScale(
df=df, loc=mu, scale=sigma)
self.assertAllClose(
math_ops.floor(self.evaluate(math_ops.abs(df))),
self.evaluate(student.df))
self.assertAllClose(self.evaluate(mu), self.evaluate(student.loc))
self.assertAllClose(
self.evaluate(nn_ops.softplus(sigma)), self.evaluate(student.scale))
if __name__ == "__main__":
test.main()
| apache-2.0 | 5,590,174,913,916,238,000 | 37.575397 | 104 | 0.623187 | false |
SUSE/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/next_hop_result.py | 2 | 1736 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class NextHopResult(Model):
"""The information about next hop from the specified VM.
:param next_hop_type: Next hop type. Possible values include: 'Internet',
'VirtualAppliance', 'VirtualNetworkGateway', 'VnetLocal',
'HyperNetGateway', 'None'
:type next_hop_type: str or :class:`NextHopType
<azure.mgmt.network.v2017_06_01.models.NextHopType>`
:param next_hop_ip_address: Next hop IP Address
:type next_hop_ip_address: str
:param route_table_id: The resource identifier for the route table
associated with the route being returned. If the route being returned does
not correspond to any user created routes then this field will be the
string 'System Route'.
:type route_table_id: str
"""
_attribute_map = {
'next_hop_type': {'key': 'nextHopType', 'type': 'str'},
'next_hop_ip_address': {'key': 'nextHopIpAddress', 'type': 'str'},
'route_table_id': {'key': 'routeTableId', 'type': 'str'},
}
def __init__(self, next_hop_type=None, next_hop_ip_address=None, route_table_id=None):
self.next_hop_type = next_hop_type
self.next_hop_ip_address = next_hop_ip_address
self.route_table_id = route_table_id
| mit | 8,696,477,861,373,701,000 | 41.341463 | 90 | 0.626152 | false |
rtshome/ansible_pgsql | library/postgresql_row.py | 1 | 6865 | #!/usr/bin/python
try:
import psycopg2
import psycopg2.extras
from psycopg2 import sql
except ImportError:
postgresqldb_found = False
else:
postgresqldb_found = True
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
from ansible.module_utils.pycompat24 import get_exception
import ast
import traceback
from ansible.module_utils.connection import *
from ansible.module_utils.table import *
# Needed to have pycharm autocompletition working
# noinspection PyBroadException
try:
from module_utils.connection import *
except:
pass
DOCUMENTATION = '''
---
module: postgresql_row
short_description: add or remove a row from PostgreSQL table
version_added: "2.3"
description:
- "add or remove a row from PostgreSQL table"
options:
database:
description:
- Name of the database to connect to.
default: postgres
login_host:
description:
- Host running the database.
default: localhost
login_password:
description:
- The password used to authenticate with.
login_unix_socket:
description:
- Path to a Unix domain socket for local connections.
login_user:
description:
- The username used to authenticate with.
port:
description:
- Database port to connect to.
default: 5432
schema:
description:
- Schema where the table is defined
default: public
table:
description:
- The table to check for row presence/absence
required: true
row:
description:
- Dictionary with the fields of the row
required: true
state:
description:
- The row state
choices:
- present
- absent
extends_documentation_fragment:
- Postgresql
notes:
- This module uses I(psycopg2), a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on
the host before using this module. If the remote host is the PostgreSQL server (which is the default case),
then PostgreSQL must also be installed on the remote host.
For Ubuntu-based systems, install the C(postgresql), C(libpq-dev), and C(python-psycopg2) packages
on the remote host before using this module.
requirements: [ psycopg2 ]
author:
- Denis Gasparin (@rtshome)
'''
EXAMPLES = '''
---
# Ensure row with fields key="environment" and value="production" is present in db
- postgresql_row:
database: my_app_config
table: app_config
row:
key: environment
value: production
state:
present
'''
RETURN = '''
executed_query:
description: the body of the last query sent to the backend (including bound arguments) as bytes string
executed_command:
description: the body of the command executed to insert the missing rows including bound arguments
'''
def run_module():
module_args = dict(
login_user=dict(default="postgres"),
login_password=dict(default="", no_log=True),
login_host=dict(default=""),
login_unix_socket=dict(default=""),
database=dict(default="postgres"),
port=dict(default="5432"),
schema=dict(default="public"),
table=dict(required=True),
row=dict(required=True),
state=dict(default="present"),
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
database = module.params["database"]
schema = module.params["schema"]
table = module.params["table"]
row_columns = ast.literal_eval(module.params["row"])
state = module.params["state"]
if not postgresqldb_found:
module.fail_json(msg="the python psycopg2 module is required")
cursor = None
try:
cursor = connect(database, prepare_connection_params(module.params))
cursor.connection.autocommit = False
sql_identifiers = {
'schema': sql.Identifier(schema),
'table': sql.Identifier(table)
}
sql_where = []
sql_insert_columns = []
sql_parameters = []
col_id = 0
for c, v in row_columns.iteritems():
sql_identifiers['col_%d' % col_id] = sql.Identifier(c)
sql_where.append('{%s} = %%s' % ('col_%d' % col_id))
sql_insert_columns.append('{%s}' % ('col_%d' % col_id))
sql_parameters.append(v)
col_id += 1
cursor.execute("LOCK {schema}.{table}".format(schema=schema, table=table))
cursor.execute(
sql.SQL(
"SELECT COUNT(*) FROM {schema}.{table} WHERE " + " AND ".join(sql_where)
).format(**sql_identifiers),
sql_parameters
)
executed_query = cursor.query
row_count = cursor.fetchone()['count']
if row_count > 1:
raise psycopg2.ProgrammingError('More than 1 one returned by selection query %s' % executed_query)
changed = False
if state == 'present' and row_count != 1:
changed = True
if state == 'absent' and row_count == 1:
changed = True
if module.check_mode or not changed:
cursor.connection.rollback()
module.exit_json(
changed=changed,
executed_query=executed_query
)
if state == 'present':
cursor.execute(
sql.SQL(
'INSERT INTO {schema}.{table} (' + ', '.join(sql_insert_columns) + ') ' +
'VALUES (' + ', '.join(['%s'] * len(sql_parameters)) + ')'
).format(**sql_identifiers),
sql_parameters
)
executed_cmd = cursor.query
else:
cursor.execute(
sql.SQL(
'DELETE FROM {schema}.{table} WHERE ' + ' AND '.join(sql_where)
).format(**sql_identifiers),
sql_parameters
)
executed_cmd = cursor.query
cursor.connection.commit()
module.exit_json(
changed=changed,
executed_query=executed_query,
executed_command=executed_cmd,
)
except psycopg2.ProgrammingError:
e = get_exception()
module.fail_json(msg="database error: the query did not produce any resultset, %s" % to_native(e))
except psycopg2.DatabaseError:
e = get_exception()
module.fail_json(msg="database error: %s" % to_native(e), exception=traceback.format_exc())
except TypeError:
e = get_exception()
module.fail_json(msg="parameters error: %s" % to_native(e))
finally:
if cursor:
cursor.connection.rollback()
if __name__ == '__main__':
run_module()
| bsd-2-clause | -8,077,004,353,811,047,000 | 28.463519 | 118 | 0.595921 | false |
selboo/PyCommand | main.py | 1 | 2351 | #!/usr/bin/env python
# encoding:utf-8
# AUTHOR written by Selboo 2015/03/12
import db, config
import os, sys, re, threading
from pyinotify import WatchManager, Notifier, ProcessEvent
from pyinotify import IN_DELETE, IN_CREATE, IN_MODIFY
from re import compile, findall
from base64 import b64decode
class EventHandler(ProcessEvent):
def process_IN_CREATE(self, event):
#print "Create file: %s " % os.path.join(event.path,event.name)
return 10
def process_IN_DELETE(self, event):
#print "Delete file: %s " % os.path.join(event.path,event.name)
return 20
def process_IN_MODIFY(self, event):
#print "Modify file: %s " % os.path.join(event.path,event.name)
return 30
class ReadLog:
def __init__(self):
logfile = config.readConfig()[0]
self._logfile = logfile
def log(self):
f = self._logfile
try:
read_access_file = open(f, 'r')
read_access_file.seek(2, os.SEEK_END)
return read_access_file
except IOError, e:
print e
sys.exit()
def insert(self):
logfile = self.log()
watch = WatchManager()
mask = IN_DELETE | IN_CREATE | IN_MODIFY
notifier = Notifier(watch, EventHandler())
watch.add_watch(self._logfile, mask,rec=True)
while True:
try:
notifier.process_events()
for line in logfile.readlines():
try:
self.data.db_insert(self.redata(line))
except:
pass
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break
def redata(self, line):
command_re = compile( '(?={).*(?<=})' )
return eval(findall( command_re, line )[0])
def start(self):
self.data = db.PyLog()
self.data.db_conn()
threadings = []
threadings.append(threading.Thread(target=self.data.db_ping))
threadings.append(threading.Thread(target=self.insert))
for t in threadings:
t.start()
if __name__ == '__main__':
Commandlog = ReadLog()
Commandlog.start()
| apache-2.0 | -5,778,610,143,709,891,000 | 26.988095 | 71 | 0.546576 | false |
sloria/osf.io | api_tests/nodes/views/test_node_registrations_list.py | 10 | 3374 | import pytest
from urlparse import urlparse
from api.base.settings.defaults import API_BASE
from osf_tests.factories import (
ProjectFactory,
RegistrationFactory,
AuthUserFactory,
)
def node_url_for(n_id):
return '/{}nodes/{}/'.format(API_BASE, n_id)
@pytest.fixture()
def user():
return AuthUserFactory()
@pytest.mark.django_db
class TestNodeRegistrationList:
@pytest.fixture()
def private_project(self, user):
return ProjectFactory(is_public=False, creator=user)
@pytest.fixture()
def private_registration(self, user, private_project):
return RegistrationFactory(
creator=user,
project=private_project,
is_public=True)
@pytest.fixture()
def private_url(self, private_project):
return '/{}nodes/{}/registrations/'.format(
API_BASE, private_project._id)
@pytest.fixture()
def public_project(self, user):
return ProjectFactory(is_public=True, creator=user)
@pytest.fixture()
def public_registration(self, user, public_project):
return RegistrationFactory(
creator=user,
project=public_project,
is_public=True)
@pytest.fixture()
def public_url(self, public_project):
return '/{}nodes/{}/registrations/'.format(
API_BASE, public_project._id)
def test_node_registration_list(
self, app, user, public_project, private_project, public_registration,
private_registration, public_url, private_url):
# test_return_public_registrations_logged_out
res = app.get(public_url)
assert res.status_code == 200
assert res.content_type == 'application/vnd.api+json'
assert res.json['data'][0]['attributes']['registration'] is True
url = res.json['data'][0]['relationships']['registered_from']['links']['related']['href']
assert urlparse(
url).path == '/{}nodes/{}/'.format(API_BASE, public_project._id)
assert res.json['data'][0]['type'] == 'registrations'
# test_return_public_registrations_logged_in
res = app.get(public_url, auth=user.auth)
assert res.status_code == 200
assert res.json['data'][0]['attributes']['registration'] is True
url = res.json['data'][0]['relationships']['registered_from']['links']['related']['href']
assert urlparse(
url
).path == '/{}nodes/{}/'.format(API_BASE, public_project._id)
assert res.content_type == 'application/vnd.api+json'
assert res.json['data'][0]['type'] == 'registrations'
# test_return_private_registrations_logged_out
res = app.get(private_url, expect_errors=True)
assert res.status_code == 401
assert 'detail' in res.json['errors'][0]
# test_return_private_registrations_logged_in_contributor
res = app.get(private_url, auth=user.auth)
assert res.status_code == 200
assert res.json['data'][0]['attributes']['registration'] is True
url = res.json['data'][0]['relationships']['registered_from']['links']['related']['href']
assert urlparse(
url
).path == '/{}nodes/{}/'.format(API_BASE, private_project._id)
assert res.content_type == 'application/vnd.api+json'
assert res.json['data'][0]['type'] == 'registrations'
| apache-2.0 | 1,766,313,734,836,958,500 | 34.515789 | 97 | 0.623296 | false |
mcolom/ipolDevel | tools/demo_copy/demo_copy.py | 1 | 11377 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# GNU General Public Licence (GPL)
#
# 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
#
"""
This script clones a demo from a source environment
"""
import argparse
import sys
import json
import os
import socket
import urllib.request
import requests
def post(service, host, params=None, data=None, files=None, servicejson=None):
"""
Post request to service
"""
url = 'http://{}{}'.format(host, service)
return requests.post(url, params=params, data=data, files=files, json=servicejson)
def get(service, host, params=None):
"""
Get resource
"""
url = 'http://{}{}/{}'.format(host, service, params)
return urllib.request.urlopen(url)
def copy_demo(demo_id, host, source_host):
"""
Copy demo main method.
"""
print("Origin demo:", demo_id)
new_id = demo_id
ddl = get_ddl(demo_id, source_host)
demo_state = get_demo_state(source_host, demo_id)
if 'demo_title' in ddl['general']:
demo_title = ddl['general']['demo_title']
else:
print('**Please change the demo title and add it to the general section in the ddl**')
demo_title = "CHANGE THIS DEMO TITLE"
if ddl_exists(demo_id, host):
new_id = input("\nDemo ID already exists. Choose a new ID or the same to overwrite a demo:")
print("Destination demo:", new_id)
try:
new_id = int(new_id)
except ValueError:
print("That isn't a number")
return
create_demo_response = create_demo(new_id, demo_title, demo_state, host)
if create_demo_response['status'] != 'OK':
demo_title = input("\nChoose a new title: ") or sys.exit("Title cannot be empty")
create_demo(new_id, demo_title, demo_state, host)
print('Adding ddl...')
add_ddl(host, new_id)
os.remove('ddl.json')
print('Adding demo_extras...')
clone_demo_extras(host, source_host, demo_id, new_id)
print('Adding blobs...')
copy_blobs_to_demo(host, source_host, demo_id, new_id)
demo_templates = get_demo_template_names(source_host, demo_id)
local_templates = get_all_templates(host)
for template_name in demo_templates:
if template_name not in local_templates:
print('Cloning template: {}...'.format(template_name))
copy_template(host, source_host, template_name)
associate_template(host, new_id, template_name)
else:
print('Associating template: {}...'.format(template_name))
associate_template(host, new_id, template_name)
print('Done')
def ddl_exists(demo_id, host):
"""
Check if DDL exists
"""
http_response = post('/api/demoinfo/get_ddl', host, params={"demo_id": demo_id}).json()
if http_response['status'] == 'OK':
return True
return False
def get_demo_state(host, demo_id):
"""
Get a demo state
"""
response = get('/api/demoinfo/read_demo_metainfo', host, demo_id)
string = response.read().decode('utf-8')
json_obj = json.loads(string)
return json_obj['state']
def get_ddl(demo_id, host):
"""
Read a DDL
"""
try:
resp = post('/api/demoinfo/get_ddl', host, params={"demo_id": demo_id})
response = resp.json()
if response['status'] != 'OK':
message = "ERROR: get_ddl returned KO for demo {} from {}".format(demo_id, host)
raise GetDDLError(message)
ddl = response['last_demodescription']
if not ddl:
raise GetDDLError("ERROR: Empty or non-existing DDL for demo #{} on {}".format(demo_id, host))
last_demodescription = ddl
ddl_json = last_demodescription['ddl']
with open('ddl.json', 'w') as out:
out.write(ddl_json)
return json.loads(ddl_json)
except GetDDLError:
print(message)
sys.exit("Aborted")
except Exception as ex:
print("ERROR: Failed to read DDL from {}".format(ex))
sys.exit("Aborted")
def add_ddl(host, demo_id):
"""
Add the ddl to the demo
"""
params = {'demoid': demo_id}
with open('ddl.json', 'r') as out:
ddl = out.read()
response = post('/api/demoinfo/save_ddl', host, params=params, data=ddl)
return response.json()
def create_demo(demo_id, title, state, host):
"""
Creates a demo
"""
response = post('/api/demoinfo/add_demo', host, params={'editorsdemoid': demo_id, 'title': title, 'state': state})
return response.json()
def clone_demo_extras(host, source_host, demo_id, new_id):
"""
Get DemoExtras from a demo
"""
serviceparams = {'demo_id': demo_id}
response = post('/api/demoinfo/get_demo_extras_info', source_host, params=serviceparams).json()
if 'url' in response:
url = response['url']
filename = response['url'].split("/")[-1]
demo_extras = urllib.request.urlopen(url)
add_demo_extras(host, new_id, demo_extras, filename)
def add_demo_extras(host, demo_id, demo_extras, demo_extras_name):
"""
Add DemoExtras to the demo
"""
files = {'demoextras': demo_extras}
params = {'demo_id': demo_id, 'demoextras_name': demo_extras_name}
response = post('/api/demoinfo/add_demoextras', host, params=params, files=files)
return response.json()
def copy_blobs_to_demo(host, source_host, demo_id, new_id):
"""
Copy blobs to demo or template
"""
blobs_json = post('/api/blobs/get_demo_owned_blobs', source_host, params={'demo_id': demo_id}).json()
local_demo_blobs = get_demo_owned_blobs(host, new_id)
for blobset in blobs_json['sets']:
set_name = blobset['name']
blobs = blobset['blobs']
for pos_in_set in blobs:
blob = blobs[pos_in_set]
if blob['blob'] not in local_demo_blobs:
title = blob['title']
credit = blob['credit']
blob_file = get_blob_data(source_host, blob['blob'])
if 'vr' in blob:
vr = get_blob_data(source_host, blob['vr'])
add_blob_to_demo(host, new_id, blob_file, title, set_name, pos_in_set, credit, vr=vr)
else:
add_blob_to_demo(host, new_id, blob_file, title, set_name, pos_in_set, credit)
def get_demo_owned_blobs(host, demo_id):
"""
Get all blobs owned by a demo
"""
params = {'demo_id': demo_id}
blobs_response = post('/api/blobs/get_demo_owned_blobs', host, params=params).json()
owned_blobs = []
for blobset in blobs_response['sets']:
blobs = blobset['blobs']
for index in blobs:
blob = blobs[index]
owned_blobs.append(blob['blob'])
return owned_blobs
def get_blob_data(host, url):
"""
Get a blob binary data from url
"""
url = 'http://{}{}'.format(host, url)
blob = urllib.request.urlopen(url)
return blob
def add_blob_to_demo(host, demo_id, blob, blob_title, set_name, pos_in_set, credit, vr=None):
"""
Add a blob to demo
"""
files = {'blob': blob}
if vr:
files['blob_vr'] = vr
params = {'demo_id': demo_id, 'title': blob_title, 'blob_set': set_name, 'pos_set': pos_in_set, 'credit': credit}
response = post('/api/blobs/add_blob_to_demo', host, params=params, files=files)
return response.json()
#####################
# Template methods #
#####################
def get_all_templates(host):
"""
Get all existing templates from a host
"""
response = post('/api/blobs/get_all_templates', host).json()
return response['templates']
def get_demo_template_names(host, demo_id):
"""
Get all templates associated to a demo
"""
params = {'demo_id': demo_id}
response = post('/api/blobs/get_demo_templates', host, params=params).json()
return response['templates']
def associate_template(host, new_id, template_name):
"""
Associate template to a demo
"""
params = {'demo_id': new_id, 'template_names': template_name}
post('/api/blobs/add_templates_to_demo', host, params=params)
def copy_template(host, source_host, template_name):
"""
Copy template to local
"""
params = {'template_name': template_name}
post('/api/blobs/create_template', host, params=params).json()
copy_blobs_from_template(host, source_host, template_name)
def copy_blobs_from_template(host, source_host, template_name):
"""
Copy blobs to template
"""
params = {'template_name': template_name}
blobs_json = post('/api/blobs/get_template_blobs', source_host, params=params).json()
# blobs_json = blobs_response.json()
for blobset in blobs_json['sets']:
set_name = blobset['name']
blobs = blobset['blobs']
for index in blobs:
blob = blobs[index]
title = blob['title']
credit = blob['credit']
pos_in_set = index
blob_file = get_blob_data(source_host, blob['blob'])
if 'vr' in blob:
vr = get_blob_data(source_host, blob['vr'])
add_blob_to_template(host, template_name, blob_file, set_name, pos_in_set, credit, title, vr=vr)
else:
add_blob_to_template(host, template_name, blob_file, set_name, pos_in_set, credit, title)
def add_blob_to_template(host, template_name, blob, set_name, pos_in_set, credit, title, vr=None):
"""
Add a blob to the demo
"""
files = {'blob': blob}
if vr:
files['blob_vr'] = vr
params = {'template_name': template_name, 'title': title, 'blob_set': set_name, 'pos_set': pos_in_set, 'credit': credit}
response = post('/api/blobs/add_blob_to_template', host, params=params, files=files)
return response.json()
class Error(Exception):
"""
Base class for exceptions in this module.
"""
pass
class GetDDLError(Error):
"""
GetDDLError handler
"""
def __init__(self, message):
super().__init__()
self.message = message
# Command help
parser = argparse.ArgumentParser()
parser.add_argument("demo_id", type=int, help="identifier of the demo to be copied")
parser.add_argument("-i", '--integration', help="Use integration environment", action="store_true")
args = parser.parse_args()
# Obtain demo ID from arguments
args_demo_id = args.demo_id
# Source host
if args.integration:
origin_host = "integration.ipol.im"
else:
origin_host = "ipolcore.ipol.im"
print('Source: ', origin_host)
# Host destination of the demo
destination_host = socket.getfqdn()
if (destination_host != "integration.ipol.im" and destination_host != "ipolcore.ipol.im"):
destination_host = "127.0.0.1"
copy_demo(args_demo_id, destination_host, origin_host)
| agpl-3.0 | 2,079,383,569,601,409,500 | 32.961194 | 124 | 0.617298 | false |
UCL-INGI/INGInious | inginious/agent/docker_agent/_docker_interface.py | 1 | 12251 | # -*- coding: utf-8 -*-
#
# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
# more information about the licensing of this file.
"""
(not asyncio) Interface to Docker
"""
import os
from datetime import datetime
from typing import List, Tuple, Dict
import docker
import logging
from inginious.agent.docker_agent._docker_runtime import DockerRuntime
DOCKER_AGENT_VERSION = 3
class DockerInterface(object): # pragma: no cover
"""
(not asyncio) Interface to Docker
We do not test coverage here, as it is a bit complicated to interact with docker in tests.
Docker-py itself is already well tested.
"""
@property
def _docker(self):
return docker.from_env()
def get_containers(self, runtimes: List[DockerRuntime]) -> Dict[str, Dict[str, Dict[str, str]]]:
"""
:param runtimes: a list of DockerRuntime. Each DockerRuntime.envtype must appear only once.
:return: a dict of available containers in the form
{
"envtype": { # the value of DockerRuntime.envtype. Eg "docker".
"name": { # for example, "default"
"id": "container img id", # "sha256:715c5cb5575cdb2641956e42af4a53e69edf763ce701006b2c6e0f4f39b68dd3"
"created": 12345678, # create date
"ports": [22, 434], # list of ports needed
"runtime": "runtime" # the value of DockerRuntime.runtime. Eg "runc".
}
}
}
"""
assert len(set(x.envtype for x in runtimes)) == len(runtimes) # no duplicates in the envtypes
logger = logging.getLogger("inginious.agent.docker")
# First, create a dict with {"env": {"id": {"title": "alias", "created": 000, "ports": [0, 1]}}}
images = {x.envtype: {} for x in runtimes}
for x in self._docker.images.list(filters={"label": "org.inginious.grading.name"}):
title = None
try:
title = x.labels["org.inginious.grading.name"]
created = datetime.strptime(x.attrs['Created'][:-4], "%Y-%m-%dT%H:%M:%S.%f").timestamp()
ports = [int(y) for y in x.labels["org.inginious.grading.ports"].split(
",")] if "org.inginious.grading.ports" in x.labels else []
for docker_runtime in runtimes:
if docker_runtime.run_as_root or "org.inginious.grading.need_root" not in x.labels:
logger.info("Envtype %s (%s) can use container %s", docker_runtime.envtype, docker_runtime.runtime, title)
if x.labels.get("org.inginious.grading.agent_version") != str(DOCKER_AGENT_VERSION):
logger.warning(
"Container %s is made for an old/newer version of the agent (container version is "
"%s, but it should be %i). INGInious will ignore the container.", title,
str(x.labels.get("org.inginious.grading.agent_version")), DOCKER_AGENT_VERSION)
continue
images[docker_runtime.envtype][x.attrs['Id']] = {
"title": title,
"created": created,
"ports": ports,
"runtime": docker_runtime.runtime
}
except:
logging.getLogger("inginious.agent").exception("Container %s is badly formatted", title or "[cannot load title]")
# Then, we keep only the last version of each name
latest = {}
for envtype, content in images.items():
latest[envtype] = {}
for img_id, img_c in content.items():
if img_c["title"] not in latest[envtype] or latest[envtype][img_c["title"]]["created"] < img_c["created"]:
latest[envtype][img_c["title"]] = {"id": img_id, **img_c}
return latest
def get_host_ip(self, env_with_dig='ingi/inginious-c-default'):
"""
Get the external IP of the host of the docker daemon. Uses OpenDNS internally.
:param env_with_dig: any container image that has dig
"""
try:
container = self._docker.containers.create(env_with_dig, command="dig +short myip.opendns.com @resolver1.opendns.com")
container.start()
response = container.wait()
assert response["StatusCode"] == 0 if isinstance(response, dict) else response == 0
answer = container.logs(stdout=True, stderr=False).decode('utf8').strip()
container.remove(v=True, link=False, force=True)
return answer
except:
return None
def create_container(self, image, network_grading, mem_limit, task_path, sockets_path,
course_common_path, course_common_student_path, runtime: str, ports=None):
"""
Creates a container.
:param image: env to start (name/id of a docker image)
:param network_grading: boolean to indicate if the network should be enabled in the container or not
:param mem_limit: in Mo
:param task_path: path to the task directory that will be mounted in the container
:param sockets_path: path to the socket directory that will be mounted in the container
:param course_common_path:
:param course_common_student_path:
:param runtime: name of the docker runtime to use
:param ports: dictionary in the form {docker_port: external_port}
:return: the container id
"""
task_path = os.path.abspath(task_path)
sockets_path = os.path.abspath(sockets_path)
course_common_path = os.path.abspath(course_common_path)
course_common_student_path = os.path.abspath(course_common_student_path)
if ports is None:
ports = {}
response = self._docker.containers.create(
image,
stdin_open=True,
mem_limit=str(mem_limit) + "M",
memswap_limit=str(mem_limit) + "M",
mem_swappiness=0,
oom_kill_disable=True,
network_mode=("bridge" if (network_grading or len(ports) > 0) else 'none'),
ports=ports,
volumes={
task_path: {'bind': '/task'},
sockets_path: {'bind': '/sockets'},
course_common_path: {'bind': '/course/common', 'mode': 'ro'},
course_common_student_path: {'bind': '/course/common/student', 'mode': 'ro'}
},
runtime=runtime
)
return response.id
def create_container_student(self, runtime: str, image: str, mem_limit, student_path,
socket_path, systemfiles_path, course_common_student_path,
share_network_of_container: str=None):
"""
Creates a student container
:param runtime: name of the docker runtime to use
:param image: env to start (name/id of a docker image)
:param mem_limit: in Mo
:param student_path: path to the task directory that will be mounted in the container
:param socket_path: path to the socket that will be mounted in the container
:param systemfiles_path: path to the systemfiles folder containing files that can override partially some defined system files
:param course_common_student_path:
:param share_network_of_container: (deprecated) if a container id is given, the new container will share its
network stack.
:return: the container id
"""
student_path = os.path.abspath(student_path)
socket_path = os.path.abspath(socket_path)
systemfiles_path = os.path.abspath(systemfiles_path)
course_common_student_path = os.path.abspath(course_common_student_path)
response = self._docker.containers.create(
image,
stdin_open=True,
command="_run_student_intern",
mem_limit=str(mem_limit) + "M",
memswap_limit=str(mem_limit) + "M",
mem_swappiness=0,
oom_kill_disable=True,
network_mode=('none' if not share_network_of_container else ('container:' + share_network_of_container)),
volumes={
student_path: {'bind': '/task/student'},
socket_path: {'bind': '/__parent.sock'},
systemfiles_path: {'bind': '/task/systemfiles', 'mode': 'ro'},
course_common_student_path: {'bind': '/course/common/student', 'mode': 'ro'}
},
runtime=runtime
)
return response.id
def start_container(self, container_id):
""" Starts a container (obviously) """
self._docker.containers.get(container_id).start()
def attach_to_container(self, container_id):
""" A socket attached to the stdin/stdout of a container. The object returned contains a get_socket() function to get a socket.socket
object and close_socket() to close the connection """
sock = self._docker.containers.get(container_id).attach_socket(params={
'stdin': 1,
'stdout': 1,
'stderr': 0,
'stream': 1,
})
# fix a problem with docker-py; we must keep a reference of sock at every time
return FixDockerSocket(sock)
def get_logs(self, container_id):
""" Return the full stdout/stderr of a container"""
stdout = self._docker.containers.get(container_id).logs(stdout=True, stderr=False).decode('utf8')
stderr = self._docker.containers.get(container_id).logs(stdout=False, stderr=True).decode('utf8')
return stdout, stderr
def get_stats(self, container_id):
"""
:param container_id:
:return: an iterable that contains dictionnaries with the stats of the running container. See the docker api for content.
"""
return self._docker.containers.get(container_id).stats(decode=True)
def list_running_containers(self):
""" Returns a set of running container ids """
return {x.attrs.get('Id') for x in self._docker.containers.list(all=False, sparse=True)}
def remove_container(self, container_id):
"""
Removes a container (with fire)
"""
self._docker.containers.get(container_id).remove(v=True, link=False, force=True)
def kill_container(self, container_id, signal=None):
"""
Kills a container
:param signal: custom signal. Default is SIGKILL.
"""
self._docker.containers.get(container_id).kill(signal)
def event_stream(self, filters=None, since=None):
"""
:param filters: filters to apply on messages. See docker api.
:param since: time since when the events should be sent. See docker api.
:return: an iterable that contains events from docker. See the docker api for content.
"""
if filters is None:
filters = {}
return self._docker.events(decode=True, filters=filters, since=since)
def list_runtimes(self) -> Dict[str, str]:
"""
:return: dict of runtime: path_to_runtime
"""
return {name: x["path"] for name, x in self._docker.info()["Runtimes"].items()}
class FixDockerSocket(): # pragma: no cover
"""
Fix the API inconsistency of docker-py with attach_socket
"""
def __init__(self, docker_py_sock):
self.docker_py_sock = docker_py_sock
def get_socket(self):
"""
Returns a valid socket.socket object
"""
try:
return self.docker_py_sock._sock # pylint: disable=protected-access
except AttributeError:
return self.docker_py_sock
def close_socket(self):
"""
Correctly closes the socket
:return:
"""
try:
self.docker_py_sock._sock.close() # pylint: disable=protected-access
except AttributeError:
pass
self.docker_py_sock.close()
| agpl-3.0 | -131,092,979,959,046,900 | 43.875458 | 141 | 0.583299 | false |
boberfly/gaffer | python/GafferSceneTest/CopyPrimitiveVariablesTest.py | 7 | 9258 | ##########################################################################
#
# Copyright (c) 2019, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software 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 unittest
import six
import IECore
import Gaffer
import GafferScene
import GafferSceneTest
class CopyPrimitiveVariablesTest( GafferSceneTest.SceneTestCase ) :
def testConstantVariables( self ) :
sphere = GafferScene.Sphere()
sphere["name"].setValue( "object" )
cube = GafferScene.Cube()
cube["name"].setValue( "object" )
cubeVariables = GafferScene.PrimitiveVariables()
cubeVariables["in"].setInput( cube["out"] )
cubeVariables["primitiveVariables"].addChild( Gaffer.NameValuePlug( "ten", IECore.IntData( 10 ) ) )
cubeVariables["primitiveVariables"].addChild( Gaffer.NameValuePlug( "twenty", IECore.IntData( 20 ) ) )
copy = GafferScene.CopyPrimitiveVariables()
copy["in"].setInput( sphere["out"] )
copy["source"].setInput( cubeVariables["out"] )
# Not filtered to anything, so should be a perfect pass through.
self.assertScenesEqual( sphere["out"], copy["out"] )
self.assertSceneHashesEqual( sphere["out"], copy["out"] )
# Add a filter, should still be a pass through because we haven't
# asked for any variables to be copied.
objectFilter = GafferScene.PathFilter()
objectFilter["paths"].setValue( IECore.StringVectorData( [ "/object" ] ) )
copy["filter"].setInput( objectFilter["out"] )
self.assertScenesEqual( sphere["out"], copy["out"] )
# Copy something that doesn't exist. This isn't an error, because the
# variables are treated as match patterns.
copy["primitiveVariables"].setValue( "these don't exist" )
self.assertScenesEqual( sphere["out"], copy["out"] )
# Copy things that do exist, and check that it has worked.
copy["primitiveVariables"].setValue( "ten twenty" )
self.assertEqual(
set( copy["out"].object( "/object" ).keys() ),
set( sphere["out"].object( "/object" ).keys() ) | { "ten", "twenty" },
)
self.assertEqual(
copy["out"].object( "/object" )["ten"],
cubeVariables["out"].object( "/object" )["ten"],
)
self.assertEqual(
copy["out"].object( "/object" )["twenty"],
cubeVariables["out"].object( "/object" )["twenty"],
)
# Check that wildcards work
copy["primitiveVariables"].setValue( "twen*" )
self.assertEqual(
set( copy["out"].object( "/object" ).keys() ),
set( sphere["out"].object( "/object" ).keys() ) | { "twenty" },
)
def testInterpolatedVariables( self ) :
littleSphere = GafferScene.Sphere()
bigSphere = GafferScene.Sphere()
bigSphere["radius"].setValue( 10 )
sphereFilter = GafferScene.PathFilter()
sphereFilter["paths"].setValue( IECore.StringVectorData( [ "/sphere" ] ) )
copy = GafferScene.CopyPrimitiveVariables()
copy["in"].setInput( littleSphere["out"] )
copy["source"].setInput( bigSphere["out"] )
copy["filter"].setInput( sphereFilter["out"] )
self.assertScenesEqual( copy["out"], littleSphere["out"] )
copy["primitiveVariables"].setValue( "*" )
self.assertScenesEqual( copy["out"], bigSphere["out"] )
# If the spheres have differing topologies, then we can't copy
# and should get an error.
bigSphere["divisions"][0].setValue( 100 )
with six.assertRaisesRegex( self, RuntimeError, 'Cannot copy .* from "/sphere" to "/sphere" because source and destination primitives have different topology' ) :
copy["out"].object( "/sphere" )
def testMismatchedHierarchy( self ) :
sphere = GafferScene.Sphere()
cube = GafferScene.Cube()
sphereFilter = GafferScene.PathFilter()
sphereFilter["paths"].setValue( IECore.StringVectorData( [ "/sphere" ] ) )
copy = GafferScene.CopyPrimitiveVariables()
copy["in"].setInput( sphere["out"] )
copy["source"].setInput( cube["out"] )
copy["filter"].setInput( sphereFilter["out"] )
copy["primitiveVariables"].setValue( "*" )
self.assertEqual( copy["out"].object( "/sphere" ), copy["in"].object( "/sphere" ) )
def testSourceLocation( self ) :
sphere1 = GafferScene.Sphere()
sphere2 = GafferScene.Sphere()
sphere2["radius"].setValue( 2 )
sphere3 = GafferScene.Sphere()
sphere3["radius"].setValue( 3 )
group = GafferScene.Group()
group["in"][0].setInput( sphere2["out"] )
group["in"][1].setInput( sphere3["out"] )
sphereFilter = GafferScene.PathFilter()
sphereFilter["paths"].setValue( IECore.StringVectorData( [ "/sphere" ] ) )
copy = GafferScene.CopyPrimitiveVariables()
copy["in"].setInput( sphere1["out"] )
copy["source"].setInput( group["out"] )
copy["filter"].setInput( sphereFilter["out"] )
copy["primitiveVariables"].setValue( "P" )
copy["sourceLocation"].setValue( "/group/sphere" )
self.assertEqual( copy["out"].object( "/sphere" )["P"], group["out"].object( "/group/sphere" )["P"] )
copy["sourceLocation"].setValue( "/group/sphere1" )
self.assertEqual( copy["out"].object( "/sphere" )["P"], group["out"].object( "/group/sphere1" )["P"] )
# Copying from a non-existing location should be a no-op
copy["sourceLocation"].setValue( "/road/to/nowhere" )
self.assertScenesEqual( copy["out"], sphere1["out"] )
def testBoundUpdate( self ) :
sphere1 = GafferScene.Sphere()
sphere2 = GafferScene.Sphere()
sphere2["radius"].setValue( 2 )
group = GafferScene.Group()
group["in"][0].setInput( sphere1["out"] )
sphereFilter = GafferScene.PathFilter()
sphereFilter["paths"].setValue( IECore.StringVectorData( [ "/group/sphere" ] ) )
copy = GafferScene.CopyPrimitiveVariables()
copy["in"].setInput( group["out"] )
copy["source"].setInput( sphere2["out"] )
copy["filter"].setInput( sphereFilter["out"] )
copy["sourceLocation"].setValue( "/sphere" )
copy["primitiveVariables"].setValue( "P" )
# We're copying "P", so the bounds need updating.
self.assertEqual( copy["out"].object( "/group/sphere" )["P"], sphere2["out"].object( "/sphere" )["P"] )
self.assertSceneValid( copy["out"] )
self.assertEqual( copy["out"].bound( "/" ), sphere2["out"].bound( "/" ) )
self.assertEqual( copy["out"].bound( "/group" ), sphere2["out"].bound( "/" ) )
self.assertEqual( copy["out"].bound( "/group/sphere" ), sphere2["out"].bound( "/" ) )
# If we turn off "adjustBounds", we want a perfect pass through of the input
# bounds.
copy["adjustBounds"].setValue( False )
self.assertScenesEqual( copy["out"], group["out"], checks = { "bound" } )
self.assertSceneHashesEqual( copy["out"], group["out"], checks = { "bound" } )
# If "adjustBounds" is on, but "P" isn't being copied, we also want
# a perfect pass through of the input bounds. We don't want to pay for
# unnecessary bounds propagation.
copy["adjustBounds"].setValue( True )
copy["primitiveVariables"].setValue( "uv" )
self.assertScenesEqual( copy["out"], group["out"], checks = { "bound" } )
self.assertSceneHashesEqual( copy["out"], group["out"], checks = { "bound" } )
def testDeleteSourceLocation( self ) :
sphere1 = GafferScene.Sphere()
sphere2 = GafferScene.Sphere()
sphere2["radius"].setValue( 2 )
sphereFilter = GafferScene.PathFilter()
sphereFilter["paths"].setValue( IECore.StringVectorData( [ "/sphere" ] ) )
prune = GafferScene.Prune()
prune["in"].setInput( sphere2["out"] )
copy = GafferScene.CopyPrimitiveVariables()
copy["in"].setInput( sphere1["out"] )
copy["source"].setInput( prune["out"] )
copy["filter"].setInput( sphereFilter["out"] )
copy["primitiveVariables"].setValue( "*" )
self.assertScenesEqual( copy["out"], sphere2["out"] )
prune["filter"].setInput( sphereFilter["out"] )
self.assertScenesEqual( copy["out"], sphere1["out"] )
if __name__ == "__main__":
unittest.main()
| bsd-3-clause | -6,846,627,221,472,812,000 | 35.164063 | 164 | 0.67628 | false |
rmotr-curriculum/quiz-itp-w2 | quiz-questions/question_2.py | 1 | 2558 | import unittest
def number_of_customers_per_state(customers):
"""Return the number of customers per state.
This function receives a dictionary containing states (as keys) and
customers for those states (as a list of dictionaries) and should
return a final dictionary containing the count of customers per state.
customers = {
'UT': [{
'name': 'Mary',
'age': 28
}, {
'name': 'John', # Eldest
'age': 31
}],
'NY': [{
'name': 'Linda', # Eldest
'age': 71
}]
}
number_of_customers_per_state(customers)
>>>
{
'UT': 2,
'NY': 1
}
"""
# Write your code here
pass
class NumberOfCustomersPerStateTestCase(unittest.TestCase):
def test_number_of_customers_per_state(self):
"""Should return the correct number of customers per state."""
customers = {
'UT': [{
'name': 'Mary',
'age': 28
}, {
'name': 'John',
'age': 31
}, {
'name': 'Robert',
'age': 16
}],
'NY': [{
'name': 'Linda',
'age': 71
}],
'CA': [{
'name': 'Barbara',
'age': 15
}, {
'name': 'Paul',
'age': 18
}]
}
expected_result = {
'UT': 3,
'NY': 1,
'CA': 2
}
self.assertEqual(
number_of_customers_per_state(customers), expected_result)
def test_number_of_customers_per_state_with_blank_state(self):
"""Should return the correct number of customers per state."""
customers = {
'UT': [{
'name': 'Mary',
'age': 28
}, {
'name': 'John',
'age': 31
}, {
'name': 'Robert',
'age': 16
}],
'NY': None, # Be Careful! NY value is None
'CA': [{
'name': 'Barbara',
'age': 15
}, {
'name': 'Paul',
'age': 18
}]
}
expected_result = {
'UT': 3,
'NY': 0,
'CA': 2
}
self.assertEqual(
number_of_customers_per_state(customers), expected_result)
if __name__ == '__main__':
unittest.main()
| mit | 3,779,246,963,487,866,000 | 24.326733 | 74 | 0.397576 | false |
paour/weblate | weblate/trans/migrations/0021_auto__chg_field_change_user.py | 2 | 14771 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2014 Michal Čihař <[email protected]>
#
# This file is part of Weblate <http://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Change.user'
db.alter_column('trans_change', 'user_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True))
def backwards(self, orm):
# User chose to not deal with backwards NULL issues for 'Change.user'
raise RuntimeError("Cannot reverse this migration. 'Change.user' and its values cannot be restored.")
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'lang.language': {
'Meta': {'ordering': "['name']", 'object_name': 'Language'},
'code': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'nplurals': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'pluralequation': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
},
'trans.change': {
'Meta': {'ordering': "['-timestamp']", 'object_name': 'Change'},
'action': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'translation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.Translation']"}),
'unit': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.Unit']", 'null': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'})
},
'trans.check': {
'Meta': {'object_name': 'Check'},
'check': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ignore': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lang.Language']", 'null': 'True', 'blank': 'True'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.Project']"})
},
'trans.comment': {
'Meta': {'ordering': "['timestamp']", 'object_name': 'Comment'},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'}),
'comment': ('django.db.models.fields.TextField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lang.Language']", 'null': 'True', 'blank': 'True'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.Project']"}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
},
'trans.dictionary': {
'Meta': {'ordering': "['source']", 'object_name': 'Dictionary'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lang.Language']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.Project']"}),
'source': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'}),
'target': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'trans.indexupdate': {
'Meta': {'object_name': 'IndexUpdate'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'source': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'unit': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.Unit']"})
},
'trans.project': {
'Meta': {'ordering': "['name']", 'object_name': 'Project'},
'commit_message': ('django.db.models.fields.CharField', [], {'default': "'Translated using Weblate.'", 'max_length': '200'}),
'committer_email': ('django.db.models.fields.EmailField', [], {'default': "'[email protected]'", 'max_length': '75'}),
'committer_name': ('django.db.models.fields.CharField', [], {'default': "'Weblate'", 'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'instructions': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'mail': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'merge_style': ('django.db.models.fields.CharField', [], {'default': "'merge'", 'max_length': '10'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'new_lang': ('django.db.models.fields.CharField', [], {'default': "'contact'", 'max_length': '10'}),
'push_on_commit': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'set_translation_team': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'web': ('django.db.models.fields.URLField', [], {'max_length': '200'})
},
'trans.subproject': {
'Meta': {'ordering': "['project__name', 'name']", 'object_name': 'SubProject'},
'branch': ('django.db.models.fields.CharField', [], {'default': "'master'", 'max_length': '50'}),
'file_format': ('django.db.models.fields.CharField', [], {'default': "'auto'", 'max_length': '50'}),
'filemask': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'locked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.Project']"}),
'push': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
'repo': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'report_source_bugs': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'repoweb': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'template': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'})
},
'trans.suggestion': {
'Meta': {'object_name': 'Suggestion'},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lang.Language']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.Project']"}),
'target': ('django.db.models.fields.TextField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
},
'trans.translation': {
'Meta': {'ordering': "['language__name']", 'object_name': 'Translation'},
'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True'}),
'filename': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'fuzzy': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['lang.Language']"}),
'language_code': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '20'}),
'lock_time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'lock_user': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'revision': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100', 'blank': 'True'}),
'subproject': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.SubProject']"}),
'total': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'}),
'translated': ('django.db.models.fields.IntegerField', [], {'default': '0', 'db_index': 'True'})
},
'trans.unit': {
'Meta': {'ordering': "['position']", 'object_name': 'Unit'},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'}),
'comment': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'context': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'flags': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'fuzzy': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'position': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'source': ('django.db.models.fields.TextField', [], {}),
'target': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'translated': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'translation': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['trans.Translation']"})
}
}
complete_apps = ['trans']
| gpl-3.0 | 7,479,276,465,363,045,000 | 74.346939 | 182 | 0.552207 | false |
bionoid/kivy | kivy/modules/touchring.py | 10 | 2568 | '''
Touchring
=========
Shows rings around every touch on the surface / screen. You can use this module
to check that you don't have any calibration issues with touches.
Configuration
-------------
:Parameters:
`image`: str, defaults to '<kivy>/data/images/ring.png'
Filename of the image to use.
`scale`: float, defaults to 1.
Scale of the image.
`alpha`: float, defaults to 1.
Opacity of the image.
Example
-------
In your configuration (`~/.kivy/config.ini`), you can add something like
this::
[modules]
touchring = image=mypointer.png,scale=.3,alpha=.7
'''
__all__ = ('start', 'stop')
from kivy.core.image import Image
from kivy.graphics import Color, Rectangle
from kivy import kivy_data_dir
from os.path import join
pointer_image = None
pointer_scale = 1.0
pointer_alpha = 0.7
def _touch_down(win, touch):
ud = touch.ud
with win.canvas.after:
ud['tr.color'] = Color(1, 1, 1, pointer_alpha)
iw, ih = pointer_image.size
ud['tr.rect'] = Rectangle(
pos=(
touch.x - (pointer_image.width / 2. * pointer_scale),
touch.y - (pointer_image.height / 2. * pointer_scale)),
size=(iw * pointer_scale, ih * pointer_scale),
texture=pointer_image.texture)
if not ud.get('tr.grab', False):
ud['tr.grab'] = True
touch.grab(win)
def _touch_move(win, touch):
ud = touch.ud
if not ud.get('tr.rect', False):
_touch_down(win, touch)
ud['tr.rect'].pos = (
touch.x - (pointer_image.width / 2. * pointer_scale),
touch.y - (pointer_image.height / 2. * pointer_scale))
def _touch_up(win, touch):
if touch.grab_current is win:
ud = touch.ud
win.canvas.after.remove(ud['tr.color'])
win.canvas.after.remove(ud['tr.rect'])
if ud.get('tr.grab') is True:
touch.ungrab(win)
ud['tr.grab'] = False
def start(win, ctx):
# XXX use ctx !
global pointer_image, pointer_scale, pointer_alpha
pointer_fn = ctx.config.get('image',
'atlas://data/images/defaulttheme/ring')
pointer_scale = float(ctx.config.get('scale', 1.0))
pointer_alpha = float(ctx.config.get('alpha', 1.0))
pointer_image = Image(pointer_fn)
win.bind(on_touch_down=_touch_down,
on_touch_move=_touch_move,
on_touch_up=_touch_up)
def stop(win, ctx):
win.unbind(on_touch_down=_touch_down,
on_touch_move=_touch_move,
on_touch_up=_touch_up)
| mit | -8,605,356,993,669,973,000 | 25.474227 | 79 | 0.590343 | false |
kravent/autosubs | src/autosubsTranslate.py | 1 | 9306 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import urllib, urllib2
import copy
import re
import codecs
import threading
import time
import simplejson
def htmldecode(text):
text = text.replace('<','<').replace('>','>')
text = text.replace(''',"'").replace('"','"')
text = text.replace('&','&')
return text
def mejoraformato(text):
n = len(text)
i=0
while i < n:
if text[i] == '!':
salto = re.search('(\s*[.?!]\s*)*$',text[:i+1])
if salto:
nsalto = 1+len(salto.group(0))
else:
nsalto = 1
j = i-nsalto
while j < 0 or text[j] != u'¡':
if j < 0:
text = u'¡' + text
n += 1
i += 1
break
elif text[j] == '!' or text[j] == '?' or text[j] == '.':
text = text[:j+1] + u'¡' + text[j+1:]
n += 1
i += 1
break
j -= 1
elif text[i] == '?':
salto = re.search('(\s*[.?!]\s*)*$',text[:i+1])
if salto:
nsalto = 1+len(salto.group(0))
else:
nsalto = 1
j = i-nsalto
while j < 0 or text[j] != u'¿':
if j < 0:
text = u'¿' + text
n += 1
i += 1
break
elif text[j] == '!' or text[j] == '?' or text[j] == '.':
text = text[:j+1] + u'¿' + text[j+1:]
n += 1
i += 1
break
j -= 1
i += 1
text = re.sub(u'\s*¿\s*',u' ¿',text)
text = re.sub(u'\s*¡\s*',u' ¡',text)
text = re.sub('\s*\?\s*','? ',text)
text = re.sub('\s*!\s*','! ',text)
text = re.sub('\s*\.\s*','. ',text)
text = re.sub('\s*\.\s*\.\s*\.\s*','... ',text)
text = re.sub('\s*\?\s*!\s*','?! ',text)
text = re.sub('\s*!\s*\?\s*','!? ',text)
text = re.sub(u'\s*¿\s*¡\s*',u' ¿¡',text)
text = re.sub(u'\s*¡\s*¿\s*',u' ¡¿',text)
text = re.sub(u'^\s*¿\s*',u'¿',text)
text = re.sub(u'^\s*¡\s*',u'¡',text)
return text
GTRANSLATOR_URL = 'http://ajax.googleapis.com/ajax/services/language/translate'
NRECONECTIONS = 10
RECONECTIONSLEEP = 15
def gtranslate(text, lang_from='en', lang_to='es'):
try:
params = urllib.urlencode({'langpair': '%s|%s' % (lang_from, lang_to),
'v': '1.0',
'q': text.encode('ascii', 'xmlcharrefreplace')
})
resp = simplejson.load(urllib2.urlopen(GTRANSLATOR_URL, params))
if resp['responseStatus']==200:
return mejoraformato(resp['responseData']['translatedText'])
print >> sys.stderr, '\nERROR al traducir "%s"' % text.encode('ascii', 'xmlcharrefreplace')
print >> sys.stderr, ' responseStatus:', resp['responseStatus']
print >> sys.stderr, ' responseDetails:', resp['responseDetails']
except urllib2.HTTPError, e:
print >> sys.stderr, '\nERROR al traducir "%s"' % text.encode('ascii', 'xmlcharrefreplace')
print >> sys.stderr, e.code
except urllib2.URLError, e:
print >> sys.stderr, '\nERROR al traducir "%s"' % text.encode('ascii', 'xmlcharrefreplace')
print >> sys.stderr, e.reason
return None
th_n = 0
th_lista = []
th_lbool = []
th_loock = threading.Lock()
th_error = False
def savelistafrases(lista):
global th_n
global th_lista
global th_lbool
th_n = len(lista)
th_lista = lista
th_lbool = []
for i in range(0, th_n):
th_lbool.append(0)
def getnfrase():
global th_loock
global th_n
global th_lista
global th_lbool
th_loock.acquire()
res = None
for i in range(0, th_n):
if not th_lbool[i]:
th_lbool[i] = 1
res = i
break
th_loock.release()
return res
def getfrase(n):
global th_lista
return th_lista[n]
def savefrase(n, frase):
global th_loock
global th_lista
global th_lbool
th_loock.acquire()
th_lbool[n] = 2
th_lista[n] = frase
th_loock.release()
def syncfrasestofile(fileobject):
global th_n
global th_lista
global th_lbool
ntraducidas = 0
traducir = True
for i in range(0, th_n):
if th_lbool[i] < 2:
traducir = False
elif th_lbool[i] >= 2:
ntraducidas += 1
if traducir and th_lbool[i] == 2:
fileobject.write(th_lista[i])
th_lbool[i] = 3
return ntraducidas
class ThreadTraduceFrases(threading.Thread):
def __init__(self, lang_from='', lang_to='es'):
threading.Thread.__init__(self)
self.lang_from = lang_from
self.lang_to = lang_to
self.killed = False
def run(self):
while not self.killed:
n = getnfrase()
if n == None:
break
line = getfrase(n).strip()
line = re.sub('\s*\\\\N\s*', ' ', line)
line = re.sub('\{\\\\be\d+\}', '', line)
m = re.search('Dialogue:((.*?,){9})(.*)', line)
if m:
traduction = gtranslate(m.group(3), self.lang_from, self.lang_to)
if not traduction:
traduction = u'{ERROR AL TRADUCIR}%s' % m.group(3)
trad = u'Dialogue:' + m.group(1) + traduction
else:
trad = line
trad = trad + u'\n'
savefrase(n, trad)
def stop(self):
self.killed = True
NTHREADS = 1
REFRESHTIME = 1
def asstranslate(ass_in, ass_out, lang_from='', lang_to='es', nthreads=NTHREADS):
global th_n
print 'Preparando traductor...',
sys.stdout.flush()
f_in = codecs.open(ass_in, encoding='utf-8')
lines = f_in.readlines()
f_in.close()
savelistafrases(lines)
f_out = codecs.open(ass_out, mode='w', encoding='utf-8')
threads = []
try:
for i in range(0, NTHREADS):
threads.append(ThreadTraduceFrases(lang_from, lang_to))
for th in threads:
th.start()
while True:
time.sleep(REFRESHTIME)
alive = True
for th in threads:
alive = alive and th.is_alive()
nlinea = syncfrasestofile(f_out)
print '\rTraducidas %d líneas de %d' % (nlinea, th_n),
sys.stdout.flush()
if not alive:
break
except:
for th in threads:
th.stop()
raise
f_out.close()
print '\rTraducidas %d líneas de %d' % (th_n, th_n)
####################
# ESTILOS ASS #
####################
def assStyleClear(assfile):
f = codecs.open(assfile, encoding='utf-8')
text = f.readlines()
f.close()
existe = False
for line in text:
if re.search('\[.*Styles.*\]',line):
existe = True
break
exit = u''
i = 0
n = len(text)
if existe:
sal = u''
i = 0
while not re.search('\[.*Styles.*\]', text[i]):
sal = sal + text[i]
i += 1
sal = sal + u"[V4+ Styles]\nFormat: Name, Fontname, Fontsize, "
sal = sal + u"PrimaryColour, SecondaryColour, OutlineColour, "
sal = sal + u"BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, "
sal = sal + u"ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, "
sal = sal + u"Alignment, MarginL, MarginR, MarginV, Encoding\n\n"
i = i+1 #Salto la linea de definición de estilos en la que todavía estoy
while i < n and not re.match('\s*\[.*\]',text[i]):
i += 1
while i < n:
sal = sal + text[i]
i +=1
else:
sal = text.join('')
sal = sal + u"\n\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, "
sal = sal + u"PrimaryColour, SecondaryColour, OutlineColour, "
sal = sal + u"BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, "
sal = sal + u"ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, "
sal = sal + u"Alignment, MarginL, MarginR, MarginV, Encoding\n\n"
f = codecs.open(assfile, mode='w', encoding='utf-8')
f.write(sal)
f.close()
def assStyleSet(assfile, name, fontname='Arial', fontsize='30', \
primarycolour='&H00FFFFFF', secondarycolour='&H000000FF', \
outlinecolour='&H00000000', backcolour='&H00000000', bold='-1', \
italic='0', underline='0', strikeout='0', scalex='100', scaley='100', \
spacing='1', angle='0', borderstyle='1', outline='2', shadow='0', \
alignment='2', marginl='15', marginr='30', marginv='15', encoding='1'):
f = codecs.open(assfile, encoding='utf-8')
lines = f.readlines()
f.close()
sal = u''
i = 0
n = len(lines)
while not re.search('\[.*Styles.*\]', lines[i]):
sal = sal + lines [i]
i +=1
sal = sal + lines[i]
i += 1
while re.match('\s*$', lines[i]):
sal = sal + lines[i]
i +=1
while re.match('\s*Format:', lines[i]):
sal = sal + lines[i]
i += 1
espaciado = u""
while re.match('\s*$', lines[i]):
espaciado = espaciado + lines[i]
i +=1
while re.match('\s*Style:', lines[i]):
sal = sal + lines[i]
i += 1
sal = sal + "Style: %s,%s,%s,%s,%s,%s,%s,%s,%s,%s," %( \
name, fontname, fontsize, primarycolour, secondarycolour, \
outlinecolour, backcolour, bold, italic, underline)
sal = sal + "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n" %( \
strikeout, scalex, scaley, spacing, angle, borderstyle, outline, \
shadow, alignment, marginl, marginr, marginv, encoding)
sal = sal + espaciado
while i < n:
sal = sal + lines[i]
i += 1
f = codecs.open(assfile, mode='w', encoding='utf-8')
f.write(sal)
f.close()
if __name__ == '__main__':
nargs = len(sys.argv)
if nargs < 3:
print 'USO: autosubs-translate ass_in ass_out [lang_in [lang_out]]'
exit(-1)
elif nargs <= 3:
asstranslate(sys.argv[1],sys.argv[2])
elif nargs <=4:
asstranslate(sys.argv[1],sys.argv[2],sys.argv[3])
else:
asstranslate(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
| gpl-3.0 | 4,717,834,657,142,963,000 | 27.206687 | 95 | 0.557328 | false |
shrutisingala/ns-3-dev-git-limited-slow-start | src/network/bindings/modulegen__gcc_ILP32.py | 20 | 688489 | 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.network', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## packetbb.h (module 'network'): ns3::PbbAddressLength [enumeration]
module.add_enum('PbbAddressLength', ['IPV4', 'IPV6'])
## log.h (module 'core'): ns3::LogLevel [enumeration]
module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_INFO', 'LOG_FUNCTION', 'LOG_LEVEL_FUNCTION', 'LOG_LOGIC', 'LOG_LEVEL_LOGIC', 'LOG_ALL', 'LOG_LEVEL_ALL', 'LOG_PREFIX_FUNC', 'LOG_PREFIX_TIME', 'LOG_PREFIX_NODE', 'LOG_PREFIX_LEVEL', 'LOG_PREFIX_ALL'], import_from_module='ns.core')
## ethernet-header.h (module 'network'): ns3::ethernet_header_t [enumeration]
module.add_enum('ethernet_header_t', ['LENGTH', 'VLAN', 'QINQ'])
## address.h (module 'network'): ns3::Address [class]
module.add_class('Address')
## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration]
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'])
## application-container.h (module 'network'): ns3::ApplicationContainer [class]
module.add_class('ApplicationContainer')
## ascii-file.h (module 'network'): ns3::AsciiFile [class]
module.add_class('AsciiFile')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class]
module.add_class('AsciiTraceHelper')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class]
module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True)
## 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')
## buffer.h (module 'network'): ns3::Buffer::Iterator [class]
module.add_class('Iterator', outer_class=root_module['ns3::Buffer'])
## packet.h (module 'network'): ns3::ByteTagIterator [class]
module.add_class('ByteTagIterator')
## packet.h (module 'network'): ns3::ByteTagIterator::Item [class]
module.add_class('Item', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList')
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class]
module.add_class('Iterator', outer_class=root_module['ns3::ByteTagList'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct]
module.add_class('Item', outer_class=root_module['ns3::ByteTagList::Iterator'])
## callback.h (module 'core'): ns3::CallbackBase [class]
module.add_class('CallbackBase', import_from_module='ns.core')
## channel-list.h (module 'network'): ns3::ChannelList [class]
module.add_class('ChannelList')
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback [class]
module.add_class('DataOutputCallback', allow_subclassing=True, import_from_module='ns.stats')
## data-rate.h (module 'network'): ns3::DataRate [class]
module.add_class('DataRate')
## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation [class]
module.add_class('DelayJitterEstimation')
## event-id.h (module 'core'): ns3::EventId [class]
module.add_class('EventId', import_from_module='ns.core')
## hash.h (module 'core'): ns3::Hasher [class]
module.add_class('Hasher', import_from_module='ns.core')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
module.add_class('Inet6SocketAddress')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
module.add_class('InetSocketAddress')
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address')
## 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')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address')
## 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')
## log.h (module 'core'): ns3::LogComponent [class]
module.add_class('LogComponent', import_from_module='ns.core')
## mac16-address.h (module 'network'): ns3::Mac16Address [class]
module.add_class('Mac16Address')
## mac16-address.h (module 'network'): ns3::Mac16Address [class]
root_module['ns3::Mac16Address'].implicitly_converts_to(root_module['ns3::Address'])
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
module.add_class('Mac48Address')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
## mac64-address.h (module 'network'): ns3::Mac64Address [class]
module.add_class('Mac64Address')
## mac64-address.h (module 'network'): ns3::Mac64Address [class]
root_module['ns3::Mac64Address'].implicitly_converts_to(root_module['ns3::Address'])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class]
module.add_class('NetDeviceContainer')
## node-container.h (module 'network'): ns3::NodeContainer [class]
module.add_class('NodeContainer')
## node-list.h (module 'network'): ns3::NodeList [class]
module.add_class('NodeList')
## non-copyable.h (module 'core'): ns3::NonCopyable [class]
module.add_class('NonCopyable', destructor_visibility='protected', import_from_module='ns.core')
## 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')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct]
module.add_class('Item', 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'])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class]
module.add_class('ItemIterator', outer_class=root_module['ns3::PacketMetadata'])
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class]
module.add_class('PacketSocketAddress')
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class]
root_module['ns3::PacketSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper [class]
module.add_class('PacketSocketHelper')
## packet.h (module 'network'): ns3::PacketTagIterator [class]
module.add_class('PacketTagIterator')
## packet.h (module 'network'): ns3::PacketTagIterator::Item [class]
module.add_class('Item', outer_class=root_module['ns3::PacketTagIterator'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList [class]
module.add_class('PacketTagList')
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct]
module.add_class('TagData', outer_class=root_module['ns3::PacketTagList'])
## log.h (module 'core'): ns3::ParameterLogger [class]
module.add_class('ParameterLogger', import_from_module='ns.core')
## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock [class]
module.add_class('PbbAddressTlvBlock')
## packetbb.h (module 'network'): ns3::PbbTlvBlock [class]
module.add_class('PbbTlvBlock')
## pcap-file.h (module 'network'): ns3::PcapFile [class]
module.add_class('PcapFile')
## trace-helper.h (module 'network'): ns3::PcapHelper [class]
module.add_class('PcapHelper')
## trace-helper.h (module 'network'): ns3::PcapHelper::DataLinkType [enumeration]
module.add_enum('DataLinkType', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_LINUX_SLL', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO', 'DLT_IEEE802_15_4', 'DLT_NETLINK'], outer_class=root_module['ns3::PcapHelper'])
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class]
module.add_class('PcapHelperForDevice', allow_subclassing=True)
## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned int, int> [class]
module.add_class('SequenceNumber32')
## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned short, short> [class]
module.add_class('SequenceNumber16')
## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper [class]
module.add_class('SimpleNetDeviceHelper')
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simulator.h (module 'core'): ns3::Simulator [class]
module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core')
## simulator.h (module 'core'): ns3::Simulator [enumeration]
module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core')
## data-calculator.h (module 'stats'): ns3::StatisticalSummary [class]
module.add_class('StatisticalSummary', allow_subclassing=True, import_from_module='ns.stats')
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class]
module.add_class('SystemWallClockMs', import_from_module='ns.core')
## tag.h (module 'network'): ns3::Tag [class]
module.add_class('Tag', parent=root_module['ns3::ObjectBase'])
## tag-buffer.h (module 'network'): ns3::TagBuffer [class]
module.add_class('TagBuffer')
## nstime.h (module 'core'): ns3::TimeWithUnit [class]
module.add_class('TimeWithUnit', import_from_module='ns.core')
## traced-value.h (module 'core'): ns3::TracedValue<unsigned int> [class]
module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['unsigned int'])
## 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', parent=root_module['ns3::ObjectBase'])
## packet-socket.h (module 'network'): ns3::DeviceNameTag [class]
module.add_class('DeviceNameTag', parent=root_module['ns3::Tag'])
## flow-id-tag.h (module 'network'): ns3::FlowIdTag [class]
module.add_class('FlowIdTag', parent=root_module['ns3::Tag'])
## header.h (module 'network'): ns3::Header [class]
module.add_class('Header', parent=root_module['ns3::Chunk'])
## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader [class]
module.add_class('LlcSnapHeader', parent=root_module['ns3::Header'])
## object.h (module 'core'): ns3::Object [class]
module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
## object.h (module 'core'): ns3::Object::AggregateIterator [class]
module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object'])
## packet-burst.h (module 'network'): ns3::PacketBurst [class]
module.add_class('PacketBurst', parent=root_module['ns3::Object'])
## packet-socket.h (module 'network'): ns3::PacketSocketTag [class]
module.add_class('PacketSocketTag', parent=root_module['ns3::Tag'])
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class]
module.add_class('PcapFileWrapper', parent=root_module['ns3::Object'])
## queue.h (module 'network'): ns3::QueueBase [class]
module.add_class('QueueBase', parent=root_module['ns3::Object'])
## queue.h (module 'network'): ns3::QueueBase::QueueMode [enumeration]
module.add_enum('QueueMode', ['QUEUE_MODE_PACKETS', 'QUEUE_MODE_BYTES'], outer_class=root_module['ns3::QueueBase'])
## queue-limits.h (module 'network'): ns3::QueueLimits [class]
module.add_class('QueueLimits', parent=root_module['ns3::Object'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [class]
module.add_class('RadiotapHeader', parent=root_module['ns3::Header'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::FrameFlag [enumeration]
module.add_enum('FrameFlag', ['FRAME_FLAG_NONE', 'FRAME_FLAG_CFP', 'FRAME_FLAG_SHORT_PREAMBLE', 'FRAME_FLAG_WEP', 'FRAME_FLAG_FRAGMENTED', 'FRAME_FLAG_FCS_INCLUDED', 'FRAME_FLAG_DATA_PADDING', 'FRAME_FLAG_BAD_FCS', 'FRAME_FLAG_SHORT_GUARD'], outer_class=root_module['ns3::RadiotapHeader'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::ChannelFlags [enumeration]
module.add_enum('ChannelFlags', ['CHANNEL_FLAG_NONE', 'CHANNEL_FLAG_TURBO', 'CHANNEL_FLAG_CCK', 'CHANNEL_FLAG_OFDM', 'CHANNEL_FLAG_SPECTRUM_2GHZ', 'CHANNEL_FLAG_SPECTRUM_5GHZ', 'CHANNEL_FLAG_PASSIVE', 'CHANNEL_FLAG_DYNAMIC', 'CHANNEL_FLAG_GFSK'], outer_class=root_module['ns3::RadiotapHeader'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::McsKnown [enumeration]
module.add_enum('McsKnown', ['MCS_KNOWN_NONE', 'MCS_KNOWN_BANDWIDTH', 'MCS_KNOWN_INDEX', 'MCS_KNOWN_GUARD_INTERVAL', 'MCS_KNOWN_HT_FORMAT', 'MCS_KNOWN_FEC_TYPE', 'MCS_KNOWN_STBC', 'MCS_KNOWN_NESS', 'MCS_KNOWN_NESS_BIT_1'], outer_class=root_module['ns3::RadiotapHeader'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::McsFlags [enumeration]
module.add_enum('McsFlags', ['MCS_FLAGS_NONE', 'MCS_FLAGS_BANDWIDTH_40', 'MCS_FLAGS_BANDWIDTH_20L', 'MCS_FLAGS_BANDWIDTH_20U', 'MCS_FLAGS_GUARD_INTERVAL', 'MCS_FLAGS_HT_GREENFIELD', 'MCS_FLAGS_FEC_TYPE', 'MCS_FLAGS_STBC_STREAMS', 'MCS_FLAGS_NESS_BIT_0'], outer_class=root_module['ns3::RadiotapHeader'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::AmpduFlags [enumeration]
module.add_enum('AmpduFlags', ['A_MPDU_STATUS_NONE', 'A_MPDU_STATUS_REPORT_ZERO_LENGTH', 'A_MPDU_STATUS_IS_ZERO_LENGTH', 'A_MPDU_STATUS_LAST_KNOWN', 'A_MPDU_STATUS_LAST', 'A_MPDU_STATUS_DELIMITER_CRC_ERROR', 'A_MPDU_STATUS_DELIMITER_CRC_KNOWN'], outer_class=root_module['ns3::RadiotapHeader'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::VhtKnown [enumeration]
module.add_enum('VhtKnown', ['VHT_KNOWN_NONE', 'VHT_KNOWN_STBC', 'VHT_KNOWN_TXOP_PS_NOT_ALLOWED', 'VHT_KNOWN_GUARD_INTERVAL', 'VHT_KNOWN_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_KNOWN_LDPC_EXTRA_OFDM_SYMBOL', 'VHT_KNOWN_BEAMFORMED', 'VHT_KNOWN_BANDWIDTH', 'VHT_KNOWN_GROUP_ID', 'VHT_KNOWN_PARTIAL_AID'], outer_class=root_module['ns3::RadiotapHeader'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::VhtFlags [enumeration]
module.add_enum('VhtFlags', ['VHT_FLAGS_NONE', 'VHT_FLAGS_STBC', 'VHT_FLAGS_TXOP_PS_NOT_ALLOWED', 'VHT_FLAGS_GUARD_INTERVAL', 'VHT_FLAGS_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_FLAGS_LDPC_EXTRA_OFDM_SYMBOL', 'VHT_FLAGS_BEAMFORMED'], outer_class=root_module['ns3::RadiotapHeader'])
## 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::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, 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, 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, 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, template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbAddressBlock', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbAddressBlock>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbMessage', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbMessage>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbPacket', 'ns3::Header', 'ns3::DefaultDeleter<ns3::PbbPacket>'], parent=root_module['ns3::Header'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::PbbTlv', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbTlv>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## sll-header.h (module 'network'): ns3::SllHeader [class]
module.add_class('SllHeader', parent=root_module['ns3::Header'])
## sll-header.h (module 'network'): ns3::SllHeader::PacketType [enumeration]
module.add_enum('PacketType', ['UNICAST_FROM_PEER_TO_ME', 'BROADCAST_BY_PEER', 'MULTICAST_BY_PEER', 'INTERCEPTED_PACKET', 'SENT_BY_US'], outer_class=root_module['ns3::SllHeader'])
## socket.h (module 'network'): ns3::Socket [class]
module.add_class('Socket', parent=root_module['ns3::Object'])
## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration]
module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'])
## socket.h (module 'network'): ns3::Socket::SocketType [enumeration]
module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'])
## socket.h (module 'network'): ns3::Socket::SocketPriority [enumeration]
module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'])
## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration]
module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'])
## socket-factory.h (module 'network'): ns3::SocketFactory [class]
module.add_class('SocketFactory', parent=root_module['ns3::Object'])
## socket.h (module 'network'): ns3::SocketIpTosTag [class]
module.add_class('SocketIpTosTag', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpTtlTag [class]
module.add_class('SocketIpTtlTag', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class]
module.add_class('SocketIpv6HopLimitTag', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class]
module.add_class('SocketIpv6TclassTag', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketPriorityTag [class]
module.add_class('SocketPriorityTag', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class]
module.add_class('SocketSetDontFragmentTag', parent=root_module['ns3::Tag'])
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time', import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time::Unit [enumeration]
module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time [class]
root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t'])
## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class]
module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
## trailer.h (module 'network'): ns3::Trailer [class]
module.add_class('Trailer', parent=root_module['ns3::Chunk'])
## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class]
module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class]
module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class]
module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class]
module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class]
module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## application.h (module 'network'): ns3::Application [class]
module.add_class('Application', parent=root_module['ns3::Object'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## boolean.h (module 'core'): ns3::BooleanChecker [class]
module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## boolean.h (module 'core'): ns3::BooleanValue [class]
module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## 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', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class]
module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## data-calculator.h (module 'stats'): ns3::DataCalculator [class]
module.add_class('DataCalculator', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-collection-object.h (module 'stats'): ns3::DataCollectionObject [class]
module.add_class('DataCollectionObject', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface [class]
module.add_class('DataOutputInterface', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-rate.h (module 'network'): ns3::DataRateChecker [class]
module.add_class('DataRateChecker', parent=root_module['ns3::AttributeChecker'])
## data-rate.h (module 'network'): ns3::DataRateValue [class]
module.add_class('DataRateValue', 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'])
## double.h (module 'core'): ns3::DoubleValue [class]
module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## dynamic-queue-limits.h (module 'network'): ns3::DynamicQueueLimits [class]
module.add_class('DynamicQueueLimits', parent=root_module['ns3::QueueLimits'])
## 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::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'])
## enum.h (module 'core'): ns3::EnumChecker [class]
module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## enum.h (module 'core'): ns3::EnumValue [class]
module.add_class('EnumValue', 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', parent=root_module['ns3::Object'])
## ethernet-header.h (module 'network'): ns3::EthernetHeader [class]
module.add_class('EthernetHeader', parent=root_module['ns3::Header'])
## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer [class]
module.add_class('EthernetTrailer', parent=root_module['ns3::Trailer'])
## event-impl.h (module 'core'): ns3::EventImpl [class]
module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class]
module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class]
module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## integer.h (module 'core'): ns3::IntegerValue [class]
module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class]
module.add_class('Ipv4AddressChecker', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class]
module.add_class('Ipv4AddressValue', parent=root_module['ns3::AttributeValue'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class]
module.add_class('Ipv4MaskChecker', parent=root_module['ns3::AttributeChecker'])
## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class]
module.add_class('Ipv4MaskValue', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class]
module.add_class('Ipv6AddressChecker', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class]
module.add_class('Ipv6AddressValue', parent=root_module['ns3::AttributeValue'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class]
module.add_class('Ipv6PrefixChecker', parent=root_module['ns3::AttributeChecker'])
## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class]
module.add_class('Ipv6PrefixValue', parent=root_module['ns3::AttributeValue'])
## error-model.h (module 'network'): ns3::ListErrorModel [class]
module.add_class('ListErrorModel', 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'])
## mac16-address.h (module 'network'): ns3::Mac16AddressChecker [class]
module.add_class('Mac16AddressChecker', parent=root_module['ns3::AttributeChecker'])
## mac16-address.h (module 'network'): ns3::Mac16AddressValue [class]
module.add_class('Mac16AddressValue', parent=root_module['ns3::AttributeValue'])
## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class]
module.add_class('Mac48AddressChecker', parent=root_module['ns3::AttributeChecker'])
## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class]
module.add_class('Mac48AddressValue', parent=root_module['ns3::AttributeValue'])
## mac64-address.h (module 'network'): ns3::Mac64AddressChecker [class]
module.add_class('Mac64AddressChecker', parent=root_module['ns3::AttributeChecker'])
## mac64-address.h (module 'network'): ns3::Mac64AddressValue [class]
module.add_class('Mac64AddressValue', parent=root_module['ns3::AttributeValue'])
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int> [class]
module.add_class('MinMaxAvgTotalCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=[root_module['ns3::DataCalculator'], root_module['ns3::StatisticalSummary']])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', 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'])
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueue [class]
module.add_class('NetDeviceQueue', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >'])
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface [class]
module.add_class('NetDeviceQueueInterface', parent=root_module['ns3::Object'])
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', 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', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator [class]
module.add_class('PacketSizeMinMaxAvgTotalCalculator', parent=root_module['ns3::MinMaxAvgTotalCalculator< unsigned int >'])
## packet-socket.h (module 'network'): ns3::PacketSocket [class]
module.add_class('PacketSocket', parent=root_module['ns3::Socket'])
## packet-socket-client.h (module 'network'): ns3::PacketSocketClient [class]
module.add_class('PacketSocketClient', parent=root_module['ns3::Application'])
## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory [class]
module.add_class('PacketSocketFactory', parent=root_module['ns3::SocketFactory'])
## packet-socket-server.h (module 'network'): ns3::PacketSocketServer [class]
module.add_class('PacketSocketServer', parent=root_module['ns3::Application'])
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class]
module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## packetbb.h (module 'network'): ns3::PbbAddressBlock [class]
module.add_class('PbbAddressBlock', parent=root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >'])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4 [class]
module.add_class('PbbAddressBlockIpv4', parent=root_module['ns3::PbbAddressBlock'])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6 [class]
module.add_class('PbbAddressBlockIpv6', parent=root_module['ns3::PbbAddressBlock'])
## packetbb.h (module 'network'): ns3::PbbMessage [class]
module.add_class('PbbMessage', parent=root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >'])
## packetbb.h (module 'network'): ns3::PbbMessageIpv4 [class]
module.add_class('PbbMessageIpv4', parent=root_module['ns3::PbbMessage'])
## packetbb.h (module 'network'): ns3::PbbMessageIpv6 [class]
module.add_class('PbbMessageIpv6', parent=root_module['ns3::PbbMessage'])
## packetbb.h (module 'network'): ns3::PbbPacket [class]
module.add_class('PbbPacket', parent=root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >'])
## packetbb.h (module 'network'): ns3::PbbTlv [class]
module.add_class('PbbTlv', parent=root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >'])
## probe.h (module 'stats'): ns3::Probe [class]
module.add_class('Probe', import_from_module='ns.stats', parent=root_module['ns3::DataCollectionObject'])
## queue.h (module 'network'): ns3::Queue<ns3::Packet> [class]
module.add_class('Queue', template_parameters=['ns3::Packet'], parent=root_module['ns3::QueueBase'])
## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem> [class]
module.add_class('Queue', template_parameters=['ns3::QueueDiscItem'], parent=root_module['ns3::QueueBase'])
## queue-item.h (module 'network'): ns3::QueueItem [class]
module.add_class('QueueItem', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >'])
## queue-item.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration]
module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'])
## error-model.h (module 'network'): ns3::RateErrorModel [class]
module.add_class('RateErrorModel', 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'])
## error-model.h (module 'network'): ns3::ReceiveListErrorModel [class]
module.add_class('ReceiveListErrorModel', parent=root_module['ns3::ErrorModel'])
## simple-channel.h (module 'network'): ns3::SimpleChannel [class]
module.add_class('SimpleChannel', parent=root_module['ns3::Channel'])
## simple-net-device.h (module 'network'): ns3::SimpleNetDevice [class]
module.add_class('SimpleNetDevice', parent=root_module['ns3::NetDevice'])
## 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'])
## uinteger.h (module 'core'): ns3::UintegerValue [class]
module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## address.h (module 'network'): ns3::AddressChecker [class]
module.add_class('AddressChecker', parent=root_module['ns3::AttributeChecker'])
## address.h (module 'network'): ns3::AddressValue [class]
module.add_class('AddressValue', parent=root_module['ns3::AttributeValue'])
## error-model.h (module 'network'): ns3::BinaryErrorModel [class]
module.add_class('BinaryErrorModel', parent=root_module['ns3::ErrorModel'])
## error-model.h (module 'network'): ns3::BurstErrorModel [class]
module.add_class('BurstErrorModel', parent=root_module['ns3::ErrorModel'])
## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int> [class]
module.add_class('CounterCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=root_module['ns3::DataCalculator'])
## error-channel.h (module 'network'): ns3::ErrorChannel [class]
module.add_class('ErrorChannel', parent=root_module['ns3::SimpleChannel'])
## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator [class]
module.add_class('PacketCounterCalculator', parent=root_module['ns3::CounterCalculator< unsigned int >'])
## packet-probe.h (module 'network'): ns3::PacketProbe [class]
module.add_class('PacketProbe', parent=root_module['ns3::Probe'])
## packetbb.h (module 'network'): ns3::PbbAddressTlv [class]
module.add_class('PbbAddressTlv', parent=root_module['ns3::PbbTlv'])
## queue-item.h (module 'network'): ns3::QueueDiscItem [class]
module.add_class('QueueDiscItem', parent=root_module['ns3::QueueItem'])
module.add_container('std::map< std::string, ns3::LogComponent * >', ('std::string', 'ns3::LogComponent *'), container_type=u'map')
module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type=u'list')
module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector')
module.add_container('std::list< unsigned int >', 'unsigned int', container_type=u'list')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxEndCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxEndCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxEndCallback&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned short, short >', u'ns3::SequenceNumber16')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned short, short >*', u'ns3::SequenceNumber16*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned short, short >&', u'ns3::SequenceNumber16&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >', u'ns3::SequenceNumber32')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >*', u'ns3::SequenceNumber32*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >&', u'ns3::SequenceNumber32&')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogNodePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogNodePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogNodePrinter&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxStartCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxStartCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxStartCallback&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >', u'ns3::SequenceNumber8')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >*', u'ns3::SequenceNumber8*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >&', u'ns3::SequenceNumber8&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndErrorCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndErrorCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndErrorCallback&')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxStartCallback')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxStartCallback*')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxStartCallback&')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *', u'ns3::LogTimePrinter')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) **', u'ns3::LogTimePrinter*')
typehandlers.add_type_alias(u'void ( * ) ( std::ostream & ) *&', u'ns3::LogTimePrinter&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndOkCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndOkCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndOkCallback&')
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace 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)
## Register a nested module for the namespace addressUtils
nested_module = module.add_cpp_namespace('addressUtils')
register_types_ns3_addressUtils(nested_module)
## Register a nested module for the namespace internal
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(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 ( * ) ( double, double ) *', u'ns3::TracedValueCallback::Double')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) **', u'ns3::TracedValueCallback::Double*')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) *&', u'ns3::TracedValueCallback::Double&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 ) *', u'ns3::TracedValueCallback::SequenceNumber32')
typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 ) **', u'ns3::TracedValueCallback::SequenceNumber32*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 ) *&', u'ns3::TracedValueCallback::SequenceNumber32&')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *', u'ns3::TracedValueCallback::Int8')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) **', u'ns3::TracedValueCallback::Int8*')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *&', u'ns3::TracedValueCallback::Int8&')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *', u'ns3::TracedValueCallback::Uint8')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) **', u'ns3::TracedValueCallback::Uint8*')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *&', u'ns3::TracedValueCallback::Uint8&')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *', u'ns3::TracedValueCallback::Int32')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) **', u'ns3::TracedValueCallback::Int32*')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *&', u'ns3::TracedValueCallback::Int32&')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *', u'ns3::TracedValueCallback::Bool')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) **', u'ns3::TracedValueCallback::Bool*')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *&', u'ns3::TracedValueCallback::Bool&')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *', u'ns3::TracedValueCallback::Uint16')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) **', u'ns3::TracedValueCallback::Uint16*')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *&', u'ns3::TracedValueCallback::Uint16&')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *', u'ns3::TracedValueCallback::Uint32')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) **', u'ns3::TracedValueCallback::Uint32*')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *&', u'ns3::TracedValueCallback::Uint32&')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *', u'ns3::TracedValueCallback::Int16')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) **', u'ns3::TracedValueCallback::Int16*')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *&', u'ns3::TracedValueCallback::Int16&')
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&')
typehandlers.add_type_alias(u'void ( * ) ( ) *', u'ns3::TracedValueCallback::Void')
typehandlers.add_type_alias(u'void ( * ) ( ) **', u'ns3::TracedValueCallback::Void*')
typehandlers.add_type_alias(u'void ( * ) ( ) *&', u'ns3::TracedValueCallback::Void&')
def register_types_ns3_addressUtils(module):
root_module = module.get_root()
def register_types_ns3_internal(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3ApplicationContainer_methods(root_module, root_module['ns3::ApplicationContainer'])
register_Ns3AsciiFile_methods(root_module, root_module['ns3::AsciiFile'])
register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper'])
register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_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_Ns3ChannelList_methods(root_module, root_module['ns3::ChannelList'])
register_Ns3DataOutputCallback_methods(root_module, root_module['ns3::DataOutputCallback'])
register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate'])
register_Ns3DelayJitterEstimation_methods(root_module, root_module['ns3::DelayJitterEstimation'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher'])
register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress'])
register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_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_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent'])
register_Ns3Mac16Address_methods(root_module, root_module['ns3::Mac16Address'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3Mac64Address_methods(root_module, root_module['ns3::Mac64Address'])
register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3NodeList_methods(root_module, root_module['ns3::NodeList'])
register_Ns3NonCopyable_methods(root_module, root_module['ns3::NonCopyable'])
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_Ns3PacketSocketAddress_methods(root_module, root_module['ns3::PacketSocketAddress'])
register_Ns3PacketSocketHelper_methods(root_module, root_module['ns3::PacketSocketHelper'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3ParameterLogger_methods(root_module, root_module['ns3::ParameterLogger'])
register_Ns3PbbAddressTlvBlock_methods(root_module, root_module['ns3::PbbAddressTlvBlock'])
register_Ns3PbbTlvBlock_methods(root_module, root_module['ns3::PbbTlvBlock'])
register_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile'])
register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper'])
register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice'])
register_Ns3SequenceNumber32_methods(root_module, root_module['ns3::SequenceNumber32'])
register_Ns3SequenceNumber16_methods(root_module, root_module['ns3::SequenceNumber16'])
register_Ns3SimpleNetDeviceHelper_methods(root_module, root_module['ns3::SimpleNetDeviceHelper'])
register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator'])
register_Ns3StatisticalSummary_methods(root_module, root_module['ns3::StatisticalSummary'])
register_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit'])
register_Ns3TracedValue__Unsigned_int_methods(root_module, root_module['ns3::TracedValue< unsigned int >'])
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_Ns3DeviceNameTag_methods(root_module, root_module['ns3::DeviceNameTag'])
register_Ns3FlowIdTag_methods(root_module, root_module['ns3::FlowIdTag'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3LlcSnapHeader_methods(root_module, root_module['ns3::LlcSnapHeader'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3PacketBurst_methods(root_module, root_module['ns3::PacketBurst'])
register_Ns3PacketSocketTag_methods(root_module, root_module['ns3::PacketSocketTag'])
register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper'])
register_Ns3QueueBase_methods(root_module, root_module['ns3::QueueBase'])
register_Ns3QueueLimits_methods(root_module, root_module['ns3::QueueLimits'])
register_Ns3RadiotapHeader_methods(root_module, root_module['ns3::RadiotapHeader'])
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__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >'])
register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
register_Ns3SimpleRefCount__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >'])
register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >'])
register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >'])
register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >'])
register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3SllHeader_methods(root_module, root_module['ns3::SllHeader'])
register_Ns3Socket_methods(root_module, root_module['ns3::Socket'])
register_Ns3SocketFactory_methods(root_module, root_module['ns3::SocketFactory'])
register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag'])
register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag'])
register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag'])
register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag'])
register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag'])
register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable'])
register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable'])
register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable'])
register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable'])
register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable'])
register_Ns3Application_methods(root_module, root_module['ns3::Application'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker'])
register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable'])
register_Ns3DataCalculator_methods(root_module, root_module['ns3::DataCalculator'])
register_Ns3DataCollectionObject_methods(root_module, root_module['ns3::DataCollectionObject'])
register_Ns3DataOutputInterface_methods(root_module, root_module['ns3::DataOutputInterface'])
register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker'])
register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue'])
register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3DynamicQueueLimits_methods(root_module, root_module['ns3::DynamicQueueLimits'])
register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable'])
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_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker'])
register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue'])
register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable'])
register_Ns3ErrorModel_methods(root_module, root_module['ns3::ErrorModel'])
register_Ns3EthernetHeader_methods(root_module, root_module['ns3::EthernetHeader'])
register_Ns3EthernetTrailer_methods(root_module, root_module['ns3::EthernetTrailer'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable'])
register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable'])
register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue'])
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_Ns3Mac16AddressChecker_methods(root_module, root_module['ns3::Mac16AddressChecker'])
register_Ns3Mac16AddressValue_methods(root_module, root_module['ns3::Mac16AddressValue'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3Mac64AddressChecker_methods(root_module, root_module['ns3::Mac64AddressChecker'])
register_Ns3Mac64AddressValue_methods(root_module, root_module['ns3::Mac64AddressValue'])
register_Ns3MinMaxAvgTotalCalculator__Unsigned_int_methods(root_module, root_module['ns3::MinMaxAvgTotalCalculator< unsigned int >'])
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_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_Ns3PacketSizeMinMaxAvgTotalCalculator_methods(root_module, root_module['ns3::PacketSizeMinMaxAvgTotalCalculator'])
register_Ns3PacketSocket_methods(root_module, root_module['ns3::PacketSocket'])
register_Ns3PacketSocketClient_methods(root_module, root_module['ns3::PacketSocketClient'])
register_Ns3PacketSocketFactory_methods(root_module, root_module['ns3::PacketSocketFactory'])
register_Ns3PacketSocketServer_methods(root_module, root_module['ns3::PacketSocketServer'])
register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable'])
register_Ns3PbbAddressBlock_methods(root_module, root_module['ns3::PbbAddressBlock'])
register_Ns3PbbAddressBlockIpv4_methods(root_module, root_module['ns3::PbbAddressBlockIpv4'])
register_Ns3PbbAddressBlockIpv6_methods(root_module, root_module['ns3::PbbAddressBlockIpv6'])
register_Ns3PbbMessage_methods(root_module, root_module['ns3::PbbMessage'])
register_Ns3PbbMessageIpv4_methods(root_module, root_module['ns3::PbbMessageIpv4'])
register_Ns3PbbMessageIpv6_methods(root_module, root_module['ns3::PbbMessageIpv6'])
register_Ns3PbbPacket_methods(root_module, root_module['ns3::PbbPacket'])
register_Ns3PbbTlv_methods(root_module, root_module['ns3::PbbTlv'])
register_Ns3Probe_methods(root_module, root_module['ns3::Probe'])
register_Ns3Queue__Ns3Packet_methods(root_module, root_module['ns3::Queue< ns3::Packet >'])
register_Ns3Queue__Ns3QueueDiscItem_methods(root_module, root_module['ns3::Queue< ns3::QueueDiscItem >'])
register_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem'])
register_Ns3RateErrorModel_methods(root_module, root_module['ns3::RateErrorModel'])
register_Ns3ReceiveListErrorModel_methods(root_module, root_module['ns3::ReceiveListErrorModel'])
register_Ns3SimpleChannel_methods(root_module, root_module['ns3::SimpleChannel'])
register_Ns3SimpleNetDevice_methods(root_module, root_module['ns3::SimpleNetDevice'])
register_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_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3BinaryErrorModel_methods(root_module, root_module['ns3::BinaryErrorModel'])
register_Ns3BurstErrorModel_methods(root_module, root_module['ns3::BurstErrorModel'])
register_Ns3CounterCalculator__Unsigned_int_methods(root_module, root_module['ns3::CounterCalculator< unsigned int >'])
register_Ns3ErrorChannel_methods(root_module, root_module['ns3::ErrorChannel'])
register_Ns3PacketCounterCalculator_methods(root_module, root_module['ns3::PacketCounterCalculator'])
register_Ns3PacketProbe_methods(root_module, root_module['ns3::PacketProbe'])
register_Ns3PbbAddressTlv_methods(root_module, root_module['ns3::PbbAddressTlv'])
register_Ns3QueueDiscItem_methods(root_module, root_module['ns3::QueueDiscItem'])
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_Ns3ApplicationContainer_methods(root_module, cls):
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::ApplicationContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ApplicationContainer const &', 'arg0')])
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer() [constructor]
cls.add_constructor([])
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::Ptr<ns3::Application> application) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Application >', 'application')])
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(std::string name) [constructor]
cls.add_constructor([param('std::string', 'name')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::ApplicationContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::ApplicationContainer', 'other')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Application >', 'application')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(std::string name) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name')])
## application-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Application>*,std::vector<ns3::Ptr<ns3::Application>, std::allocator<ns3::Ptr<ns3::Application> > > > ns3::ApplicationContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Application > const, std::vector< ns3::Ptr< ns3::Application > > >',
[],
is_const=True)
## application-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Application>*,std::vector<ns3::Ptr<ns3::Application>, std::allocator<ns3::Ptr<ns3::Application> > > > ns3::ApplicationContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Application > const, std::vector< ns3::Ptr< ns3::Application > > >',
[],
is_const=True)
## application-container.h (module 'network'): ns3::Ptr<ns3::Application> ns3::ApplicationContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'i')],
is_const=True)
## application-container.h (module 'network'): uint32_t ns3::ApplicationContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## application-container.h (module 'network'): void ns3::ApplicationContainer::Start(ns3::Time start) [member function]
cls.add_method('Start',
'void',
[param('ns3::Time', 'start')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Stop(ns3::Time stop) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time', 'stop')])
return
def register_Ns3AsciiFile_methods(root_module, cls):
## ascii-file.h (module 'network'): ns3::AsciiFile::AsciiFile() [constructor]
cls.add_constructor([])
## ascii-file.h (module 'network'): bool ns3::AsciiFile::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## ascii-file.h (module 'network'): bool ns3::AsciiFile::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## ascii-file.h (module 'network'): void ns3::AsciiFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## ascii-file.h (module 'network'): void ns3::AsciiFile::Close() [member function]
cls.add_method('Close',
'void',
[])
## ascii-file.h (module 'network'): void ns3::AsciiFile::Read(std::string & line) [member function]
cls.add_method('Read',
'void',
[param('std::string &', 'line')])
## ascii-file.h (module 'network'): static bool ns3::AsciiFile::Diff(std::string const & f1, std::string const & f2, uint64_t & lineNumber) [member function]
cls.add_method('Diff',
'bool',
[param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint64_t &', 'lineNumber')],
is_static=True)
return
def register_Ns3AsciiTraceHelper_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::_Ios_Openmode filemode=std::ios_base::out) [member function]
cls.add_method('CreateFileStream',
'ns3::Ptr< ns3::OutputStreamWrapper >',
[param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode', default_value='std::ios_base::out')])
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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'): 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_Ns3ChannelList_methods(root_module, cls):
## channel-list.h (module 'network'): ns3::ChannelList::ChannelList() [constructor]
cls.add_constructor([])
## channel-list.h (module 'network'): ns3::ChannelList::ChannelList(ns3::ChannelList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ChannelList const &', 'arg0')])
## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::Add(ns3::Ptr<ns3::Channel> channel) [member function]
cls.add_method('Add',
'uint32_t',
[param('ns3::Ptr< ns3::Channel >', 'channel')],
is_static=True)
## channel-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >',
[],
is_static=True)
## channel-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >',
[],
is_static=True)
## channel-list.h (module 'network'): static ns3::Ptr<ns3::Channel> ns3::ChannelList::GetChannel(uint32_t n) [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[param('uint32_t', 'n')],
is_static=True)
## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::GetNChannels() [member function]
cls.add_method('GetNChannels',
'uint32_t',
[],
is_static=True)
return
def register_Ns3DataOutputCallback_methods(root_module, cls):
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback() [constructor]
cls.add_constructor([])
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback(ns3::DataOutputCallback const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataOutputCallback const &', 'arg0')])
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, int val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('int', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, uint32_t val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('uint32_t', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, double val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('double', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, std::string val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('std::string', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, ns3::Time val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('ns3::Time', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputStatistic(std::string key, std::string variable, ns3::StatisticalSummary const * statSum) [member function]
cls.add_method('OutputStatistic',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('ns3::StatisticalSummary const *', 'statSum')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3DataRate_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('>=')
## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRate const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor]
cls.add_constructor([param('uint64_t', 'bps')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor]
cls.add_constructor([param('std::string', 'rate')])
## data-rate.h (module 'network'): 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_Ns3DelayJitterEstimation_methods(root_module, cls):
## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation::DelayJitterEstimation(ns3::DelayJitterEstimation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DelayJitterEstimation const &', 'arg0')])
## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation::DelayJitterEstimation() [constructor]
cls.add_constructor([])
## delay-jitter-estimation.h (module 'network'): ns3::Time ns3::DelayJitterEstimation::GetLastDelay() const [member function]
cls.add_method('GetLastDelay',
'ns3::Time',
[],
is_const=True)
## delay-jitter-estimation.h (module 'network'): uint64_t ns3::DelayJitterEstimation::GetLastJitter() const [member function]
cls.add_method('GetLastJitter',
'uint64_t',
[],
is_const=True)
## delay-jitter-estimation.h (module 'network'): static void ns3::DelayJitterEstimation::PrepareTx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('PrepareTx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')],
is_static=True)
## delay-jitter-estimation.h (module 'network'): void ns3::DelayJitterEstimation::RecordRx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('RecordRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
return
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('==')
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventId const &', 'arg0')])
## event-id.h (module 'core'): ns3::EventId::EventId() [constructor]
cls.add_constructor([])
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')])
## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function]
cls.add_method('GetTs',
'uint64_t',
[],
is_const=True)
## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function]
cls.add_method('PeekEventImpl',
'ns3::EventImpl *',
[],
is_const=True)
return
def register_Ns3Hasher_methods(root_module, cls):
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hasher const &', 'arg0')])
## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor]
cls.add_constructor([])
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('std::string const', 's')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('std::string const', 's')])
## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function]
cls.add_method('clear',
'ns3::Hasher &',
[])
return
def register_Ns3Inet6SocketAddress_methods(root_module, cls):
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor]
cls.add_constructor([param('char const *', 'ipv6')])
## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function]
cls.add_method('ConvertFrom',
'ns3::Inet6SocketAddress',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function]
cls.add_method('GetIpv6',
'ns3::Ipv6Address',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function]
cls.add_method('SetIpv6',
'void',
[param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function]
cls.add_method('SetPort',
'void',
[param('uint16_t', 'port')])
return
def register_Ns3InetSocketAddress_methods(root_module, cls):
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor]
cls.add_constructor([param('char const *', 'ipv4')])
## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::InetSocketAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function]
cls.add_method('GetIpv4',
'ns3::Ipv4Address',
[],
is_const=True)
## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet-socket-address.h (module 'network'): uint8_t ns3::InetSocketAddress::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ipv4Address', 'address')])
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function]
cls.add_method('SetPort',
'void',
[param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor]
cls.add_constructor([param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('CombineMask',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv4Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv4Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('GetSubnetDirectedBroadcast',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsAny() const [member function]
cls.add_method('IsAny',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Address const &', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function]
cls.add_method('IsLocalMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function]
cls.add_method('IsLocalhost',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('IsSubnetDirectedBroadcast',
'bool',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
return
def register_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_Ns3LogComponent_methods(root_module, cls):
## log.h (module 'core'): ns3::LogComponent::LogComponent(ns3::LogComponent const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LogComponent const &', 'arg0')])
## log.h (module 'core'): ns3::LogComponent::LogComponent(std::string const & name, std::string const & file, ns3::LogLevel const mask=::ns3::LOG_NONE) [constructor]
cls.add_constructor([param('std::string const &', 'name'), param('std::string const &', 'file'), param('ns3::LogLevel const', 'mask', default_value='::ns3::LOG_NONE')])
## log.h (module 'core'): void ns3::LogComponent::Disable(ns3::LogLevel const level) [member function]
cls.add_method('Disable',
'void',
[param('ns3::LogLevel const', 'level')])
## log.h (module 'core'): void ns3::LogComponent::Enable(ns3::LogLevel const level) [member function]
cls.add_method('Enable',
'void',
[param('ns3::LogLevel const', 'level')])
## log.h (module 'core'): std::string ns3::LogComponent::File() const [member function]
cls.add_method('File',
'std::string',
[],
is_const=True)
## log.h (module 'core'): static std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >,ns3::LogComponent*,std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, ns3::LogComponent*> > > * ns3::LogComponent::GetComponentList() [member function]
cls.add_method('GetComponentList',
'std::map< std::string, ns3::LogComponent * > *',
[],
is_static=True)
## log.h (module 'core'): static std::string ns3::LogComponent::GetLevelLabel(ns3::LogLevel const level) [member function]
cls.add_method('GetLevelLabel',
'std::string',
[param('ns3::LogLevel const', 'level')],
is_static=True)
## log.h (module 'core'): bool ns3::LogComponent::IsEnabled(ns3::LogLevel const level) const [member function]
cls.add_method('IsEnabled',
'bool',
[param('ns3::LogLevel const', 'level')],
is_const=True)
## log.h (module 'core'): bool ns3::LogComponent::IsNoneEnabled() const [member function]
cls.add_method('IsNoneEnabled',
'bool',
[],
is_const=True)
## log.h (module 'core'): char const * ns3::LogComponent::Name() const [member function]
cls.add_method('Name',
'char const *',
[],
is_const=True)
## log.h (module 'core'): void ns3::LogComponent::SetMask(ns3::LogLevel const level) [member function]
cls.add_method('SetMask',
'void',
[param('ns3::LogLevel const', 'level')])
return
def register_Ns3Mac16Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(ns3::Mac16Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac16Address const &', 'arg0')])
## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address() [constructor]
cls.add_constructor([])
## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac16Address',
[],
is_static=True)
## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac16Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac16-address.h (module 'network'): static bool ns3::Mac16Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3Mac48Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac48Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv4Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv6Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function]
cls.add_method('GetMulticast6Prefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function]
cls.add_method('GetMulticastPrefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function]
cls.add_method('IsGroup',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3Mac64Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(ns3::Mac64Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac64Address const &', 'arg0')])
## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address() [constructor]
cls.add_constructor([])
## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac64Address',
[],
is_static=True)
## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac64Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac64-address.h (module 'network'): static bool ns3::Mac64Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3NetDeviceContainer_methods(root_module, cls):
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor]
cls.add_constructor([])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor]
cls.add_constructor([param('std::string', 'devName')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NetDeviceContainer', 'other')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'deviceName')])
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True)
## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeContainer_methods(root_module, cls):
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor]
cls.add_constructor([])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor]
cls.add_constructor([param('std::string', 'nodeName')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NodeContainer', 'other')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'nodeName')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n')])
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n'), param('uint32_t', 'systemId')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'i')],
is_const=True)
## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function]
cls.add_method('GetGlobal',
'ns3::NodeContainer',
[],
is_static=True)
## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeList_methods(root_module, cls):
## node-list.h (module 'network'): ns3::NodeList::NodeList() [constructor]
cls.add_constructor([])
## node-list.h (module 'network'): ns3::NodeList::NodeList(ns3::NodeList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeList const &', 'arg0')])
## node-list.h (module 'network'): static uint32_t ns3::NodeList::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'uint32_t',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_static=True)
## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_static=True)
## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_static=True)
## node-list.h (module 'network'): static uint32_t ns3::NodeList::GetNNodes() [member function]
cls.add_method('GetNNodes',
'uint32_t',
[],
is_static=True)
## node-list.h (module 'network'): static ns3::Ptr<ns3::Node> ns3::NodeList::GetNode(uint32_t n) [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'n')],
is_static=True)
return
def register_Ns3NonCopyable_methods(root_module, cls):
## non-copyable.h (module 'core'): ns3::NonCopyable::NonCopyable() [constructor]
cls.add_constructor([],
visibility='protected')
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_Ns3PacketSocketAddress_methods(root_module, cls):
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress(ns3::PacketSocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketAddress const &', 'arg0')])
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress() [constructor]
cls.add_constructor([])
## packet-socket-address.h (module 'network'): static ns3::PacketSocketAddress ns3::PacketSocketAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::PacketSocketAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## packet-socket-address.h (module 'network'): ns3::Address ns3::PacketSocketAddress::GetPhysicalAddress() const [member function]
cls.add_method('GetPhysicalAddress',
'ns3::Address',
[],
is_const=True)
## packet-socket-address.h (module 'network'): uint16_t ns3::PacketSocketAddress::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint16_t',
[],
is_const=True)
## packet-socket-address.h (module 'network'): uint32_t ns3::PacketSocketAddress::GetSingleDevice() const [member function]
cls.add_method('GetSingleDevice',
'uint32_t',
[],
is_const=True)
## packet-socket-address.h (module 'network'): static bool ns3::PacketSocketAddress::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## packet-socket-address.h (module 'network'): bool ns3::PacketSocketAddress::IsSingleDevice() const [member function]
cls.add_method('IsSingleDevice',
'bool',
[],
is_const=True)
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetAllDevices() [member function]
cls.add_method('SetAllDevices',
'void',
[])
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetPhysicalAddress(ns3::Address const address) [member function]
cls.add_method('SetPhysicalAddress',
'void',
[param('ns3::Address const', 'address')])
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetProtocol(uint16_t protocol) [member function]
cls.add_method('SetProtocol',
'void',
[param('uint16_t', 'protocol')])
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetSingleDevice(uint32_t device) [member function]
cls.add_method('SetSingleDevice',
'void',
[param('uint32_t', 'device')])
return
def register_Ns3PacketSocketHelper_methods(root_module, cls):
## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper() [constructor]
cls.add_constructor([])
## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper(ns3::PacketSocketHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketHelper const &', 'arg0')])
## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'void',
[param('std::string', 'nodeName')],
is_const=True)
## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'void',
[param('ns3::NodeContainer', 'c')],
is_const=True)
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
## 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 [ 1 ]', 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::size [variable]
cls.add_instance_attribute('size', 'uint32_t', 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_Ns3ParameterLogger_methods(root_module, cls):
## log.h (module 'core'): ns3::ParameterLogger::ParameterLogger(ns3::ParameterLogger const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ParameterLogger const &', 'arg0')])
## log.h (module 'core'): ns3::ParameterLogger::ParameterLogger(std::ostream & os) [constructor]
cls.add_constructor([param('std::ostream &', 'os')])
return
def register_Ns3PbbAddressTlvBlock_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock(ns3::PbbAddressTlvBlock const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressTlvBlock const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Back() const [member function]
cls.add_method('Back',
'ns3::Ptr< ns3::PbbAddressTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() [member function]
cls.add_method('Begin',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): bool ns3::PbbAddressTlvBlock::Empty() const [member function]
cls.add_method('Empty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() [member function]
cls.add_method('End',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Front() const [member function]
cls.add_method('Front',
'ns3::Ptr< ns3::PbbAddressTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbAddressTlvBlock::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbAddressTlv> const tlv) [member function]
cls.add_method('Insert',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbAddressTlv > const', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopBack() [member function]
cls.add_method('PopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopFront() [member function]
cls.add_method('PopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushBack(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function]
cls.add_method('PushBack',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushFront(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): int ns3::PbbAddressTlvBlock::Size() const [member function]
cls.add_method('Size',
'int',
[],
is_const=True)
return
def register_Ns3PbbTlvBlock_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock(ns3::PbbTlvBlock const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbTlvBlock const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Back() const [member function]
cls.add_method('Back',
'ns3::Ptr< ns3::PbbTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() [member function]
cls.add_method('Begin',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): bool ns3::PbbTlvBlock::Empty() const [member function]
cls.add_method('Empty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() [member function]
cls.add_method('End',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Front() const [member function]
cls.add_method('Front',
'ns3::Ptr< ns3::PbbTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbTlvBlock::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position, ns3::Ptr<ns3::PbbTlv> const tlv) [member function]
cls.add_method('Insert',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopBack() [member function]
cls.add_method('PopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopFront() [member function]
cls.add_method('PopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('PushBack',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): int ns3::PbbTlvBlock::Size() const [member function]
cls.add_method('Size',
'int',
[],
is_const=True)
return
def register_Ns3PcapFile_methods(root_module, cls):
## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor]
cls.add_constructor([])
## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t & packets, 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 &', 'packets'), 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, bool nanosecMode=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'), param('bool', 'nanosecMode', default_value='false')])
## pcap-file.h (module 'network'): bool ns3::PcapFile::IsNanoSecMode() [member function]
cls.add_method('IsNanoSecMode',
'bool',
[])
## 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<ns3::Packet const> 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 const & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header const &', '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, ns3::PcapHelper::DataLinkType dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=0) [member function]
cls.add_method('CreateFile',
'ns3::Ptr< ns3::PcapFileWrapper >',
[param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode'), param('ns3::PcapHelper::DataLinkType', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), 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_Ns3SequenceNumber32_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_numeric_operator('+', root_module['ns3::SequenceNumber32'], root_module['ns3::SequenceNumber32'], param('ns3::SequenceNumber< unsigned int, int > const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::SequenceNumber32'], root_module['ns3::SequenceNumber32'], param('int', u'right'))
cls.add_inplace_numeric_operator('+=', param('int', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::SequenceNumber32'], root_module['ns3::SequenceNumber32'], param('int', u'right'))
cls.add_inplace_numeric_operator('-=', param('int', u'right'))
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('>=')
## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned int, int>::SequenceNumber() [constructor]
cls.add_constructor([])
## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned int, int>::SequenceNumber(unsigned int value) [constructor]
cls.add_constructor([param('unsigned int', 'value')])
## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned int, int>::SequenceNumber(ns3::SequenceNumber<unsigned int, int> const & value) [copy constructor]
cls.add_constructor([param('ns3::SequenceNumber< unsigned int, int > const &', 'value')])
## sequence-number.h (module 'network'): unsigned int ns3::SequenceNumber<unsigned int, int>::GetValue() const [member function]
cls.add_method('GetValue',
'unsigned int',
[],
is_const=True)
return
def register_Ns3SequenceNumber16_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_numeric_operator('+', root_module['ns3::SequenceNumber16'], root_module['ns3::SequenceNumber16'], param('ns3::SequenceNumber< unsigned short, short > const &', u'right'))
cls.add_binary_numeric_operator('+', root_module['ns3::SequenceNumber16'], root_module['ns3::SequenceNumber16'], param('short int', u'right'))
cls.add_inplace_numeric_operator('+=', param('short int', u'right'))
cls.add_binary_numeric_operator('-', root_module['ns3::SequenceNumber16'], root_module['ns3::SequenceNumber16'], param('short int', u'right'))
cls.add_inplace_numeric_operator('-=', param('short int', u'right'))
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('>=')
## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned short, short>::SequenceNumber() [constructor]
cls.add_constructor([])
## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned short, short>::SequenceNumber(short unsigned int value) [constructor]
cls.add_constructor([param('short unsigned int', 'value')])
## sequence-number.h (module 'network'): ns3::SequenceNumber<unsigned short, short>::SequenceNumber(ns3::SequenceNumber<unsigned short, short> const & value) [copy constructor]
cls.add_constructor([param('ns3::SequenceNumber< unsigned short, short > const &', 'value')])
## sequence-number.h (module 'network'): short unsigned int ns3::SequenceNumber<unsigned short, short>::GetValue() const [member function]
cls.add_method('GetValue',
'short unsigned int',
[],
is_const=True)
return
def register_Ns3SimpleNetDeviceHelper_methods(root_module, cls):
## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper::SimpleNetDeviceHelper(ns3::SimpleNetDeviceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimpleNetDeviceHelper const &', 'arg0')])
## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper::SimpleNetDeviceHelper() [constructor]
cls.add_constructor([])
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::SimpleChannel> channel) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::SimpleChannel >', 'channel')],
is_const=True)
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::NodeContainer const & c) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer const &', 'c')],
is_const=True)
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::NodeContainer const & c, ns3::Ptr<ns3::SimpleChannel> channel) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer const &', 'c'), param('ns3::Ptr< ns3::SimpleChannel >', 'channel')],
is_const=True)
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetChannel(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('SetChannel',
'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()')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetChannelAttribute(std::string n1, ns3::AttributeValue const & v1) [member function]
cls.add_method('SetChannelAttribute',
'void',
[param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function]
cls.add_method('SetDeviceAttribute',
'void',
[param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetNetDevicePointToPointMode(bool pointToPointMode) [member function]
cls.add_method('SetNetDevicePointToPointMode',
'void',
[param('bool', 'pointToPointMode')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::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()')])
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function]
cls.add_method('SetImplementation',
'void',
[param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'delay')],
is_static=True)
return
def register_Ns3StatisticalSummary_methods(root_module, cls):
## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary() [constructor]
cls.add_constructor([])
## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary(ns3::StatisticalSummary const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StatisticalSummary const &', 'arg0')])
## data-calculator.h (module 'stats'): long int ns3::StatisticalSummary::getCount() const [member function]
cls.add_method('getCount',
'long int',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMax() const [member function]
cls.add_method('getMax',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMean() const [member function]
cls.add_method('getMean',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMin() const [member function]
cls.add_method('getMin',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSqrSum() const [member function]
cls.add_method('getSqrSum',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getStddev() const [member function]
cls.add_method('getStddev',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSum() const [member function]
cls.add_method('getSum',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getVariance() const [member function]
cls.add_method('getVariance',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3SystemWallClockMs_methods(root_module, cls):
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')])
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor]
cls.add_constructor([])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function]
cls.add_method('End',
'int64_t',
[])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function]
cls.add_method('GetElapsedReal',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function]
cls.add_method('GetElapsedSystem',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function]
cls.add_method('GetElapsedUser',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_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_Ns3TracedValue__Unsigned_int_methods(root_module, cls):
## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue() [constructor]
cls.add_constructor([])
## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue(ns3::TracedValue<unsigned int> const & o) [copy constructor]
cls.add_constructor([param('ns3::TracedValue< unsigned int > const &', 'o')])
## traced-value.h (module 'core'): ns3::TracedValue<unsigned int>::TracedValue(unsigned int const & v) [constructor]
cls.add_constructor([param('unsigned int const &', 'v')])
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Connect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function]
cls.add_method('Connect',
'void',
[param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')])
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::ConnectWithoutContext(ns3::CallbackBase const & cb) [member function]
cls.add_method('ConnectWithoutContext',
'void',
[param('ns3::CallbackBase const &', 'cb')])
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Disconnect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function]
cls.add_method('Disconnect',
'void',
[param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')])
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::DisconnectWithoutContext(ns3::CallbackBase const & cb) [member function]
cls.add_method('DisconnectWithoutContext',
'void',
[param('ns3::CallbackBase const &', 'cb')])
## traced-value.h (module 'core'): unsigned int ns3::TracedValue<unsigned int>::Get() const [member function]
cls.add_method('Get',
'unsigned int',
[],
is_const=True)
## traced-value.h (module 'core'): void ns3::TracedValue<unsigned int>::Set(unsigned int const & v) [member function]
cls.add_method('Set',
'void',
[param('unsigned int const &', 'v')])
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, 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::SetParent() [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[],
template_parameters=['ns3::Object'])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent() [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[],
template_parameters=['ns3::QueueBase'])
## 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_comparison_operator('<=')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', 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_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_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('>=')
## 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_Ns3DeviceNameTag_methods(root_module, cls):
## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag(ns3::DeviceNameTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeviceNameTag const &', 'arg0')])
## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag() [constructor]
cls.add_constructor([])
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## packet-socket.h (module 'network'): std::string ns3::DeviceNameTag::GetDeviceName() const [member function]
cls.add_method('GetDeviceName',
'std::string',
[],
is_const=True)
## packet-socket.h (module 'network'): ns3::TypeId ns3::DeviceNameTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): uint32_t ns3::DeviceNameTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): static ns3::TypeId ns3::DeviceNameTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::SetDeviceName(std::string n) [member function]
cls.add_method('SetDeviceName',
'void',
[param('std::string', 'n')])
return
def register_Ns3FlowIdTag_methods(root_module, cls):
## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(ns3::FlowIdTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FlowIdTag const &', 'arg0')])
## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag() [constructor]
cls.add_constructor([])
## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(uint32_t flowId) [constructor]
cls.add_constructor([param('uint32_t', 'flowId')])
## flow-id-tag.h (module 'network'): static uint32_t ns3::FlowIdTag::AllocateFlowId() [member function]
cls.add_method('AllocateFlowId',
'uint32_t',
[],
is_static=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Deserialize(ns3::TagBuffer buf) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'buf')],
is_virtual=True)
## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetFlowId() const [member function]
cls.add_method('GetFlowId',
'uint32_t',
[],
is_const=True)
## flow-id-tag.h (module 'network'): ns3::TypeId ns3::FlowIdTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): static ns3::TypeId ns3::FlowIdTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Serialize(ns3::TagBuffer buf) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'buf')],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::SetFlowId(uint32_t flowId) [member function]
cls.add_method('SetFlowId',
'void',
[param('uint32_t', 'flowId')])
return
def register_Ns3Header_methods(root_module, cls):
cls.add_output_stream_operator()
## header.h (module 'network'): ns3::Header::Header() [constructor]
cls.add_constructor([])
## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Header const &', 'arg0')])
## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3LlcSnapHeader_methods(root_module, cls):
## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader(ns3::LlcSnapHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LlcSnapHeader const &', 'arg0')])
## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader() [constructor]
cls.add_constructor([])
## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## llc-snap-header.h (module 'network'): ns3::TypeId ns3::LlcSnapHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): uint16_t ns3::LlcSnapHeader::GetType() [member function]
cls.add_method('GetType',
'uint16_t',
[])
## llc-snap-header.h (module 'network'): static ns3::TypeId ns3::LlcSnapHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::SetType(uint16_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint16_t', 'type')])
return
def register_Ns3Object_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::Object() [constructor]
cls.add_constructor([])
## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function]
cls.add_method('AggregateObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'other')])
## object.h (module 'core'): void ns3::Object::Dispose() [member function]
cls.add_method('Dispose',
'void',
[])
## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function]
cls.add_method('GetAggregateIterator',
'ns3::Object::AggregateIterator',
[],
is_const=True)
## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## object.h (module 'core'): ns3::Ptr<ns3::NetDevice> ns3::Object::GetObject() const [member function]
cls.add_method('GetObject',
'ns3::Ptr< ns3::NetDevice >',
[],
is_const=True, template_parameters=['ns3::NetDevice'])
## 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_Ns3PacketBurst_methods(root_module, cls):
## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst(ns3::PacketBurst const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketBurst const &', 'arg0')])
## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst() [constructor]
cls.add_constructor([])
## packet-burst.h (module 'network'): void ns3::PacketBurst::AddPacket(ns3::Ptr<ns3::Packet> packet) [member function]
cls.add_method('AddPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet')])
## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): ns3::Ptr<ns3::PacketBurst> ns3::PacketBurst::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::PacketBurst >',
[],
is_const=True)
## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetNPackets() const [member function]
cls.add_method('GetNPackets',
'uint32_t',
[],
is_const=True)
## packet-burst.h (module 'network'): std::list<ns3::Ptr<ns3::Packet>, std::allocator<ns3::Ptr<ns3::Packet> > > ns3::PacketBurst::GetPackets() const [member function]
cls.add_method('GetPackets',
'std::list< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet-burst.h (module 'network'): static ns3::TypeId ns3::PacketBurst::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-burst.h (module 'network'): void ns3::PacketBurst::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSocketTag_methods(root_module, cls):
## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag(ns3::PacketSocketTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketTag const &', 'arg0')])
## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag() [constructor]
cls.add_constructor([])
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## packet-socket.h (module 'network'): ns3::Address ns3::PacketSocketTag::GetDestAddress() const [member function]
cls.add_method('GetDestAddress',
'ns3::Address',
[],
is_const=True)
## packet-socket.h (module 'network'): ns3::TypeId ns3::PacketSocketTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::NetDevice::PacketType ns3::PacketSocketTag::GetPacketType() const [member function]
cls.add_method('GetPacketType',
'ns3::NetDevice::PacketType',
[],
is_const=True)
## packet-socket.h (module 'network'): uint32_t ns3::PacketSocketTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocketTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetDestAddress(ns3::Address a) [member function]
cls.add_method('SetDestAddress',
'void',
[param('ns3::Address', 'a')])
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetPacketType(ns3::NetDevice::PacketType t) [member function]
cls.add_method('SetPacketType',
'void',
[param('ns3::NetDevice::PacketType', 't')])
return
def register_Ns3PcapFileWrapper_methods(root_module, cls):
## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor]
cls.add_constructor([])
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function]
cls.add_method('Init',
'void',
[param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<ns3::Packet const> 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 const & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('ns3::Header const &', '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'): ns3::Ptr<ns3::Packet> ns3::PcapFileWrapper::Read(ns3::Time & t) [member function]
cls.add_method('Read',
'ns3::Ptr< ns3::Packet >',
[param('ns3::Time &', 't')])
## 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_Ns3QueueBase_methods(root_module, cls):
## queue.h (module 'network'): ns3::QueueBase::QueueBase(ns3::QueueBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::QueueBase const &', 'arg0')])
## queue.h (module 'network'): ns3::QueueBase::QueueBase() [constructor]
cls.add_constructor([])
## queue.h (module 'network'): static void ns3::QueueBase::AppendItemTypeIfNotPresent(std::string & typeId, std::string const & itemType) [member function]
cls.add_method('AppendItemTypeIfNotPresent',
'void',
[param('std::string &', 'typeId'), param('std::string const &', 'itemType')],
is_static=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetMaxBytes() const [member function]
cls.add_method('GetMaxBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetMaxPackets() const [member function]
cls.add_method('GetMaxPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): ns3::QueueBase::QueueMode ns3::QueueBase::GetMode() const [member function]
cls.add_method('GetMode',
'ns3::QueueBase::QueueMode',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetNBytes() const [member function]
cls.add_method('GetNBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetNPackets() const [member function]
cls.add_method('GetNPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedBytes() const [member function]
cls.add_method('GetTotalDroppedBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedBytesAfterDequeue() const [member function]
cls.add_method('GetTotalDroppedBytesAfterDequeue',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedBytesBeforeEnqueue() const [member function]
cls.add_method('GetTotalDroppedBytesBeforeEnqueue',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedPackets() const [member function]
cls.add_method('GetTotalDroppedPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedPacketsAfterDequeue() const [member function]
cls.add_method('GetTotalDroppedPacketsAfterDequeue',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalDroppedPacketsBeforeEnqueue() const [member function]
cls.add_method('GetTotalDroppedPacketsBeforeEnqueue',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalReceivedBytes() const [member function]
cls.add_method('GetTotalReceivedBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::QueueBase::GetTotalReceivedPackets() const [member function]
cls.add_method('GetTotalReceivedPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): static ns3::TypeId ns3::QueueBase::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## queue.h (module 'network'): bool ns3::QueueBase::IsEmpty() const [member function]
cls.add_method('IsEmpty',
'bool',
[],
is_const=True)
## queue.h (module 'network'): void ns3::QueueBase::ResetStatistics() [member function]
cls.add_method('ResetStatistics',
'void',
[])
## queue.h (module 'network'): void ns3::QueueBase::SetMaxBytes(uint32_t maxBytes) [member function]
cls.add_method('SetMaxBytes',
'void',
[param('uint32_t', 'maxBytes')])
## queue.h (module 'network'): void ns3::QueueBase::SetMaxPackets(uint32_t maxPackets) [member function]
cls.add_method('SetMaxPackets',
'void',
[param('uint32_t', 'maxPackets')])
## queue.h (module 'network'): void ns3::QueueBase::SetMode(ns3::QueueBase::QueueMode mode) [member function]
cls.add_method('SetMode',
'void',
[param('ns3::QueueBase::QueueMode', 'mode')])
## queue.h (module 'network'): void ns3::QueueBase::DoNsLog(ns3::LogLevel const level, std::string str) const [member function]
cls.add_method('DoNsLog',
'void',
[param('ns3::LogLevel const', 'level'), param('std::string', 'str')],
is_const=True, visibility='protected')
return
def register_Ns3QueueLimits_methods(root_module, cls):
## queue-limits.h (module 'network'): ns3::QueueLimits::QueueLimits() [constructor]
cls.add_constructor([])
## queue-limits.h (module 'network'): ns3::QueueLimits::QueueLimits(ns3::QueueLimits const & arg0) [copy constructor]
cls.add_constructor([param('ns3::QueueLimits const &', 'arg0')])
## queue-limits.h (module 'network'): int32_t ns3::QueueLimits::Available() const [member function]
cls.add_method('Available',
'int32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## queue-limits.h (module 'network'): void ns3::QueueLimits::Completed(uint32_t count) [member function]
cls.add_method('Completed',
'void',
[param('uint32_t', 'count')],
is_pure_virtual=True, is_virtual=True)
## queue-limits.h (module 'network'): static ns3::TypeId ns3::QueueLimits::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## queue-limits.h (module 'network'): void ns3::QueueLimits::Queued(uint32_t count) [member function]
cls.add_method('Queued',
'void',
[param('uint32_t', 'count')],
is_pure_virtual=True, is_virtual=True)
## queue-limits.h (module 'network'): void ns3::QueueLimits::Reset() [member function]
cls.add_method('Reset',
'void',
[],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3RadiotapHeader_methods(root_module, cls):
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader(ns3::RadiotapHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RadiotapHeader const &', 'arg0')])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader() [constructor]
cls.add_constructor([])
## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetAmpduStatusFlags() const [member function]
cls.add_method('GetAmpduStatusFlags',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::GetAmpduStatusRef() const [member function]
cls.add_method('GetAmpduStatusRef',
'uint32_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetAntennaNoisePower() const [member function]
cls.add_method('GetAntennaNoisePower',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetAntennaSignalPower() const [member function]
cls.add_method('GetAntennaSignalPower',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetChannelFlags() const [member function]
cls.add_method('GetChannelFlags',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetChannelFrequency() const [member function]
cls.add_method('GetChannelFrequency',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetFrameFlags() const [member function]
cls.add_method('GetFrameFlags',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): ns3::TypeId ns3::RadiotapHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetMcsFlags() const [member function]
cls.add_method('GetMcsFlags',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetMcsKnown() const [member function]
cls.add_method('GetMcsKnown',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetMcsRate() const [member function]
cls.add_method('GetMcsRate',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetRate() const [member function]
cls.add_method('GetRate',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): uint64_t ns3::RadiotapHeader::GetTsft() const [member function]
cls.add_method('GetTsft',
'uint64_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): static ns3::TypeId ns3::RadiotapHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtBandwidth() const [member function]
cls.add_method('GetVhtBandwidth',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtCoding() const [member function]
cls.add_method('GetVhtCoding',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtFlags() const [member function]
cls.add_method('GetVhtFlags',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtGroupId() const [member function]
cls.add_method('GetVhtGroupId',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetVhtKnown() const [member function]
cls.add_method('GetVhtKnown',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser1() const [member function]
cls.add_method('GetVhtMcsNssUser1',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser2() const [member function]
cls.add_method('GetVhtMcsNssUser2',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser3() const [member function]
cls.add_method('GetVhtMcsNssUser3',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser4() const [member function]
cls.add_method('GetVhtMcsNssUser4',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtPartialAid() const [member function]
cls.add_method('GetVhtPartialAid',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAmpduStatus(uint32_t referenceNumber, uint16_t flags, uint8_t crc) [member function]
cls.add_method('SetAmpduStatus',
'void',
[param('uint32_t', 'referenceNumber'), param('uint16_t', 'flags'), param('uint8_t', 'crc')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaNoisePower(double noise) [member function]
cls.add_method('SetAntennaNoisePower',
'void',
[param('double', 'noise')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaSignalPower(double signal) [member function]
cls.add_method('SetAntennaSignalPower',
'void',
[param('double', 'signal')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetChannelFrequencyAndFlags(uint16_t frequency, uint16_t flags) [member function]
cls.add_method('SetChannelFrequencyAndFlags',
'void',
[param('uint16_t', 'frequency'), param('uint16_t', 'flags')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetFrameFlags(uint8_t flags) [member function]
cls.add_method('SetFrameFlags',
'void',
[param('uint8_t', 'flags')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetMcsFields(uint8_t known, uint8_t flags, uint8_t mcs) [member function]
cls.add_method('SetMcsFields',
'void',
[param('uint8_t', 'known'), param('uint8_t', 'flags'), param('uint8_t', 'mcs')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetRate(uint8_t rate) [member function]
cls.add_method('SetRate',
'void',
[param('uint8_t', 'rate')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetTsft(uint64_t tsft) [member function]
cls.add_method('SetTsft',
'void',
[param('uint64_t', 'tsft')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetVhtFields(uint16_t known, uint8_t flags, uint8_t bandwidth, uint8_t * mcs_nss, uint8_t coding, uint8_t group_id, uint16_t partial_aid) [member function]
cls.add_method('SetVhtFields',
'void',
[param('uint16_t', 'known'), param('uint8_t', 'flags'), param('uint8_t', 'bandwidth'), param('uint8_t *', 'mcs_nss'), param('uint8_t', 'coding'), param('uint8_t', 'group_id'), param('uint16_t', 'partial_aid')])
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__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter< ns3::PbbAddressBlock > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter< ns3::PbbMessage > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter< ns3::PbbPacket > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter< ns3::PbbTlv > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SllHeader_methods(root_module, cls):
## sll-header.h (module 'network'): ns3::SllHeader::SllHeader(ns3::SllHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SllHeader const &', 'arg0')])
## sll-header.h (module 'network'): ns3::SllHeader::SllHeader() [constructor]
cls.add_constructor([])
## sll-header.h (module 'network'): uint32_t ns3::SllHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## sll-header.h (module 'network'): uint16_t ns3::SllHeader::GetArpType() const [member function]
cls.add_method('GetArpType',
'uint16_t',
[],
is_const=True)
## sll-header.h (module 'network'): ns3::TypeId ns3::SllHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## sll-header.h (module 'network'): ns3::SllHeader::PacketType ns3::SllHeader::GetPacketType() const [member function]
cls.add_method('GetPacketType',
'ns3::SllHeader::PacketType',
[],
is_const=True)
## sll-header.h (module 'network'): uint32_t ns3::SllHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## sll-header.h (module 'network'): static ns3::TypeId ns3::SllHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## sll-header.h (module 'network'): void ns3::SllHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## sll-header.h (module 'network'): void ns3::SllHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## sll-header.h (module 'network'): void ns3::SllHeader::SetArpType(uint16_t arphdType) [member function]
cls.add_method('SetArpType',
'void',
[param('uint16_t', 'arphdType')])
## sll-header.h (module 'network'): void ns3::SllHeader::SetPacketType(ns3::SllHeader::PacketType type) [member function]
cls.add_method('SetPacketType',
'void',
[param('ns3::SllHeader::PacketType', 'type')])
return
def register_Ns3Socket_methods(root_module, cls):
## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Socket const &', 'arg0')])
## socket.h (module 'network'): ns3::Socket::Socket() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function]
cls.add_method('Bind',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind() [member function]
cls.add_method('Bind',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind6() [member function]
cls.add_method('Bind6',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function]
cls.add_method('BindToNetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'netdevice')],
is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Close() [member function]
cls.add_method('Close',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function]
cls.add_method('Connect',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')],
is_static=True)
## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function]
cls.add_method('GetAllowBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function]
cls.add_method('GetBoundNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[])
## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function]
cls.add_method('GetErrno',
'ns3::Socket::SocketErrno',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function]
cls.add_method('GetIpTos',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function]
cls.add_method('GetIpTtl',
'uint8_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function]
cls.add_method('GetIpv6HopLimit',
'uint8_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function]
cls.add_method('GetIpv6Tclass',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function]
cls.add_method('GetPeerName',
'int',
[param('ns3::Address &', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function]
cls.add_method('GetPriority',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function]
cls.add_method('GetRxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function]
cls.add_method('GetSockName',
'int',
[param('ns3::Address &', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function]
cls.add_method('GetSocketType',
'ns3::Socket::SocketType',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function]
cls.add_method('GetTxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function]
cls.add_method('IpTos2Priority',
'uint8_t',
[param('uint8_t', 'ipTos')],
is_static=True)
## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address,std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function]
cls.add_method('Ipv6JoinGroup',
'void',
[param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function]
cls.add_method('Ipv6JoinGroup',
'void',
[param('ns3::Ipv6Address', 'address')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function]
cls.add_method('Ipv6LeaveGroup',
'void',
[],
is_virtual=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function]
cls.add_method('IsIpRecvTos',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function]
cls.add_method('IsIpRecvTtl',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function]
cls.add_method('IsIpv6RecvHopLimit',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function]
cls.add_method('IsIpv6RecvTclass',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function]
cls.add_method('IsRecvPktInfo',
'bool',
[],
is_const=True)
## socket.h (module 'network'): int ns3::Socket::Listen() [member function]
cls.add_method('Listen',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[])
## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Recv',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function]
cls.add_method('SendTo',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function]
cls.add_method('SendTo',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')])
## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function]
cls.add_method('SetAcceptCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')])
## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function]
cls.add_method('SetAllowBroadcast',
'bool',
[param('bool', 'allowBroadcast')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function]
cls.add_method('SetCloseCallbacks',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')])
## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function]
cls.add_method('SetConnectCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')])
## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function]
cls.add_method('SetDataSentCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')])
## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function]
cls.add_method('SetIpRecvTos',
'void',
[param('bool', 'ipv4RecvTos')])
## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function]
cls.add_method('SetIpRecvTtl',
'void',
[param('bool', 'ipv4RecvTtl')])
## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function]
cls.add_method('SetIpTos',
'void',
[param('uint8_t', 'ipTos')])
## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function]
cls.add_method('SetIpTtl',
'void',
[param('uint8_t', 'ipTtl')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function]
cls.add_method('SetIpv6HopLimit',
'void',
[param('uint8_t', 'ipHopLimit')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function]
cls.add_method('SetIpv6RecvHopLimit',
'void',
[param('bool', 'ipv6RecvHopLimit')])
## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function]
cls.add_method('SetIpv6RecvTclass',
'void',
[param('bool', 'ipv6RecvTclass')])
## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function]
cls.add_method('SetIpv6Tclass',
'void',
[param('int', 'ipTclass')])
## socket.h (module 'network'): void ns3::Socket::SetPriority(uint8_t priority) [member function]
cls.add_method('SetPriority',
'void',
[param('uint8_t', 'priority')])
## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function]
cls.add_method('SetRecvCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')])
## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function]
cls.add_method('SetRecvPktInfo',
'void',
[param('bool', 'flag')])
## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function]
cls.add_method('SetSendCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')])
## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function]
cls.add_method('ShutdownRecv',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function]
cls.add_method('ShutdownSend',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function]
cls.add_method('IsManualIpTtl',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function]
cls.add_method('IsManualIpv6HopLimit',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function]
cls.add_method('IsManualIpv6Tclass',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function]
cls.add_method('NotifyConnectionFailed',
'void',
[],
visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function]
cls.add_method('NotifyConnectionRequest',
'bool',
[param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function]
cls.add_method('NotifyConnectionSucceeded',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function]
cls.add_method('NotifyDataRecv',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function]
cls.add_method('NotifyDataSent',
'void',
[param('uint32_t', 'size')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function]
cls.add_method('NotifyErrorClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function]
cls.add_method('NotifyNewConnectionCreated',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function]
cls.add_method('NotifyNormalClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function]
cls.add_method('NotifySend',
'void',
[param('uint32_t', 'spaceAvailable')],
visibility='protected')
return
def register_Ns3SocketFactory_methods(root_module, cls):
## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory(ns3::SocketFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketFactory const &', 'arg0')])
## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory() [constructor]
cls.add_constructor([])
## socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::SocketFactory::CreateSocket() [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_pure_virtual=True, is_virtual=True)
## socket-factory.h (module 'network'): static ns3::TypeId ns3::SocketFactory::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3SocketIpTosTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
return
def register_Ns3SocketIpTtlTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function]
cls.add_method('GetTtl',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function]
cls.add_method('SetTtl',
'void',
[param('uint8_t', 'ttl')])
return
def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function]
cls.add_method('GetHopLimit',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function]
cls.add_method('SetHopLimit',
'void',
[param('uint8_t', 'hopLimit')])
return
def register_Ns3SocketIpv6TclassTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function]
cls.add_method('GetTclass',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function]
cls.add_method('SetTclass',
'void',
[param('uint8_t', 'tclass')])
return
def register_Ns3SocketPriorityTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketPriorityTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketPriorityTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function]
cls.add_method('GetPriority',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketPriorityTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketPriorityTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketPriorityTag::SetPriority(uint8_t priority) [member function]
cls.add_method('SetPriority',
'void',
[param('uint8_t', 'priority')])
return
def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
return
def register_Ns3Time_methods(root_module, cls):
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', 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_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_inplace_numeric_operator('-=', param('ns3::Time const &', u'right'))
cls.add_output_stream_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_Ns3Application_methods(root_module, cls):
## application.h (module 'network'): ns3::Application::Application(ns3::Application const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Application const &', 'arg0')])
## application.h (module 'network'): ns3::Application::Application() [constructor]
cls.add_constructor([])
## application.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Application::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True)
## application.h (module 'network'): static ns3::TypeId ns3::Application::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## application.h (module 'network'): void ns3::Application::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## application.h (module 'network'): void ns3::Application::SetStartTime(ns3::Time start) [member function]
cls.add_method('SetStartTime',
'void',
[param('ns3::Time', 'start')])
## application.h (module 'network'): void ns3::Application::SetStopTime(ns3::Time stop) [member function]
cls.add_method('SetStopTime',
'void',
[param('ns3::Time', 'stop')])
## application.h (module 'network'): void ns3::Application::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## application.h (module 'network'): void ns3::Application::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## application.h (module 'network'): void ns3::Application::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## application.h (module 'network'): void ns3::Application::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3BooleanChecker_methods(root_module, cls):
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')])
return
def register_Ns3BooleanValue_methods(root_module, cls):
cls.add_output_stream_operator()
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor]
cls.add_constructor([param('bool', 'value')])
## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function]
cls.add_method('Get',
'bool',
[],
is_const=True)
## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function]
cls.add_method('Set',
'void',
[param('bool', 'value')])
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_Ns3Channel_methods(root_module, cls):
## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Channel const &', 'arg0')])
## channel.h (module 'network'): ns3::Channel::Channel() [constructor]
cls.add_constructor([])
## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3ConstantRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function]
cls.add_method('GetConstant',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'constant')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'constant')])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DataCalculator_methods(root_module, cls):
## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator(ns3::DataCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataCalculator const &', 'arg0')])
## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator() [constructor]
cls.add_constructor([])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetContext() const [member function]
cls.add_method('GetContext',
'std::string',
[],
is_const=True)
## data-calculator.h (module 'stats'): bool ns3::DataCalculator::GetEnabled() const [member function]
cls.add_method('GetEnabled',
'bool',
[],
is_const=True)
## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetKey() const [member function]
cls.add_method('GetKey',
'std::string',
[],
is_const=True)
## data-calculator.h (module 'stats'): static ns3::TypeId ns3::DataCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetContext(std::string const context) [member function]
cls.add_method('SetContext',
'void',
[param('std::string const', 'context')])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetKey(std::string const key) [member function]
cls.add_method('SetKey',
'void',
[param('std::string const', 'key')])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Start(ns3::Time const & startTime) [member function]
cls.add_method('Start',
'void',
[param('ns3::Time const &', 'startTime')],
is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Stop(ns3::Time const & stopTime) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'stopTime')],
is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3DataCollectionObject_methods(root_module, cls):
## data-collection-object.h (module 'stats'): ns3::DataCollectionObject::DataCollectionObject(ns3::DataCollectionObject const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataCollectionObject const &', 'arg0')])
## data-collection-object.h (module 'stats'): ns3::DataCollectionObject::DataCollectionObject() [constructor]
cls.add_constructor([])
## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## data-collection-object.h (module 'stats'): std::string ns3::DataCollectionObject::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## data-collection-object.h (module 'stats'): static ns3::TypeId ns3::DataCollectionObject::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## data-collection-object.h (module 'stats'): bool ns3::DataCollectionObject::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True, is_virtual=True)
## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::SetName(std::string name) [member function]
cls.add_method('SetName',
'void',
[param('std::string', 'name')])
return
def register_Ns3DataOutputInterface_methods(root_module, cls):
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface(ns3::DataOutputInterface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataOutputInterface const &', 'arg0')])
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface() [constructor]
cls.add_constructor([])
## data-output-interface.h (module 'stats'): std::string ns3::DataOutputInterface::GetFilePrefix() const [member function]
cls.add_method('GetFilePrefix',
'std::string',
[],
is_const=True)
## data-output-interface.h (module 'stats'): static ns3::TypeId ns3::DataOutputInterface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::Output(ns3::DataCollector & dc) [member function]
cls.add_method('Output',
'void',
[param('ns3::DataCollector &', 'dc')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::SetFilePrefix(std::string const prefix) [member function]
cls.add_method('SetFilePrefix',
'void',
[param('std::string const', 'prefix')])
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3DataRateChecker_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')])
return
def register_Ns3DataRateValue_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor]
cls.add_constructor([param('ns3::DataRate const &', 'value')])
## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## data-rate.h (module 'network'): bool ns3::DataRateValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function]
cls.add_method('Get',
'ns3::DataRate',
[],
is_const=True)
## data-rate.h (module 'network'): std::string ns3::DataRateValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::DataRate const &', 'value')])
return
def register_Ns3DeterministicRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function]
cls.add_method('SetValueArray',
'void',
[param('double *', 'values'), param('uint64_t', 'length')])
## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DoubleValue_methods(root_module, cls):
## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor]
cls.add_constructor([])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor]
cls.add_constructor([param('double const &', 'value')])
## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## double.h (module 'core'): bool ns3::DoubleValue::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)
## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function]
cls.add_method('Get',
'double',
[],
is_const=True)
## double.h (module 'core'): std::string ns3::DoubleValue::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)
## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function]
cls.add_method('Set',
'void',
[param('double const &', 'value')])
return
def register_Ns3DynamicQueueLimits_methods(root_module, cls):
## dynamic-queue-limits.h (module 'network'): ns3::DynamicQueueLimits::DynamicQueueLimits(ns3::DynamicQueueLimits const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DynamicQueueLimits const &', 'arg0')])
## dynamic-queue-limits.h (module 'network'): ns3::DynamicQueueLimits::DynamicQueueLimits() [constructor]
cls.add_constructor([])
## dynamic-queue-limits.h (module 'network'): int32_t ns3::DynamicQueueLimits::Available() const [member function]
cls.add_method('Available',
'int32_t',
[],
is_const=True, is_virtual=True)
## dynamic-queue-limits.h (module 'network'): void ns3::DynamicQueueLimits::Completed(uint32_t count) [member function]
cls.add_method('Completed',
'void',
[param('uint32_t', 'count')],
is_virtual=True)
## dynamic-queue-limits.h (module 'network'): static ns3::TypeId ns3::DynamicQueueLimits::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## dynamic-queue-limits.h (module 'network'): void ns3::DynamicQueueLimits::Queued(uint32_t count) [member function]
cls.add_method('Queued',
'void',
[param('uint32_t', 'count')],
is_virtual=True)
## dynamic-queue-limits.h (module 'network'): void ns3::DynamicQueueLimits::Reset() [member function]
cls.add_method('Reset',
'void',
[],
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 c1, double c2, double v1, double v2, double r) [member function]
cls.add_method('Interpolate',
'double',
[param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')],
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_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_Ns3EnumChecker_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): void ns3::EnumChecker::Add(int value, std::string name) [member function]
cls.add_method('Add',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int value, std::string name) [member function]
cls.add_method('AddDefault',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EnumValue_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumValue const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): ns3::EnumValue::EnumValue(int value) [constructor]
cls.add_constructor([param('int', 'value')])
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumValue::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)
## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function]
cls.add_method('Get',
'int',
[],
is_const=True)
## enum.h (module 'core'): std::string ns3::EnumValue::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)
## enum.h (module 'core'): void ns3::EnumValue::Set(int value) [member function]
cls.add_method('Set',
'void',
[param('int', 'value')])
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_Ns3EthernetHeader_methods(root_module, cls):
## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(ns3::EthernetHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EthernetHeader const &', 'arg0')])
## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(bool hasPreamble) [constructor]
cls.add_constructor([param('bool', 'hasPreamble')])
## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader() [constructor]
cls.add_constructor([])
## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Mac48Address',
[],
is_const=True)
## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetHeaderSize() const [member function]
cls.add_method('GetHeaderSize',
'uint32_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): ns3::TypeId ns3::EthernetHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): uint16_t ns3::EthernetHeader::GetLengthType() const [member function]
cls.add_method('GetLengthType',
'uint16_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): ns3::ethernet_header_t ns3::EthernetHeader::GetPacketType() const [member function]
cls.add_method('GetPacketType',
'ns3::ethernet_header_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): uint64_t ns3::EthernetHeader::GetPreambleSfd() const [member function]
cls.add_method('GetPreambleSfd',
'uint64_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Mac48Address',
[],
is_const=True)
## ethernet-header.h (module 'network'): static ns3::TypeId ns3::EthernetHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetDestination(ns3::Mac48Address destination) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Mac48Address', 'destination')])
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetLengthType(uint16_t size) [member function]
cls.add_method('SetLengthType',
'void',
[param('uint16_t', 'size')])
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetPreambleSfd(uint64_t preambleSfd) [member function]
cls.add_method('SetPreambleSfd',
'void',
[param('uint64_t', 'preambleSfd')])
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetSource(ns3::Mac48Address source) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Mac48Address', 'source')])
return
def register_Ns3EthernetTrailer_methods(root_module, cls):
## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer(ns3::EthernetTrailer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EthernetTrailer const &', 'arg0')])
## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer() [constructor]
cls.add_constructor([])
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::CalcFcs(ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('CalcFcs',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p')])
## ethernet-trailer.h (module 'network'): bool ns3::EthernetTrailer::CheckFcs(ns3::Ptr<ns3::Packet const> p) const [member function]
cls.add_method('CheckFcs',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p')],
is_const=True)
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::Deserialize(ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'end')],
is_virtual=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::EnableFcs(bool enable) [member function]
cls.add_method('EnableFcs',
'void',
[param('bool', 'enable')])
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetFcs() const [member function]
cls.add_method('GetFcs',
'uint32_t',
[],
is_const=True)
## ethernet-trailer.h (module 'network'): ns3::TypeId ns3::EthernetTrailer::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetTrailerSize() const [member function]
cls.add_method('GetTrailerSize',
'uint32_t',
[],
is_const=True)
## ethernet-trailer.h (module 'network'): static ns3::TypeId ns3::EthernetTrailer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Serialize(ns3::Buffer::Iterator end) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'end')],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::SetFcs(uint32_t fcs) [member function]
cls.add_method('SetFcs',
'void',
[param('uint32_t', 'fcs')])
return
def register_Ns3EventImpl_methods(root_module, cls):
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventImpl const &', 'arg0')])
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor]
cls.add_constructor([])
## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[])
## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function]
cls.add_method('IsCancelled',
'bool',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function]
cls.add_method('Notify',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3ExponentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3GammaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function]
cls.add_method('GetBeta',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha'), param('double', 'beta')])
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha'), param('uint32_t', 'beta')])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3IntegerValue_methods(root_module, cls):
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor]
cls.add_constructor([])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor]
cls.add_constructor([param('int64_t const &', 'value')])
## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## integer.h (module 'core'): bool ns3::IntegerValue::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)
## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function]
cls.add_method('Get',
'int64_t',
[],
is_const=True)
## integer.h (module 'core'): std::string ns3::IntegerValue::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)
## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('int64_t const &', 'value')])
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_Ns3Mac16AddressChecker_methods(root_module, cls):
## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker() [constructor]
cls.add_constructor([])
## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker(ns3::Mac16AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac16AddressChecker const &', 'arg0')])
return
def register_Ns3Mac16AddressValue_methods(root_module, cls):
## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue() [constructor]
cls.add_constructor([])
## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac16AddressValue const &', 'arg0')])
## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac16Address const &', 'value')])
## mac16-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac16AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac16-address.h (module 'network'): bool ns3::Mac16AddressValue::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)
## mac16-address.h (module 'network'): ns3::Mac16Address ns3::Mac16AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac16Address',
[],
is_const=True)
## mac16-address.h (module 'network'): std::string ns3::Mac16AddressValue::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)
## mac16-address.h (module 'network'): void ns3::Mac16AddressValue::Set(ns3::Mac16Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac16Address 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_Ns3Mac64AddressChecker_methods(root_module, cls):
## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker() [constructor]
cls.add_constructor([])
## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker(ns3::Mac64AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac64AddressChecker const &', 'arg0')])
return
def register_Ns3Mac64AddressValue_methods(root_module, cls):
## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue() [constructor]
cls.add_constructor([])
## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac64AddressValue const &', 'arg0')])
## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac64Address const &', 'value')])
## mac64-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac64AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac64-address.h (module 'network'): bool ns3::Mac64AddressValue::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)
## mac64-address.h (module 'network'): ns3::Mac64Address ns3::Mac64AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac64Address',
[],
is_const=True)
## mac64-address.h (module 'network'): std::string ns3::Mac64AddressValue::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)
## mac64-address.h (module 'network'): void ns3::Mac64AddressValue::Set(ns3::Mac64Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac64Address const &', 'value')])
return
def register_Ns3MinMaxAvgTotalCalculator__Unsigned_int_methods(root_module, cls):
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int>::MinMaxAvgTotalCalculator(ns3::MinMaxAvgTotalCalculator<unsigned int> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MinMaxAvgTotalCalculator< unsigned int > const &', 'arg0')])
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int>::MinMaxAvgTotalCalculator() [constructor]
cls.add_constructor([])
## basic-data-calculators.h (module 'stats'): static ns3::TypeId ns3::MinMaxAvgTotalCalculator<unsigned int>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Reset() [member function]
cls.add_method('Reset',
'void',
[])
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Update(unsigned int const i) [member function]
cls.add_method('Update',
'void',
[param('unsigned int const', 'i')])
## basic-data-calculators.h (module 'stats'): long int ns3::MinMaxAvgTotalCalculator<unsigned int>::getCount() const [member function]
cls.add_method('getCount',
'long int',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMax() const [member function]
cls.add_method('getMax',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMean() const [member function]
cls.add_method('getMean',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMin() const [member function]
cls.add_method('getMin',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getSqrSum() const [member function]
cls.add_method('getSqrSum',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getStddev() const [member function]
cls.add_method('getStddev',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getSum() const [member function]
cls.add_method('getSum',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getVariance() const [member function]
cls.add_method('getVariance',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3NetDevice_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDevice const &', 'arg0')])
## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3NetDeviceQueue_methods(root_module, cls):
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')])
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor]
cls.add_constructor([])
## net-device-queue-interface.h (module 'network'): ns3::Ptr<ns3::QueueLimits> ns3::NetDeviceQueue::GetQueueLimits() [member function]
cls.add_method('GetQueueLimits',
'ns3::Ptr< ns3::QueueLimits >',
[])
## net-device-queue-interface.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function]
cls.add_method('IsStopped',
'bool',
[],
is_const=True)
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::NotifyQueuedBytes(uint32_t bytes) [member function]
cls.add_method('NotifyQueuedBytes',
'void',
[param('uint32_t', 'bytes')])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::NotifyTransmittedBytes(uint32_t bytes) [member function]
cls.add_method('NotifyTransmittedBytes',
'void',
[param('uint32_t', 'bytes')])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::ResetQueueLimits() [member function]
cls.add_method('ResetQueueLimits',
'void',
[])
## net-device-queue-interface.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-queue-interface.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-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function]
cls.add_method('Start',
'void',
[],
is_virtual=True)
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_virtual=True)
## net-device-queue-interface.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-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')])
## net-device-queue-interface.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor]
cls.add_constructor([])
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::CreateTxQueues() [member function]
cls.add_method('CreateTxQueues',
'void',
[])
## net-device-queue-interface.h (module 'network'): bool ns3::NetDeviceQueueInterface::GetLateTxQueuesCreation() const [member function]
cls.add_method('GetLateTxQueuesCreation',
'bool',
[],
is_const=True)
## net-device-queue-interface.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function]
cls.add_method('GetNTxQueues',
'uint8_t',
[],
is_const=True)
## net-device-queue-interface.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-queue-interface.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-queue-interface.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::SetLateTxQueuesCreation(bool value) [member function]
cls.add_method('SetLateTxQueuesCreation',
'void',
[param('bool', 'value')])
## net-device-queue-interface.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-queue-interface.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function]
cls.add_method('SetTxQueuesN',
'void',
[param('uint8_t', 'numTxQueues')])
## net-device-queue-interface.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_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<ns3::Packet const> 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_Ns3PacketSizeMinMaxAvgTotalCalculator_methods(root_module, cls):
## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator::PacketSizeMinMaxAvgTotalCalculator(ns3::PacketSizeMinMaxAvgTotalCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSizeMinMaxAvgTotalCalculator const &', 'arg0')])
## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator::PacketSizeMinMaxAvgTotalCalculator() [constructor]
cls.add_constructor([])
## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::FrameUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address realto) [member function]
cls.add_method('FrameUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'realto')])
## packet-data-calculators.h (module 'network'): static ns3::TypeId ns3::PacketSizeMinMaxAvgTotalCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::PacketUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('PacketUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3PacketSocket_methods(root_module, cls):
## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket(ns3::PacketSocket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocket const &', 'arg0')])
## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket() [constructor]
cls.add_constructor([])
## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind() [member function]
cls.add_method('Bind',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind(ns3::Address const & address) [member function]
cls.add_method('Bind',
'int',
[param('ns3::Address const &', 'address')],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind6() [member function]
cls.add_method('Bind6',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Close() [member function]
cls.add_method('Close',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Connect(ns3::Address const & address) [member function]
cls.add_method('Connect',
'int',
[param('ns3::Address const &', 'address')],
is_virtual=True)
## packet-socket.h (module 'network'): bool ns3::PacketSocket::GetAllowBroadcast() const [member function]
cls.add_method('GetAllowBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::Socket::SocketErrno ns3::PacketSocket::GetErrno() const [member function]
cls.add_method('GetErrno',
'ns3::Socket::SocketErrno',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::PacketSocket::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::GetPeerName(ns3::Address & address) const [member function]
cls.add_method('GetPeerName',
'int',
[param('ns3::Address &', 'address')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetRxAvailable() const [member function]
cls.add_method('GetRxAvailable',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::GetSockName(ns3::Address & address) const [member function]
cls.add_method('GetSockName',
'int',
[param('ns3::Address &', 'address')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::Socket::SocketType ns3::PacketSocket::GetSocketType() const [member function]
cls.add_method('GetSocketType',
'ns3::Socket::SocketType',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetTxAvailable() const [member function]
cls.add_method('GetTxAvailable',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Listen() [member function]
cls.add_method('Listen',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::Recv(uint32_t maxSize, uint32_t flags) [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags')],
is_virtual=True)
## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function]
cls.add_method('SendTo',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')],
is_virtual=True)
## packet-socket.h (module 'network'): bool ns3::PacketSocket::SetAllowBroadcast(bool allowBroadcast) [member function]
cls.add_method('SetAllowBroadcast',
'bool',
[param('bool', 'allowBroadcast')],
is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocket::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownRecv() [member function]
cls.add_method('ShutdownRecv',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownSend() [member function]
cls.add_method('ShutdownSend',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocket::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSocketClient_methods(root_module, cls):
## packet-socket-client.h (module 'network'): ns3::PacketSocketClient::PacketSocketClient(ns3::PacketSocketClient const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketClient const &', 'arg0')])
## packet-socket-client.h (module 'network'): ns3::PacketSocketClient::PacketSocketClient() [constructor]
cls.add_constructor([])
## packet-socket-client.h (module 'network'): uint8_t ns3::PacketSocketClient::GetPriority() const [member function]
cls.add_method('GetPriority',
'uint8_t',
[],
is_const=True)
## packet-socket-client.h (module 'network'): static ns3::TypeId ns3::PacketSocketClient::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::SetRemote(ns3::PacketSocketAddress addr) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::PacketSocketAddress', 'addr')])
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSocketFactory_methods(root_module, cls):
## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory(ns3::PacketSocketFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketFactory const &', 'arg0')])
## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory() [constructor]
cls.add_constructor([])
## packet-socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::PacketSocketFactory::CreateSocket() [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_virtual=True)
## packet-socket-factory.h (module 'network'): static ns3::TypeId ns3::PacketSocketFactory::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3PacketSocketServer_methods(root_module, cls):
## packet-socket-server.h (module 'network'): ns3::PacketSocketServer::PacketSocketServer(ns3::PacketSocketServer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketServer const &', 'arg0')])
## packet-socket-server.h (module 'network'): ns3::PacketSocketServer::PacketSocketServer() [constructor]
cls.add_constructor([])
## packet-socket-server.h (module 'network'): static ns3::TypeId ns3::PacketSocketServer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::SetLocal(ns3::PacketSocketAddress addr) [member function]
cls.add_method('SetLocal',
'void',
[param('ns3::PacketSocketAddress', 'addr')])
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3ParetoRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
deprecated=True, is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetScale() const [member function]
cls.add_method('GetScale',
'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 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::ParetoRandomVariable::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::ParetoRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3PbbAddressBlock_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock(ns3::PbbAddressBlock const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressBlock const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressBack() const [member function]
cls.add_method('AddressBack',
'ns3::Address',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() [member function]
cls.add_method('AddressBegin',
'std::_List_iterator< ns3::Address >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() const [member function]
cls.add_method('AddressBegin',
'std::_List_const_iterator< ns3::Address >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressClear() [member function]
cls.add_method('AddressClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::AddressEmpty() const [member function]
cls.add_method('AddressEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() [member function]
cls.add_method('AddressEnd',
'std::_List_iterator< ns3::Address >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() const [member function]
cls.add_method('AddressEnd',
'std::_List_const_iterator< ns3::Address >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> position) [member function]
cls.add_method('AddressErase',
'std::_List_iterator< ns3::Address >',
[param('std::_List_iterator< ns3::Address >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> first, std::_List_iterator<ns3::Address> last) [member function]
cls.add_method('AddressErase',
'std::_List_iterator< ns3::Address >',
[param('std::_List_iterator< ns3::Address >', 'first'), param('std::_List_iterator< ns3::Address >', 'last')])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressFront() const [member function]
cls.add_method('AddressFront',
'ns3::Address',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressInsert(std::_List_iterator<ns3::Address> position, ns3::Address const value) [member function]
cls.add_method('AddressInsert',
'std::_List_iterator< ns3::Address >',
[param('std::_List_iterator< ns3::Address >', 'position'), param('ns3::Address const', 'value')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopBack() [member function]
cls.add_method('AddressPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopFront() [member function]
cls.add_method('AddressPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushBack(ns3::Address address) [member function]
cls.add_method('AddressPushBack',
'void',
[param('ns3::Address', 'address')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushFront(ns3::Address address) [member function]
cls.add_method('AddressPushFront',
'void',
[param('ns3::Address', 'address')])
## packetbb.h (module 'network'): int ns3::PbbAddressBlock::AddressSize() const [member function]
cls.add_method('AddressSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): uint32_t ns3::PbbAddressBlock::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixBack() const [member function]
cls.add_method('PrefixBack',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() [member function]
cls.add_method('PrefixBegin',
'std::_List_iterator< unsigned char >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() const [member function]
cls.add_method('PrefixBegin',
'std::_List_const_iterator< unsigned char >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixClear() [member function]
cls.add_method('PrefixClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::PrefixEmpty() const [member function]
cls.add_method('PrefixEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() [member function]
cls.add_method('PrefixEnd',
'std::_List_iterator< unsigned char >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() const [member function]
cls.add_method('PrefixEnd',
'std::_List_const_iterator< unsigned char >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> position) [member function]
cls.add_method('PrefixErase',
'std::_List_iterator< unsigned char >',
[param('std::_List_iterator< unsigned char >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> first, std::_List_iterator<unsigned char> last) [member function]
cls.add_method('PrefixErase',
'std::_List_iterator< unsigned char >',
[param('std::_List_iterator< unsigned char >', 'first'), param('std::_List_iterator< unsigned char >', 'last')])
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixFront() const [member function]
cls.add_method('PrefixFront',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixInsert(std::_List_iterator<unsigned char> position, uint8_t const value) [member function]
cls.add_method('PrefixInsert',
'std::_List_iterator< unsigned char >',
[param('std::_List_iterator< unsigned char >', 'position'), param('uint8_t const', 'value')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopBack() [member function]
cls.add_method('PrefixPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopFront() [member function]
cls.add_method('PrefixPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushBack(uint8_t prefix) [member function]
cls.add_method('PrefixPushBack',
'void',
[param('uint8_t', 'prefix')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushFront(uint8_t prefix) [member function]
cls.add_method('PrefixPushFront',
'void',
[param('uint8_t', 'prefix')])
## packetbb.h (module 'network'): int ns3::PbbAddressBlock::PrefixSize() const [member function]
cls.add_method('PrefixSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvBack() [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbAddressTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvBack() const [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbAddressTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() [member function]
cls.add_method('TlvBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() const [member function]
cls.add_method('TlvBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvClear() [member function]
cls.add_method('TlvClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::TlvEmpty() const [member function]
cls.add_method('TlvEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() [member function]
cls.add_method('TlvEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() const [member function]
cls.add_method('TlvEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvFront() [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbAddressTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvFront() const [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbAddressTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvInsert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbTlv> const value) [member function]
cls.add_method('TlvInsert',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'value')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopBack() [member function]
cls.add_method('TlvPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopFront() [member function]
cls.add_method('TlvPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushBack(ns3::Ptr<ns3::PbbAddressTlv> address) [member function]
cls.add_method('TlvPushBack',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushFront(ns3::Ptr<ns3::PbbAddressTlv> address) [member function]
cls.add_method('TlvPushFront',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')])
## packetbb.h (module 'network'): int ns3::PbbAddressBlock::TlvSize() const [member function]
cls.add_method('TlvSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::DeserializeAddress(uint8_t * buffer) const [member function]
cls.add_method('DeserializeAddress',
'ns3::Address',
[param('uint8_t *', 'buffer')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'uint8_t',
[],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('PrintAddress',
'void',
[param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('SerializeAddress',
'void',
[param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbAddressBlockIpv4_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4(ns3::PbbAddressBlockIpv4 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressBlockIpv4 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv4::DeserializeAddress(uint8_t * buffer) const [member function]
cls.add_method('DeserializeAddress',
'ns3::Address',
[param('uint8_t *', 'buffer')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv4::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'uint8_t',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('PrintAddress',
'void',
[param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('SerializeAddress',
'void',
[param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbAddressBlockIpv6_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6(ns3::PbbAddressBlockIpv6 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressBlockIpv6 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv6::DeserializeAddress(uint8_t * buffer) const [member function]
cls.add_method('DeserializeAddress',
'ns3::Address',
[param('uint8_t *', 'buffer')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv6::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'uint8_t',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('PrintAddress',
'void',
[param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('SerializeAddress',
'void',
[param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbMessage_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage(ns3::PbbMessage const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbMessage const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockBack() [member function]
cls.add_method('AddressBlockBack',
'ns3::Ptr< ns3::PbbAddressBlock >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockBack() const [member function]
cls.add_method('AddressBlockBack',
'ns3::Ptr< ns3::PbbAddressBlock > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() [member function]
cls.add_method('AddressBlockBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() const [member function]
cls.add_method('AddressBlockBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockClear() [member function]
cls.add_method('AddressBlockClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbMessage::AddressBlockEmpty() const [member function]
cls.add_method('AddressBlockEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() [member function]
cls.add_method('AddressBlockEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() const [member function]
cls.add_method('AddressBlockEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > position) [member function]
cls.add_method('AddressBlockErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > last) [member function]
cls.add_method('AddressBlockErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockFront() [member function]
cls.add_method('AddressBlockFront',
'ns3::Ptr< ns3::PbbAddressBlock >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockFront() const [member function]
cls.add_method('AddressBlockFront',
'ns3::Ptr< ns3::PbbAddressBlock > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopBack() [member function]
cls.add_method('AddressBlockPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopFront() [member function]
cls.add_method('AddressBlockPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushBack(ns3::Ptr<ns3::PbbAddressBlock> block) [member function]
cls.add_method('AddressBlockPushBack',
'void',
[param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')])
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushFront(ns3::Ptr<ns3::PbbAddressBlock> block) [member function]
cls.add_method('AddressBlockPushFront',
'void',
[param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')])
## packetbb.h (module 'network'): int ns3::PbbMessage::AddressBlockSize() const [member function]
cls.add_method('AddressBlockSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): static ns3::Ptr<ns3::PbbMessage> ns3::PbbMessage::DeserializeMessage(ns3::Buffer::Iterator & start) [member function]
cls.add_method('DeserializeMessage',
'ns3::Ptr< ns3::PbbMessage >',
[param('ns3::Buffer::Iterator &', 'start')],
is_static=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopCount() const [member function]
cls.add_method('GetHopCount',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopLimit() const [member function]
cls.add_method('GetHopLimit',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::GetOriginatorAddress() const [member function]
cls.add_method('GetOriginatorAddress',
'ns3::Address',
[],
is_const=True)
## packetbb.h (module 'network'): uint16_t ns3::PbbMessage::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbMessage::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopCount() const [member function]
cls.add_method('HasHopCount',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopLimit() const [member function]
cls.add_method('HasHopLimit',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasOriginatorAddress() const [member function]
cls.add_method('HasOriginatorAddress',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasSequenceNumber() const [member function]
cls.add_method('HasSequenceNumber',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopCount(uint8_t hopcount) [member function]
cls.add_method('SetHopCount',
'void',
[param('uint8_t', 'hopcount')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopLimit(uint8_t hoplimit) [member function]
cls.add_method('SetHopLimit',
'void',
[param('uint8_t', 'hoplimit')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetOriginatorAddress(ns3::Address address) [member function]
cls.add_method('SetOriginatorAddress',
'void',
[param('ns3::Address', 'address')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetSequenceNumber(uint16_t seqnum) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'seqnum')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvBack() [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvBack() const [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() [member function]
cls.add_method('TlvBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() const [member function]
cls.add_method('TlvBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvClear() [member function]
cls.add_method('TlvClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbMessage::TlvEmpty() const [member function]
cls.add_method('TlvEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() [member function]
cls.add_method('TlvEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() const [member function]
cls.add_method('TlvEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvFront() [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvFront() const [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopBack() [member function]
cls.add_method('TlvPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopFront() [member function]
cls.add_method('TlvPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushBack',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushFront',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): int ns3::PbbMessage::TlvSize() const [member function]
cls.add_method('TlvSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('AddressBlockDeserialize',
'ns3::Ptr< ns3::PbbAddressBlock >',
[param('ns3::Buffer::Iterator &', 'start')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('DeserializeOriginatorAddress',
'ns3::Address',
[param('ns3::Buffer::Iterator &', 'start')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessage::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'ns3::PbbAddressLength',
[],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::PrintOriginatorAddress(std::ostream & os) const [member function]
cls.add_method('PrintOriginatorAddress',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('SerializeOriginatorAddress',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbMessageIpv4_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4(ns3::PbbMessageIpv4 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbMessageIpv4 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv4::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('AddressBlockDeserialize',
'ns3::Ptr< ns3::PbbAddressBlock >',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv4::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('DeserializeOriginatorAddress',
'ns3::Address',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv4::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'ns3::PbbAddressLength',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::PrintOriginatorAddress(std::ostream & os) const [member function]
cls.add_method('PrintOriginatorAddress',
'void',
[param('std::ostream &', 'os')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('SerializeOriginatorAddress',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbMessageIpv6_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6(ns3::PbbMessageIpv6 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbMessageIpv6 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv6::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('AddressBlockDeserialize',
'ns3::Ptr< ns3::PbbAddressBlock >',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv6::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('DeserializeOriginatorAddress',
'ns3::Address',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv6::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'ns3::PbbAddressLength',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::PrintOriginatorAddress(std::ostream & os) const [member function]
cls.add_method('PrintOriginatorAddress',
'void',
[param('std::ostream &', 'os')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('SerializeOriginatorAddress',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbPacket_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket(ns3::PbbPacket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbPacket const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > first, std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'last')])
## packetbb.h (module 'network'): ns3::TypeId ns3::PbbPacket::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): uint16_t ns3::PbbPacket::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): static ns3::TypeId ns3::PbbPacket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbPacket::GetVersion() const [member function]
cls.add_method('GetVersion',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbPacket::HasSequenceNumber() const [member function]
cls.add_method('HasSequenceNumber',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageBack() [member function]
cls.add_method('MessageBack',
'ns3::Ptr< ns3::PbbMessage >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageBack() const [member function]
cls.add_method('MessageBack',
'ns3::Ptr< ns3::PbbMessage > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() [member function]
cls.add_method('MessageBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() const [member function]
cls.add_method('MessageBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::MessageClear() [member function]
cls.add_method('MessageClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbPacket::MessageEmpty() const [member function]
cls.add_method('MessageEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() [member function]
cls.add_method('MessageEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() const [member function]
cls.add_method('MessageEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageFront() [member function]
cls.add_method('MessageFront',
'ns3::Ptr< ns3::PbbMessage >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageFront() const [member function]
cls.add_method('MessageFront',
'ns3::Ptr< ns3::PbbMessage > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopBack() [member function]
cls.add_method('MessagePopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopFront() [member function]
cls.add_method('MessagePopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushBack(ns3::Ptr<ns3::PbbMessage> message) [member function]
cls.add_method('MessagePushBack',
'void',
[param('ns3::Ptr< ns3::PbbMessage >', 'message')])
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushFront(ns3::Ptr<ns3::PbbMessage> message) [member function]
cls.add_method('MessagePushFront',
'void',
[param('ns3::Ptr< ns3::PbbMessage >', 'message')])
## packetbb.h (module 'network'): int ns3::PbbPacket::MessageSize() const [member function]
cls.add_method('MessageSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::SetSequenceNumber(uint16_t number) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'number')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvBack() [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvBack() const [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() [member function]
cls.add_method('TlvBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() const [member function]
cls.add_method('TlvBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvClear() [member function]
cls.add_method('TlvClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbPacket::TlvEmpty() const [member function]
cls.add_method('TlvEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() [member function]
cls.add_method('TlvEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() const [member function]
cls.add_method('TlvEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvFront() [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvFront() const [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopBack() [member function]
cls.add_method('TlvPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopFront() [member function]
cls.add_method('TlvPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushBack',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushFront',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): int ns3::PbbPacket::TlvSize() const [member function]
cls.add_method('TlvSize',
'int',
[],
is_const=True)
return
def register_Ns3PbbTlv_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv(ns3::PbbTlv const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbTlv const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): void ns3::PbbTlv::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): uint32_t ns3::PbbTlv::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetTypeExt() const [member function]
cls.add_method('GetTypeExt',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Buffer ns3::PbbTlv::GetValue() const [member function]
cls.add_method('GetValue',
'ns3::Buffer',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasTypeExt() const [member function]
cls.add_method('HasTypeExt',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasValue() const [member function]
cls.add_method('HasValue',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
## packetbb.h (module 'network'): void ns3::PbbTlv::SetTypeExt(uint8_t type) [member function]
cls.add_method('SetTypeExt',
'void',
[param('uint8_t', 'type')])
## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(ns3::Buffer start) [member function]
cls.add_method('SetValue',
'void',
[param('ns3::Buffer', 'start')])
## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('SetValue',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStart() const [member function]
cls.add_method('GetIndexStart',
'uint8_t',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStop() const [member function]
cls.add_method('GetIndexStop',
'uint8_t',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStart() const [member function]
cls.add_method('HasIndexStart',
'bool',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStop() const [member function]
cls.add_method('HasIndexStop',
'bool',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): bool ns3::PbbTlv::IsMultivalue() const [member function]
cls.add_method('IsMultivalue',
'bool',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStart(uint8_t index) [member function]
cls.add_method('SetIndexStart',
'void',
[param('uint8_t', 'index')],
visibility='protected')
## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStop(uint8_t index) [member function]
cls.add_method('SetIndexStop',
'void',
[param('uint8_t', 'index')],
visibility='protected')
## packetbb.h (module 'network'): void ns3::PbbTlv::SetMultivalue(bool isMultivalue) [member function]
cls.add_method('SetMultivalue',
'void',
[param('bool', 'isMultivalue')],
visibility='protected')
return
def register_Ns3Probe_methods(root_module, cls):
## probe.h (module 'stats'): ns3::Probe::Probe(ns3::Probe const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Probe const &', 'arg0')])
## probe.h (module 'stats'): ns3::Probe::Probe() [constructor]
cls.add_constructor([])
## probe.h (module 'stats'): bool ns3::Probe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function]
cls.add_method('ConnectByObject',
'bool',
[param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')],
is_pure_virtual=True, is_virtual=True)
## probe.h (module 'stats'): void ns3::Probe::ConnectByPath(std::string path) [member function]
cls.add_method('ConnectByPath',
'void',
[param('std::string', 'path')],
is_pure_virtual=True, is_virtual=True)
## probe.h (module 'stats'): static ns3::TypeId ns3::Probe::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## probe.h (module 'stats'): bool ns3::Probe::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3Queue__Ns3Packet_methods(root_module, cls):
## queue.h (module 'network'): ns3::Queue<ns3::Packet>::Queue(ns3::Queue<ns3::Packet> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Queue< ns3::Packet > const &', 'arg0')])
## queue.h (module 'network'): ns3::Queue<ns3::Packet>::Queue() [constructor]
cls.add_constructor([])
## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::Dequeue() [member function]
cls.add_method('Dequeue',
'ns3::Ptr< ns3::Packet >',
[],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): bool ns3::Queue<ns3::Packet>::Enqueue(ns3::Ptr<ns3::Packet> item) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'item')],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): void ns3::Queue<ns3::Packet>::Flush() [member function]
cls.add_method('Flush',
'void',
[])
## queue.h (module 'network'): static ns3::TypeId ns3::Queue<ns3::Packet>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## queue.h (module 'network'): ns3::Ptr<ns3::Packet const> ns3::Queue<ns3::Packet>::Peek() const [member function]
cls.add_method('Peek',
'ns3::Ptr< ns3::Packet const >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::Remove() [member function]
cls.add_method('Remove',
'ns3::Ptr< ns3::Packet >',
[],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::DoDequeue(std::_List_const_iterator<ns3::Ptr<ns3::Packet> > pos) [member function]
cls.add_method('DoDequeue',
'ns3::Ptr< ns3::Packet >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', 'pos')],
visibility='protected')
## queue.h (module 'network'): bool ns3::Queue<ns3::Packet>::DoEnqueue(std::_List_const_iterator<ns3::Ptr<ns3::Packet> > pos, ns3::Ptr<ns3::Packet> item) [member function]
cls.add_method('DoEnqueue',
'bool',
[param('std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', 'pos'), param('ns3::Ptr< ns3::Packet >', 'item')],
visibility='protected')
## queue.h (module 'network'): ns3::Ptr<ns3::Packet const> ns3::Queue<ns3::Packet>::DoPeek(std::_List_const_iterator<ns3::Ptr<ns3::Packet> > pos) const [member function]
cls.add_method('DoPeek',
'ns3::Ptr< ns3::Packet const >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', 'pos')],
is_const=True, visibility='protected')
## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue<ns3::Packet>::DoRemove(std::_List_const_iterator<ns3::Ptr<ns3::Packet> > pos) [member function]
cls.add_method('DoRemove',
'ns3::Ptr< ns3::Packet >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::Packet > >', 'pos')],
visibility='protected')
## queue.h (module 'network'): void ns3::Queue<ns3::Packet>::DropAfterDequeue(ns3::Ptr<ns3::Packet> item) [member function]
cls.add_method('DropAfterDequeue',
'void',
[param('ns3::Ptr< ns3::Packet >', 'item')],
visibility='protected')
## queue.h (module 'network'): void ns3::Queue<ns3::Packet>::DropBeforeEnqueue(ns3::Ptr<ns3::Packet> item) [member function]
cls.add_method('DropBeforeEnqueue',
'void',
[param('ns3::Ptr< ns3::Packet >', 'item')],
visibility='protected')
## queue.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::Queue<ns3::Packet>::Head() const [member function]
cls.add_method('Head',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True, visibility='protected')
## queue.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::Queue<ns3::Packet>::Tail() const [member function]
cls.add_method('Tail',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True, visibility='protected')
return
def register_Ns3Queue__Ns3QueueDiscItem_methods(root_module, cls):
## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem>::Queue(ns3::Queue<ns3::QueueDiscItem> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Queue< ns3::QueueDiscItem > const &', 'arg0')])
## queue.h (module 'network'): ns3::Queue<ns3::QueueDiscItem>::Queue() [constructor]
cls.add_constructor([])
## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::Dequeue() [member function]
cls.add_method('Dequeue',
'ns3::Ptr< ns3::QueueDiscItem >',
[],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): bool ns3::Queue<ns3::QueueDiscItem>::Enqueue(ns3::Ptr<ns3::QueueDiscItem> item) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::QueueDiscItem >', 'item')],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): void ns3::Queue<ns3::QueueDiscItem>::Flush() [member function]
cls.add_method('Flush',
'void',
[])
## queue.h (module 'network'): static ns3::TypeId ns3::Queue<ns3::QueueDiscItem>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## queue.h (module 'network'): ns3::Ptr<const ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::Peek() const [member function]
cls.add_method('Peek',
'ns3::Ptr< ns3::QueueDiscItem const >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::Remove() [member function]
cls.add_method('Remove',
'ns3::Ptr< ns3::QueueDiscItem >',
[],
is_pure_virtual=True, is_virtual=True)
## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::DoDequeue(std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > pos) [member function]
cls.add_method('DoDequeue',
'ns3::Ptr< ns3::QueueDiscItem >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >', 'pos')],
visibility='protected')
## queue.h (module 'network'): bool ns3::Queue<ns3::QueueDiscItem>::DoEnqueue(std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > pos, ns3::Ptr<ns3::QueueDiscItem> item) [member function]
cls.add_method('DoEnqueue',
'bool',
[param('std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >', 'pos'), param('ns3::Ptr< ns3::QueueDiscItem >', 'item')],
visibility='protected')
## queue.h (module 'network'): ns3::Ptr<const ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::DoPeek(std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > pos) const [member function]
cls.add_method('DoPeek',
'ns3::Ptr< ns3::QueueDiscItem const >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >', 'pos')],
is_const=True, visibility='protected')
## queue.h (module 'network'): ns3::Ptr<ns3::QueueDiscItem> ns3::Queue<ns3::QueueDiscItem>::DoRemove(std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > pos) [member function]
cls.add_method('DoRemove',
'ns3::Ptr< ns3::QueueDiscItem >',
[param('std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >', 'pos')],
visibility='protected')
## queue.h (module 'network'): void ns3::Queue<ns3::QueueDiscItem>::DropAfterDequeue(ns3::Ptr<ns3::QueueDiscItem> item) [member function]
cls.add_method('DropAfterDequeue',
'void',
[param('ns3::Ptr< ns3::QueueDiscItem >', 'item')],
visibility='protected')
## queue.h (module 'network'): void ns3::Queue<ns3::QueueDiscItem>::DropBeforeEnqueue(ns3::Ptr<ns3::QueueDiscItem> item) [member function]
cls.add_method('DropBeforeEnqueue',
'void',
[param('ns3::Ptr< ns3::QueueDiscItem >', 'item')],
visibility='protected')
## queue.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > ns3::Queue<ns3::QueueDiscItem>::Head() const [member function]
cls.add_method('Head',
'std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >',
[],
is_const=True, visibility='protected')
## queue.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::QueueDiscItem> > ns3::Queue<ns3::QueueDiscItem>::Tail() const [member function]
cls.add_method('Tail',
'std::_List_const_iterator< ns3::Ptr< ns3::QueueDiscItem > >',
[],
is_const=True, visibility='protected')
return
def register_Ns3QueueItem_methods(root_module, cls):
cls.add_output_stream_operator()
## queue-item.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')])
## queue-item.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function]
cls.add_method('GetPacket',
'ns3::Ptr< ns3::Packet >',
[],
is_const=True)
## queue-item.h (module 'network'): uint32_t ns3::QueueItem::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## queue-item.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)
## queue-item.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_Ns3RateErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel(ns3::RateErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RateErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): int64_t ns3::RateErrorModel::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## error-model.h (module 'network'): double ns3::RateErrorModel::GetRate() const [member function]
cls.add_method('GetRate',
'double',
[],
is_const=True)
## error-model.h (module 'network'): static ns3::TypeId ns3::RateErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit ns3::RateErrorModel::GetUnit() const [member function]
cls.add_method('GetUnit',
'ns3::RateErrorModel::ErrorUnit',
[],
is_const=True)
## error-model.h (module 'network'): void ns3::RateErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> arg0) [member function]
cls.add_method('SetRandomVariable',
'void',
[param('ns3::Ptr< ns3::RandomVariableStream >', 'arg0')])
## error-model.h (module 'network'): void ns3::RateErrorModel::SetRate(double rate) [member function]
cls.add_method('SetRate',
'void',
[param('double', 'rate')])
## error-model.h (module 'network'): void ns3::RateErrorModel::SetUnit(ns3::RateErrorModel::ErrorUnit error_unit) [member function]
cls.add_method('SetUnit',
'void',
[param('ns3::RateErrorModel::ErrorUnit', 'error_unit')])
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptBit(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorruptBit',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptByte(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorruptByte',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptPkt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorruptPkt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::RateErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3ReceiveListErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel(ns3::ReceiveListErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ReceiveListErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ReceiveListErrorModel::GetList() const [member function]
cls.add_method('GetList',
'std::list< unsigned int >',
[],
is_const=True)
## error-model.h (module 'network'): static ns3::TypeId ns3::ReceiveListErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function]
cls.add_method('SetList',
'void',
[param('std::list< unsigned int > const &', 'packetlist')])
## error-model.h (module 'network'): bool ns3::ReceiveListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3SimpleChannel_methods(root_module, cls):
## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel(ns3::SimpleChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimpleChannel const &', 'arg0')])
## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel() [constructor]
cls.add_constructor([])
## simple-channel.h (module 'network'): void ns3::SimpleChannel::Add(ns3::Ptr<ns3::SimpleNetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'device')],
is_virtual=True)
## simple-channel.h (module 'network'): void ns3::SimpleChannel::BlackList(ns3::Ptr<ns3::SimpleNetDevice> from, ns3::Ptr<ns3::SimpleNetDevice> to) [member function]
cls.add_method('BlackList',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'to')],
is_virtual=True)
## simple-channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::SimpleChannel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## simple-channel.h (module 'network'): uint32_t ns3::SimpleChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## simple-channel.h (module 'network'): static ns3::TypeId ns3::SimpleChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## simple-channel.h (module 'network'): void ns3::SimpleChannel::Send(ns3::Ptr<ns3::Packet> p, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from, ns3::Ptr<ns3::SimpleNetDevice> sender) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'sender')],
is_virtual=True)
## simple-channel.h (module 'network'): void ns3::SimpleChannel::UnBlackList(ns3::Ptr<ns3::SimpleNetDevice> from, ns3::Ptr<ns3::SimpleNetDevice> to) [member function]
cls.add_method('UnBlackList',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'to')],
is_virtual=True)
return
def register_Ns3SimpleNetDevice_methods(root_module, cls):
## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice(ns3::SimpleNetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimpleNetDevice const &', 'arg0')])
## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice() [constructor]
cls.add_constructor([])
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::SimpleNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): uint32_t ns3::SimpleNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): uint16_t ns3::SimpleNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::SimpleNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Queue<ns3::Packet> > ns3::SimpleNetDevice::GetQueue() const [member function]
cls.add_method('GetQueue',
'ns3::Ptr< ns3::Queue< ns3::Packet > >',
[],
is_const=True)
## simple-net-device.h (module 'network'): static ns3::TypeId ns3::SimpleNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::Receive(ns3::Ptr<ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')])
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetChannel(ns3::Ptr<ns3::SimpleChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::SimpleChannel >', 'channel')])
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetQueue(ns3::Ptr<ns3::Queue<ns3::Packet> > queue) [member function]
cls.add_method('SetQueue',
'void',
[param('ns3::Ptr< ns3::Queue< ns3::Packet > >', 'queue')])
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetReceiveErrorModel(ns3::Ptr<ns3::ErrorModel> em) [member function]
cls.add_method('SetReceiveErrorModel',
'void',
[param('ns3::Ptr< ns3::ErrorModel >', 'em')])
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', 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_Ns3UintegerValue_methods(root_module, cls):
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor]
cls.add_constructor([])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor]
cls.add_constructor([param('uint64_t const &', 'value')])
## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): bool ns3::UintegerValue::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)
## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function]
cls.add_method('Get',
'uint64_t',
[],
is_const=True)
## uinteger.h (module 'core'): std::string ns3::UintegerValue::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)
## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('uint64_t 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_Ns3BinaryErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::BinaryErrorModel::BinaryErrorModel(ns3::BinaryErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BinaryErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::BinaryErrorModel::BinaryErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): static ns3::TypeId ns3::BinaryErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): bool ns3::BinaryErrorModel::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::BinaryErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
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_Ns3CounterCalculator__Unsigned_int_methods(root_module, cls):
## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int>::CounterCalculator(ns3::CounterCalculator<unsigned int> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CounterCalculator< unsigned int > const &', 'arg0')])
## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int>::CounterCalculator() [constructor]
cls.add_constructor([])
## basic-data-calculators.h (module 'stats'): unsigned int ns3::CounterCalculator<unsigned int>::GetCount() const [member function]
cls.add_method('GetCount',
'unsigned int',
[],
is_const=True)
## basic-data-calculators.h (module 'stats'): static ns3::TypeId ns3::CounterCalculator<unsigned int>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Update() [member function]
cls.add_method('Update',
'void',
[])
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Update(unsigned int const i) [member function]
cls.add_method('Update',
'void',
[param('unsigned int const', 'i')])
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ErrorChannel_methods(root_module, cls):
## error-channel.h (module 'network'): ns3::ErrorChannel::ErrorChannel(ns3::ErrorChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ErrorChannel const &', 'arg0')])
## error-channel.h (module 'network'): ns3::ErrorChannel::ErrorChannel() [constructor]
cls.add_constructor([])
## error-channel.h (module 'network'): void ns3::ErrorChannel::Add(ns3::Ptr<ns3::SimpleNetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'device')],
is_virtual=True)
## error-channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::ErrorChannel::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)
## error-channel.h (module 'network'): uint32_t ns3::ErrorChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## error-channel.h (module 'network'): static ns3::TypeId ns3::ErrorChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-channel.h (module 'network'): void ns3::ErrorChannel::Send(ns3::Ptr<ns3::Packet> p, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from, ns3::Ptr<ns3::SimpleNetDevice> sender) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'sender')],
is_virtual=True)
## error-channel.h (module 'network'): void ns3::ErrorChannel::SetDuplicateMode(bool mode) [member function]
cls.add_method('SetDuplicateMode',
'void',
[param('bool', 'mode')])
## error-channel.h (module 'network'): void ns3::ErrorChannel::SetDuplicateTime(ns3::Time delay) [member function]
cls.add_method('SetDuplicateTime',
'void',
[param('ns3::Time', 'delay')])
## error-channel.h (module 'network'): void ns3::ErrorChannel::SetJumpingMode(bool mode) [member function]
cls.add_method('SetJumpingMode',
'void',
[param('bool', 'mode')])
## error-channel.h (module 'network'): void ns3::ErrorChannel::SetJumpingTime(ns3::Time delay) [member function]
cls.add_method('SetJumpingTime',
'void',
[param('ns3::Time', 'delay')])
return
def register_Ns3PacketCounterCalculator_methods(root_module, cls):
## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator::PacketCounterCalculator(ns3::PacketCounterCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketCounterCalculator const &', 'arg0')])
## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator::PacketCounterCalculator() [constructor]
cls.add_constructor([])
## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::FrameUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address realto) [member function]
cls.add_method('FrameUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'realto')])
## packet-data-calculators.h (module 'network'): static ns3::TypeId ns3::PacketCounterCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::PacketUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('PacketUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3PacketProbe_methods(root_module, cls):
## packet-probe.h (module 'network'): ns3::PacketProbe::PacketProbe(ns3::PacketProbe const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketProbe const &', 'arg0')])
## packet-probe.h (module 'network'): ns3::PacketProbe::PacketProbe() [constructor]
cls.add_constructor([])
## packet-probe.h (module 'network'): bool ns3::PacketProbe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function]
cls.add_method('ConnectByObject',
'bool',
[param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')],
is_virtual=True)
## packet-probe.h (module 'network'): void ns3::PacketProbe::ConnectByPath(std::string path) [member function]
cls.add_method('ConnectByPath',
'void',
[param('std::string', 'path')],
is_virtual=True)
## packet-probe.h (module 'network'): static ns3::TypeId ns3::PacketProbe::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-probe.h (module 'network'): void ns3::PacketProbe::SetValue(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('SetValue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet-probe.h (module 'network'): static void ns3::PacketProbe::SetValueByPath(std::string path, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('SetValueByPath',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')],
is_static=True)
return
def register_Ns3PbbAddressTlv_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv(ns3::PbbAddressTlv const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressTlv const &', 'arg0')])
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStart() const [member function]
cls.add_method('GetIndexStart',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStop() const [member function]
cls.add_method('GetIndexStop',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStart() const [member function]
cls.add_method('HasIndexStart',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStop() const [member function]
cls.add_method('HasIndexStop',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::IsMultivalue() const [member function]
cls.add_method('IsMultivalue',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStart(uint8_t index) [member function]
cls.add_method('SetIndexStart',
'void',
[param('uint8_t', 'index')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStop(uint8_t index) [member function]
cls.add_method('SetIndexStop',
'void',
[param('uint8_t', 'index')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetMultivalue(bool isMultivalue) [member function]
cls.add_method('SetMultivalue',
'void',
[param('bool', 'isMultivalue')])
return
def register_Ns3QueueDiscItem_methods(root_module, cls):
## queue-item.h (module 'network'): ns3::QueueDiscItem::QueueDiscItem(ns3::Ptr<ns3::Packet> p, ns3::Address const & addr, uint16_t protocol) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Address const &', 'addr'), param('uint16_t', 'protocol')])
## queue-item.h (module 'network'): ns3::Address ns3::QueueDiscItem::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True)
## queue-item.h (module 'network'): uint16_t ns3::QueueDiscItem::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint16_t',
[],
is_const=True)
## queue-item.h (module 'network'): uint8_t ns3::QueueDiscItem::GetTxQueueIndex() const [member function]
cls.add_method('GetTxQueueIndex',
'uint8_t',
[],
is_const=True)
## queue-item.h (module 'network'): void ns3::QueueDiscItem::SetTxQueueIndex(uint8_t txq) [member function]
cls.add_method('SetTxQueueIndex',
'void',
[param('uint8_t', 'txq')])
## queue-item.h (module 'network'): void ns3::QueueDiscItem::AddHeader() [member function]
cls.add_method('AddHeader',
'void',
[],
is_pure_virtual=True, is_virtual=True)
## queue-item.h (module 'network'): void ns3::QueueDiscItem::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## queue-item.h (module 'network'): bool ns3::QueueDiscItem::Mark() [member function]
cls.add_method('Mark',
'bool',
[],
is_pure_virtual=True, 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
## crc32.h (module 'network'): extern uint32_t ns3::CRC32Calculate(uint8_t const * data, int length) [free function]
module.add_function('CRC32Calculate',
'uint32_t',
[param('uint8_t const *', 'data'), param('int', 'length')])
## address.h (module 'network'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeAddressChecker() [free function]
module.add_function('MakeAddressChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## data-rate.h (module 'network'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeDataRateChecker() [free function]
module.add_function('MakeDataRateChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## ipv4-address.h (module 'network'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeIpv4AddressChecker() [free function]
module.add_function('MakeIpv4AddressChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## ipv4-address.h (module 'network'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeIpv4MaskChecker() [free function]
module.add_function('MakeIpv4MaskChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## ipv6-address.h (module 'network'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeIpv6AddressChecker() [free function]
module.add_function('MakeIpv6AddressChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## ipv6-address.h (module 'network'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeIpv6PrefixChecker() [free function]
module.add_function('MakeIpv6PrefixChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## mac16-address.h (module 'network'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeMac16AddressChecker() [free function]
module.add_function('MakeMac16AddressChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## mac48-address.h (module 'network'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeMac48AddressChecker() [free function]
module.add_function('MakeMac48AddressChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## mac64-address.h (module 'network'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeMac64AddressChecker() [free function]
module.add_function('MakeMac64AddressChecker',
'ns3::Ptr< ns3::AttributeChecker const >',
[])
## address-utils.h (module 'network'): extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Address & ad, uint32_t len) [free function]
module.add_function('ReadFrom',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Address &', 'ad'), param('uint32_t', 'len')])
## address-utils.h (module 'network'): extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Ipv4Address & ad) [free function]
module.add_function('ReadFrom',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv4Address &', 'ad')])
## address-utils.h (module 'network'): extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Ipv6Address & ad) [free function]
module.add_function('ReadFrom',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv6Address &', 'ad')])
## address-utils.h (module 'network'): extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Mac16Address & ad) [free function]
module.add_function('ReadFrom',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac16Address &', 'ad')])
## address-utils.h (module 'network'): extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Mac48Address & ad) [free function]
module.add_function('ReadFrom',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac48Address &', 'ad')])
## address-utils.h (module 'network'): extern void ns3::ReadFrom(ns3::Buffer::Iterator & i, ns3::Mac64Address & ad) [free function]
module.add_function('ReadFrom',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac64Address &', 'ad')])
## address-utils.h (module 'network'): extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Address const & ad) [free function]
module.add_function('WriteTo',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Address const &', 'ad')])
## address-utils.h (module 'network'): extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Ipv4Address ad) [free function]
module.add_function('WriteTo',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv4Address', 'ad')])
## address-utils.h (module 'network'): extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Ipv6Address ad) [free function]
module.add_function('WriteTo',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Ipv6Address', 'ad')])
## address-utils.h (module 'network'): extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Mac16Address ad) [free function]
module.add_function('WriteTo',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac16Address', 'ad')])
## address-utils.h (module 'network'): extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Mac48Address ad) [free function]
module.add_function('WriteTo',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac48Address', 'ad')])
## address-utils.h (module 'network'): extern void ns3::WriteTo(ns3::Buffer::Iterator & i, ns3::Mac64Address ad) [free function]
module.add_function('WriteTo',
'void',
[param('ns3::Buffer::Iterator &', 'i'), param('ns3::Mac64Address', 'ad')])
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)
register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module)
register_functions_ns3_internal(module.get_submodule('internal'), 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 register_functions_ns3_addressUtils(module, root_module):
## address-utils.h (module 'network'): extern bool ns3::addressUtils::IsMulticast(ns3::Address const & ad) [free function]
module.add_function('IsMulticast',
'bool',
[param('ns3::Address const &', 'ad')])
return
def register_functions_ns3_internal(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 | 5,879,978,282,618,899,000 | 61.915928 | 594 | 0.601395 | false |
google-research/falken | service/learner/brains/specs_test.py | 1 | 57941 | # Copyright 2021 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 specs."""
# pylint: disable=g-bad-import-order
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
from google.protobuf import text_format
import common.generate_protos # pylint: disable=unused-import
import action_pb2
import brain_pb2
import observation_pb2
import primitives_pb2
from learner.brains import specs
_OBSERVATION_SPEC = """
player {
position {}
rotation {}
entity_fields {
name: "panache"
number {
minimum: 0.0
maximum: 100.0
}
}
entity_fields {
name: "favorite_poison"
category {
enum_values: "GIN"
enum_values: "ABSINTH"
enum_values: "BATTERY_ACID"
}
}
entity_fields {
name: "feeler"
feeler {
count: 3
distance {
minimum: 0.0
maximum: 100.0
}
yaw_angles: [-10.0, 0, 10.0]
experimental_data: {
minimum: 0.0
maximum: 100.0
}
}
}
}
camera {
position {}
rotation {}
}
global_entities {
rotation { }
entity_fields {
name: "pizzazz"
number {
minimum: 0.0
maximum: 100.0
}
}
}
global_entities {
entity_fields {
name: "chutzpah"
number {
minimum: 0.0
maximum: 100.0
}
}
}
"""
_OBSERVATION_DATA = """
player {
position {
x: 0
y: 10
z: 20
}
rotation {
w: 1
}
entity_fields {
number {
value: 60.0
}
}
entity_fields {
category {
value: 1
}
}
entity_fields {
feeler {
measurements: {
distance {
value: 1.0
}
experimental_data: {
value: 1.1
}
}
measurements: {
distance {
value: 2.0
}
experimental_data: {
value: 2.1
}
}
measurements: {
distance {
value: 3.0
}
experimental_data: {
value: 3.1
}
}
}
}
}
camera {
position {
x: 10
y: 10
z: 10
}
rotation {
w: 1
}
}
global_entities {
rotation {
x: 0
y: 0
z: 0
w: 1
}
entity_fields {
number {
value: 64
}
}
}
global_entities {
entity_fields {
number {
value: 34
}
}
}
"""
_ACTION_SPEC = """
actions {
name: "what_do"
category {
enum_values: "STAY"
enum_values: "GO"
}
}
actions {
name: "trouble"
number {
minimum: 1000
maximum: 2000
}
}
actions {
name: "left_stick"
joystick {
axes_mode: DIRECTION_XZ
controlled_entity: "player"
control_frame: "player"
}
}
actions {
name: "right_stick"
joystick {
axes_mode: DELTA_PITCH_YAW
controlled_entity: "camera"
}
}
"""
_ACTION_DATA = """
source: 2
actions {
category {
value: 1
}
}
actions {
number {
value: 1500
}
}
actions {
joystick {
x_axis: 0
y_axis: 1
}
}
actions {
joystick {
x_axis: -1
y_axis: 0
}
}
"""
class ProtobufValidatorTest(parameterized.TestCase):
"""Test ProtobufValidator."""
def test_check_category_type_valid(self):
"""Check a valid CategoryType proto."""
spec = primitives_pb2.CategoryType()
spec.enum_values.append('gin')
spec.enum_values.append('tonic')
specs.ProtobufValidator.check_spec(spec, 'observations/player/drink')
@parameterized.named_parameters(('EmptyCategory', []),
('SingleCategory', ['gin']))
def test_check_category_type_not_enough_categories(self, categories):
"""Ensure validation fails with not enough categories."""
spec = primitives_pb2.CategoryType()
spec.enum_values.extend(categories)
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'observations/player/drink has less than two categories: '
f'{categories}.'):
specs.ProtobufValidator.check_spec(spec, 'observations/player/drink')
def test_check_number_type_valid(self):
"""Check a valid NumberType proto."""
spec = primitives_pb2.NumberType()
spec.minimum = 1
spec.maximum = 42
specs.ProtobufValidator.check_spec(spec, 'observations/player/health')
@parameterized.named_parameters(
('ReservedNamePosition', 1.0, 1.0),
('ReservedNameRotation', -1.0, 1.0))
def test_check_number_type_invalid_range(self, maximum, minimum):
"""Ensure validation fails with an invalid number range."""
spec = primitives_pb2.NumberType()
spec.minimum = minimum
spec.maximum = maximum
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'observations/player/health has invalid or missing range: '
f'[{minimum}, {maximum}].'):
specs.ProtobufValidator.check_spec(spec, 'observations/player/health')
def test_check_number_type_no_range(self):
spec = primitives_pb2.NumberType()
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'observations/player/health has invalid or missing range: [0.0, 0.0].'):
specs.ProtobufValidator.check_spec(spec, 'observations/player/health')
def test_check_feeler_type_valid(self):
"""Check valid FeelerType proto."""
spec = observation_pb2.FeelerType()
spec.count = 2
spec.distance.minimum = 1
spec.distance.maximum = 5
spec.yaw_angles.extend([-2, 2])
data = spec.experimental_data.add()
data.minimum = 0
data.maximum = 9
specs.ProtobufValidator.check_spec(spec, 'observations/player/feeler')
def test_check_feeler_type_invalid_distance(self):
"""Ensure FeelerType validation fails with invalid distance range."""
spec = observation_pb2.FeelerType()
spec.count = 2
spec.distance.minimum = 2
spec.distance.maximum = 2
spec.yaw_angles.extend([-2, 2])
data = spec.experimental_data.add()
data.minimum = 0
data.maximum = 9
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'observations/player/feeler/distance has invalid or '
'missing range: [2.0, 2.0].'):
specs.ProtobufValidator.check_spec(spec, 'observations/player/feeler')
def test_check_feeler_type_invalid_experimental_data(self):
"""Ensure FeelerType validation fails with a invalid experimental data."""
spec = observation_pb2.FeelerType()
spec.count = 2
spec.distance.minimum = 1
spec.distance.maximum = 5
spec.yaw_angles.extend([-2, 2])
data = spec.experimental_data.add()
data.minimum = 4
data.maximum = 4
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'observations/player/feeler/experimental_data[0] has '
'invalid or missing range: [4.0, 4.0].'):
specs.ProtobufValidator.check_spec(spec, 'observations/player/feeler')
def test_check_feeler_type_mismatched_yaw_angles(self):
"""Ensure FeelerType validation fails with a invalid yaw angles."""
spec = observation_pb2.FeelerType()
spec.count = 2
spec.distance.minimum = 1
spec.distance.maximum = 5
spec.yaw_angles.extend([-2, 2, 3])
data = spec.experimental_data.add()
data.minimum = 0
data.maximum = 9
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'observations/player/feeler has 3 yaw_angles that '
'mismatch feeler count 2.'):
specs.ProtobufValidator.check_spec(spec, 'observations/player/feeler')
def test_check_joystick_type_valid(self):
"""Check valid JoystickType protos."""
spec = action_pb2.JoystickType()
spec.controlled_entity = 'player'
spec.axes_mode = action_pb2.DELTA_PITCH_YAW
specs.ProtobufValidator.check_spec(spec, 'actions/joystick')
spec = action_pb2.JoystickType()
spec.controlled_entity = 'player'
spec.control_frame = 'camera'
spec.axes_mode = action_pb2.DIRECTION_XZ
specs.ProtobufValidator.check_spec(spec, 'actions/joystick')
def test_check_joystick_type_no_axes_mode(self):
"""Ensure JoystickType validation fails with no joystick axes mode."""
spec = action_pb2.JoystickType()
spec.controlled_entity = 'player'
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError, 'actions/joystick has undefined axes_mode.'):
specs.ProtobufValidator.check_spec(spec, 'actions/joystick')
def test_check_joystick_type_no_entity(self):
"""Ensure JoystickType validation fails with no controlled entity."""
spec = action_pb2.JoystickType()
spec.axes_mode = action_pb2.DELTA_PITCH_YAW
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError, 'actions/joystick has no controlled_entity.'):
specs.ProtobufValidator.check_spec(spec, 'actions/joystick')
def test_check_joystick_type_invalid_control_frame(self):
"""Ensure JoystickType validation fails when no control frame is present."""
spec = action_pb2.JoystickType()
spec.controlled_entity = 'player'
spec.axes_mode = action_pb2.DELTA_PITCH_YAW
spec.control_frame = 'camera'
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'actions/joystick has invalid control frame "camera". '
'control_frame should only be set if axes_mode is '
'DIRECTION_XZ, axes_mode is currently DELTA_PITCH_YAW.'):
specs.ProtobufValidator.check_spec(spec, 'actions/joystick')
def test_check_entity_field_type_valid(self):
"""Check valid EntityFieldType proto."""
spec = observation_pb2.EntityFieldType()
spec.category.enum_values.extend(['foo', 'bar'])
specs.ProtobufValidator.check_spec(spec, 'observations/player')
spec = observation_pb2.EntityFieldType()
spec.number.minimum = 1
spec.number.maximum = 2
specs.ProtobufValidator.check_spec(spec, 'observations/player')
spec = observation_pb2.EntityFieldType()
spec.feeler.count = 1
specs.ProtobufValidator.check_spec(spec, 'observations/player')
def test_check_entity_field_type_no_type_set(self):
"""Ensure validation fails when EntityFieldType has no type."""
spec = observation_pb2.EntityFieldType()
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'observations/player type must have one of [category, number, '
'feeler] set.'):
specs.ProtobufValidator.check_spec(spec, 'observations/player')
def test_check_entity_type_valid(self):
"""Check valid EntityType proto."""
spec = observation_pb2.EntityType()
specs.ProtobufValidator.check_spec(spec, 'observations/0')
spec = observation_pb2.EntityType()
spec.entity_fields.add().name = 'gaze'
specs.ProtobufValidator.check_spec(spec, 'observations/0')
@parameterized.named_parameters(
('ReservedNamePosition', 'position'),
('ReservedNameRotation', 'rotation'))
def test_check_entity_type_reserved_name(self, name):
"""Ensure validation fails when a custom field has a reserved name."""
spec = observation_pb2.EntityType()
spec.entity_fields.add().name = name
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
f'observations/0/entity_field[0] has reserved name "{name}".'):
specs.ProtobufValidator.check_spec(spec, 'observations/0')
def test_check_entity_type_no_name(self):
"""Ensure validation fails when a custom field has no name."""
spec = observation_pb2.EntityType()
spec.entity_fields.add()
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError, 'observations/0/entity_field[0] has no name.'):
specs.ProtobufValidator.check_spec(spec, 'observations/0')
def test_check_entity_type_duplicate_name(self):
"""Ensure validation fails when a custom field has a duplicate name."""
spec = observation_pb2.EntityType()
spec.entity_fields.add().name = 'foo'
spec.entity_fields.add().name = 'foo'
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'observations/0/entity_field[1] has name "foo" that already exists in '
'observations/0'):
specs.ProtobufValidator.check_spec(spec, 'observations/0')
def test_check_action_type_valid(self):
"""Check valid ActionType proto."""
spec = action_pb2.ActionType()
spec.name = 'jump'
spec.category.enum_values.extend(['false', 'true'])
specs.ProtobufValidator.check_spec(spec, 'actions/jump')
def test_check_action_type_no_type_set(self):
"""Ensure validation fails when ActionType has no type."""
spec = action_pb2.ActionType()
spec.name = 'jump'
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError, 'actions/jump action_types must have one of '
'[category, number, joystick] set.'):
specs.ProtobufValidator.check_spec(spec, 'actions/jump')
def test_check_action_spec_valid(self):
"""Check valid ActionSpec proto."""
spec = action_pb2.ActionSpec()
spec.actions.add().name = 'jump'
specs.ProtobufValidator.check_spec(spec, 'actions')
def test_check_action_spec_empty(self):
spec = action_pb2.ActionSpec()
with self.assertRaisesWithLiteralMatch(specs.InvalidSpecError,
'actions is empty.'):
specs.ProtobufValidator.check_spec(spec, 'actions')
def test_check_action_spec_no_name(self):
"""Ensure validation fails when an ActionType field has no name."""
spec = action_pb2.ActionSpec()
spec.actions.add()
with self.assertRaisesWithLiteralMatch(specs.InvalidSpecError,
'actions/actions[0] has no name.'):
specs.ProtobufValidator.check_spec(spec, 'actions')
def test_check_action_spec_duplicate_name(self):
"""Ensure validation fails when an ActionType field has a duplicate name."""
spec = action_pb2.ActionSpec()
spec.actions.add().name = 'jump'
spec.actions.add().name = 'jump'
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'actions/actions[1] has duplicate name "jump".'):
specs.ProtobufValidator.check_spec(spec, 'actions')
def test_check_observation_spec_empty(self):
spec = observation_pb2.ObservationSpec()
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'observations must contain at least one non-camera entity.'):
specs.ProtobufValidator.check_spec(spec, 'observations')
def test_check_brain_spec_empty(self):
spec = brain_pb2.BrainSpec()
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'brain must have an observation spec and action spec.'):
specs.ProtobufValidator.check_spec(spec, 'brain')
def test_check_spec_unknown_proto(self):
"""Ensure spec validation fails when an unsupported proto is checked."""
spec = brain_pb2.Brain()
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError, 'Validator not found for Brain at "brain".'):
specs.ProtobufValidator.check_spec(spec, 'brain')
def test_check_unknown_proto(self):
"""Ensure data validation fails when an unsupported proto is checked."""
data = brain_pb2.Brain()
with self.assertRaisesWithLiteralMatch(
specs.TypingError, 'Validator not found for Brain at "brain".'):
specs.ProtobufValidator.check_data(data, brain_pb2.BrainSpec(), 'brain',
True)
def test_check_category(self):
"""Validate a category value that is in range."""
spec = primitives_pb2.CategoryType()
spec.enum_values.extend(['rose', 'lilly'])
data = primitives_pb2.Category()
data.value = 1
specs.ProtobufValidator.check_data(data, spec, 'observations/player/item',
True)
@parameterized.named_parameters(
('BelowRange', -1),
('AboveRange', 2))
def test_check_category_out_of_range(self, value):
"""Ensure validation fails when a category value is out of range."""
spec = primitives_pb2.CategoryType()
spec.enum_values.extend(['rose', 'lilly'])
data = primitives_pb2.Category()
data.value = value
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
f'observations/player/item category has value {value} '
f'that is out of the specified range [0, 1] (rose, lilly).'):
specs.ProtobufValidator.check_data(data, spec, 'observations/player/item',
True)
def test_check_number_valid(self):
"""Check a valid number."""
spec = primitives_pb2.NumberType()
spec.minimum = 2
spec.maximum = 9
data = primitives_pb2.Number()
data.value = 2
specs.ProtobufValidator.check_data(data, spec, 'observations/player/spirit',
True)
@parameterized.named_parameters(
('BelowRange', 1.0),
('AboveRange', 10.0))
def test_check_number_out_of_range(self, value):
"""Ensure validation fails with a number out of range."""
spec = primitives_pb2.NumberType()
spec.minimum = 2
spec.maximum = 9
data = primitives_pb2.Number()
data.value = value
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
f'observations/player/spirit number has value {value} '
'that is out of the specified range [2.0, 9.0].'):
specs.ProtobufValidator.check_data(data, spec,
'observations/player/spirit', True)
@staticmethod
def _create_feeler_spec_and_data():
"""Create a valid feeler spec and data.
Returns:
(spec, data) where spec is a FeelerType proto and data is a Feeler proto.
"""
spec = observation_pb2.FeelerType()
spec.count = 2
spec.distance.minimum = 0
spec.distance.maximum = 42
spec.yaw_angles.extend([-2, 2])
# Categorical value with 3 potential values, one-hot encoded.
number_of_categories = 3
for _ in range(0, number_of_categories):
experimental_data = spec.experimental_data.add()
experimental_data.minimum = 0
experimental_data.maximum = 1
data = observation_pb2.Feeler()
for distance_value, categorical_value in ((2, 0), (5, 2)):
measurement = data.measurements.add()
measurement.distance.value = distance_value
for category in range(0, number_of_categories):
experimental_data = measurement.experimental_data.add()
experimental_data.value = 1 if categorical_value == category else 0
return (spec, data)
def test_check_feeler(self):
"""Check a valid feeler."""
spec, data = ProtobufValidatorTest._create_feeler_spec_and_data()
specs.ProtobufValidator.check_data(data, spec, 'observations/player/feeler',
True)
def test_check_feeler_invalid_measurements(self):
"""Ensure feeler validation fails with a measurement count mismatch."""
spec, data = ProtobufValidatorTest._create_feeler_spec_and_data()
del data.measurements[1] # Remove the second feeler.
with self.assertRaisesWithLiteralMatch(
specs.TypingError, 'observations/player/feeler feeler has an invalid '
'number of measurements 1 vs. expected 2.'):
specs.ProtobufValidator.check_data(data, spec,
'observations/player/feeler', True)
def test_check_feeler_invalid_distance(self):
"""Ensure feeler validation fails with distance out of range."""
spec, data = ProtobufValidatorTest._create_feeler_spec_and_data()
data.measurements[1].distance.value = 43
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
'observations/player/feeler/measurements[1]/distance '
'number has value 43.0 that is out of the specified range '
'[0.0, 42.0].'):
specs.ProtobufValidator.check_data(data, spec,
'observations/player/feeler', True)
def test_check_feeler_invalid_experimental_data(self):
"""Ensure feeler validation fails with mismatched categorical data."""
spec, data = ProtobufValidatorTest._create_feeler_spec_and_data()
del data.measurements[0].experimental_data[2]
with self.assertRaisesWithLiteralMatch(
specs.TypingError, 'observations/player/feeler/measurements[0] '
'feeler contains 2 experimental_data vs. '
'expected 3 experimental_data.'):
specs.ProtobufValidator.check_data(data, spec,
'observations/player/feeler', True)
def test_check_feeler_experimental_data_out_of_range(self):
"""Ensure feeler validation fails with out of range categorical data."""
spec, data = ProtobufValidatorTest._create_feeler_spec_and_data()
data.measurements[0].experimental_data[1].value = 2
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
'observations/player/feeler/measurements[0]/experimental_data[1] '
'number has value 2.0 that is out of the specified range [0.0, 1.0].'):
specs.ProtobufValidator.check_data(data, spec,
'observations/player/feeler', True)
def test_check_entity_field_valid(self):
"""Check a valid EntityField."""
data = observation_pb2.EntityField()
data.category.value = 1
spec = observation_pb2.EntityFieldType()
spec.category.enum_values.extend(['false', 'true'])
specs.ProtobufValidator.check_data(data, spec,
'observations/player/shades_on', True)
def test_check_entity_field_mismatched_type(self):
"""Ensure validation fails for EntityField with a mismatched type."""
data = observation_pb2.EntityField()
data.number.value = 1
spec = observation_pb2.EntityFieldType()
spec.category.enum_values.extend(['false', 'true'])
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
'observations/player/shades_on/value entity field "number" does not '
'match the spec type "category".'):
specs.ProtobufValidator.check_data(data, spec,
'observations/player/shades_on', True)
@staticmethod
def _create_entity_spec_and_data():
"""Create a valid entity spec and data.
Returns:
(spec, data) where spec is an EntityType proto and data is an Entity
proto.
"""
data = observation_pb2.Entity()
data.position.CopyFrom(primitives_pb2.Position())
data.rotation.CopyFrom(primitives_pb2.Rotation())
data.entity_fields.add()
data.entity_fields.add()
spec = observation_pb2.EntityType()
spec.position.CopyFrom(primitives_pb2.PositionType())
spec.rotation.CopyFrom(primitives_pb2.RotationType())
spec.entity_fields.add()
spec.entity_fields.add()
return spec, data
def test_check_entity_valid(self):
"""Check a valid Entity."""
spec, data = ProtobufValidatorTest._create_entity_spec_and_data()
specs.ProtobufValidator.check_data(data, spec, 'observations/player', True)
def test_check_entity_optional_field_mismatch(self):
"""Ensure validation fails for Entity with mismatched optional fields."""
spec, data = ProtobufValidatorTest._create_entity_spec_and_data()
data.ClearField('position')
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
'observations/player entity does not have "position" but spec has '
'"position".'):
specs.ProtobufValidator.check_data(data, spec, 'observations/player',
True)
spec, data = ProtobufValidatorTest._create_entity_spec_and_data()
spec.ClearField('rotation')
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
'observations/player entity has "rotation" but spec does not have '
'"rotation".'):
specs.ProtobufValidator.check_data(data, spec, 'observations/player',
True)
def test_check_entity_field_mismatch(self):
"""Ensure validation fails for Entity with mismatched fields."""
spec, data = ProtobufValidatorTest._create_entity_spec_and_data()
del data.entity_fields[1]
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
'observations/player entity contains 1 entity_fields vs. '
'expected 2 entity_fields.'):
specs.ProtobufValidator.check_data(data, spec, 'observations/player',
True)
def test_check_action_valid(self):
"""Check a valid Action."""
data = action_pb2.Action()
data.category.value = 1
spec = action_pb2.ActionType()
spec.category.enum_values.extend(['foo', 'bar'])
specs.ProtobufValidator.check_data(data, spec, 'actions/shout', True)
def test_check_action_value_mismatched_type(self):
"""Ensure validation fails for Action with a mismatched type."""
data = action_pb2.Action()
data.number.value = 1
spec = action_pb2.ActionType()
spec.category.enum_values.extend(['foo', 'bar'])
with self.assertRaisesWithLiteralMatch(
specs.TypingError, 'actions/shout/action action "number" does not '
'match the spec action_types "category".'):
specs.ProtobufValidator.check_data(data, spec, 'actions/shout', True)
def test_check_action_data_valid(self):
"""Check a valid ActionData."""
data = action_pb2.ActionData(
source=action_pb2.ActionData.HUMAN_DEMONSTRATION)
data.actions.add()
spec = action_pb2.ActionSpec()
spec.actions.add()
specs.ProtobufValidator.check_data(data, spec, 'actions', True)
def test_check_action_data_no_source(self):
"""Check ActionData with no source."""
data = action_pb2.ActionData()
data.actions.add()
spec = action_pb2.ActionSpec()
spec.actions.add()
with self.assertRaisesWithLiteralMatch(
specs.TypingError, 'ActionData action data\'s source is unknown.'):
specs.ProtobufValidator.check_data(data, spec, 'ActionData', True)
def test_check_action_data_mismatched_actions(self):
"""Ensure validation fails when the number of actions mismatch."""
data = action_pb2.ActionData(
source=action_pb2.ActionData.HUMAN_DEMONSTRATION)
spec = action_pb2.ActionSpec()
spec.actions.add()
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
'ActionData actions contains 0 actions vs. expected 1 actions.'):
specs.ProtobufValidator.check_data(data, spec, 'ActionData', True)
@staticmethod
def _create_observation_spec_and_data():
"""Create a valid observation spec and data.
Returns:
(spec, data) where spec is an ObservationSpec proto and data is an
ObservationData proto.
"""
data = observation_pb2.ObservationData()
data.player.entity_fields.add()
data.global_entities.add()
spec = observation_pb2.ObservationSpec()
spec.player.entity_fields.add()
spec.global_entities.add()
return (spec, data)
def test_check_observation_valid(self):
"""Check a valid Observation."""
spec, data = ProtobufValidatorTest._create_observation_spec_and_data()
specs.ProtobufValidator.check_data(data, spec, 'observations', True)
def test_check_observation_mismatched_optional_entity(self):
"""Ensure Observation validation fails with a mismatched optional entity."""
spec, data = ProtobufValidatorTest._create_observation_spec_and_data()
data.camera.entity_fields.add()
with self.assertRaisesWithLiteralMatch(
specs.TypingError, 'observations entity has "camera" but spec does not '
'have "camera".'):
specs.ProtobufValidator.check_data(data, spec, 'observations', True)
def test_check_observation_mismatched_global_entities(self):
"""Ensure Observation validation fails with a mismatched global entities."""
spec, data = ProtobufValidatorTest._create_observation_spec_and_data()
data.global_entities.add()
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
'observations observations contains 2 global_entities '
'vs. expected 1 global_entities.',
):
specs.ProtobufValidator.check_data(data, spec, 'observations', True)
def test_check_joystick_valid(self):
"""Check a valid Joystick."""
data = action_pb2.Joystick()
data.x_axis = 0.707
data.y_axis = -0.707
specs.ProtobufValidator.check_data(data, action_pb2.JoystickType(),
'left_stick', True)
@parameterized.named_parameters(
('BelowRange', -2.0),
('AboveRange', 1.5))
def test_check_joystick_out_of_range(self, value):
"""Ensure Joystick validation fails with out of range values."""
data = action_pb2.Joystick()
data.x_axis = value
with self.assertRaisesWithLiteralMatch(
specs.TypingError,
f'left_stick joystick x_axis value {value} is out of '
'range [-1.0, 1.0].'):
specs.ProtobufValidator.check_data(data, action_pb2.JoystickType(),
'left_stick', True)
class ProtobufNodeTest(parameterized.TestCase):
"""Test specs.ProtobufNode."""
def test_construct(self):
"""Construct a ProtobufNode."""
spec = observation_pb2.ObservationSpec()
node = specs.ProtobufNode('foo', spec, 'fooey')
self.assertEqual(node.name, 'foo')
self.assertEqual(node.proto, spec)
self.assertEqual(node.proto_field_name, 'fooey')
self.assertCountEqual(node.children, [])
self.assertIsNone(node.parent)
def test_add_remove_children(self):
"""Test adding children to and removing children from a ProtobufNode."""
spec = observation_pb2.ObservationSpec()
# Add bish and bash as children of foo.
foo = specs.ProtobufNode('foo', spec, 'fee')
bish = specs.ProtobufNode('bish', spec, 'bishy')
bash = specs.ProtobufNode('bash', spec, 'bashy')
self.assertEqual(foo.add_children([bish, bash]), foo)
self.assertCountEqual(foo.children, [bish, bash])
self.assertEqual(foo.child_by_proto_field_name('bishy'), bish)
self.assertEqual(foo.child_by_proto_field_name('bashy'), bash)
self.assertEqual(bish.parent, foo)
self.assertEqual(bash.parent, foo)
# Add bosh to bar and move bash to bar.
bar = specs.ProtobufNode('bar', spec, 'bee')
bosh = specs.ProtobufNode('bosh', spec, 'boshy')
self.assertEqual(bar.add_children([bash, bosh]), bar)
self.assertCountEqual(bar.children, [bash, bosh])
self.assertCountEqual(foo.children, [bish])
self.assertEqual(bar.child_by_proto_field_name('boshy'), bosh)
self.assertEqual(foo.child_by_proto_field_name('bishy'), bish)
self.assertEqual(bash.parent, bar)
self.assertEqual(bosh.parent, bar)
self.assertEqual(bish.parent, foo)
# Remove bosh from bar.
bosh.remove_from_parent()
self.assertIsNone(bosh.parent)
self.assertCountEqual(bar.children, [bash])
def test_get_path(self):
"""Get the path of a node relative to the root of a tree."""
spec = observation_pb2.ObservationSpec()
foo = specs.ProtobufNode('foo', spec, '')
bar = specs.ProtobufNode('bar', spec, '')
foo.add_children([bar])
baz = specs.ProtobufNode('baz', spec, '')
bar.add_children([baz])
self.assertEqual(foo.path, 'foo')
self.assertEqual(bar.path, 'foo/bar')
self.assertEqual(baz.path, 'foo/bar/baz')
def test_infer_path_components_from_spec_with_name(self):
"""Test constructing path components from a proto with a name."""
spec = action_pb2.ActionType()
spec.name = 'throttle'
self.assertEqual(
('throttle', '', 'throttle'),
specs.ProtobufNode._infer_path_components_from_spec(spec, None, None))
self.assertEqual(
('throttle', 'actions', 'actions/throttle'),
specs.ProtobufNode._infer_path_components_from_spec(spec, None,
'actions'))
self.assertEqual(
('gas', 'actions', 'actions/gas'),
specs.ProtobufNode._infer_path_components_from_spec(spec, 'gas',
'actions'))
def test_infer_path_components_from_spec_no_name(self):
"""Test constructing path components from a proto without a name."""
spec = observation_pb2.ObservationSpec()
self.assertEqual(
('ObservationSpec', '', 'ObservationSpec'),
specs.ProtobufNode._infer_path_components_from_spec(spec, None, None))
self.assertEqual(
('ObservationSpec', 'brain', 'brain/ObservationSpec'),
specs.ProtobufNode._infer_path_components_from_spec(spec, None,
'brain'))
self.assertEqual(
('observations', 'brain', 'brain/observations'),
specs.ProtobufNode._infer_path_components_from_spec(
spec, 'observations', 'brain'))
@mock.patch.object(specs.ProtobufValidator, 'check_spec')
@mock.patch.object(specs.ProtobufNode, 'add_children')
@mock.patch.object(specs.ProtobufNode, '_from_observation_spec')
@mock.patch.object(specs.ProtobufNode, '_from_action_spec')
def test_from_spec_brain_spec_calls_protobuf_validator(
self, from_action_spec, from_observation_spec, add_children, check_spec):
"""Ensure from_spec() calls check_spec() and add_children()."""
mock_action_node = mock.Mock()
mock_observation_node = mock.Mock()
from_action_spec.return_value = mock_action_node
from_observation_spec.return_value = mock_observation_node
observation_spec = observation_pb2.ObservationSpec()
action_spec = action_pb2.ActionSpec()
text_format.Parse(_OBSERVATION_SPEC, observation_spec)
text_format.Parse(_ACTION_SPEC, action_spec)
spec = brain_pb2.BrainSpec(
observation_spec=observation_spec, action_spec=action_spec)
specs.ProtobufNode.from_spec(spec)
check_spec.assert_has_calls([mock.call(spec, 'BrainSpec')])
from_action_spec.assert_has_calls([
mock.call(spec.action_spec, 'action_spec', 'BrainSpec', 'action_spec')
])
from_observation_spec.assert_has_calls([
mock.call(spec.observation_spec, 'observation_spec', 'BrainSpec',
'observation_spec')
])
add_children.assert_has_calls(
[mock.call([mock_observation_node, mock_action_node])])
@mock.patch.object(specs.ProtobufValidator, 'check_spec')
def test_from_spec_observation_spec_calls_protobuf_validator(
self, check_spec):
"""Ensure from_spec() calls ProtobufValidator.check_spec()."""
spec = observation_pb2.ObservationSpec()
text_format.Parse(_OBSERVATION_SPEC, spec)
specs.ProtobufNode.from_spec(spec)
check_spec.assert_has_calls([
mock.call(spec, 'ObservationSpec'),
mock.call(spec.player, 'ObservationSpec/player'),
mock.call(spec.player.position, 'ObservationSpec/player/position'),
mock.call(spec.player.rotation, 'ObservationSpec/player/rotation'),
mock.call(spec.player.entity_fields[0],
'ObservationSpec/player/panache'),
mock.call(spec.player.entity_fields[0].number,
'ObservationSpec/player/panache'),
mock.call(spec.player.entity_fields[1],
'ObservationSpec/player/favorite_poison'),
mock.call(spec.player.entity_fields[1].category,
'ObservationSpec/player/favorite_poison'),
mock.call(spec.player.entity_fields[2],
'ObservationSpec/player/feeler'),
mock.call(spec.player.entity_fields[2].feeler,
'ObservationSpec/player/feeler'),
mock.call(spec.camera, 'ObservationSpec/camera'),
mock.call(spec.camera.position, 'ObservationSpec/camera/position'),
mock.call(spec.camera.rotation, 'ObservationSpec/camera/rotation'),
mock.call(spec.global_entities[0], 'ObservationSpec/0'),
mock.call(spec.global_entities[0].rotation,
'ObservationSpec/0/rotation'),
mock.call(spec.global_entities[0].entity_fields[0],
'ObservationSpec/0/pizzazz'),
mock.call(spec.global_entities[0].entity_fields[0].number,
'ObservationSpec/0/pizzazz'),
mock.call(spec.global_entities[1], 'ObservationSpec/1'),
mock.call(spec.global_entities[1].entity_fields[0],
'ObservationSpec/1/chutzpah'),
mock.call(spec.global_entities[1].entity_fields[0].number,
'ObservationSpec/1/chutzpah'),
], any_order=True)
@mock.patch.object(specs.ProtobufValidator, 'check_spec')
def test_from_spec_action_spec_calls_protobuf_validator(self,
check_spec):
"""Ensure from_spec() calls ProtobufValidator.check_spec()."""
spec = action_pb2.ActionSpec()
text_format.Parse(_ACTION_SPEC, spec)
specs.ProtobufNode.from_spec(spec)
check_spec.assert_has_calls([
mock.call(spec, 'ActionSpec'),
mock.call(spec.actions[0], 'ActionSpec/what_do'),
mock.call(spec.actions[0].category, 'ActionSpec/what_do'),
mock.call(spec.actions[1], 'ActionSpec/trouble'),
mock.call(spec.actions[1].number, 'ActionSpec/trouble'),
mock.call(spec.actions[2], 'ActionSpec/left_stick'),
mock.call(spec.actions[2].joystick, 'ActionSpec/left_stick'),
mock.call(spec.actions[3], 'ActionSpec/right_stick'),
mock.call(spec.actions[3].joystick, 'ActionSpec/right_stick'),
], any_order=True)
@staticmethod
def _create_protobuf_node_tree():
"""Create a test ProtobufNode tree."""
obs = observation_pb2.ObservationSpec()
return specs.ProtobufNode('observations', obs, '').add_children([
specs.ProtobufNode('player', obs.player, 'player').add_children([
specs.ProtobufNode('position', obs.player.position, 'position')]),
specs.ProtobufNode('camera', obs.camera, 'camera').add_children([
specs.ProtobufNode('rotation', obs.camera.rotation, 'rotation')])])
def test_protobuf_node_equal(self):
"""Test equality and inequality of two ProtobufNode trees."""
observations = ProtobufNodeTest._create_protobuf_node_tree()
other_observations = ProtobufNodeTest._create_protobuf_node_tree()
self.assertTrue(observations.__eq__(other_observations))
self.assertFalse(observations.__ne__(other_observations))
other_observations.children[-1].remove_from_parent()
self.assertFalse(observations.__eq__(other_observations))
self.assertTrue(observations.__ne__(other_observations))
def test_protobuf_node_string(self):
"""Test conversion of ProtobufNode to a string."""
observations = ProtobufNodeTest._create_protobuf_node_tree()
self.assertEqual(
'observations: (proto=(ObservationSpec, : ), children=['
'player: (proto=(EntityType, player: ), children=['
'position: (proto=(PositionType, position: ), children=[])]), '
'camera: (proto=(EntityType, camera: ), children=['
'rotation: (proto=(RotationType, rotation: ), children=[])])])'
'', str(observations))
def test_protobuf_node_as_nest(self):
"""Test conversion from a ProtobufNode instance tree to a nest."""
observations = ProtobufNodeTest._create_protobuf_node_tree()
player_position = observations.children[0].children[0]
camera_rotation = observations.children[1].children[0]
self.assertEqual(
{'observations': {'player': {'position': player_position},
'camera': {'rotation': camera_rotation}}},
observations.as_nest())
self.assertEqual(
{'player': {'position': player_position},
'camera': {'rotation': camera_rotation}},
observations.as_nest(include_self=False))
def test_observation_spec_to_protobuf_nodes(self):
"""Test conversion from an ObservationSpec to ProtobufNode instances."""
spec = observation_pb2.ObservationSpec()
text_format.Parse(_OBSERVATION_SPEC, spec)
observations = specs.ProtobufNode.from_spec(spec)
expected = specs.ProtobufNode('ObservationSpec', spec, '').add_children([
specs.ProtobufNode('player', spec.player, 'player').add_children([
specs.ProtobufNode('position', spec.player.position, 'position'),
specs.ProtobufNode('rotation', spec.player.rotation, 'rotation'),
specs.ProtobufNode('panache', spec.player.entity_fields[0].number,
'entity_fields[0]'),
specs.ProtobufNode('favorite_poison',
spec.player.entity_fields[1].category,
'entity_fields[1]'),
specs.ProtobufNode('feeler',
spec.player.entity_fields[2].feeler,
'entity_fields[2]'),
]),
specs.ProtobufNode('camera', spec.camera, 'camera').add_children([
specs.ProtobufNode('position', spec.camera.position, 'position'),
specs.ProtobufNode('rotation', spec.camera.rotation, 'rotation'),
]),
specs.ProtobufNode(
'global_entities', spec.global_entities,
'global_entities').add_children([
specs.ProtobufNode(
'0', spec.global_entities[0],
'global_entities[0]').add_children([
specs.ProtobufNode(
'rotation',
spec.global_entities[0].rotation,
'rotation'),
specs.ProtobufNode(
'pizzazz',
spec.global_entities[0].entity_fields[0].number,
'entity_fields[0]'),
]),
specs.ProtobufNode(
'1', spec.global_entities[1],
'global_entities[1]').add_children([
specs.ProtobufNode(
'chutzpah',
spec.global_entities[1].entity_fields[0].number,
'entity_fields[0]'),
]),
]),
])
self.assertEqual(str(expected), str(observations))
def test_action_spec_to_protobuf_nodes(self):
"""Test conversion from an ActionSpec to ProtobufNode instances."""
spec = action_pb2.ActionSpec()
text_format.Parse(_ACTION_SPEC, spec)
actions = specs.ProtobufNode.from_spec(spec)
expected = specs.ProtobufNode(
'ActionSpec', spec, '').add_children([
specs.ProtobufNode('what_do', spec.actions[0].category,
'actions[0]'),
specs.ProtobufNode('trouble', spec.actions[1].number,
'actions[1]'),
specs.ProtobufNode('left_stick', spec.actions[2].joystick,
'actions[2]'),
specs.ProtobufNode('right_stick', spec.actions[3].joystick,
'actions[3]'),
])
self.assertEqual(str(expected), str(actions))
def test_observation_data_to_protobuf_nest(self):
"""Test conversion from ObservationData to a protobuf nest."""
mapped = [] # List of proto, name tuples that have been mapped.
spec = observation_pb2.ObservationSpec()
text_format.Parse(_OBSERVATION_SPEC, spec)
data = observation_pb2.ObservationData()
text_format.Parse(_OBSERVATION_DATA, data)
nest = specs.ProtobufNode.from_spec(spec).data_to_proto_nest(
data, mapper=lambda p, n: mapped.append((p, n)) or p)
expected = {
'ObservationSpec': {
'player': {
'position': data.player.position,
'rotation': data.player.rotation,
'panache': data.player.entity_fields[0].number,
'favorite_poison': data.player.entity_fields[1].category,
'feeler': data.player.entity_fields[2].feeler
},
'camera': {
'position': data.camera.position,
'rotation': data.camera.rotation,
},
'global_entities': {
'0': {
'rotation': data.global_entities[0].rotation,
'pizzazz': data.global_entities[0].entity_fields[0].number,
},
'1': {
'chutzpah': data.global_entities[1].entity_fields[0].number,
},
},
}
}
self.assertEqual(nest, expected)
# Verify the mapper was applied.
self.assertCountEqual(
mapped,
[(data.player.position, 'ObservationSpec/player/position'),
(data.player.rotation, 'ObservationSpec/player/rotation'),
(data.player.entity_fields[0].number,
'ObservationSpec/player/panache'),
(data.player.entity_fields[1].category,
'ObservationSpec/player/favorite_poison'),
(data.player.entity_fields[2].feeler,
'ObservationSpec/player/feeler'),
(data.camera.position, 'ObservationSpec/camera/position'),
(data.camera.rotation, 'ObservationSpec/camera/rotation'),
(data.global_entities[0].rotation,
'ObservationSpec/global_entities/0/rotation'),
(data.global_entities[0].entity_fields[0].number,
'ObservationSpec/global_entities/0/pizzazz'),
(data.global_entities[1].entity_fields[0].number,
'ObservationSpec/global_entities/1/chutzpah')])
def test_action_data_to_protobuf_nest(self):
"""Test conversion from ActionData to a protobuf nest."""
mapped = [] # List of proto, name tuples that have been mapped.
spec = action_pb2.ActionSpec()
text_format.Parse(_ACTION_SPEC, spec)
data = action_pb2.ActionData()
text_format.Parse(_ACTION_DATA, data)
nest = specs.ProtobufNode.from_spec(spec).data_to_proto_nest(
data, mapper=lambda p, n: mapped.append((p, n)) or p)
expected = {
'ActionSpec': {
'what_do': data.actions[0].category,
'trouble': data.actions[1].number,
'left_stick': data.actions[2].joystick,
'right_stick': data.actions[3].joystick,
},
}
self.assertEqual(nest, expected)
# Verify the mapper was applied.
self.assertEqual(
mapped,
[(data.actions[0].category, 'ActionSpec/what_do'),
(data.actions[1].number, 'ActionSpec/trouble'),
(data.actions[2].joystick, 'ActionSpec/left_stick'),
(data.actions[3].joystick, 'ActionSpec/right_stick')])
@mock.patch.object(specs.ProtobufValidator, 'check_data')
def test_observation_data_to_protobuf_nest_calls_validator(self, check_data):
"""Verify all ObservationData nodes are validated against the spec."""
spec = observation_pb2.ObservationSpec()
text_format.Parse(_OBSERVATION_SPEC, spec)
data = observation_pb2.ObservationData()
text_format.Parse(_OBSERVATION_DATA, data)
specs.ProtobufNode.from_spec(spec).data_to_proto_nest(data)
# Check the subset of calls that represent all paths to protos.
check_data.assert_has_calls([
mock.call(data, spec, 'ObservationSpec', True),
mock.call(data.player, spec.player, 'ObservationSpec/player', False),
mock.call(data.player.position, spec.player.position,
'ObservationSpec/player/position', False),
mock.call(data.player.rotation, spec.player.rotation,
'ObservationSpec/player/rotation', False),
mock.call(data.player.entity_fields[0], spec.player.entity_fields[0],
'ObservationSpec/player/panache', False),
mock.call(data.player.entity_fields[0].number,
spec.player.entity_fields[0].number,
'ObservationSpec/player/panache', False),
mock.call(data.player.entity_fields[1], spec.player.entity_fields[1],
'ObservationSpec/player/favorite_poison', False),
mock.call(data.player.entity_fields[1].category,
spec.player.entity_fields[1].category,
'ObservationSpec/player/favorite_poison', False),
mock.call(data.player.entity_fields[2], spec.player.entity_fields[2],
'ObservationSpec/player/feeler', False),
mock.call(data.player.entity_fields[2].feeler,
spec.player.entity_fields[2].feeler,
'ObservationSpec/player/feeler', False),
mock.call(data.global_entities[0].rotation,
spec.global_entities[0].rotation,
'ObservationSpec/global_entities/0/rotation', False),
mock.call(data.global_entities[0].entity_fields[0],
spec.global_entities[0].entity_fields[0],
'ObservationSpec/global_entities/0/pizzazz', False),
mock.call(data.global_entities[0].entity_fields[0].number,
spec.global_entities[0].entity_fields[0].number,
'ObservationSpec/global_entities/0/pizzazz', False),
], any_order=True)
@mock.patch.object(specs.ProtobufValidator, 'check_data')
def test_action_data_to_protobuf_nest_calls_validator(self, check_data):
"""Verify all ActionData nodes are validated against the spec."""
spec = action_pb2.ActionSpec()
text_format.Parse(_ACTION_SPEC, spec)
data = action_pb2.ActionData()
text_format.Parse(_ACTION_DATA, data)
specs.ProtobufNode.from_spec(spec).data_to_proto_nest(data)
check_data.assert_has_calls([
mock.call(data.actions[0], spec.actions[0],
'ActionSpec/what_do', False),
mock.call(data.actions[0].category, spec.actions[0].category,
'ActionSpec/what_do', False),
mock.call(data.actions[1].number, spec.actions[1].number,
'ActionSpec/trouble', False),
mock.call(data.actions[2].joystick, spec.actions[2].joystick,
'ActionSpec/left_stick', False),
mock.call(data.actions[3].joystick, spec.actions[3].joystick,
'ActionSpec/right_stick', False),
], any_order=True)
class SpecsTest(parameterized.TestCase):
def test_spec_base_get_proto(self):
"""Test accessing the protobuf from a SpecBase."""
spec = observation_pb2.ObservationSpec()
spec.player.position.CopyFrom(primitives_pb2.PositionType())
self.assertEqual(spec, specs.SpecBase(spec).proto)
def test_brain_spec(self):
brain_spec_pb = brain_pb2.BrainSpec()
text_format.Parse(_OBSERVATION_SPEC, brain_spec_pb.observation_spec)
text_format.Parse(_ACTION_SPEC, brain_spec_pb.action_spec)
brain_spec = specs.BrainSpec(brain_spec_pb)
self.assertIsInstance(brain_spec.observation_spec,
specs.ObservationSpec)
self.assertIsInstance(brain_spec.action_spec,
specs.ActionSpec)
def test_empty_brain_spec(self):
empty_brain_spec = brain_pb2.BrainSpec()
with self.assertRaisesWithLiteralMatch(
specs.InvalidSpecError,
'BrainSpec must have an observation spec and action spec.'):
specs.BrainSpec(empty_brain_spec)
@parameterized.named_parameters(
('IllegalEntity', 'Joystick(s) reference invalid entities: '
'joy_bar --> [\'bar\'], joy_foo --> [\'foo\'].', """
actions {
name: "joy_foo"
joystick {
axes_mode: DELTA_PITCH_YAW
controlled_entity: "foo"
}
}
actions {
name: "joy_bar"
joystick {
axes_mode: DELTA_PITCH_YAW
controlled_entity: "bar"
}
}
""", """
player {
position {}
rotation {}
}
"""), ('MissingPlayer',
'Missing entity player referenced by joysticks [\'joy\'].', """
actions {
name: "joy"
joystick {
axes_mode: DELTA_PITCH_YAW
controlled_entity: "player"
}
}
""", """
camera {
position {}
rotation {}
}
global_entities {
rotation { }
entity_fields {
name: "despair",
number {
minimum: -100.0
maximum: 0.0
}
}
}
"""),
('MissingPlayerRotation',
'Entity player referenced by joysticks [\'joy\'] has no rotation.', """
actions {
name: "joy"
joystick {
axes_mode: DELTA_PITCH_YAW
controlled_entity: "player"
}
}
""", """
player {
position {}
}
camera {
position {}
rotation {}
}
"""), ('MissingCamera',
'Missing entity camera referenced by joysticks [\'joy\'].', """
actions {
name: "joy"
joystick {
axes_mode: DIRECTION_XZ
controlled_entity: "player"
control_frame: "camera"
}
}
""", """
player {
position {}
rotation {}
}
"""))
def test_bad_brain_spec(self, expected_error, action, observation):
brain_spec_pb = brain_pb2.BrainSpec()
text_format.Parse(action, brain_spec_pb.action_spec)
text_format.Parse(observation, brain_spec_pb.observation_spec)
with self.assertRaisesWithLiteralMatch(specs.InvalidSpecError,
expected_error):
_ = specs.BrainSpec(brain_spec_pb)
def test_known_fields(self):
"""Ensure that specs.py knows about all fields.
If this test fails, someone has changed the proto and specs.py
needs to be updated to reflect and test that change.
"""
act_spec = action_pb2.ActionSpec().DESCRIPTOR
act_data = action_pb2.ActionData().DESCRIPTOR
obs_spec = observation_pb2.ObservationSpec().DESCRIPTOR
obs_data = observation_pb2.ObservationData().DESCRIPTOR
fields = set()
def _find_fields(proto_descriptor):
for name, fd in proto_descriptor.fields_by_name.items():
if (proto_descriptor.full_name, name) in fields:
continue
fields.add((proto_descriptor.full_name, name))
if fd.message_type:
_find_fields(fd.message_type)
_find_fields(act_spec)
_find_fields(act_data)
_find_fields(obs_spec)
_find_fields(obs_data)
self.assertEqual(
fields, {
('falken.proto.Action', 'category'),
('falken.proto.Action', 'joystick'),
('falken.proto.Action', 'number'),
('falken.proto.ActionData', 'actions'),
('falken.proto.ActionData', 'source'),
('falken.proto.ActionSpec', 'actions'),
('falken.proto.ActionType', 'category'),
('falken.proto.ActionType', 'name'),
('falken.proto.ActionType', 'number'),
('falken.proto.EntityField', 'category'),
('falken.proto.EntityField', 'feeler'),
('falken.proto.ActionType', 'joystick'),
('falken.proto.EntityField', 'number'),
('falken.proto.EntityFieldType', 'category'),
('falken.proto.EntityFieldType', 'feeler'),
('falken.proto.EntityFieldType', 'name'),
('falken.proto.EntityFieldType', 'number'),
('falken.proto.Category', 'value'),
('falken.proto.CategoryType', 'enum_values'),
('falken.proto.Entity', 'entity_fields'),
('falken.proto.Entity', 'position'),
('falken.proto.Entity', 'rotation'),
('falken.proto.EntityType', 'entity_fields'),
('falken.proto.EntityType', 'position'),
('falken.proto.EntityType', 'rotation'),
('falken.proto.Feeler', 'measurements'),
('falken.proto.FeelerMeasurement', 'distance'),
('falken.proto.FeelerMeasurement', 'experimental_data'),
('falken.proto.FeelerType', 'count'),
('falken.proto.FeelerType', 'distance'),
('falken.proto.FeelerType', 'yaw_angles'),
('falken.proto.FeelerType', 'experimental_data'),
('falken.proto.FeelerType', 'thickness'),
('falken.proto.Joystick', 'x_axis'),
('falken.proto.Joystick', 'y_axis'),
('falken.proto.JoystickType', 'axes_mode'),
('falken.proto.JoystickType', 'controlled_entity'),
('falken.proto.JoystickType', 'control_frame'),
('falken.proto.Number', 'value'),
('falken.proto.NumberType', 'maximum'),
('falken.proto.NumberType', 'minimum'),
('falken.proto.ObservationData', 'camera'),
('falken.proto.ObservationData', 'global_entities'),
('falken.proto.ObservationData', 'player'),
('falken.proto.ObservationSpec', 'camera'),
('falken.proto.ObservationSpec', 'global_entities'),
('falken.proto.ObservationSpec', 'player'),
('falken.proto.Position', 'x'),
('falken.proto.Position', 'y'),
('falken.proto.Position', 'z'),
('falken.proto.Rotation', 'w'),
('falken.proto.Rotation', 'x'),
('falken.proto.Rotation', 'y'),
('falken.proto.Rotation', 'z'),
})
if __name__ == '__main__':
absltest.main()
| apache-2.0 | 2,687,925,033,447,588,000 | 38.096491 | 80 | 0.629451 | false |
lucychambers/lucychambers.github.io | .bundle/ruby/2.0.0/gems/pygments.rb-0.6.3/vendor/simplejson/simplejson/__init__.py | 37 | 20581 | r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
:mod:`simplejson` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
version of the :mod:`json` library contained in Python 2.6, but maintains
compatibility with Python 2.4 and Python 2.5 and (currently) has
significant performance advantages, even without using the optional C
extension for speedups.
Encoding basic Python object hierarchies::
>>> import simplejson as json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar")
"\"foo\bar"
>>> print json.dumps(u'\u1234')
"\u1234"
>>> print json.dumps('\\')
"\\"
>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
Compact encoding::
>>> import simplejson as json
>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'
Pretty printing::
>>> import simplejson as json
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=' ')
>>> print '\n'.join([l.rstrip() for l in s.splitlines()])
{
"4": 5,
"6": 7
}
Decoding JSON::
>>> import simplejson as json
>>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
True
>>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
True
>>> from StringIO import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)[0] == 'streaming API'
True
Specializing JSON object decoding::
>>> import simplejson as json
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
>>> from decimal import Decimal
>>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
True
Specializing JSON object encoding::
>>> import simplejson as json
>>> def encode_complex(obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... raise TypeError(repr(o) + " is not JSON serializable")
...
>>> json.dumps(2 + 1j, default=encode_complex)
'[2.0, 1.0]'
>>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
'[2.0, 1.0]'
>>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
'[2.0, 1.0]'
Using simplejson.tool from the shell to validate and pretty-print::
$ echo '{"json":"obj"}' | python -m simplejson.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m simplejson.tool
Expecting property name: line 1 column 2 (char 2)
"""
__version__ = '2.6.0'
__all__ = [
'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
'OrderedDict', 'simple_first',
]
__author__ = 'Bob Ippolito <[email protected]>'
from decimal import Decimal
from decoder import JSONDecoder, JSONDecodeError
from encoder import JSONEncoder
def _import_OrderedDict():
import collections
try:
return collections.OrderedDict
except AttributeError:
import ordered_dict
return ordered_dict.OrderedDict
OrderedDict = _import_OrderedDict()
def _import_c_make_encoder():
try:
from simplejson._speedups import make_encoder
return make_encoder
except ImportError:
return None
_default_encoder = JSONEncoder(
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
encoding='utf-8',
default=None,
use_decimal=True,
namedtuple_as_object=True,
tuple_as_array=True,
bigint_as_string=False,
item_sort_key=None,
)
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True,
namedtuple_as_object=True, tuple_as_array=True,
bigint_as_string=False, sort_keys=False, item_sort_key=None,
**kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the some chunks written to ``fp``
may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If *indent* is a string, then JSON array elements and object members
will be pretty-printed with a newline followed by that string repeated
for each level of nesting. ``None`` (the default) selects the most compact
representation without any newlines. For backwards compatibility with
versions of simplejson earlier than 2.1.0, an integer is also accepted
and is converted to a string with that many spaces.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If *use_decimal* is true (default: ``True``) then decimal.Decimal
will be natively serialized to JSON with full precision.
If *namedtuple_as_object* is true (default: ``True``),
:class:`tuple` subclasses with ``_asdict()`` methods will be encoded
as JSON objects.
If *tuple_as_array* is true (default: ``True``),
:class:`tuple` (and subclasses) will be encoded as JSON arrays.
If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher
or lower than -2**53 will be encoded as strings. This is to avoid the
rounding that happens in Javascript otherwise. Note that this is still a
lossy operation that will not round-trip correctly and should be used
sparingly.
If specified, *item_sort_key* is a callable used to sort the items in
each dictionary. This is useful if you want to sort items other than
in alphabetical order by key. This option takes precedence over
*sort_keys*.
If *sort_keys* is true (default: ``False``), the output of dictionaries
will be sorted by item.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and use_decimal
and namedtuple_as_object and tuple_as_array
and not bigint_as_string and not item_sort_key and not kw):
iterable = _default_encoder.iterencode(obj)
else:
if cls is None:
cls = JSONEncoder
iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding,
default=default, use_decimal=use_decimal,
namedtuple_as_object=namedtuple_as_object,
tuple_as_array=tuple_as_array,
bigint_as_string=bigint_as_string,
sort_keys=sort_keys,
item_sort_key=item_sort_key,
**kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
for chunk in iterable:
fp.write(chunk)
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True,
namedtuple_as_object=True, tuple_as_array=True,
bigint_as_string=False, sort_keys=False, item_sort_key=None,
**kw):
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, then the return value will be a
``unicode`` instance subject to normal Python ``str`` to ``unicode``
coercion rules instead of being escaped to an ASCII ``str``.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a string, then JSON array elements and object members
will be pretty-printed with a newline followed by that string repeated
for each level of nesting. ``None`` (the default) selects the most compact
representation without any newlines. For backwards compatibility with
versions of simplejson earlier than 2.1.0, an integer is also accepted
and is converted to a string with that many spaces.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If *use_decimal* is true (default: ``True``) then decimal.Decimal
will be natively serialized to JSON with full precision.
If *namedtuple_as_object* is true (default: ``True``),
:class:`tuple` subclasses with ``_asdict()`` methods will be encoded
as JSON objects.
If *tuple_as_array* is true (default: ``True``),
:class:`tuple` (and subclasses) will be encoded as JSON arrays.
If *bigint_as_string* is true (not the default), ints 2**53 and higher
or lower than -2**53 will be encoded as strings. This is to avoid the
rounding that happens in Javascript otherwise.
If specified, *item_sort_key* is a callable used to sort the items in
each dictionary. This is useful if you want to sort items other than
in alphabetical order by key. This option takes precendence over
*sort_keys*.
If *sort_keys* is true (default: ``False``), the output of dictionaries
will be sorted by item.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
# cached encoder
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and use_decimal
and namedtuple_as_object and tuple_as_array
and not bigint_as_string and not sort_keys
and not item_sort_key and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, encoding=encoding, default=default,
use_decimal=use_decimal,
namedtuple_as_object=namedtuple_as_object,
tuple_as_array=tuple_as_array,
bigint_as_string=bigint_as_string,
sort_keys=sort_keys,
item_sort_key=item_sort_key,
**kw).encode(obj)
_default_decoder = JSONDecoder(encoding=None, object_hook=None,
object_pairs_hook=None)
def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None,
use_decimal=False, namedtuple_as_object=True, tuple_as_array=True,
**kw):
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
*encoding* determines the encoding used to interpret any
:class:`str` objects decoded by this instance (``'utf-8'`` by
default). It has no effect when decoding :class:`unicode` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as :class:`unicode`.
*object_hook*, if specified, will be called with the result of every
JSON object decoded and its return value will be used in place of the
given :class:`dict`. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
*object_pairs_hook* is an optional function that will be called with
the result of any object literal decode with an ordered list of pairs.
The return value of *object_pairs_hook* will be used instead of the
:class:`dict`. This feature can be used to implement custom decoders
that rely on the order that the key and value pairs are decoded (for
example, :func:`collections.OrderedDict` will remember the order of
insertion). If *object_hook* is also defined, the *object_pairs_hook*
takes priority.
*parse_float*, if specified, will be called with the string of every
JSON float to be decoded. By default, this is equivalent to
``float(num_str)``. This can be used to use another datatype or parser
for JSON floats (e.g. :class:`decimal.Decimal`).
*parse_int*, if specified, will be called with the string of every
JSON int to be decoded. By default, this is equivalent to
``int(num_str)``. This can be used to use another datatype or parser
for JSON integers (e.g. :class:`float`).
*parse_constant*, if specified, will be called with one of the
following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This
can be used to raise an exception if invalid JSON numbers are
encountered.
If *use_decimal* is true (default: ``False``) then it implies
parse_float=decimal.Decimal for parity with ``dump``.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
return loads(fp.read(),
encoding=encoding, cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook,
use_decimal=use_decimal, **kw)
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None,
use_decimal=False, **kw):
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
*encoding* determines the encoding used to interpret any
:class:`str` objects decoded by this instance (``'utf-8'`` by
default). It has no effect when decoding :class:`unicode` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as :class:`unicode`.
*object_hook*, if specified, will be called with the result of every
JSON object decoded and its return value will be used in place of the
given :class:`dict`. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
*object_pairs_hook* is an optional function that will be called with
the result of any object literal decode with an ordered list of pairs.
The return value of *object_pairs_hook* will be used instead of the
:class:`dict`. This feature can be used to implement custom decoders
that rely on the order that the key and value pairs are decoded (for
example, :func:`collections.OrderedDict` will remember the order of
insertion). If *object_hook* is also defined, the *object_pairs_hook*
takes priority.
*parse_float*, if specified, will be called with the string of every
JSON float to be decoded. By default, this is equivalent to
``float(num_str)``. This can be used to use another datatype or parser
for JSON floats (e.g. :class:`decimal.Decimal`).
*parse_int*, if specified, will be called with the string of every
JSON int to be decoded. By default, this is equivalent to
``int(num_str)``. This can be used to use another datatype or parser
for JSON integers (e.g. :class:`float`).
*parse_constant*, if specified, will be called with one of the
following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This
can be used to raise an exception if invalid JSON numbers are
encountered.
If *use_decimal* is true (default: ``False``) then it implies
parse_float=decimal.Decimal for parity with ``dump``.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if (cls is None and encoding is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and object_pairs_hook is None
and not use_decimal and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if object_pairs_hook is not None:
kw['object_pairs_hook'] = object_pairs_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
if use_decimal:
if parse_float is not None:
raise TypeError("use_decimal=True implies parse_float=Decimal")
kw['parse_float'] = Decimal
return cls(encoding=encoding, **kw).decode(s)
def _toggle_speedups(enabled):
import simplejson.decoder as dec
import simplejson.encoder as enc
import simplejson.scanner as scan
c_make_encoder = _import_c_make_encoder()
if enabled:
dec.scanstring = dec.c_scanstring or dec.py_scanstring
enc.c_make_encoder = c_make_encoder
enc.encode_basestring_ascii = (enc.c_encode_basestring_ascii or
enc.py_encode_basestring_ascii)
scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner
else:
dec.scanstring = dec.py_scanstring
enc.c_make_encoder = None
enc.encode_basestring_ascii = enc.py_encode_basestring_ascii
scan.make_scanner = scan.py_make_scanner
dec.make_scanner = scan.make_scanner
global _default_decoder
_default_decoder = JSONDecoder(
encoding=None,
object_hook=None,
object_pairs_hook=None,
)
global _default_encoder
_default_encoder = JSONEncoder(
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
encoding='utf-8',
default=None,
)
def simple_first(kv):
"""Helper function to pass to item_sort_key to sort simple
elements to the top, then container elements.
"""
return (isinstance(kv[1], (list, dict, tuple)), kv[0])
| gpl-2.0 | -4,017,454,985,689,951,700 | 39.354902 | 79 | 0.656431 | false |
justin212k/cogent_rnj | test_rnj.py | 1 | 1224 | #! /usr/bin/env python
import unittest, os
from cogent.phylo.distance import *
from rnj import rnj
from cogent import LoadTree
__author__ = "Justin Kuczynski"
__copyright__ = ""
__credits__ = ["Justin Kuczynski"]
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Justin Kuczynski"
__email__ = "[email protected]"
__status__ = "Prototype"
class TreeReconstructionTests(unittest.TestCase):
def setUp(self):
pass
def _test_tree(self, method, treestring):
t = LoadTree(treestring=treestring)
t_distances = t.getDistances()
reconstructed = method(t_distances)
distances = reconstructed.getDistances()
for key in t_distances:
self.assertAlmostEqual(t_distances[key], distances[key])
def _test_phylo_method(self, method):
"""testing (well, exercising at least), rnj"""
self._test_tree(method, '((a:3,b:4):20,(c:6,d:7):30,e:5)')
self._test_tree(method, '((a:3,b:4):0,(c:6,d:7):30,e:5)')
self._test_tree(method, '((a:3,b:4,c:6,d:7):30,e:5)')
def test_rnj(self):
"""testing (well, exercising at least), rnj"""
self._test_phylo_method(rnj)
if __name__ == '__main__':
unittest.main()
| mit | 84,138,358,852,427,620 | 29.6 | 68 | 0.607026 | false |
rimbalinux/LMD3 | django/utils/simplejson/encoder.py | 13 | 16050 | """Implementation of JSONEncoder
"""
import re
c_encode_basestring_ascii = None
c_make_encoder = None
ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
HAS_UTF8 = re.compile(r'[\x80-\xff]')
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}
for i in range(0x20):
ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
# Assume this produces an infinity on all machines (probably not guaranteed)
INFINITY = float('1e66666')
FLOAT_REPR = repr
def encode_basestring(s):
"""Return a JSON representation of a Python string
"""
def replace(match):
return ESCAPE_DCT[match.group(0)]
return '"' + ESCAPE.sub(replace, s) + '"'
def py_encode_basestring_ascii(s):
"""Return an ASCII-only JSON representation of a Python string
"""
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
s = s.decode('utf-8')
def replace(match):
s = match.group(0)
try:
return ESCAPE_DCT[s]
except KeyError:
n = ord(s)
if n < 0x10000:
return '\\u%04x' % (n,)
else:
# surrogate pair
n -= 0x10000
s1 = 0xd800 | ((n >> 10) & 0x3ff)
s2 = 0xdc00 | (n & 0x3ff)
return '\\u%04x\\u%04x' % (s1, s2)
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii
class JSONEncoder(object):
"""Extensible JSON <http://json.org> encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str, unicode | string |
+-------------------+---------------+
| int, long, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
``.default()`` method with another method that returns a serializable
object for ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
"""
item_separator = ', '
key_separator = ': '
def __init__(self, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None, separators=None, encoding='utf-8', default=None):
"""Constructor for JSONEncoder, with sensible defaults.
If skipkeys is False, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is True, the output is guaranteed to be str
objects with all incoming unicode characters escaped. If
ensure_ascii is false, the output will be unicode object.
If check_circular is True, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is True, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is True, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
If specified, separators should be a (item_separator, key_separator)
tuple. The default is (', ', ': '). To get the most compact JSON
representation you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a ``TypeError``.
If encoding is not None, then all input strings will be
transformed into unicode using that encoding prior to JSON-encoding.
The default is UTF-8.
"""
self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
if separators is not None:
self.item_separator, self.key_separator = separators
if default is not None:
self.default = default
self.encoding = encoding
def default(self, o):
"""Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
"""
raise TypeError("%r is not JSON serializable" % (o,))
def encode(self, o):
"""Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
"""
# This is for extremely simple cases and benchmarks.
if isinstance(o, basestring):
if isinstance(o, str):
_encoding = self.encoding
if (_encoding is not None
and not (_encoding == 'utf-8')):
o = o.decode(_encoding)
if self.ensure_ascii:
return encode_basestring_ascii(o)
else:
return encode_basestring(o)
# This doesn't pass the iterator directly to ''.join() because the
# exceptions aren't as detailed. The list call should be roughly
# equivalent to the PySequence_Fast that ''.join() would do.
chunks = self.iterencode(o, _one_shot=True)
if not isinstance(chunks, (list, tuple)):
chunks = list(chunks)
return ''.join(chunks)
def iterencode(self, o, _one_shot=False):
"""Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encode_basestring_ascii
else:
_encoder = encode_basestring
if self.encoding != 'utf-8':
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
if isinstance(o, str):
o = o.decode(_encoding)
return _orig_encoder(o)
def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
# Check for specials. Note that this type of test is processor- and/or
# platform-specific, so do tests which don't depend on the internals.
if o != o:
text = 'NaN'
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return _repr(o)
if not allow_nan:
raise ValueError("Out of range float values are not JSON compliant: %r"
% (o,))
return text
if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys:
_iterencode = c_make_encoder(
markers, self.default, _encoder, self.indent,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, self.allow_nan)
else:
_iterencode = _make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot)
return _iterencode(o, 0)
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
## HACK: hand-optimized bytecode; turn globals into locals
False=False,
True=True,
ValueError=ValueError,
basestring=basestring,
dict=dict,
float=float,
id=id,
int=int,
isinstance=isinstance,
list=list,
long=long,
str=str,
tuple=tuple,
):
def _iterencode_list(lst, _current_indent_level):
if not lst:
yield '[]'
return
if markers is not None:
markerid = id(lst)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = lst
buf = '['
if _indent is not None:
_current_indent_level += 1
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
separator = _item_separator + newline_indent
buf += newline_indent
else:
newline_indent = None
separator = _item_separator
first = True
for value in lst:
if first:
first = False
else:
buf = separator
if isinstance(value, basestring):
yield buf + _encoder(value)
elif value is None:
yield buf + 'null'
elif value is True:
yield buf + 'true'
elif value is False:
yield buf + 'false'
elif isinstance(value, (int, long)):
yield buf + str(value)
elif isinstance(value, float):
yield buf + _floatstr(value)
else:
yield buf
if isinstance(value, (list, tuple)):
chunks = _iterencode_list(value, _current_indent_level)
elif isinstance(value, dict):
chunks = _iterencode_dict(value, _current_indent_level)
else:
chunks = _iterencode(value, _current_indent_level)
for chunk in chunks:
yield chunk
if newline_indent is not None:
_current_indent_level -= 1
yield '\n' + (' ' * (_indent * _current_indent_level))
yield ']'
if markers is not None:
del markers[markerid]
def _iterencode_dict(dct, _current_indent_level):
if not dct:
yield '{}'
return
if markers is not None:
markerid = id(dct)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = dct
yield '{'
if _indent is not None:
_current_indent_level += 1
newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
item_separator = _item_separator + newline_indent
yield newline_indent
else:
newline_indent = None
item_separator = _item_separator
first = True
if _sort_keys:
items = dct.items()
items.sort(key=lambda kv: kv[0])
else:
items = dct.iteritems()
for key, value in items:
if isinstance(key, basestring):
pass
# JavaScript is weakly typed for these, so it makes sense to
# also allow them. Many encoders seem to do something like this.
elif isinstance(key, float):
key = _floatstr(key)
elif isinstance(key, (int, long)):
key = str(key)
elif key is True:
key = 'true'
elif key is False:
key = 'false'
elif key is None:
key = 'null'
elif _skipkeys:
continue
else:
raise TypeError("key %r is not a string" % (key,))
if first:
first = False
else:
yield item_separator
yield _encoder(key)
yield _key_separator
if isinstance(value, basestring):
yield _encoder(value)
elif value is None:
yield 'null'
elif value is True:
yield 'true'
elif value is False:
yield 'false'
elif isinstance(value, (int, long)):
yield str(value)
elif isinstance(value, float):
yield _floatstr(value)
else:
if isinstance(value, (list, tuple)):
chunks = _iterencode_list(value, _current_indent_level)
elif isinstance(value, dict):
chunks = _iterencode_dict(value, _current_indent_level)
else:
chunks = _iterencode(value, _current_indent_level)
for chunk in chunks:
yield chunk
if newline_indent is not None:
_current_indent_level -= 1
yield '\n' + (' ' * (_indent * _current_indent_level))
yield '}'
if markers is not None:
del markers[markerid]
def _iterencode(o, _current_indent_level):
if isinstance(o, basestring):
yield _encoder(o)
elif o is None:
yield 'null'
elif o is True:
yield 'true'
elif o is False:
yield 'false'
elif isinstance(o, (int, long)):
yield str(o)
elif isinstance(o, float):
yield _floatstr(o)
elif isinstance(o, (list, tuple)):
for chunk in _iterencode_list(o, _current_indent_level):
yield chunk
elif isinstance(o, dict):
for chunk in _iterencode_dict(o, _current_indent_level):
yield chunk
else:
if markers is not None:
markerid = id(o)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = o
o = _default(o)
for chunk in _iterencode(o, _current_indent_level):
yield chunk
if markers is not None:
del markers[markerid]
return _iterencode
| bsd-3-clause | -679,986,628,007,827,100 | 35.325581 | 136 | 0.509782 | false |
olavopeixoto/plugin.video.brplay | resources/lib/modules/netnow/scraper_vod.py | 1 | 12025 | # -*- coding: utf-8 -*-
from auth import PLATFORM
from auth import get_request_data
import requests
import resources.lib.modules.control as control
from resources.lib.modules import cache
from resources.lib.modules import workers
import scraper_live
import player
import os
import urllib
PLAYER_HANDLER = player.__name__
proxy = control.proxy_url
proxy = None if proxy is None or proxy == '' else {
'http': proxy,
'https': proxy,
}
class CATEGORIES:
INICIO = u'INÍCIO'
ESPECIAIS = u'ESPECIAIS E PROMOÇÕES'
TV = u'PROGRAMAS DE TV'
FILMES = u'FILMES'
SERIES = u'SÉRIES'
KIDS = u'KIDS'
CLARO = u'CLARO VIDEO'
CLUBE = u'NOW CLUBE'
CATEGORY_SLUG = {
CATEGORIES.INICIO: 'home',
CATEGORIES.ESPECIAIS: 'home-especiais-e-promocoes',
CATEGORIES.TV: 'home-programas-de-tv',
CATEGORIES.FILMES: 'home-cinema',
CATEGORIES.SERIES: 'home-series',
CATEGORIES.KIDS: 'home-kids',
CATEGORIES.CLARO: 'home-clarovideo',
CATEGORIES.CLUBE: 'home-now-clube'
}
CATEGORIES_HIDE = [
'live',
'categories', # TODO
'tv_channels' # TODO
]
LOGO = os.path.join(control.artPath(), 'logo_now.png')
FANART = 'https://t2.tudocdn.net/391136'
THUMB = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcScaBeflBdP6AdV246I7YtH6j9r997X39OeHg&usqp=CAU'
def get_channels():
return [{
'handler': __name__,
'method': 'get_channel_categories',
"label": 'Now Online',
"adult": False,
'art': {
'icon': LOGO,
'clearlogo': LOGO,
'thumb': LOGO,
'fanart': FANART
}
}]
def get_channel_categories():
categories = [
CATEGORIES.INICIO,
CATEGORIES.ESPECIAIS,
CATEGORIES.TV,
CATEGORIES.FILMES,
CATEGORIES.SERIES,
CATEGORIES.KIDS,
CATEGORIES.CLARO,
CATEGORIES.CLUBE,
]
for category in categories:
yield {
'handler': __name__,
'method': 'get_page',
'category': category,
'label': category,
'art': {
'thumb': LOGO,
'fanart': FANART
}
}
def _get_page(category, validate=False):
url = None
slug = CATEGORY_SLUG.get(category)
if slug:
url = 'https://www.nowonline.com.br/avsclient/usercontent/categories/{slug}?channel={platform}'.format(platform=PLATFORM, slug=slug)
if not url:
control.log('NO CONTENT AVAILABLE FOR CATEGORY: %s' % category)
return {}
return request_logged_in(url, validate=validate)
def get_page(category):
response = _get_page(category)
response = response.get('response', {}) or {}
if not response:
response = _get_page(category, validate=True)
response = response.get('response', {}) or {}
if not response:
return
for item in response.get('categories', []):
if item.get('type', '') not in CATEGORIES_HIDE:
yield {
'handler': __name__,
'method': 'get_content',
'category': category,
'subcategory': item.get('title', '').encode('utf-8'),
'label': item.get('title', '').encode('utf-8'),
'art': {
'thumb': LOGO,
'fanart': FANART
}
}
def get_content(category, subcategory):
response = _get_page(category)
item = next((item for item in response.get('response', {}).get('categories', []) if item.get('title', '') == subcategory), {})
if not item.get('contents', []):
if item.get('type') == 'continue_watching':
url = 'https://www.nowonline.com.br/AGL/1.0/R/ENG/{platform}/ALL/NET/USER/BOOKMARKS'.format(platform=PLATFORM)
response = request_logged_in(url, False)
contents = [result.get('content', {}) for result in response.get('resultObj', []) if result.get('content', {})]
else:
id = item.get('id', -1)
url = 'https://www.nowonline.com.br/avsclient/categories/{id}/contents?offset=1&channel={platform}&limit=30'.format(platform=PLATFORM, id=id)
response = request_logged_in(url)
contents = response.get('response', {}).get('contents', [])
else:
contents = item.get('contents', [])
threads = [{
'thread': workers.Thread(_get_content, content.get('id', -1)),
'id': content.get('id', -1)
} for content in contents if content.get('type', '') in ['tvshow', 'movie', 'episode']]
[i['thread'].start() for i in threads]
[i['thread'].join() for i in threads]
return [_hydrate_content(next((next(iter(t['thread'].get_result().get('response', [])), {}) for t in threads if t['id'] == content.get('id', -1)), content)) for content in contents]
def _get_content(id):
url = 'https://www.nowonline.com.br/avsclient/contents?id={id}&include=images&include=details&include=adult&channel={platform}'.format(platform=PLATFORM, id=id)
return request_logged_in(url)
def _hydrate_content(content):
playable = content.get('type', '') == 'movie' or content.get('type', '') == "episode"
return {
'handler': PLAYER_HANDLER if playable else __name__,
'method': 'playlive' if playable else 'get_seasons',
'IsPlayable': playable,
'id': content.get('id'),
'label': content.get('title', ''),
'title': content.get('title', ''),
'mediatype': 'movie' if content.get('type', '') == 'movie' else 'episode' if content.get('type', '') == "episode" else 'tvshow',
'plot': content.get('description'),
'plotoutline': content.get('description'),
'genre': content.get('genres', []),
'year': content.get('releaseYear'),
'country': content.get('country'),
'director': content.get('directors', []),
'cast': content.get('actors', []),
'episode': content.get('episodeNumber'),
'season': content.get('seasonNumber'),
'duration': content.get('duration'),
'rating': content.get('averageRating'),
'userrating': content.get('userRating'),
'mpaa': content.get('ageRating'),
'encrypted': True,
'trailer': content.get('trailerUri'),
'art': {
'thumb': content.get('images', {}).get('banner') if content.get('type', '') != "episode" else content.get('images', {}).get('coverLandscape'),
'poster': content.get('images', {}).get('coverPortrait') if content.get('type', '') == 'movie' else None,
'tvshow.poster': content.get('images', {}).get('coverPortrait') if content.get('type', '') != 'movie' else None,
'fanart': content.get('images', {}).get('banner'),
'clearlogo': content.get('tvChannel', {}).get('logo', LOGO),
'icon': LOGO
}
}
def get_seasons(id):
control.log('get_seasons = %s' % id)
content = next(iter(_get_content(id).get('response', [])), {})
program = _hydrate_content(content)
program['seasons'] = []
seasons = content.get('seasons', [])
for season in seasons:
poster = content.get('images', {}).get('coverPortrait') if content.get('type', '') == 'movie' else content.get('images', {}).get('banner')
yield {
'handler': __name__,
'method': 'get_episodes',
'id': id,
'season_number': season.get('seasonNumber', 0),
'label': 'Temporada %s' % season.get('seasonNumber', 0),
'title': 'Temporada %s' % season.get('seasonNumber', 0),
'tvshowtitle': content.get('title', ''),
'plot': content.get('description'),
'plotoutline': content.get('description'),
'genre': content.get('genres', []),
'year': content.get('releaseYear'),
'country': content.get('country'),
'director': content.get('directors', []),
'cast': content.get('actors', []),
'episode': content.get('episodeNumber'),
'season': content.get('seasonNumber'),
'mpaa': content.get('ageRating'),
'mediatype': 'season',
'content': 'seasons',
'art': {
'poster': poster,
'tvshow.poster': poster,
'fanart': content.get('images', {}).get('banner', FANART)
}
}
def get_episodes(id, season_number=None):
control.log('get_episodes = %s | %s' % (id, season_number))
content = next(iter(_get_content(id).get('response', [])), {})
# program = _hydrate_content(content)
episodes = next((season.get('episodes', []) for season in content.get('seasons', []) if str(season.get('seasonNumber', 0)) == str(season_number) or season_number is None), [])
threads = [{
'thread': workers.Thread(_get_content, content.get('id', -1)),
'id': content.get('id', -1)
} for content in episodes if content.get('id', -1) > 0]
[i['thread'].start() for i in threads]
[i['thread'].join() for i in threads]
for eps in episodes:
yield _hydrate_content(next((next(iter(t['thread'].get_result().get('response', [])), {}) for t in threads if t['id'] == eps.get('id', -1)), eps))
def search(term, page=1, limit=20):
params = {
'query': urllib.quote_plus(term),
'limit': limit,
'offset': (page-1) * limit,
'onlyMyPackages': 'Y',
'onlyTvVas': 'N',
'order': '',
'type': ['live:tv', 'tv_channels:tv_single_row', 'moviesvod:movies', 'series:tv'],
# 'type': ['series:tv', 'moviesvod:movies'],
'channel': PLATFORM
}
url = 'https://www.nowonline.com.br/avsclient/contents/search?{qs}'.format(qs=urllib.urlencode(params, True))
response = request_logged_in(url).get('response', []) or []
has_more_pages = False
for section in response:
if not has_more_pages and int(section.get('total', 0)) > (int(section.get('startIndex', 0)) + int(section.get('maxResult', 0))):
has_more_pages = True
live_tv = section.get('category') in ['tv_channels', 'live']
for item in section.get('results', []) or []:
if live_tv:
result = scraper_live.hydrate_channel(item)
else:
result = _hydrate_content(item)
result.update({
'studio': 'Now Online'
})
yield result
if has_more_pages:
yield {
'handler': __name__,
'method': 'search',
'term': term,
'page': page + 1,
'limit': limit,
'label': control.lang(34136).encode('utf-8'),
'art': {
'poster': control.addonNext(),
'fanart': FANART
},
'properties': {
'SpecialSort': 'bottom'
}
}
def request_logged_in(url, use_cache=True, validate=False, force_refresh=False, retry=1):
headers, cookies = get_request_data(validate)
control.log('GET %s' % url)
if use_cache:
response = cache.get(requests.get, 1, url, headers=headers, cookies=cookies, force_refresh=force_refresh, table="netnow")
else:
response = requests.get(url, headers=headers, cookies=cookies)
if response.status_code >= 400 and retry > 0:
control.log('ERROR FOR URL: %s' % url)
control.log(response.status_code)
control.log(response.content)
control.log('Retrying... (%s)' % retry)
return request_logged_in(url, use_cache, validate=True, force_refresh=True, retry=retry-1)
response.raise_for_status()
result = response.json()
return result
| gpl-3.0 | 6,716,482,351,882,543,000 | 33.642651 | 185 | 0.54829 | false |
rosmo/ansible | lib/ansible/modules/cloud/azure/azure_rm_aks.py | 3 | 33951 | #!/usr/bin/python
#
# Copyright (c) 2018 Sertac Ozercan, <[email protected]>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_aks
version_added: "2.6"
short_description: Manage a managed Azure Container Service (AKS) instance
description:
- Create, update and delete a managed Azure Container Service (AKS) instance.
options:
resource_group:
description:
- Name of a resource group where the managed Azure Container Services (AKS) exists or will be created.
required: true
name:
description:
- Name of the managed Azure Container Services (AKS) instance.
required: true
state:
description:
- Assert the state of the AKS. Use C(present) to create or update an AKS and C(absent) to delete it.
default: present
choices:
- absent
- present
location:
description:
- Valid azure location. Defaults to location of the resource group.
dns_prefix:
description:
- DNS prefix specified when creating the managed cluster.
kubernetes_version:
description:
- Version of Kubernetes specified when creating the managed cluster.
linux_profile:
description:
- The Linux profile suboptions.
suboptions:
admin_username:
description:
- The Admin Username for the cluster.
required: true
ssh_key:
description:
- The Public SSH Key used to access the cluster.
required: true
agent_pool_profiles:
description:
- The agent pool profile suboptions.
suboptions:
name:
description:
- Unique name of the agent pool profile in the context of the subscription and resource group.
required: true
count:
description:
- Number of agents (VMs) to host docker containers.
- Allowed values must be in the range of C(1) to C(100) (inclusive).
required: true
vm_size:
description:
- The VM Size of each of the Agent Pool VM's (e.g. C(Standard_F1) / C(Standard_D2v2)).
required: true
os_disk_size_gb:
description:
- Size of the OS disk.
service_principal:
description:
- The service principal suboptions.
suboptions:
client_id:
description:
- The ID for the Service Principal.
required: true
client_secret:
description:
- The secret password associated with the service principal.
required: true
enable_rbac:
description:
- Enable RBAC.
- Existing non-RBAC enabled AKS clusters cannot currently be updated for RBAC use.
type: bool
default: no
version_added: "2.8"
network_profile:
description:
- Profile of network configuration.
suboptions:
network_plugin:
description:
- Network plugin used for building Kubernetes network.
- This property cannot been changed.
- With C(kubenet), nodes get an IP address from the Azure virtual network subnet.
- AKS features such as Virtual Nodes or network policies aren't supported with C(kubenet).
- C(azure) enables Azure Container Networking Interface(CNI), every pod gets an IP address from the subnet and can be accessed directly.
default: kubenet
choices:
- azure
- kubenet
network_policy:
description: Network policy used for building Kubernetes network.
choices:
- azure
- calico
pod_cidr:
description:
- A CIDR notation IP range from which to assign pod IPs when I(network_plugin=kubenet) is used.
- It should be a large address space that isn't in use elsewhere in your network environment.
- This address range must be large enough to accommodate the number of nodes that you expect to scale up to.
default: "10.244.0.0/16"
service_cidr:
description:
- A CIDR notation IP range from which to assign service cluster IPs.
- It must not overlap with any Subnet IP ranges.
- It should be the *.10 address of your service IP address range.
default: "10.0.0.0/16"
dns_service_ip:
description:
- An IP address assigned to the Kubernetes DNS service.
- It must be within the Kubernetes service address range specified in serviceCidr.
default: "10.0.0.10"
docker_bridge_cidr:
description:
- A CIDR notation IP range assigned to the Docker bridge network.
- It must not overlap with any Subnet IP ranges or the Kubernetes service address range.
default: "172.17.0.1/16"
version_added: "2.8"
aad_profile:
description:
- Profile of Azure Active Directory configuration.
suboptions:
client_app_id:
description: The client AAD application ID.
server_app_id:
description: The server AAD application ID.
server_app_secret:
description: The server AAD application secret.
tenant_id:
description:
- The AAD tenant ID to use for authentication.
- If not specified, will use the tenant of the deployment subscription.
version_added: "2.8"
addon:
description:
- Profile of managed cluster add-on.
- Key can be C(http_application_routing), C(monitoring), C(virtual_node).
- Value must be a dict contains a bool variable C(enabled).
type: dict
suboptions:
http_application_routing:
description:
- The HTTP application routing solution makes it easy to access applications that are deployed to your cluster.
type: dict
suboptions:
enabled:
description:
- Whether the solution enabled.
type: bool
monitoring:
description:
- It gives you performance visibility by collecting memory and processor metrics from controllers, nodes,
and containers that are available in Kubernetes through the Metrics API.
type: dict
suboptions:
enabled:
description:
- Whether the solution enabled.
type: bool
log_analytics_workspace_resource_id:
description:
- Where to store the container metrics.
virtual_node:
description:
- With virtual nodes, you have quick provisioning of pods, and only pay per second for their execution time.
- You don't need to wait for Kubernetes cluster autoscaler to deploy VM compute nodes to run the additional pods.
type: dict
suboptions:
enabled:
description:
- Whether the solution enabled.
type: bool
subnet_resource_id:
description:
- Subnet associdated to the cluster.
version_added: "2.8"
extends_documentation_fragment:
- azure
- azure_tags
author:
- Sertac Ozercan (@sozercan)
- Yuwei Zhou (@yuwzho)
'''
EXAMPLES = '''
- name: Create a managed Azure Container Services (AKS) instance
azure_rm_aks:
name: myAKS
location: eastus
resource_group: myResourceGroup
dns_prefix: akstest
linux_profile:
admin_username: azureuser
ssh_key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAA...
service_principal:
client_id: "cf72ca99-f6b9-4004-b0e0-bee10c521948"
client_secret: "mySPNp@ssw0rd!"
agent_pool_profiles:
- name: default
count: 5
vm_size: Standard_D2_v2
tags:
Environment: Production
- name: Remove a managed Azure Container Services (AKS) instance
azure_rm_aks:
name: myAKS
resource_group: myResourceGroup
state: absent
'''
RETURN = '''
state:
description: Current state of the Azure Container Service (AKS).
returned: always
type: dict
example:
agent_pool_profiles:
- count: 1
dns_prefix: Null
name: default
os_disk_size_gb: Null
os_type: Linux
ports: Null
storage_profile: ManagedDisks
vm_size: Standard_DS1_v2
vnet_subnet_id: Null
changed: false
dns_prefix: aks9860bdcd89
id: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/myResourceGroup/providers/Microsoft.ContainerService/managedClusters/aks9860bdc"
kube_config: "......"
kubernetes_version: 1.11.4
linux_profile:
admin_username: azureuser
ssh_key: ssh-rsa AAAAB3NzaC1yc2EAAAADA.....
location: eastus
name: aks9860bdc
provisioning_state: Succeeded
service_principal_profile:
client_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
tags: {}
type: Microsoft.ContainerService/ManagedClusters
'''
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
except ImportError:
# This is handled in azure_rm_common
pass
def create_aks_dict(aks):
'''
Helper method to deserialize a ContainerService to a dict
:param: aks: ContainerService or AzureOperationPoller with the Azure callback object
:return: dict with the state on Azure
'''
return dict(
id=aks.id,
name=aks.name,
location=aks.location,
dns_prefix=aks.dns_prefix,
kubernetes_version=aks.kubernetes_version,
tags=aks.tags,
linux_profile=create_linux_profile_dict(aks.linux_profile),
service_principal_profile=create_service_principal_profile_dict(
aks.service_principal_profile),
provisioning_state=aks.provisioning_state,
agent_pool_profiles=create_agent_pool_profiles_dict(
aks.agent_pool_profiles),
type=aks.type,
kube_config=aks.kube_config,
enable_rbac=aks.enable_rbac,
network_profile=create_network_profiles_dict(aks.network_profile),
aad_profile=create_aad_profiles_dict(aks.aad_profile),
addon=create_addon_dict(aks.addon_profiles),
fqdn=aks.fqdn,
node_resource_group=aks.node_resource_group
)
def create_network_profiles_dict(network):
return dict(
network_plugin=network.network_plugin,
network_policy=network.network_policy,
pod_cidr=network.pod_cidr,
service_cidr=network.service_cidr,
dns_service_ip=network.dns_service_ip,
docker_bridge_cidr=network.docker_bridge_cidr
) if network else dict()
def create_aad_profiles_dict(aad):
return aad.as_dict() if aad else dict()
def create_addon_dict(addon):
result = dict()
addon = addon or dict()
for key in addon.keys():
result[key] = addon[key].config
result[key]['enabled'] = addon[key].enabled
return result
def create_linux_profile_dict(linuxprofile):
'''
Helper method to deserialize a ContainerServiceLinuxProfile to a dict
:param: linuxprofile: ContainerServiceLinuxProfile with the Azure callback object
:return: dict with the state on Azure
'''
return dict(
ssh_key=linuxprofile.ssh.public_keys[0].key_data,
admin_username=linuxprofile.admin_username
)
def create_service_principal_profile_dict(serviceprincipalprofile):
'''
Helper method to deserialize a ContainerServiceServicePrincipalProfile to a dict
Note: For security reason, the service principal secret is skipped on purpose.
:param: serviceprincipalprofile: ContainerServiceServicePrincipalProfile with the Azure callback object
:return: dict with the state on Azure
'''
return dict(
client_id=serviceprincipalprofile.client_id
)
def create_agent_pool_profiles_dict(agentpoolprofiles):
'''
Helper method to deserialize a ContainerServiceAgentPoolProfile to a dict
:param: agentpoolprofiles: ContainerServiceAgentPoolProfile with the Azure callback object
:return: dict with the state on Azure
'''
return [dict(
count=profile.count,
vm_size=profile.vm_size,
name=profile.name,
os_disk_size_gb=profile.os_disk_size_gb,
storage_profile=profile.storage_profile,
vnet_subnet_id=profile.vnet_subnet_id,
os_type=profile.os_type
) for profile in agentpoolprofiles] if agentpoolprofiles else None
def create_addon_profiles_spec():
'''
Helper method to parse the ADDONS dictionary and generate the addon spec
'''
spec = dict()
for key in ADDONS.keys():
values = ADDONS[key]
addon_spec = dict(
enabled=dict(type='bool', default=True)
)
configs = values.get('config') or {}
for item in configs.keys():
addon_spec[item] = dict(type='str', aliases=[configs[item]], required=True)
spec[key] = dict(type='dict', options=addon_spec, aliases=[values['name']])
return spec
ADDONS = {
'http_application_routing': dict(name='httpApplicationRouting'),
'monitoring': dict(name='omsagent', config={'log_analytics_workspace_resource_id': 'logAnalyticsWorkspaceResourceID'}),
'virtual_node': dict(name='aciConnector', config={'subnet_resource_id': 'SubnetName'})
}
linux_profile_spec = dict(
admin_username=dict(type='str', required=True),
ssh_key=dict(type='str', required=True)
)
service_principal_spec = dict(
client_id=dict(type='str', required=True),
client_secret=dict(type='str', no_log=True)
)
agent_pool_profile_spec = dict(
name=dict(type='str', required=True),
count=dict(type='int', required=True),
vm_size=dict(type='str', required=True),
os_disk_size_gb=dict(type='int'),
dns_prefix=dict(type='str'),
ports=dict(type='list', elements='int'),
storage_profiles=dict(type='str', choices=[
'StorageAccount', 'ManagedDisks']),
vnet_subnet_id=dict(type='str'),
os_type=dict(type='str', choices=['Linux', 'Windows'])
)
network_profile_spec = dict(
network_plugin=dict(type='str', choices=['azure', 'kubenet']),
network_policy=dict(type='str'),
pod_cidr=dict(type='str'),
service_cidr=dict(type='str'),
dns_service_ip=dict(type='str'),
docker_bridge_cidr=dict(type='str')
)
aad_profile_spec = dict(
client_app_id=dict(type='str'),
server_app_id=dict(type='str'),
server_app_secret=dict(type='str', no_log=True),
tenant_id=dict(type='str')
)
class AzureRMManagedCluster(AzureRMModuleBase):
"""Configuration class for an Azure RM container service (AKS) resource"""
def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(
type='str',
required=True
),
name=dict(
type='str',
required=True
),
state=dict(
type='str',
default='present',
choices=['present', 'absent']
),
location=dict(
type='str'
),
dns_prefix=dict(
type='str'
),
kubernetes_version=dict(
type='str'
),
linux_profile=dict(
type='dict',
options=linux_profile_spec
),
agent_pool_profiles=dict(
type='list',
elements='dict',
options=agent_pool_profile_spec
),
service_principal=dict(
type='dict',
options=service_principal_spec
),
enable_rbac=dict(
type='bool',
default=False
),
network_profile=dict(
type='dict',
options=network_profile_spec
),
aad_profile=dict(
type='dict',
options=aad_profile_spec
),
addon=dict(
type='dict',
options=create_addon_profiles_spec()
)
)
self.resource_group = None
self.name = None
self.location = None
self.dns_prefix = None
self.kubernetes_version = None
self.tags = None
self.state = None
self.linux_profile = None
self.agent_pool_profiles = None
self.service_principal = None
self.enable_rbac = False
self.network_profile = None
self.aad_profile = None
self.addon = None
required_if = [
('state', 'present', [
'dns_prefix', 'linux_profile', 'agent_pool_profiles', 'service_principal'])
]
self.results = dict(changed=False)
super(AzureRMManagedCluster, self).__init__(derived_arg_spec=self.module_arg_spec,
supports_check_mode=True,
supports_tags=True,
required_if=required_if)
def exec_module(self, **kwargs):
"""Main module execution method"""
for key in list(self.module_arg_spec.keys()) + ['tags']:
setattr(self, key, kwargs[key])
resource_group = None
to_be_updated = False
update_tags = False
resource_group = self.get_resource_group(self.resource_group)
if not self.location:
self.location = resource_group.location
response = self.get_aks()
# Check if the AKS instance already present in the RG
if self.state == 'present':
# For now Agent Pool cannot be more than 1, just remove this part in the future if it change
agentpoolcount = len(self.agent_pool_profiles)
if agentpoolcount > 1:
self.fail('You cannot specify more than one agent_pool_profiles currently')
available_versions = self.get_all_versions()
if not response:
to_be_updated = True
if self.kubernetes_version not in available_versions.keys():
self.fail("Unsupported kubernetes version. Expected one of {0} but got {1}".format(available_versions.keys(), self.kubernetes_version))
else:
self.results = response
self.results['changed'] = False
self.log('Results : {0}'.format(response))
update_tags, response['tags'] = self.update_tags(response['tags'])
if response['provisioning_state'] == "Succeeded":
def is_property_changed(profile, property, ignore_case=False):
base = response[profile].get(property)
new = getattr(self, profile).get(property)
if ignore_case:
return base.lower() != new.lower()
else:
return base != new
# Cannot Update the SSH Key for now // Let service to handle it
if is_property_changed('linux_profile', 'ssh_key'):
self.log(("Linux Profile Diff SSH, Was {0} / Now {1}"
.format(response['linux_profile']['ssh_key'], self.linux_profile.get('ssh_key'))))
to_be_updated = True
# self.module.warn("linux_profile.ssh_key cannot be updated")
# self.log("linux_profile response : {0}".format(response['linux_profile'].get('admin_username')))
# self.log("linux_profile self : {0}".format(self.linux_profile[0].get('admin_username')))
# Cannot Update the Username for now // Let service to handle it
if is_property_changed('linux_profile', 'admin_username'):
self.log(("Linux Profile Diff User, Was {0} / Now {1}"
.format(response['linux_profile']['admin_username'], self.linux_profile.get('admin_username'))))
to_be_updated = True
# self.module.warn("linux_profile.admin_username cannot be updated")
# Cannot have more that one agent pool profile for now
if len(response['agent_pool_profiles']) != len(self.agent_pool_profiles):
self.log("Agent Pool count is diff, need to updated")
to_be_updated = True
if response['kubernetes_version'] != self.kubernetes_version:
upgrade_versions = available_versions.get(response['kubernetes_version']) or available_versions.keys()
if upgrade_versions and self.kubernetes_version not in upgrade_versions:
self.fail('Cannot upgrade kubernetes version to {0}, supported value are {1}'.format(self.kubernetes_version, upgrade_versions))
to_be_updated = True
if response['enable_rbac'] != self.enable_rbac:
to_be_updated = True
if self.network_profile:
for key in self.network_profile.keys():
original = response['network_profile'].get(key) or ''
if self.network_profile[key] and self.network_profile[key].lower() != original.lower():
to_be_updated = True
def compare_addon(origin, patch, config):
if not patch:
return True
if not origin:
return False
if origin['enabled'] != patch['enabled']:
return False
config = config or dict()
for key in config.keys():
if origin.get(config[key]) != patch.get(key):
return False
return True
if self.addon:
for key in ADDONS.keys():
addon_name = ADDONS[key]['name']
if not compare_addon(response['addon'].get(addon_name), self.addon.get(key), ADDONS[key].get('config')):
to_be_updated = True
for profile_result in response['agent_pool_profiles']:
matched = False
for profile_self in self.agent_pool_profiles:
if profile_result['name'] == profile_self['name']:
matched = True
os_disk_size_gb = profile_self.get('os_disk_size_gb') or profile_result['os_disk_size_gb']
if profile_result['count'] != profile_self['count'] \
or profile_result['vm_size'] != profile_self['vm_size'] \
or profile_result['os_disk_size_gb'] != os_disk_size_gb \
or profile_result['vnet_subnet_id'] != profile_self.get('vnet_subnet_id', profile_result['vnet_subnet_id']):
self.log(("Agent Profile Diff - Origin {0} / Update {1}".format(str(profile_result), str(profile_self))))
to_be_updated = True
if not matched:
self.log("Agent Pool not found")
to_be_updated = True
if to_be_updated:
self.log("Need to Create / Update the AKS instance")
if not self.check_mode:
self.results = self.create_update_aks()
self.log("Creation / Update done")
self.results['changed'] = True
elif update_tags:
self.log("Need to Update the AKS tags")
if not self.check_mode:
self.results['tags'] = self.update_aks_tags()
self.results['changed'] = True
return self.results
elif self.state == 'absent' and response:
self.log("Need to Delete the AKS instance")
self.results['changed'] = True
if self.check_mode:
return self.results
self.delete_aks()
self.log("AKS instance deleted")
return self.results
def create_update_aks(self):
'''
Creates or updates a managed Azure container service (AKS) with the specified configuration of agents.
:return: deserialized AKS instance state dictionary
'''
self.log("Creating / Updating the AKS instance {0}".format(self.name))
agentpools = []
if self.agent_pool_profiles:
agentpools = [self.create_agent_pool_profile_instance(profile) for profile in self.agent_pool_profiles]
service_principal_profile = self.create_service_principal_profile_instance(self.service_principal)
parameters = self.managedcluster_models.ManagedCluster(
location=self.location,
dns_prefix=self.dns_prefix,
kubernetes_version=self.kubernetes_version,
tags=self.tags,
service_principal_profile=service_principal_profile,
agent_pool_profiles=agentpools,
linux_profile=self.create_linux_profile_instance(self.linux_profile),
enable_rbac=self.enable_rbac,
network_profile=self.create_network_profile_instance(self.network_profile),
aad_profile=self.create_aad_profile_instance(self.aad_profile),
addon_profiles=self.create_addon_profile_instance(self.addon)
)
# self.log("service_principal_profile : {0}".format(parameters.service_principal_profile))
# self.log("linux_profile : {0}".format(parameters.linux_profile))
# self.log("ssh from yaml : {0}".format(results.get('linux_profile')[0]))
# self.log("ssh : {0}".format(parameters.linux_profile.ssh))
# self.log("agent_pool_profiles : {0}".format(parameters.agent_pool_profiles))
try:
poller = self.managedcluster_client.managed_clusters.create_or_update(self.resource_group, self.name, parameters)
response = self.get_poller_result(poller)
response.kube_config = self.get_aks_kubeconfig()
return create_aks_dict(response)
except CloudError as exc:
self.log('Error attempting to create the AKS instance.')
self.fail("Error creating the AKS instance: {0}".format(exc.message))
def update_aks_tags(self):
try:
poller = self.managedcluster_client.managed_clusters.update_tags(self.resource_group, self.name, self.tags)
response = self.get_poller_result(poller)
return response.tags
except CloudError as exc:
self.fail("Error attempting to update AKS tags: {0}".format(exc.message))
def delete_aks(self):
'''
Deletes the specified managed container service (AKS) in the specified subscription and resource group.
:return: True
'''
self.log("Deleting the AKS instance {0}".format(self.name))
try:
poller = self.managedcluster_client.managed_clusters.delete(self.resource_group, self.name)
self.get_poller_result(poller)
return True
except CloudError as e:
self.log('Error attempting to delete the AKS instance.')
self.fail("Error deleting the AKS instance: {0}".format(e.message))
return False
def get_aks(self):
'''
Gets the properties of the specified container service.
:return: deserialized AKS instance state dictionary
'''
self.log("Checking if the AKS instance {0} is present".format(self.name))
try:
response = self.managedcluster_client.managed_clusters.get(self.resource_group, self.name)
self.log("Response : {0}".format(response))
self.log("AKS instance : {0} found".format(response.name))
response.kube_config = self.get_aks_kubeconfig()
return create_aks_dict(response)
except CloudError:
self.log('Did not find the AKS instance.')
return False
def get_all_versions(self):
try:
result = dict()
response = self.containerservice_client.container_services.list_orchestrators(self.location, resource_type='managedClusters')
orchestrators = response.orchestrators
for item in orchestrators:
result[item.orchestrator_version] = [x.orchestrator_version for x in item.upgrades] if item.upgrades else []
return result
except Exception as exc:
self.fail('Error when getting AKS supported kubernetes version list for location {0} - {1}'.format(self.location, exc.message or str(exc)))
def get_aks_kubeconfig(self):
'''
Gets kubeconfig for the specified AKS instance.
:return: AKS instance kubeconfig
'''
access_profile = self.managedcluster_client.managed_clusters.get_access_profile(resource_group_name=self.resource_group,
resource_name=self.name,
role_name="clusterUser")
return access_profile.kube_config.decode('utf-8')
def create_agent_pool_profile_instance(self, agentpoolprofile):
'''
Helper method to serialize a dict to a ManagedClusterAgentPoolProfile
:param: agentpoolprofile: dict with the parameters to setup the ManagedClusterAgentPoolProfile
:return: ManagedClusterAgentPoolProfile
'''
return self.managedcluster_models.ManagedClusterAgentPoolProfile(**agentpoolprofile)
def create_service_principal_profile_instance(self, spnprofile):
'''
Helper method to serialize a dict to a ManagedClusterServicePrincipalProfile
:param: spnprofile: dict with the parameters to setup the ManagedClusterServicePrincipalProfile
:return: ManagedClusterServicePrincipalProfile
'''
return self.managedcluster_models.ManagedClusterServicePrincipalProfile(
client_id=spnprofile['client_id'],
secret=spnprofile['client_secret']
)
def create_linux_profile_instance(self, linuxprofile):
'''
Helper method to serialize a dict to a ContainerServiceLinuxProfile
:param: linuxprofile: dict with the parameters to setup the ContainerServiceLinuxProfile
:return: ContainerServiceLinuxProfile
'''
return self.managedcluster_models.ContainerServiceLinuxProfile(
admin_username=linuxprofile['admin_username'],
ssh=self.managedcluster_models.ContainerServiceSshConfiguration(public_keys=[
self.managedcluster_models.ContainerServiceSshPublicKey(key_data=str(linuxprofile['ssh_key']))])
)
def create_network_profile_instance(self, network):
return self.managedcluster_models.ContainerServiceNetworkProfile(**network) if network else None
def create_aad_profile_instance(self, aad):
return self.managedcluster_models.ManagedClusterAADProfile(**aad) if aad else None
def create_addon_profile_instance(self, addon):
result = dict()
addon = addon or {}
for key in addon.keys():
if not ADDONS.get(key):
self.fail('Unsupported addon {0}'.format(key))
if addon.get(key):
name = ADDONS[key]['name']
config_spec = ADDONS[key].get('config') or dict()
config = addon[key]
for v in config_spec.keys():
config[config_spec[v]] = config[v]
result[name] = self.managedcluster_models.ManagedClusterAddonProfile(config=config, enabled=config['enabled'])
return result
def main():
"""Main execution"""
AzureRMManagedCluster()
if __name__ == '__main__':
main()
| gpl-3.0 | 279,072,542,825,387,300 | 39.562724 | 160 | 0.570646 | false |
aiueogawa/ccxt | datagrid/exchanges.py | 1 | 653294 | # -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2017 Igor Kroitor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
#------------------------------------------------------------------------------
exchanges = [
'_1broker',
'_1btcxe',
'acx',
'anxpro',
'binance',
'bit2c',
'bitbay',
'bitcoincoid',
'bitfinex',
'bitfinex2',
'bitflyer',
'bitlish',
'bitmarket',
'bitmex',
'bitso',
'bitstamp1',
'bitstamp',
'bittrex',
'bl3p',
'bleutrade',
'btcchina',
'btcexchange',
'btcmarkets',
'btctradeua',
'btcturk',
'btcx',
'bter',
'bxinth',
'ccex',
'cex',
'chbtc',
'chilebit',
'coincheck',
'coinfloor',
'coingi',
'coinmarketcap',
'coinmate',
'coinsecure',
'coinspot',
'cryptopia',
'dsx',
'exmo',
'flowbtc',
'foxbit',
'fybse',
'fybsg',
'gatecoin',
'gdax',
'gemini',
'hitbtc',
'hitbtc2',
'huobi',
'huobicny',
'huobipro',
'independentreserve',
'itbit',
'jubi',
'kraken',
'lakebtc',
'livecoin',
'liqui',
'luno',
'mercado',
'mixcoins',
'nova',
'okcoincny',
'okcoinusd',
'okex',
'paymium',
'poloniex',
'quadrigacx',
'quoine',
'southxchange',
'surbitcoin',
'therock',
'urdubit',
'vaultoro',
'vbtc',
'virwox',
'xbtce',
'yobit',
'yunbi',
'zaif',
]
#------------------------------------------------------------------------------
__all__ = exchanges + [
'exchanges',
]
#------------------------------------------------------------------------------
# Python 2 & 3
import base64
import calendar
import datetime
import hashlib
import json
import math
import sys
import time
import decimal
import re
#------------------------------------------------------------------------------
from datagrid.errors import CCXTError
from datagrid.errors import ExchangeError
from datagrid.errors import NotSupported
from datagrid.errors import AuthenticationError
from datagrid.errors import InsufficientFunds
from datagrid.errors import NetworkError
from datagrid.errors import DDoSProtection
from datagrid.errors import RequestTimeout
from datagrid.errors import ExchangeNotAvailable
from datagrid.errors import ApiNonceError
#------------------------------------------------------------------------------
from datagrid.exchange import Exchange
#==============================================================================
class _1broker (Exchange):
def __init__(self, config={}):
params = {
'id': '_1broker',
'name': '1Broker',
'countries': 'US',
'rateLimit': 1500,
'version': 'v2',
'hasPublicAPI': False,
'hasFetchOHLCV': True,
'timeframes': {
'1m': '60',
'15m': '900',
'1h': '3600',
'1d': '86400',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766021-420bd9fc-5ecb-11e7-8ed6-56d0081efed2.jpg',
'api': 'https://1broker.com/api',
'www': 'https://1broker.com',
'doc': 'https://1broker.com/?c=en/content/api-documentation',
},
'api': {
'private': {
'get': [
'market/bars',
'market/categories',
'market/details',
'market/list',
'market/quotes',
'market/ticks',
'order/cancel',
'order/create',
'order/open',
'position/close',
'position/close_cancel',
'position/edit',
'position/history',
'position/open',
'position/shared/get',
'social/profile_statistics',
'social/profile_trades',
'user/bitcoin_deposit_address',
'user/details',
'user/overview',
'user/quota_status',
'user/transaction_log',
],
},
},
}
params.update(config)
super(_1broker, self).__init__(params)
def fetchCategories(self):
response = self.privateGetMarketCategories()
# they return an empty string among their categories, wtf?
categories = response['response']
result = []
for i in range(0, len(categories)):
if categories[i]:
result.append(categories[i])
return result
def fetch_markets(self):
self_ = self # workaround for Babel bug(not passing `self` to _recursive() call)
categories = self.fetchCategories()
result = []
for c in range(0, len(categories)):
category = categories[c]
markets = self_.privateGetMarketList({
'category': category.lower(),
})
for p in range(0, len(markets['response'])):
market = markets['response'][p]
id = market['symbol']
symbol = None
base = None
quote = None
if(category == 'FOREX') or(category == 'CRYPTO'):
symbol = market['name']
parts = symbol.split('/')
base = parts[0]
quote = parts[1]
else:
base = id
quote = 'USD'
symbol = base + '/' + quote
base = self_.commonCurrencyCode(base)
quote = self_.commonCurrencyCode(quote)
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balance = self.privateGetUserOverview()
response = balance['response']
result = {
'info': response,
}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
result[currency] = self.account()
total = float(response['balance'])
result['BTC']['free'] = total
result['BTC']['total'] = total
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
response = self.privateGetMarketQuotes(self.extend({
'symbols': self.market_id(symbol),
}, params))
orderbook = response['response'][0]
timestamp = self.parse8601(orderbook['updated'])
bidPrice = float(orderbook['bid'])
askPrice = float(orderbook['ask'])
bid = [bidPrice, None]
ask = [askPrice, None]
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'bids': [bid],
'asks': [ask],
}
def fetch_trades(self, symbol):
raise ExchangeError(self.id + ' fetchTrades() method not implemented yet')
def fetch_ticker(self, symbol):
self.load_markets()
result = self.privateGetMarketBars({
'symbol': self.market_id(symbol),
'resolution': 60,
'limit': 1,
})
orderbook = self.fetchOrderBook(symbol)
ticker = result['response'][0]
timestamp = self.parse8601(ticker['date'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['h']),
'low': float(ticker['l']),
'bid': orderbook['bids'][0][0],
'ask': orderbook['asks'][0][0],
'vwap': None,
'open': float(ticker['o']),
'close': float(ticker['c']),
'first': None,
'last': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': None,
}
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
return [
self.parse8601(ohlcv['date']),
float(ohlcv['o']),
float(ohlcv['h']),
float(ohlcv['l']),
float(ohlcv['c']),
None,
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
'resolution': self.timeframes[timeframe],
}
if since:
request['date_start'] = self.iso8601(since) # they also support date_end
if limit:
request['limit'] = limit
result = self.privateGetMarketBars(self.extend(request, params))
return self.parse_ohlcvs(result['response'], market, timeframe, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'symbol': self.market_id(symbol),
'margin': amount,
'direction': 'short' if(side == 'sell') else 'long',
'leverage': 1,
'type': side,
}
if type == 'limit':
order['price'] = price
else:
order['type'] += '_market'
result = self.privateGetOrderCreate(self.extend(order, params))
return {
'info': result,
'id': result['response']['order_id'],
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostOrderCancel({'order_id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
if not self.apiKey:
raise AuthenticationError(self.id + ' requires apiKey for all requests')
url = self.urls['api'] + '/' + self.version + '/' + path + '.php'
query = self.extend({'token': self.apiKey}, params)
url += '?' + self.urlencode(query)
response = self.fetch(url, method)
if 'warning' in response:
if response['warning']:
raise ExchangeError(self.id + ' ' + self.json(response))
if 'error' in response:
if response['error']:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class cryptocapital (Exchange):
def __init__(self, config={}):
params = {
'id': 'cryptocapital',
'name': 'Crypto Capital',
'comment': 'Crypto Capital API',
'countries': 'PA', # Panama
'hasFetchOHLCV': True,
'hasWithdraw': True,
'timeframes': {
'1d': '1year',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27993158-7a13f140-64ac-11e7-89cc-a3b441f0b0f8.jpg',
'www': 'https://cryptocapital.co',
'doc': 'https://github.com/cryptocap',
},
'api': {
'public': {
'get': [
'stats',
'historical-prices',
'order-book',
'transactions',
],
},
'private': {
'post': [
'balances-and-info',
'open-orders',
'user-transactions',
'btc-deposit-address/get',
'btc-deposit-address/new',
'deposits/get',
'withdrawals/get',
'orders/new',
'orders/edit',
'orders/cancel',
'orders/status',
'withdrawals/new',
],
},
},
}
params.update(config)
super(cryptocapital, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostBalancesAndInfo()
balance = response['balances-and-info']
result = {'info': balance}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
account['free'] = self.safe_float(balance['available'], currency, 0.0)
account['used'] = self.safe_float(balance['on_hold'], currency, 0.0)
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, market, params={}):
response = self.publicGetOrderBook(self.extend({
'currency': self.market_id(market),
}, params))
timestamp = self.milliseconds()
orderbook = response['order-book']
return self.parse_order_book(orderbook, None, 'bid', 'ask', 'price', 'order_amount')
def fetch_ticker(self, market):
response = self.publicGetStats({
'currency': self.market_id(market),
})
ticker = response['stats']
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['max']),
'low': float(ticker['min']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': float(ticker['open']),
'close': None,
'first': None,
'last': float(ticker['last_price']),
'change': float(ticker['daily_change']),
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['total_btc_traded']),
}
def parse_ohlcv(self, ohlcv, market=None, timeframe='1d', since=None, limit=None):
return [
self.parse8601(ohlcv['date'] + ' 00:00:00'),
None,
None,
None,
float(ohlcv['price']),
None,
]
def fetch_ohlcv(self, symbol, timeframe='1d', since=None, limit=None, params={}):
market = self.market(symbol)
response = self.publicGetHistoricalPrices(self.extend({
'currency': market['id'],
'timeframe': self.timeframes[timeframe],
}, params))
ohlcvs = self.omit(response['historical-prices'], 'request_currency')
return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)
def parse_trade(self, trade, market):
timestamp = int(trade['timestamp']) * 1000
return {
'id': trade['id'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': None,
'type': None,
'side': trade['maker_type'],
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTransactions(self.extend({
'currency': market['id'],
}, params))
trades = self.omit(response['transactions'], 'request_currency')
return self.parse_trades(trades, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
order = {
'side': side,
'type': type,
'currency': self.market_id(symbol),
'amount': amount,
}
if type == 'limit':
order['limit_price'] = price
result = self.privatePostOrdersNew(self.extend(order, params))
return {
'info': result,
'id': result,
}
def cancel_order(self, id):
return self.privatePostOrdersCancel({'id': id})
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
response = self.privatePostWithdrawalsNew(self.extend({
'currency': currency,
'amount': float(amount),
'address': address,
}, params))
return {
'info': response,
'id': response['result']['uuid'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
if self.id == 'cryptocapital':
raise ExchangeError(self.id + ' is an abstract base API for _1btcxe')
url = self.urls['api'] + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
query = self.extend({
'api_key': self.apiKey,
'nonce': self.nonce(),
}, params)
request = self.json(query)
query['signature'] = self.hmac(self.encode(request), self.encode(self.secret))
body = self.json(query)
headers = {'Content-Type': 'application/json'}
response = self.fetch(url, method, headers, body)
if 'errors' in response:
errors = []
for e in range(0, len(response['errors'])):
error = response['errors'][e]
errors.append(error['code'] + ': ' + error['message'])
errors = ' '.join(errors)
raise ExchangeError(self.id + ' ' + errors)
return response
#------------------------------------------------------------------------------
class _1btcxe (cryptocapital):
def __init__(self, config={}):
params = {
'id': '_1btcxe',
'name': '1BTCXE',
'countries': 'PA', # Panama
'comment': 'Crypto Capital API',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766049-2b294408-5ecc-11e7-85cc-adaff013dc1a.jpg',
'api': 'https://1btcxe.com/api',
'www': 'https://1btcxe.com',
'doc': 'https://1btcxe.com/api-docs.php',
},
'markets': {
'BTC/USD': {'id': 'USD', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'BTC/EUR': {'id': 'EUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
'BTC/CNY': {'id': 'CNY', 'symbol': 'BTC/CNY', 'base': 'BTC', 'quote': 'CNY'},
'BTC/RUB': {'id': 'RUB', 'symbol': 'BTC/RUB', 'base': 'BTC', 'quote': 'RUB'},
'BTC/CHF': {'id': 'CHF', 'symbol': 'BTC/CHF', 'base': 'BTC', 'quote': 'CHF'},
'BTC/JPY': {'id': 'JPY', 'symbol': 'BTC/JPY', 'base': 'BTC', 'quote': 'JPY'},
'BTC/GBP': {'id': 'GBP', 'symbol': 'BTC/GBP', 'base': 'BTC', 'quote': 'GBP'},
'BTC/CAD': {'id': 'CAD', 'symbol': 'BTC/CAD', 'base': 'BTC', 'quote': 'CAD'},
'BTC/AUD': {'id': 'AUD', 'symbol': 'BTC/AUD', 'base': 'BTC', 'quote': 'AUD'},
'BTC/AED': {'id': 'AED', 'symbol': 'BTC/AED', 'base': 'BTC', 'quote': 'AED'},
'BTC/BGN': {'id': 'BGN', 'symbol': 'BTC/BGN', 'base': 'BTC', 'quote': 'BGN'},
'BTC/CZK': {'id': 'CZK', 'symbol': 'BTC/CZK', 'base': 'BTC', 'quote': 'CZK'},
'BTC/DKK': {'id': 'DKK', 'symbol': 'BTC/DKK', 'base': 'BTC', 'quote': 'DKK'},
'BTC/HKD': {'id': 'HKD', 'symbol': 'BTC/HKD', 'base': 'BTC', 'quote': 'HKD'},
'BTC/HRK': {'id': 'HRK', 'symbol': 'BTC/HRK', 'base': 'BTC', 'quote': 'HRK'},
'BTC/HUF': {'id': 'HUF', 'symbol': 'BTC/HUF', 'base': 'BTC', 'quote': 'HUF'},
'BTC/ILS': {'id': 'ILS', 'symbol': 'BTC/ILS', 'base': 'BTC', 'quote': 'ILS'},
'BTC/INR': {'id': 'INR', 'symbol': 'BTC/INR', 'base': 'BTC', 'quote': 'INR'},
'BTC/MUR': {'id': 'MUR', 'symbol': 'BTC/MUR', 'base': 'BTC', 'quote': 'MUR'},
'BTC/MXN': {'id': 'MXN', 'symbol': 'BTC/MXN', 'base': 'BTC', 'quote': 'MXN'},
'BTC/NOK': {'id': 'NOK', 'symbol': 'BTC/NOK', 'base': 'BTC', 'quote': 'NOK'},
'BTC/NZD': {'id': 'NZD', 'symbol': 'BTC/NZD', 'base': 'BTC', 'quote': 'NZD'},
'BTC/PLN': {'id': 'PLN', 'symbol': 'BTC/PLN', 'base': 'BTC', 'quote': 'PLN'},
'BTC/RON': {'id': 'RON', 'symbol': 'BTC/RON', 'base': 'BTC', 'quote': 'RON'},
'BTC/SEK': {'id': 'SEK', 'symbol': 'BTC/SEK', 'base': 'BTC', 'quote': 'SEK'},
'BTC/SGD': {'id': 'SGD', 'symbol': 'BTC/SGD', 'base': 'BTC', 'quote': 'SGD'},
'BTC/THB': {'id': 'THB', 'symbol': 'BTC/THB', 'base': 'BTC', 'quote': 'THB'},
'BTC/TRY': {'id': 'TRY', 'symbol': 'BTC/TRY', 'base': 'BTC', 'quote': 'TRY'},
'BTC/ZAR': {'id': 'ZAR', 'symbol': 'BTC/ZAR', 'base': 'BTC', 'quote': 'ZAR'},
},
}
params.update(config)
super(_1btcxe, self).__init__(params)
#------------------------------------------------------------------------------
class acx (Exchange):
def __init__(self, config={}):
params = {
'id': 'acx',
'name': 'ACX',
'countries': 'AU',
'rateLimit': 1000,
'version': 'v2',
'hasFetchTickers': True,
'hasFetchOHLCV': True,
'timeframes': {
'1m': '1',
'5m': '5',
'15m': '15',
'30m': '30',
'1h': '60',
'2h': '120',
'4h': '240',
'12h': '720',
'1d': '1440',
'3d': '4320',
'1w': '10080',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/30247614-1fe61c74-9621-11e7-9e8c-f1a627afa279.jpg',
'api': 'https://acx.io/api',
'www': 'https://acx.io',
'doc': 'https://acx.io/documents/api_v2',
},
'api': {
'public': {
'get': [
'markets', # Get all available markets
'tickers', # Get ticker of all markets
'tickers/{market}', # Get ticker of specific market
'trades', # Get recent trades on market, each trade is included only once Trades are sorted in reverse creation order.
'order_book', # Get the order book of specified market
'depth', # Get depth or specified market Both asks and bids are sorted from highest price to lowest.
'k', # Get OHLC(k line) of specific market
'k_with_pending_trades', # Get K data with pending trades, which are the trades not included in K data yet, because there's delay between trade generated and processed by K data generator
'timestamp', # Get server current time, in seconds since Unix epoch
],
},
'private': {
'get': [
'members/me', # Get your profile and accounts info
'deposits', # Get your deposits history
'deposit', # Get details of specific deposit
'deposit_address', # Where to deposit The address field could be empty when a new address is generating (e.g. for bitcoin), you should try again later in that case.
'orders', # Get your orders, results is paginated
'order', # Get information of specified order
'trades/my', # Get your executed trades Trades are sorted in reverse creation order.
'withdraws', # Get your cryptocurrency withdraws
'withdraw', # Get your cryptocurrency withdraw
],
'post': [
'orders', # Create a Sell/Buy order
'orders/multi', # Create multiple sell/buy orders
'orders/clear', # Cancel all my orders
'order/delete', # Cancel an order
'withdraw', # Create a withdraw
],
},
},
}
params.update(config)
super(acx, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetMarkets()
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['id']
symbol = market['name']
base, quote = symbol.split('/')
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetMembersMe()
balances = response['accounts']
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
uppercase = currency.upper()
account = {
'free': float(balance['balance']),
'used': float(balance['locked']),
'total': 0.0,
}
account['total'] = self.sum(account['free'], account['used'])
result[uppercase] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
orderbook = self.publicGetDepth(self.extend({
'market': market['id'],
'limit': 300,
}, params))
timestamp = orderbook['timestamp'] * 1000
result = self.parse_order_book(orderbook, timestamp)
result['bids'] = self.sort_by(result['bids'], 0, True)
result['asks'] = self.sort_by(result['asks'], 0)
return result
def parse_ticker(self, ticker, market):
timestamp = ticker['at'] * 1000
ticker = ticker['ticker']
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['vol']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGetTickers()
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = None
symbol = id
if id in self.markets_by_id:
market = self.markets_by_id[id]
symbol = market['symbol']
else:
base = id[0:3]
quote = id[3:6]
base = base.upper()
quote = quote.upper()
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTickersMarket({
'market': market['id'],
})
return self.parse_ticker(response, market)
def parse_trade(self, trade, market=None):
timestamp = trade['timestamp'] * 1000
side = 'buy' if(trade['type'] == 'bid') else 'sell'
return {
'info': trade,
'id': str(trade['tid']),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTrades(self.extend({
'market': market['id'],
}, params))
# looks like they switched self endpoint off
# it returns 503 Service Temporarily Unavailable always
# return self.parse_trades(reponse, market)
return response
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
return [
ohlcv[0] * 1000,
ohlcv[1],
ohlcv[2],
ohlcv[3],
ohlcv[4],
ohlcv[5],
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
if not limit:
limit = 500 # default is 30
request = {
'market': market['id'],
'period': self.timeframes[timeframe],
'limit': limit,
}
if since:
request['timestamp'] = since
response = self.publicGetK(self.extend(request, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'market': self.market_id(symbol),
'side': side,
'volume': str(amount),
'ord_type': type,
}
if type == 'limit':
order['price'] = str(price)
response = self.privatePostOrders(self.extend(order, params))
return {
'info': response,
'id': str(response['id']),
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostOrderDelete({'id': id})
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
result = self.privatePostWithdraw(self.extend({
'currency': currency.lower(),
'sum': amount,
'address': address,
}, params))
return {
'info': result,
'id': None,
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
request = '/api' + '/' + self.version + '/' + self.implode_params(path, params) + '.json'
query = self.omit(params, self.extract_params(path))
url = self.urls['api'] + request
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = str(self.nonce())
query = self.urlencode(self.keysort(self.extend({
'access_key': self.apiKey,
'tonce': nonce,
}, params)))
auth = method + '|' + request + '|' + query
signature = self.hmac(self.encode(auth), self.encode(self.secret))
suffix = query + '&signature=' + signature
if method == 'GET':
url += '?' + suffix
else:
body = suffix
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': len(body),
}
response = self.fetch(url, method, headers, body)
if 'error' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class anxpro (Exchange):
def __init__(self, config={}):
params = {
'id': 'anxpro',
'name': 'ANXPro',
'countries': ['JP', 'SG', 'HK', 'NZ'],
'version': '2',
'rateLimit': 1500,
'hasWithdraw': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27765983-fd8595da-5ec9-11e7-82e3-adb3ab8c2612.jpg',
'api': 'https://anxpro.com/api',
'www': 'https://anxpro.com',
'doc': [
'http://docs.anxv2.apiary.io',
'https://anxpro.com/pages/api',
],
},
'api': {
'public': {
'get': [
'{currency_pair}/money/ticker',
'{currency_pair}/money/depth/full',
'{currency_pair}/money/trade/fetch', # disabled by ANXPro
],
},
'private': {
'post': [
'{currency_pair}/money/order/add',
'{currency_pair}/money/order/cancel',
'{currency_pair}/money/order/quote',
'{currency_pair}/money/order/result',
'{currency_pair}/money/orders',
'money/{currency}/address',
'money/{currency}/send_simple',
'money/info',
'money/trade/list',
'money/wallet/history',
],
},
},
'markets': {
'BTC/USD': {'id': 'BTCUSD', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'BTC/HKD': {'id': 'BTCHKD', 'symbol': 'BTC/HKD', 'base': 'BTC', 'quote': 'HKD'},
'BTC/EUR': {'id': 'BTCEUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
'BTC/CAD': {'id': 'BTCCAD', 'symbol': 'BTC/CAD', 'base': 'BTC', 'quote': 'CAD'},
'BTC/AUD': {'id': 'BTCAUD', 'symbol': 'BTC/AUD', 'base': 'BTC', 'quote': 'AUD'},
'BTC/SGD': {'id': 'BTCSGD', 'symbol': 'BTC/SGD', 'base': 'BTC', 'quote': 'SGD'},
'BTC/JPY': {'id': 'BTCJPY', 'symbol': 'BTC/JPY', 'base': 'BTC', 'quote': 'JPY'},
'BTC/GBP': {'id': 'BTCGBP', 'symbol': 'BTC/GBP', 'base': 'BTC', 'quote': 'GBP'},
'BTC/NZD': {'id': 'BTCNZD', 'symbol': 'BTC/NZD', 'base': 'BTC', 'quote': 'NZD'},
'LTC/BTC': {'id': 'LTCBTC', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'DOGE/BTC': {'id': 'DOGEBTC', 'symbol': 'DOGE/BTC', 'base': 'DOGE', 'quote': 'BTC'},
'STR/BTC': {'id': 'STRBTC', 'symbol': 'STR/BTC', 'base': 'STR', 'quote': 'BTC'},
'XRP/BTC': {'id': 'XRPBTC', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC'},
},
}
params.update(config)
super(anxpro, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostMoneyInfo()
balance = response['data']
currencies = list(balance['Wallets'].keys())
result = {'info': balance}
for c in range(0, len(currencies)):
currency = currencies[c]
account = self.account()
if currency in balance['Wallets']:
wallet = balance['Wallets'][currency]
account['free'] = float(wallet['Available_Balance']['value'])
account['total'] = float(wallet['Balance']['value'])
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def fetch_order_book(self, market, params={}):
response = self.publicGetCurrencyPairMoneyDepthFull(self.extend({
'currency_pair': self.market_id(market),
}, params))
orderbook = response['data']
t = int(orderbook['dataUpdateTime'])
timestamp = int(t / 1000)
return self.parse_order_book(orderbook, timestamp, 'bids', 'asks', 'price', 'amount')
def fetch_ticker(self, market):
response = self.publicGetCurrencyPairMoneyTicker({
'currency_pair': self.market_id(market),
})
ticker = response['data']
t = int(ticker['dataUpdateTime'])
timestamp = int(t / 1000)
bid = self.safe_float(ticker['buy'], 'value')
ask = self.safe_float(ticker['sell'], 'value')
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']['value']),
'low': float(ticker['low']['value']),
'bid': bid,
'ask': ask,
'vwap': float(ticker['vwap']['value']),
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']['value']),
'change': None,
'percentage': None,
'average': float(ticker['avg']['value']),
'baseVolume': None,
'quoteVolume': float(ticker['vol']['value']),
}
def fetch_trades(self, market, params={}):
error = self.id + ' switched off the trades endpoint, see their docs at http://docs.anxv2.apiary.io/reference/market-data/currencypairmoneytradefetch-disabled'
raise ExchangeError(error)
return self.publicGetCurrencyPairMoneyTradeFetch(self.extend({
'currency_pair': self.market_id(market),
}, params))
def create_order(self, market, type, side, amount, price=None, params={}):
order = {
'currency_pair': self.market_id(market),
'amount_int': int(amount * 100000000), # 10^8
'type': side,
}
if type == 'limit':
order['price_int'] = int(price * 100000) # 10^5
result = self.privatePostCurrencyPairOrderAdd(self.extend(order, params))
return {
'info': result,
'id': result['data']
}
def cancel_order(self, id):
return self.privatePostCurrencyPairOrderCancel({'oid': id})
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
response = self.privatePostMoneyCurrencySendSimple(self.extend({
'currency': currency,
'amount_int': int(amount * 100000000), # 10^8
'address': address,
}, params))
return {
'info': response,
'id': response['result']['uuid'],
}
def nonce(self):
return self.milliseconds()
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
request = self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
url = self.urls['api'] + '/' + self.version + '/' + request
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
body = self.urlencode(self.extend({'nonce': nonce}, query))
secret = base64.b64decode(self.secret)
auth = request + "\0" + body
signature = self.hmac(self.encode(auth), secret, hashlib.sha512, 'base64')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Rest-Key': self.apiKey,
'Rest-Sign': self.decode(signature),
}
response = self.fetch(url, method, headers, body)
if 'result' in response:
if response['result'] == 'success':
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class binance (Exchange):
def __init__(self, config={}):
params = {
'id': 'binance',
'name': 'Binance',
'countries': 'CN', # China
'rateLimit': 1000,
'version': 'v1',
'hasFetchOHLCV': True,
'timeframes': {
'1m': '1m',
'3m': '3m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'2h': '2h',
'4h': '4h',
'6h': '6h',
'8h': '8h',
'12h': '12h',
'1d': '1d',
'3d': '3d',
'1w': '1w',
'1M': '1M',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/29604020-d5483cdc-87ee-11e7-94c7-d1a8d9169293.jpg',
'api': 'https://www.binance.com/api',
'www': 'https://www.binance.com',
'doc': 'https://www.binance.com/restapipub.html',
},
'api': {
'public': {
'get': [
'ping',
'time',
'depth',
'aggTrades',
'klines',
'ticker/24hr',
],
},
'private': {
'get': [
'order',
'openOrders',
'allOrders',
'account',
'myTrades',
],
'post': [
'order',
'order/test',
'userDataStream',
],
'put': [
'userDataStream'
],
'delete': [
'order',
'userDataStream',
],
},
},
'markets': {
'BNB/BTC': {'id': 'BNBBTC', 'symbol': 'BNB/BTC', 'base': 'BNB', 'quote': 'BTC'},
'NEO/BTC': {'id': 'NEOBTC', 'symbol': 'NEO/BTC', 'base': 'NEO', 'quote': 'BTC'},
'ETH/BTC': {'id': 'ETHBTC', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
'HSR/BTC': {'id': 'HSRBTC', 'symbol': 'HSR/BTC', 'base': 'HSR', 'quote': 'BTC'},
'LTC/BTC': {'id': 'LTCBTC', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'GAS/BTC': {'id': 'GASBTC', 'symbol': 'GAS/BTC', 'base': 'GAS', 'quote': 'BTC'},
'HCC/BTC': {'id': 'HCCBTC', 'symbol': 'HCC/BTC', 'base': 'HCC', 'quote': 'BTC'},
'BCH/BTC': {'id': 'BCCBTC', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC'},
'BNB/ETH': {'id': 'BNBETH', 'symbol': 'BNB/ETH', 'base': 'BNB', 'quote': 'ETH'},
'DNT/ETH': {'id': 'DNTETH', 'symbol': 'DNT/ETH', 'base': 'DNT', 'quote': 'ETH'},
'OAX/ETH': {'id': 'OAXETH', 'symbol': 'OAX/ETH', 'base': 'OAX', 'quote': 'ETH'},
'MCO/ETH': {'id': 'MCOETH', 'symbol': 'MCO/ETH', 'base': 'MCO', 'quote': 'ETH'},
'BTM/ETH': {'id': 'BTMETH', 'symbol': 'BTM/ETH', 'base': 'BTM', 'quote': 'ETH'},
'SNT/ETH': {'id': 'SNTETH', 'symbol': 'SNT/ETH', 'base': 'SNT', 'quote': 'ETH'},
'EOS/ETH': {'id': 'EOSETH', 'symbol': 'EOS/ETH', 'base': 'EOS', 'quote': 'ETH'},
'BNT/ETH': {'id': 'BNTETH', 'symbol': 'BNT/ETH', 'base': 'BNT', 'quote': 'ETH'},
'ICN/ETH': {'id': 'ICNETH', 'symbol': 'ICN/ETH', 'base': 'ICN', 'quote': 'ETH'},
'BTC/USDT': {'id': 'BTCUSDT', 'symbol': 'BTC/USDT', 'base': 'BTC', 'quote': 'USDT'},
'ETH/USDT': {'id': 'ETHUSDT', 'symbol': 'ETH/USDT', 'base': 'ETH', 'quote': 'USDT'},
'QTUM/ETH': {'id': 'QTUMETH', 'symbol': 'QTUM/ETH', 'base': 'QTUM', 'quote': 'ETH'},
},
}
params.update(config)
super(binance, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privateGetAccount()
result = {'info': response}
balances = response['balances']
for i in range(0, len(balances)):
balance = balances[i]
asset = balance['asset']
currency = self.commonCurrencyCode(asset)
account = {
'free': float(balance['free']),
'used': float(balance['locked']),
'total': 0.0,
}
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
market = self.market(symbol)
orderbook = self.publicGetDepth(self.extend({
'symbol': market['id'],
'limit': 100, # default = maximum = 100
}, params))
return self.parse_order_book(orderbook)
def parse_ticker(self, ticker, market):
timestamp = ticker['closeTime']
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['highPrice']),
'low': float(ticker['lowPrice']),
'bid': float(ticker['bidPrice']),
'ask': float(ticker['askPrice']),
'vwap': float(ticker['weightedAvgPrice']),
'open': float(ticker['openPrice']),
'close': float(ticker['prevClosePrice']),
'first': None,
'last': float(ticker['lastPrice']),
'change': float(ticker['priceChangePercent']),
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def fetch_ticker(self, symbol):
market = self.market(symbol)
response = self.publicGetTicker24hr({
'symbol': market['id'],
})
return self.parse_ticker(response, market)
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
return [
ohlcv[0],
float(ohlcv[1]),
float(ohlcv[2]),
float(ohlcv[3]),
float(ohlcv[4]),
float(ohlcv[5]),
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
market = self.market(symbol)
request = {
'symbol': market['id'],
'interval': self.timeframes[timeframe],
}
request['limit'] = limit if(limit) else 500 # default == max == 500
if since:
request['startTime'] = since
response = self.publicGetKlines(self.extend(request, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def parse_trade(self, trade, market=None):
timestampField = 'T' if('T' in list(trade.keys())) else 'time'
timestamp = trade[timestampField]
priceField = 'p' if('p' in list(trade.keys())) else 'price'
price = float(trade[priceField])
amountField = 'q' if('q' in list(trade.keys())) else 'qty'
amount = float(trade[amountField])
idField = 'a' if('a' in list(trade.keys())) else 'id'
id = str(trade[idField])
side = None
if 'm' in trade:
side = 'sell'
if trade['m']:
side = 'buy'
else:
isBuyer = trade['isBuyer']
isMaker = trade['isMaker']
if isBuyer:
side = 'sell' if isMaker else 'buy'
else:
side = 'buy' if isMaker else 'sell'
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'id': id,
'type': None,
'side': side,
'price': price,
'amount': amount,
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetAggTrades(self.extend({
'symbol': market['id'],
# 'fromId': 123, # ID to get aggregate trades from INCLUSIVE.
# 'startTime': 456, # Timestamp in ms to get aggregate trades from INCLUSIVE.
# 'endTime': 789, # Timestamp in ms to get aggregate trades until INCLUSIVE.
'limit': 500, # default = maximum = 500
}, params))
return self.parse_trades(response, market)
def parse_orderStatus(self, status):
if status == 'NEW':
return 'open'
if status == 'PARTIALLY_FILLED':
return 'open'
if status == 'FILLED':
return 'closed'
if status == 'CANCELED':
return 'canceled'
return status.lower()
def parse_order(self, order, market=None):
status = self.parseOrderStatus(order['status'])
symbol = None
if market:
symbol = market['symbol']
else:
id = order['symbol']
if id in self.markets_by_id:
market = self.markets_by_id[id]
symbol = market['symbol']
timestamp = order['time']
amount = float(order['origQty'])
filled = self.safe_float(order, 'executedQty', 0.0)
remaining = max(amount - filled, 0.0)
result = {
'info': order,
'id': order['orderId'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'type': order['type'].lower(),
'side': order['side'].lower(),
'price': float(order['price']),
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
}
return result
def create_order(self, symbol, type, side, amount, price=None, params={}):
price = float(price)
order = {
'symbol': self.market_id(symbol),
'quantity': '{:.8f}'.format(amount),
'price': '{:.8f}'.format(price),
'type': type.upper(),
'side': side.upper(),
'timeInForce': 'GTC', # Good To Cancel(default)
# 'timeInForce': 'IOC', # Immediate Or Cancel
}
response = self.privatePostOrder(self.extend(order, params))
return {
'info': response,
'id': str(response['orderId']),
}
def fetch_order(self, id, params={}):
symbol = ('symbol' in list(params.keys()))
if not symbol:
raise ExchangeError(self.id + ' fetchOrder requires a symbol param')
symbol = params['symbol']
market = self.market(symbol)
query = self.omit(params, 'symbol')
response = self.privateGetOrder(self.extend({
'symbol': market['id'],
'orderId': str(id),
}, query))
return self.parse_order(response, market)
def fetch_orders(self, params={}):
if 'symbol' in params:
symbol = params['symbol']
market = self.market(symbol)
query = self.omit(params, 'symbol')
response = self.privateGetAllOrders(self.extend({
'symbol': market['id'],
}, query))
return self.parse_orders(response, market)
raise ExchangeError(self.id + ' fetchOrders requires a symbol param')
def fetch_open_orders(self, symbol=None, params={}):
if not symbol:
raise ExchangeError(self.id + ' fetchOpenOrders requires a symbol param')
market = self.market(symbol)
response = self.privateGetOpenOrders(self.extend({
'symbol': market['id'],
}, params))
return self.parse_orders(response, market)
def cancel_order(self, id, params={}):
return self.privatePostOrderCancel(self.extend({
'orderId': int(id),
# 'origClientOrderId': id,
}, params))
def nonce(self):
return self.milliseconds()
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
nonce = self.nonce()
query = self.urlencode(self.extend({'timestamp': nonce}, params))
auth = self.secret + '|' + query
signature = self.hash(self.encode(auth), 'sha256')
query += '&' + 'signature=' + signature
headers = {
'X-MBX-APIKEY': self.apiKey,
}
if method == 'GET':
url += '?' + query
else:
body = query
headers['Content-Type'] = 'application/x-www-form-urlencoded'
response = self.fetch(url, method, headers, body)
if 'code' in response:
if response['code'] < 0:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class bit2c (Exchange):
def __init__(self, config={}):
params = {
'id': 'bit2c',
'name': 'Bit2C',
'countries': 'IL', # Israel
'rateLimit': 3000,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766119-3593220e-5ece-11e7-8b3a-5a041f6bcc3f.jpg',
'api': 'https://www.bit2c.co.il',
'www': 'https://www.bit2c.co.il',
'doc': [
'https://www.bit2c.co.il/home/api',
'https://github.com/OferE/bit2c',
],
},
'api': {
'public': {
'get': [
'Exchanges/{pair}/Ticker',
'Exchanges/{pair}/orderbook',
'Exchanges/{pair}/trades',
],
},
'private': {
'post': [
'Account/Balance',
'Account/Balance/v2',
'Merchant/CreateCheckout',
'Order/AccountHistory',
'Order/AddCoinFundsRequest',
'Order/AddFund',
'Order/AddOrder',
'Order/AddOrderMarketPriceBuy',
'Order/AddOrderMarketPriceSell',
'Order/CancelOrder',
'Order/MyOrders',
'Payment/GetMyId',
'Payment/Send',
],
},
},
'markets': {
'BTC/NIS': {'id': 'BtcNis', 'symbol': 'BTC/NIS', 'base': 'BTC', 'quote': 'NIS'},
'LTC/BTC': {'id': 'LtcBtc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'LTC/NIS': {'id': 'LtcNis', 'symbol': 'LTC/NIS', 'base': 'LTC', 'quote': 'NIS'},
},
}
params.update(config)
super(bit2c, self).__init__(params)
def fetch_balance(self, params={}):
balance = self.privatePostAccountBalanceV2()
result = {'info': balance}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in balance:
available = 'AVAILABLE_' + currency
account['free'] = balance[available]
account['total'] = balance[currency]
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def fetch_order_book(self, market, params={}):
orderbook = self.publicGetExchangesPairOrderbook(self.extend({
'pair': self.market_id(market),
}, params))
return self.parse_order_book(orderbook)
def fetch_ticker(self, market):
ticker = self.publicGetExchangesPairTicker({
'pair': self.market_id(market),
})
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['h']),
'low': float(ticker['l']),
'bid': None,
'ask': None,
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['ll']),
'change': None,
'percentage': None,
'average': float(ticker['av']),
'baseVolume': None,
'quoteVolume': float(ticker['a']),
}
def parse_trade(self, trade, market=None):
timestamp = int(trade['date']) * 1000
symbol = None
if market:
symbol = market['symbol']
return {
'id': str(trade['tid']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'order': None,
'type': None,
'side': None,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetExchangesPairTrades(self.extend({
'pair': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
method = 'privatePostOrderAddOrder'
order = {
'Amount': amount,
'Pair': self.market_id(symbol),
}
if type == 'market':
method += 'MarketPrice' + self.capitalize(side)
else:
order['Price'] = price
order['Total'] = amount * price
order['IsBid'] = (side == 'buy')
result = getattr(self, method)(self.extend(order, params))
return {
'info': result,
'id': result['NewOrder']['id'],
}
def cancel_order(self, id):
return self.privatePostOrderCancelOrder({'id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.implode_params(path, params)
if api == 'public':
url += '.json'
else:
nonce = self.nonce()
query = self.extend({'nonce': nonce}, params)
body = self.urlencode(query)
signature = self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512, 'base64')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'key': self.apiKey,
'sign': self.decode(signature),
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class bitbay (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitbay',
'name': 'BitBay',
'countries': ['PL', 'EU'], # Poland
'rateLimit': 1000,
'hasWithdraw': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766132-978a7bd8-5ece-11e7-9540-bc96d1e9bbb8.jpg',
'www': 'https://bitbay.net',
'api': {
'public': 'https://bitbay.net/API/Public',
'private': 'https://bitbay.net/API/Trading/tradingApi.php',
},
'doc': [
'https://bitbay.net/public-api',
'https://bitbay.net/account/tab-api',
'https://github.com/BitBayNet/API',
],
},
'api': {
'public': {
'get': [
'{id}/all',
'{id}/market',
'{id}/orderbook',
'{id}/ticker',
'{id}/trades',
],
},
'private': {
'post': [
'info',
'trade',
'cancel',
'orderbook',
'orders',
'transfer',
'withdraw',
'history',
'transactions',
],
},
},
'markets': {
'BTC/USD': {'id': 'BTCUSD', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'BTC/EUR': {'id': 'BTCEUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
'BTC/PLN': {'id': 'BTCPLN', 'symbol': 'BTC/PLN', 'base': 'BTC', 'quote': 'PLN'},
'LTC/USD': {'id': 'LTCUSD', 'symbol': 'LTC/USD', 'base': 'LTC', 'quote': 'USD'},
'LTC/EUR': {'id': 'LTCEUR', 'symbol': 'LTC/EUR', 'base': 'LTC', 'quote': 'EUR'},
'LTC/PLN': {'id': 'LTCPLN', 'symbol': 'LTC/PLN', 'base': 'LTC', 'quote': 'PLN'},
'LTC/BTC': {'id': 'LTCBTC', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'ETH/USD': {'id': 'ETHUSD', 'symbol': 'ETH/USD', 'base': 'ETH', 'quote': 'USD'},
'ETH/EUR': {'id': 'ETHEUR', 'symbol': 'ETH/EUR', 'base': 'ETH', 'quote': 'EUR'},
'ETH/PLN': {'id': 'ETHPLN', 'symbol': 'ETH/PLN', 'base': 'ETH', 'quote': 'PLN'},
'ETH/BTC': {'id': 'ETHBTC', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
'LSK/USD': {'id': 'LSKUSD', 'symbol': 'LSK/USD', 'base': 'LSK', 'quote': 'USD'},
'LSK/EUR': {'id': 'LSKEUR', 'symbol': 'LSK/EUR', 'base': 'LSK', 'quote': 'EUR'},
'LSK/PLN': {'id': 'LSKPLN', 'symbol': 'LSK/PLN', 'base': 'LSK', 'quote': 'PLN'},
'LSK/BTC': {'id': 'LSKBTC', 'symbol': 'LSK/BTC', 'base': 'LSK', 'quote': 'BTC'},
},
}
params.update(config)
super(bitbay, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostInfo()
balance = response['balances']
result = {'info': balance}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in balance:
account['free'] = float(balance[currency]['available'])
account['used'] = float(balance[currency]['locked'])
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, market, params={}):
orderbook = self.publicGetIdOrderbook(self.extend({
'id': self.market_id(market),
}, params))
return self.parse_order_book(orderbook)
def fetch_ticker(self, market):
ticker = self.publicGetIdTicker({
'id': self.market_id(market),
})
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['max']),
'low': float(ticker['min']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': float(ticker['vwap']),
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': float(ticker['average']),
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['date'] * 1000
return {
'id': trade['tid'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['type'],
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetIdTrades(self.extend({
'id': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
market = self.market(symbol)
return self.privatePostTrade(self.extend({
'type': side,
'currency': market['base'],
'amount': amount,
'payment_currency': market['quote'],
'rate': price,
}, params))
def cancel_order(self, id):
return self.privatePostCancel({'id': id})
def isFiat(self, currency):
if currency == 'USD':
return True
if currency == 'EUR':
return True
if currency == 'PLN':
return True
return False
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
method = None
request = {
'currency': currency,
'quantity': amount,
}
if self.isFiat(currency):
method = 'privatePostWithdraw'
# request['account'] = params['account'] # they demand an account number
# request['express'] = params['express'] # whatever it means, they don't explain
# request['bic'] = ''
else:
method = 'privatePostTransfer'
request['address'] = address
response = getattr(self, method)(self.extend(request, params))
return {
'info': response,
'id': None,
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
if api == 'public':
url += '/' + self.implode_params(path, params) + '.json'
else:
body = self.urlencode(self.extend({
'method': path,
'moment': self.nonce(),
}, params))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'API-Key': self.apiKey,
'API-Hash': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class bitcoincoid (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitcoincoid',
'name': 'Bitcoin.co.id',
'countries': 'ID', # Indonesia
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766138-043c7786-5ecf-11e7-882b-809c14f38b53.jpg',
'api': {
'public': 'https://vip.bitcoin.co.id/api',
'private': 'https://vip.bitcoin.co.id/tapi',
},
'www': 'https://www.bitcoin.co.id',
'doc': [
'https://vip.bitcoin.co.id/downloads/BITCOINCOID-API-DOCUMENTATION.pdf',
'https://vip.bitcoin.co.id/trade_api',
],
},
'api': {
'public': {
'get': [
'{pair}/ticker',
'{pair}/trades',
'{pair}/depth',
],
},
'private': {
'post': [
'getInfo',
'transHistory',
'trade',
'tradeHistory',
'openOrders',
'cancelOrder',
],
},
},
'markets': {
'BTC/IDR': {'id': 'btc_idr', 'symbol': 'BTC/IDR', 'base': 'BTC', 'quote': 'IDR', 'baseId': 'btc', 'quoteId': 'idr'},
'BTS/BTC': {'id': 'bts_btc', 'symbol': 'BTS/BTC', 'base': 'BTS', 'quote': 'BTC', 'baseId': 'bts', 'quoteId': 'btc'},
'DASH/BTC': {'id': 'drk_btc', 'symbol': 'DASH/BTC', 'base': 'DASH', 'quote': 'BTC', 'baseId': 'drk', 'quoteId': 'btc'},
'DOGE/BTC': {'id': 'doge_btc', 'symbol': 'DOGE/BTC', 'base': 'DOGE', 'quote': 'BTC', 'baseId': 'doge', 'quoteId': 'btc'},
'ETH/BTC': {'id': 'eth_btc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', 'baseId': 'eth', 'quoteId': 'btc'},
'LTC/BTC': {'id': 'ltc_btc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC', 'baseId': 'ltc', 'quoteId': 'btc'},
'NXT/BTC': {'id': 'nxt_btc', 'symbol': 'NXT/BTC', 'base': 'NXT', 'quote': 'BTC', 'baseId': 'nxt', 'quoteId': 'btc'},
'STR/BTC': {'id': 'str_btc', 'symbol': 'STR/BTC', 'base': 'STR', 'quote': 'BTC', 'baseId': 'str', 'quoteId': 'btc'},
'NEM/BTC': {'id': 'nem_btc', 'symbol': 'NEM/BTC', 'base': 'NEM', 'quote': 'BTC', 'baseId': 'nem', 'quoteId': 'btc'},
'XRP/BTC': {'id': 'xrp_btc', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC', 'baseId': 'xrp', 'quoteId': 'btc'},
},
}
params.update(config)
super(bitcoincoid, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostGetInfo()
balance = response['return']
result = {'info': balance}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = self.account()
account['free'] = self.safe_float(balance['balance'], lowercase, 0.0)
account['used'] = self.safe_float(balance['balance_hold'], lowercase, 0.0)
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetPairDepth(self.extend({
'pair': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook, None, 'buy', 'sell')
def fetch_ticker(self, symbol):
market = self.market(symbol)
response = self.publicGetPairTicker({
'pair': market['id'],
})
ticker = response['ticker']
timestamp = float(ticker['server_time']) * 1000
baseVolume = 'vol_' + market['baseId'].lower()
quoteVolume = 'vol_' + market['quoteId'].lower()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker[baseVolume]),
'quoteVolume': float(ticker[quoteVolume]),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = int(trade['date']) * 1000
return {
'id': trade['tid'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['type'],
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetPairTrades(self.extend({
'pair': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
market = self.market(symbol)
order = {
'pair': market['id'],
'type': side,
'price': price,
}
base = market['base'].lower()
order[base] = amount
result = self.privatePostTrade(self.extend(order, params))
return {
'info': result,
'id': str(result['return']['order_id']),
}
def cancel_order(self, id, params={}):
return self.privatePostCancelOrder(self.extend({
'id': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
if api == 'public':
url += '/' + self.implode_params(path, params)
else:
body = self.urlencode(self.extend({
'method': path,
'nonce': self.nonce(),
}, params))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': self.apiKey,
'Sign': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
response = self.fetch(url, method, headers, body)
if 'error' in response:
raise ExchangeError(self.id + ' ' + response['error'])
return response
#------------------------------------------------------------------------------
class bitfinex (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitfinex',
'name': 'Bitfinex',
'countries': 'US',
'version': 'v1',
'rateLimit': 1500,
'hasFetchTickers': False,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766244-e328a50c-5ed2-11e7-947b-041416579bb3.jpg',
'api': 'https://api.bitfinex.com',
'www': 'https://www.bitfinex.com',
'doc': [
'https://bitfinex.readme.io/v1/docs',
'https://github.com/bitfinexcom/bitfinex-api-node',
],
},
'api': {
'public': {
'get': [
'book/{symbol}',
# 'candles/{symbol}',
'lendbook/{currency}',
'lends/{currency}',
'pubticker/{symbol}',
'stats/{symbol}',
'symbols',
'symbols_details',
'today',
'trades/{symbol}',
],
},
'private': {
'post': [
'account_infos',
'balances',
'basket_manage',
'credits',
'deposit/new',
'funding/close',
'history',
'history/movements',
'key_info',
'margin_infos',
'mytrades',
'mytrades_funding',
'offer/cancel',
'offer/new',
'offer/status',
'offers',
'offers/hist',
'order/cancel',
'order/cancel/all',
'order/cancel/multi',
'order/cancel/replace',
'order/new',
'order/new/multi',
'order/status',
'orders',
'orders/hist',
'position/claim',
'positions',
'summary',
'taken_funds',
'total_taken_funds',
'transfer',
'unused_taken_funds',
'withdraw',
],
},
},
}
params.update(config)
super(bitfinex, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetSymbolsDetails()
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['pair'].upper()
baseId = id[0:3]
quoteId = id[3:6]
base = baseId
quote = quoteId
# issue #4 Bitfinex names Dash as DSH, instead of DASH
if base == 'DSH':
base = 'DASH'
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'info': market,
})
return result
def fetch_balance(self):
self.load_markets()
balances = self.privatePostBalances()
result = {'info': balances}
for i in range(0, len(balances)):
balance = balances[i]
if balance['type'] == 'exchange':
currency = balance['currency']
uppercase = currency.upper()
# issue #4 Bitfinex names dash as dsh
if uppercase == 'DSH':
uppercase = 'DASH'
account = self.account()
account['free'] = float(balance['available'])
account['total'] = float(balance['amount'])
account['used'] = account['total'] - account['free']
result[uppercase] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetBookSymbol(self.extend({
'symbol': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook, None, 'bids', 'asks', 'price', 'amount')
def fetch_ticker(self, symbol):
self.load_markets()
ticker = self.publicGetPubtickerSymbol({
'symbol': self.market_id(symbol),
})
timestamp = float(ticker['timestamp']) * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last_price']),
'change': None,
'percentage': None,
'average': float(ticker['mid']),
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['timestamp'] * 1000
return {
'id': str(trade['tid']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['type'],
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTradesSymbol(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
orderType = type
if(type == 'limit') or(type == 'market'):
orderType = 'exchange ' + type
order = {
'symbol': self.market_id(symbol),
'amount': str(amount),
'side': side,
'type': orderType,
'ocoorder': False,
'buy_price_oco': 0,
'sell_price_oco': 0,
}
if type == 'market':
order['price'] = str(self.nonce())
else:
order['price'] = str(price)
result = self.privatePostOrderNew(self.extend(order, params))
return {
'info': result,
'id': str(result['order_id']),
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostOrderCancel({'order_id': int(id)})
def parse_order(self, order, market=None):
side = order['side']
open = order['is_live']
canceled = order['is_cancelled']
status = None
if open:
status = 'open'
elif canceled:
status = 'canceled'
else:
status = 'closed'
symbol = None
if market:
symbol = market['symbol']
else:
exchange = order['symbol'].upper()
if exchange in self.markets_by_id:
market = self.markets_by_id[exchange]
symbol = market['symbol']
orderType = order['type']
exchange = orderType.find('exchange ') >= 0
if exchange:
prefix, orderType = order['type'].split(' ')
timestamp = int(float(order['timestamp']) * 1000)
result = {
'info': order,
'id': order['id'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'type': orderType,
'side': side,
'price': float(order['price']),
'amount': float(order['original_amount']),
'remaining': float(order['remaining_amount']),
'status': status,
}
return result
def fetch_order(self, id, params={}):
self.load_markets()
response = self.privatePostOrderStatus(self.extend({
'order_id': int(id),
}, params))
return self.parse_order(response)
def getCurrencyName(self, currency):
if currency == 'BTC':
return 'bitcoin'
elif currency == 'LTC':
return 'litecoin'
elif currency == 'ETH':
return 'ethereum'
elif currency == 'ETC':
return 'ethereumc'
elif currency == 'OMNI':
return 'mastercoin' # ???
elif currency == 'ZEC':
return 'zcash'
elif currency == 'XMR':
return 'monero'
elif currency == 'USD':
return 'wire'
elif currency == 'DASH':
return 'dash'
elif currency == 'XRP':
return 'ripple'
elif currency == 'EOS':
return 'eos'
raise NotSupported(self.id + ' ' + currency + ' not supported for withdrawal')
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
name = self.getCurrencyName(currency)
response = self.privatePostWithdraw(self.extend({
'withdraw_type': name,
'walletselected': 'exchange',
'amount': amount,
'address': address,
}, params))
return {
'info': response,
'id': response['withdrawal_id'],
}
def nonce(self):
return self.milliseconds()
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
request = '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
url = self.urls['api'] + request
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
query = self.extend({
'nonce': str(nonce),
'request': request,
}, query)
query = self.json(query)
query = self.encode(query)
payload = base64.b64encode(query)
secret = self.encode(self.secret)
signature = self.hmac(payload, secret, hashlib.sha384)
headers = {
'X-BFX-APIKEY': self.apiKey,
'X-BFX-PAYLOAD': self.decode(payload),
'X-BFX-SIGNATURE': signature,
}
response = self.fetch(url, method, headers, body)
if 'message' in response:
if response['message'].find('not enough exchange balance') >= 0:
raise InsufficientFunds(self.id + ' ' + self.json(response))
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class bitfinex2 (bitfinex):
def __init__(self, config={}):
params = {
'id': 'bitfinex2',
'name': 'Bitfinex v2',
'countries': 'US',
'version': 'v2',
'hasFetchTickers': False, # True but at least one pair is required
'hasFetchOHLCV': True,
'timeframes': {
'1m': '1m',
'5m': '5m',
'15m': '15m',
'30m': '30m',
'1h': '1h',
'3h': '3h',
'6h': '6h',
'12h': '12h',
'1d': '1D',
'1w': '7D',
'2w': '14D',
'1M': '1M',
},
'rateLimit': 1500,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766244-e328a50c-5ed2-11e7-947b-041416579bb3.jpg',
'api': 'https://api.bitfinex.com',
'www': 'https://www.bitfinex.com',
'doc': [
'https://bitfinex.readme.io/v2/docs',
'https://github.com/bitfinexcom/bitfinex-api-node',
],
},
'api': {
'public': {
'get': [
'platform/status',
'tickers', # replies with an empty list :\
'ticker/{symbol}',
'trades/{symbol}/hist',
'book/{symbol}/{precision}',
'book/{symbol}/P0',
'book/{symbol}/P1',
'book/{symbol}/P2',
'book/{symbol}/P3',
'book/{symbol}/R0',
'symbols_details',
'stats1/{key}:{size}:{symbol}/{side}/{section}',
'stats1/{key}:{size}:{symbol}/long/last',
'stats1/{key}:{size}:{symbol}/long/hist',
'stats1/{key}:{size}:{symbol}/short/last',
'stats1/{key}:{size}:{symbol}/short/hist',
'candles/trade:{timeframe}:{symbol}/{section}',
'candles/trade:{timeframe}:{symbol}/last',
'candles/trade:{timeframe}:{symbol}/hist',
],
'post': [
'calc/trade/avg',
],
},
'private': {
'post': [
'auth/r/wallets',
'auth/r/orders/{symbol}',
'auth/r/orders/{symbol}/new',
'auth/r/orders/{symbol}/hist',
'auth/r/order/{symbol}:{id}/trades',
'auth/r/trades/{symbol}/hist',
'auth/r/funding/offers/{symbol}',
'auth/r/funding/offers/{symbol}/hist',
'auth/r/funding/loans/{symbol}',
'auth/r/funding/loans/{symbol}/hist',
'auth/r/funding/credits/{symbol}',
'auth/r/funding/credits/{symbol}/hist',
'auth/r/funding/trades/{symbol}/hist',
'auth/r/info/margin/{key}',
'auth/r/info/funding/{key}',
'auth/r/movements/{currency}/hist',
'auth/r/stats/perf:{timeframe}/hist',
'auth/r/alerts',
'auth/w/alert/set',
'auth/w/alert/{type}:{symbol}:{price}/del',
'auth/calc/order/avail',
],
},
},
'markets': {
'BCC/BTC': {'id': 'tBCCBTC', 'symbol': 'BCC/BTC', 'base': 'BCC', 'quote': 'BTC'},
'BCC/USD': {'id': 'tBCCUSD', 'symbol': 'BCC/USD', 'base': 'BCC', 'quote': 'USD'},
'BCH/BTC': {'id': 'tBCHBTC', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC'},
'BCH/ETH': {'id': 'tBCHETH', 'symbol': 'BCH/ETH', 'base': 'BCH', 'quote': 'ETH'},
'BCH/USD': {'id': 'tBCHUSD', 'symbol': 'BCH/USD', 'base': 'BCH', 'quote': 'USD'},
'BCU/BTC': {'id': 'tBCUBTC', 'symbol': 'BCU/BTC', 'base': 'BCU', 'quote': 'BTC'},
'BCU/USD': {'id': 'tBCUUSD', 'symbol': 'BCU/USD', 'base': 'BCU', 'quote': 'USD'},
'BTC/USD': {'id': 'tBTCUSD', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'DASH/BTC': {'id': 'tDSHBTC', 'symbol': 'DASH/BTC', 'base': 'DASH', 'quote': 'BTC'},
'DASH/USD': {'id': 'tDSHUSD', 'symbol': 'DASH/USD', 'base': 'DASH', 'quote': 'USD'},
'EOS/BTC': {'id': 'tEOSBTC', 'symbol': 'EOS/BTC', 'base': 'EOS', 'quote': 'BTC'},
'EOS/ETH': {'id': 'tEOSETH', 'symbol': 'EOS/ETH', 'base': 'EOS', 'quote': 'ETH'},
'EOS/USD': {'id': 'tEOSUSD', 'symbol': 'EOS/USD', 'base': 'EOS', 'quote': 'USD'},
'ETC/BTC': {'id': 'tETCBTC', 'symbol': 'ETC/BTC', 'base': 'ETC', 'quote': 'BTC'},
'ETC/USD': {'id': 'tETCUSD', 'symbol': 'ETC/USD', 'base': 'ETC', 'quote': 'USD'},
'ETH/BTC': {'id': 'tETHBTC', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
'ETH/USD': {'id': 'tETHUSD', 'symbol': 'ETH/USD', 'base': 'ETH', 'quote': 'USD'},
'IOT/BTC': {'id': 'tIOTBTC', 'symbol': 'IOT/BTC', 'base': 'IOT', 'quote': 'BTC'},
'IOT/ETH': {'id': 'tIOTETH', 'symbol': 'IOT/ETH', 'base': 'IOT', 'quote': 'ETH'},
'IOT/USD': {'id': 'tIOTUSD', 'symbol': 'IOT/USD', 'base': 'IOT', 'quote': 'USD'},
'LTC/BTC': {'id': 'tLTCBTC', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'LTC/USD': {'id': 'tLTCUSD', 'symbol': 'LTC/USD', 'base': 'LTC', 'quote': 'USD'},
'OMG/BTC': {'id': 'tOMGBTC', 'symbol': 'OMG/BTC', 'base': 'OMG', 'quote': 'BTC'},
'OMG/ETH': {'id': 'tOMGETH', 'symbol': 'OMG/ETH', 'base': 'OMG', 'quote': 'ETH'},
'OMG/USD': {'id': 'tOMGUSD', 'symbol': 'OMG/USD', 'base': 'OMG', 'quote': 'USD'},
'RRT/BTC': {'id': 'tRRTBTC', 'symbol': 'RRT/BTC', 'base': 'RRT', 'quote': 'BTC'},
'RRT/USD': {'id': 'tRRTUSD', 'symbol': 'RRT/USD', 'base': 'RRT', 'quote': 'USD'},
'SAN/BTC': {'id': 'tSANBTC', 'symbol': 'SAN/BTC', 'base': 'SAN', 'quote': 'BTC'},
'SAN/ETH': {'id': 'tSANETH', 'symbol': 'SAN/ETH', 'base': 'SAN', 'quote': 'ETH'},
'SAN/USD': {'id': 'tSANUSD', 'symbol': 'SAN/USD', 'base': 'SAN', 'quote': 'USD'},
'XMR/BTC': {'id': 'tXMRBTC', 'symbol': 'XMR/BTC', 'base': 'XMR', 'quote': 'BTC'},
'XMR/USD': {'id': 'tXMRUSD', 'symbol': 'XMR/USD', 'base': 'XMR', 'quote': 'USD'},
'XRP/BTC': {'id': 'tXRPBTC', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC'},
'XRP/USD': {'id': 'tXRPUSD', 'symbol': 'XRP/USD', 'base': 'XRP', 'quote': 'USD'},
'ZEC/BTC': {'id': 'tZECBTC', 'symbol': 'ZEC/BTC', 'base': 'ZEC', 'quote': 'BTC'},
'ZEC/USD': {'id': 'tZECUSD', 'symbol': 'ZEC/USD', 'base': 'ZEC', 'quote': 'USD'},
},
}
params.update(config)
super(bitfinex2, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostAuthRWallets()
result = {'info': response}
for b in range(0, len(response)):
balance = response[b]
type, currency, total, interest, available = balance
if currency[0] == 't':
currency = currency[1:]
uppercase = currency.upper()
# issue #4 Bitfinex names Dash as DSH, instead of DASH
if uppercase == 'DSH':
uppercase = 'DASH'
account = self.account()
account['free'] = available
account['total'] = total
if account['free']:
account['used'] = account['total'] - account['free']
result[uppercase] = account
return result
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetBookSymbolPrecision(self.extend({
'symbol': self.market_id(symbol),
'precision': 'R0',
}, params))
timestamp = self.milliseconds()
result = {
'bids': [],
'asks': [],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
}
for i in range(0, len(orderbook)):
order = orderbook[i]
timestamp, price, amount = order
side = 'bids' if(amount > 0) else 'asks'
amount = abs(amount)
result[side].append([price, amount, timestamp])
result['bids'] = self.sort_by(result['bids'], 0, True)
result['asks'] = self.sort_by(result['asks'], 0)
return result
def fetch_ticker(self, symbol):
ticker = self.publicGetTickerSymbol({
'symbol': self.market_id(symbol),
})
timestamp = self.milliseconds()
bid, bidSize, ask, askSize, change, percentage, last, volume, high, low = ticker
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': high,
'low': low,
'bid': bid,
'ask': ask,
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': last,
'change': change,
'percentage': percentage,
'average': None,
'baseVolume': None,
'quoteVolume': volume,
'info': ticker,
}
def parse_trade(self, trade, market):
id, timestamp, amount, price = trade
side = 'sell' if(amount < 0) else 'buy'
return {
'id': str(id),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': price,
'amount': amount,
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTradesSymbolHist(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response, market)
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
market = self.market(symbol)
request = {
'symbol': market['id'],
'timeframe': self.timeframes[timeframe],
}
if limit:
request['limit'] = limit
if since:
request['start'] = since
request = self.extend(request, params)
response = self.publicGetCandlesTradeTimeframeSymbolHist(request)
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
market = self.market(symbol)
raise NotSupported(self.id + ' createOrder not implemented yet')
def cancel_order(self, id):
raise NotSupported(self.id + ' cancelOrder not implemented yet')
def fetch_order(self, id, params={}):
raise NotSupported(self.id + ' fetchOrder not implemented yet')
def withdraw(self, currency, amount, address, params={}):
raise NotSupported(self.id + ' withdraw not implemented yet')
def nonce(self):
return self.milliseconds()
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
request = self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
url = self.urls['api'] + '/' + request
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = str(self.nonce())
body = self.json(query)
auth = '/api' + '/' + request + nonce + body
signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha384)
headers = {
'bfx-nonce': nonce,
'bfx-apikey': self.apiKey,
'bfx-signature': signature,
'Content-Type': 'application/json',
}
response = self.fetch(url, method, headers, body)
if 'message' in response:
if response['message'].find('not enough exchange balance') >= 0:
raise InsufficientFunds(self.id + ' ' + self.json(response))
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class bitflyer (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitflyer',
'name': 'bitFlyer',
'countries': 'JP',
'version': 'v1',
'rateLimit': 500,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28051642-56154182-660e-11e7-9b0d-6042d1e6edd8.jpg',
'api': 'https://api.bitflyer.jp',
'www': 'https://bitflyer.jp',
'doc': 'https://bitflyer.jp/API',
},
'api': {
'public': {
'get': [
'getmarkets', # or 'markets'
'getboard', # or 'board'
'getticker', # or 'ticker'
'getexecutions', # or 'executions'
'gethealth',
'getchats',
],
},
'private': {
'get': [
'getpermissions',
'getbalance',
'getcollateral',
'getcollateralaccounts',
'getaddresses',
'getcoinins',
'getcoinouts',
'getbankaccounts',
'getdeposits',
'getwithdrawals',
'getchildorders',
'getparentorders',
'getparentorder',
'getexecutions',
'getpositions',
'gettradingcommission',
],
'post': [
'sendcoin',
'withdraw',
'sendchildorder',
'cancelchildorder',
'sendparentorder',
'cancelparentorder',
'cancelallchildorders',
],
},
},
}
params.update(config)
super(bitflyer, self).__init__(params)
self.fetch_market_data()
self.fetch_my_balance()
self.pre_order_id = self.fetch_pre_order_id()
self.min_lot_digit = 3
self.min_lot = 0.001
def fetch_pre_order_id(self):
trade_histry = self.privateGetExecutions()
if len(trade_histry) == 0:
return None
else:
return trade_histry[0]['child_order_acceptance_id']
def update_pre_order_id(self, order_id):
self.pre_order_id = order_id
def create_arb_market_buy_order(self, symbol, amount, params={}):
f_rt = self.create_order(symbol, 'market', 'buy', amount, None, params)
self.update_pre_order_id(f_rt['id'])
return f_rt
def create_arb_market_sell_order(self, symbol, amount, params={}):
f_rt = self.create_order(symbol, 'market', 'sell', amount, None, params)
self.update_pre_order_id(f_rt['id'])
return f_rt
def fetch_open_orders(self):
return self.privateGetChildorders(params={'child_order_state': 'ACTIVE'})
def fetch_markets(self):
markets = self.publicGetMarkets()
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['product_code']
currencies = id.split('_')
base = None
quote = None
symbol = id
numCurrencies = len(currencies)
if numCurrencies == 1:
base = symbol[0:3]
quote = symbol[3:6]
elif numCurrencies == 2:
base = currencies[0]
quote = currencies[1]
symbol = base + '/' + quote
else:
base = currencies[1]
quote = currencies[2]
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetBalance()
balances = {}
for b in range(0, len(response)):
account = response[b]
currency = account['currency_code']
balances[currency] = account
result = {'info': response}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in balances:
account['total'] = balances[currency]['amount']
account['free'] = balances[currency]['available']
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetBoard(self.extend({
'product_code': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook, None, 'bids', 'asks', 'price', 'size')
def fetch_ticker(self, symbol):
self.load_markets()
ticker = self.publicGetTicker({
'product_code': self.market_id(symbol),
})
timestamp = self.parse8601(ticker['timestamp'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': float(ticker['best_bid']),
'ask': float(ticker['best_ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['ltp']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['volume_by_product']),
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market=None):
side = None
order = None
if 'side' in trade:
if trade['side']:
side = trade['side'].lower()
id = side + '_child_order_acceptance_id'
if id in trade:
order = trade[id]
timestamp = self.parse8601(trade['exec_date'])
return {
'id': str(trade['id']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': order,
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['size'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetExecutions(self.extend({
'product_code': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'product_code': self.market_id(symbol),
'child_order_type': type.upper(),
'side': side.upper(),
'price': price,
'size': amount,
}
result = self.privatePostSendchildorder(self.extend(order, params))
return {
'info': result,
'id': result['child_order_acceptance_id'],
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privatePostCancelchildorder(self.extend({
'parent_order_id': id,
}, params))
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
response = self.privatePostWithdraw(self.extend({
'currency_code': currency,
'amount': amount,
# 'bank_account_id': 1234,
}, params))
return {
'info': response,
'id': response['message_id'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
request = '/' + self.version + '/'
if api == 'private':
request += 'me/'
request += path
if method == 'GET':
if params:
request += '?' + self.urlencode(params)
url = self.urls['api'] + request
if api == 'private':
nonce = str(self.nonce())
body = self.json(params)
auth = ''.join([nonce, method, request, body])
headers = {
'ACCESS-KEY': self.apiKey,
'ACCESS-TIMESTAMP': nonce,
'ACCESS-SIGN': self.hmac(self.encode(auth), str.encode(self.secret)),
'Content-Type': 'application/json',
}
return self.fetch(url, method, headers, body)
def is_content_encoding_gzip(self, exception):
for item in exception.headers.items():
if item[0] == 'Content-Encoding':
content_encoding = item[1]
return True if content_encoding == 'gzip' else False
return False
def get_err_details(self, exception):
import gzip
import json
gzip_data = gzip.GzipFile(fileobj=exception)
details = gzip_data.read().decode('utf-8')
gzip_data.close()
details = json.loads(details)
return details['error_message']
def handle_rest_errors(self, exception, http_status_code, response, url, method='GET'):
# bitflyerはnonceがないので、ApiNonceErrorはない
gzip_flg = self.is_content_encoding_gzip(exception)
error = None
details = response if response else None
if http_status_code == 429:
error = DDoSProtection
elif http_status_code in [404, 409, 422, 500, 501, 502, 520, 521, 522, 525]:
details = self.get_err_details(exception) if gzip_flg else exception.read().decode('utf-8', 'ignore') if exception else (str(http_status_code) + ' ' + response)
# details = exception.read().decode('utf-8', 'ignore') if exception else (str(http_status_code) + ' ' + response)
error = ExchangeNotAvailable
elif http_status_code in [400, 403, 405, 503]:
# special case to detect ddos protection
reason = self.get_err_details(exception) if gzip_flg else exception.read().decode('utf-8', 'ignore') if exception else response
# reason = exception.read().decode('utf-8', 'ignore') if exception else response
ddos_protection = re.search('(cloudflare|incapsula)', reason, flags=re.IGNORECASE)
if ddos_protection:
error = DDoSProtection
elif 'The minimum order size is' in reason:
error = ExchangeError
details = reason
elif 'Insufficient funds' in reason:
error = InsufficientFunds
details = reason
elif 'Invalid order amount' in reason:
error = ExchangeError
details = reason
else:
error = ExchangeNotAvailable
details = '(possible reasons: ' + ', '.join([
'invalid API keys',
'bad or old nonce',
'exchange is down or offline',
'on maintenance',
'DDoS protection',
'rate-limiting',
reason,
]) + ')'
elif http_status_code in [408, 504]:
error = RequestTimeout
elif http_status_code in [401, 511]:
error = AuthenticationError
if error:
self.raise_error(error, url, method, exception if exception else str(http_status_code), details)
def handle_rest_response(self, response, url, method='GET', headers=None, body=None):
try:
if (len(response) < 2):
# bitFlyerのcancel系の注文のときは空のresponseのため、追記
if 'cancel' in url:
return True
raise ExchangeError(self.id, ''.join([self.id, method, url, 'returned empty response']))
return json.loads(response)
except Exception as e:
ddos_protection = re.search('(cloudflare|incapsula)', response, flags=re.IGNORECASE)
exchange_not_available = re.search('(offline|busy|retry|wait|unavailable|maintain|maintenance|maintenancing)', response, flags=re.IGNORECASE)
if ddos_protection:
raise DDoSProtection(self.id, ' '.join([self.id, method, url, response]))
if exchange_not_available:
message = 'exchange downtime, exchange closed for maintenance or offline, DDoS protection or rate-limiting in effect'
raise ExchangeNotAvailable(self.id, ' '.join([
self.id,
method,
url,
response,
message,
]))
if isinstance(e, ValueError):
raise ExchangeError(self.id, ' '.join([self.id, method, url, response, str(e)]))
raise
#------------------------------------------------------------------------------
class bitlish (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitlish',
'name': 'bitlish',
'countries': ['GB', 'EU', 'RU'],
'rateLimit': 1500,
'version': 'v1',
'hasFetchTickers': True,
'hasFetchOHLCV': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766275-dcfc6c30-5ed3-11e7-839d-00a846385d0b.jpg',
'api': 'https://bitlish.com/api',
'www': 'https://bitlish.com',
'doc': 'https://bitlish.com/api',
},
'api': {
'public': {
'get': [
'instruments',
'ohlcv',
'pairs',
'tickers',
'trades_depth',
'trades_history',
],
'post': [
'instruments',
'ohlcv',
'pairs',
'tickers',
'trades_depth',
'trades_history',
],
},
'private': {
'post': [
'accounts_operations',
'balance',
'cancel_trade',
'cancel_trades_by_ids',
'cancel_all_trades',
'create_bcode',
'create_template_wallet',
'create_trade',
'deposit',
'list_accounts_operations_from_ts',
'list_active_trades',
'list_bcodes',
'list_my_matches_from_ts',
'list_my_trades',
'list_my_trads_from_ts',
'list_payment_methods',
'list_payments',
'redeem_code',
'resign',
'signin',
'signout',
'trade_details',
'trade_options',
'withdraw',
'withdraw_by_id',
],
},
},
}
params.update(config)
super(bitlish, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetPairs()
result = []
keys = list(markets.keys())
for p in range(0, len(keys)):
market = markets[keys[p]]
id = market['id']
symbol = market['name']
base, quote = symbol.split('/')
# issue #4 bitlish names Dash as DSH, instead of DASH
if base == 'DSH':
base = 'DASH'
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['max']),
'low': float(ticker['min']),
'bid': None,
'ask': None,
'vwap': None,
'open': None,
'close': None,
'first': float(ticker['first']),
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': None,
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGetTickers()
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
tickers = self.publicGetTickers()
ticker = tickers[market['id']]
return self.parse_ticker(ticker, market)
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
now = self.seconds()
start = now - 86400 * 30 # last 30 days
interval = [str(start), None]
return self.publicPostOhlcv(self.extend({
'time_range': interval,
}, params))
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetTradesDepth(self.extend({
'pair_id': self.market_id(symbol),
}, params))
timestamp = int(int(orderbook['last']) / 1000)
return self.parse_order_book(orderbook, timestamp, 'bid', 'ask', 'price', 'volume')
def parse_trade(self, trade, market=None):
side = 'buy' if(trade['dir'] == 'bid') else 'sell'
symbol = None
timestamp = int(trade['created'] / 1000)
return {
'id': None,
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': None,
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTradesHistory(self.extend({
'pair_id': market['id'],
}, params))
return self.parse_trades(response['list'], market)
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostBalance()
result = {'info': response}
currencies = list(response.keys())
balance = {}
for c in range(0, len(currencies)):
currency = currencies[c]
account = response[currency]
currency = currency.upper()
# issue #4 bitlish names Dash as DSH, instead of DASH
if currency == 'DSH':
currency = 'DASH'
balance[currency] = account
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in balance:
account['free'] = float(balance[currency]['funds'])
account['used'] = float(balance[currency]['holded'])
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def sign_in(self):
return self.privatePostSignin({
'login': self.login,
'passwd': self.password,
})
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'pair_id': self.market_id(symbol),
'dir': 'bid' if(side == 'buy') else 'ask',
'amount': amount,
}
if type == 'limit':
order['price'] = price
result = self.privatePostCreateTrade(self.extend(order, params))
return {
'info': result,
'id': result['id'],
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostCancelTrade({'id': id})
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
if currency != 'BTC':
# they did not document other types...
raise NotSupported(self.id + ' currently supports BTC withdrawals only, until they document other currencies...')
response = self.privatePostWithdraw(self.extend({
'currency': currency.lower(),
'amount': float(amount),
'account': address,
'payment_method': 'bitcoin', # they did not document other types...
}, params))
return {
'info': response,
'id': response['message_id'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + path
if api == 'public':
if method == 'GET':
if params:
url += '?' + self.urlencode(params)
else:
body = self.json(params)
headers = {'Content-Type': 'application/json'}
else:
body = self.json(self.extend({'token': self.apiKey}, params))
headers = {'Content-Type': 'application/json'}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class bitmarket (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitmarket',
'name': 'BitMarket',
'countries': ['PL', 'EU'],
'rateLimit': 1500,
'hasFetchOHLCV': True,
'hasWithdraw': True,
'timeframes': {
'90m': '90m',
'6h': '6h',
'1d': '1d',
'1w': '7d',
'1M': '1m',
'3M': '3m',
'6M': '6m',
'1y': '1y',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27767256-a8555200-5ef9-11e7-96fd-469a65e2b0bd.jpg',
'api': {
'public': 'https://www.bitmarket.net',
'private': 'https://www.bitmarket.pl/api2/', # last slash is critical
},
'www': [
'https://www.bitmarket.pl',
'https://www.bitmarket.net',
],
'doc': [
'https://www.bitmarket.net/docs.php?file=api_public.html',
'https://www.bitmarket.net/docs.php?file=api_private.html',
'https://github.com/bitmarket-net/api',
],
},
'api': {
'public': {
'get': [
'json/{market}/ticker',
'json/{market}/orderbook',
'json/{market}/trades',
'json/ctransfer',
'graphs/{market}/90m',
'graphs/{market}/6h',
'graphs/{market}/1d',
'graphs/{market}/7d',
'graphs/{market}/1m',
'graphs/{market}/3m',
'graphs/{market}/6m',
'graphs/{market}/1y',
],
},
'private': {
'post': [
'info',
'trade',
'cancel',
'orders',
'trades',
'history',
'withdrawals',
'tradingdesk',
'tradingdeskStatus',
'tradingdeskConfirm',
'cryptotradingdesk',
'cryptotradingdeskStatus',
'cryptotradingdeskConfirm',
'withdraw',
'withdrawFiat',
'withdrawPLNPP',
'withdrawFiatFast',
'deposit',
'transfer',
'transfers',
'marginList',
'marginOpen',
'marginClose',
'marginCancel',
'marginModify',
'marginBalanceAdd',
'marginBalanceRemove',
'swapList',
'swapOpen',
'swapClose',
],
},
},
'markets': {
'BTC/PLN': {'id': 'BTCPLN', 'symbol': 'BTC/PLN', 'base': 'BTC', 'quote': 'PLN'},
'BTC/EUR': {'id': 'BTCEUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
'LTC/PLN': {'id': 'LTCPLN', 'symbol': 'LTC/PLN', 'base': 'LTC', 'quote': 'PLN'},
'LTC/BTC': {'id': 'LTCBTC', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'LiteMineX/BTC': {'id': 'LiteMineXBTC', 'symbol': 'LiteMineX/BTC', 'base': 'LiteMineX', 'quote': 'BTC'},
'PlnX/BTC': {'id': 'PlnxBTC', 'symbol': 'PlnX/BTC', 'base': 'PlnX', 'quote': 'BTC'},
},
}
params.update(config)
super(bitmarket, self).__init__(params)
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostInfo()
data = response['data']
balance = data['balances']
result = {'info': data}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in balance['available']:
account['free'] = balance['available'][currency]
if currency in balance['blocked']:
account['used'] = balance['blocked'][currency]
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetJsonMarketOrderbook(self.extend({
'market': self.market_id(symbol),
}, params))
timestamp = self.milliseconds()
return {
'bids': orderbook['bids'],
'asks': orderbook['asks'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
}
def fetch_ticker(self, symbol):
ticker = self.publicGetJsonMarketTicker({
'market': self.market_id(symbol),
})
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': float(ticker['vwap']),
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market=None):
side = 'buy' if(trade['type'] == 'bid') else 'sell'
timestamp = trade['date'] * 1000
return {
'id': str(trade['tid']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': None,
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetJsonMarketTrades(self.extend({
'market': market['id'],
}, params))
return self.parse_trades(response, market)
def parse_ohlcv(self, ohlcv, market=None, timeframe='90m', since=None, limit=None):
return [
ohlcv['time'] * 1000,
float(ohlcv['open']),
float(ohlcv['high']),
float(ohlcv['low']),
float(ohlcv['close']),
float(ohlcv['vol']),
]
def fetch_ohlcv(self, symbol, timeframe='90m', since=None, limit=None, params={}):
self.load_markets()
method = 'publicGetGraphsMarket' + self.timeframes[timeframe]
market = self.market(symbol)
response = getattr(self, method)(self.extend({
'market': market['id'],
}, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
response = self.privatePostTrade(self.extend({
'market': self.market_id(symbol),
'type': side,
'amount': amount,
'rate': price,
}, params))
result = {
'info': response,
}
if 'id' in response['order']:
result['id'] = response['id']
return result
def cancel_order(self, id):
return self.privatePostCancel({'id': id})
def isFiat(self, currency):
if currency == 'EUR':
return True
if currency == 'PLN':
return True
return False
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
method = None
request = {
'currency': currency,
'quantity': amount,
}
if self.isFiat(currency):
method = 'privatePostWithdrawFiat'
if 'account' in params:
request['account'] = params['account'] # bank account code for withdrawal
else:
raise ExchangeError(self.id + ' requires account parameter to withdraw fiat currency')
if 'account2' in params:
request['account2'] = params['account2'] # bank SWIFT code(EUR only)
else:
if currency == 'EUR':
raise ExchangeError(self.id + ' requires account2 parameter to withdraw EUR')
if 'withdrawal_note' in params:
request['withdrawal_note'] = params['withdrawal_note'] # a 10-character user-specified withdrawal note(PLN only)
else:
if currency == 'PLN':
raise ExchangeError(self.id + ' requires withdrawal_note parameter to withdraw PLN')
else:
method = 'privatePostWithdraw'
request['address'] = address
response = getattr(self, method)(self.extend(request, params))
return {
'info': response,
'id': response,
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
if api == 'public':
url += '/' + self.implode_params(path + '.json', params)
else:
nonce = self.nonce()
query = self.extend({
'tonce': nonce,
'method': path,
}, params)
body = self.urlencode(query)
headers = {
'API-Key': self.apiKey,
'API-Hash': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class bitmex (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitmex',
'name': 'BitMEX',
'countries': 'SC', # Seychelles
'version': 'v1',
'rateLimit': 1500,
'hasFetchOHLCV': True,
'timeframes': {
'1m': '1m',
'5m': '5m',
'1h': '1h',
'1d': '1d',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766319-f653c6e6-5ed4-11e7-933d-f0bc3699ae8f.jpg',
'api': 'https://www.bitmex.com',
'www': 'https://www.bitmex.com',
'doc': [
'https://www.bitmex.com/app/apiOverview',
'https://github.com/BitMEX/api-connectors/tree/master/official-http',
],
},
'api': {
'public': {
'get': [
'announcement',
'announcement/urgent',
'funding',
'instrument',
'instrument/active',
'instrument/activeAndIndices',
'instrument/activeIntervals',
'instrument/compositeIndex',
'instrument/indices',
'insurance',
'leaderboard',
'liquidation',
'orderBook',
'orderBook/L2',
'quote',
'quote/bucketed',
'schema',
'schema/websocketHelp',
'settlement',
'stats',
'stats/history',
'trade',
'trade/bucketed',
],
},
'private': {
'get': [
'apiKey',
'chat',
'chat/channels',
'chat/connected',
'execution',
'execution/tradeHistory',
'notification',
'order',
'position',
'user',
'user/affiliateStatus',
'user/checkReferralCode',
'user/commission',
'user/depositAddress',
'user/margin',
'user/minWithdrawalFee',
'user/wallet',
'user/walletHistory',
'user/walletSummary',
],
'post': [
'apiKey',
'apiKey/disable',
'apiKey/enable',
'chat',
'order',
'order/bulk',
'order/cancelAllAfter',
'order/closePosition',
'position/isolate',
'position/leverage',
'position/riskLimit',
'position/transferMargin',
'user/cancelWithdrawal',
'user/confirmEmail',
'user/confirmEnableTFA',
'user/confirmWithdrawal',
'user/disableTFA',
'user/logout',
'user/logoutAll',
'user/preferences',
'user/requestEnableTFA',
'user/requestWithdrawal',
],
'put': [
'order',
'order/bulk',
'user',
],
'delete': [
'apiKey',
'order',
'order/all',
],
}
},
}
params.update(config)
super(bitmex, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetInstrumentActiveAndIndices()
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['symbol']
base = market['underlying']
quote = market['quoteCurrency']
isFuturesContract = id != (base + quote)
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = id if isFuturesContract else(base + '/' + quote)
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetUserMargin({'currency': 'all'})
result = {'info': response}
for b in range(0, len(response)):
balance = response[b]
currency = balance['currency'].upper()
currency = self.commonCurrencyCode(currency)
account = {
'free': balance['availableMargin'],
'used': 0.0,
'total': balance['amount'],
}
if currency == 'BTC':
account['free'] = account['free'] * 0.00000001
account['total'] = account['total'] * 0.00000001
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetOrderBookL2(self.extend({
'symbol': self.market_id(symbol),
}, params))
timestamp = self.milliseconds()
result = {
'bids': [],
'asks': [],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
}
for o in range(0, len(orderbook)):
order = orderbook[o]
side = 'asks' if(order['side'] == 'Sell') else 'bids'
amount = order['size']
price = order['price']
result[side].append([price, amount])
result['bids'] = self.sort_by(result['bids'], 0, True)
result['asks'] = self.sort_by(result['asks'], 0)
return result
def fetch_ticker(self, symbol):
self.load_markets()
request = {
'symbol': self.market_id(symbol),
'binSize': '1d',
'partial': True,
'count': 1,
'reverse': True,
}
quotes = self.publicGetQuoteBucketed(request)
quotesLength = len(quotes)
quote = quotes[quotesLength - 1]
tickers = self.publicGetTradeBucketed(request)
ticker = tickers[0]
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(quote['bidPrice']),
'ask': float(quote['askPrice']),
'vwap': float(ticker['vwap']),
'open': None,
'close': float(ticker['close']),
'first': None,
'last': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['homeNotional']),
'quoteVolume': float(ticker['foreignNotional']),
'info': ticker,
}
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
timestamp = self.parse8601(ohlcv['timestamp'])
return [
timestamp,
ohlcv['open'],
ohlcv['high'],
ohlcv['low'],
ohlcv['close'],
ohlcv['volume'],
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
# send JSON key/value pairs, such as {"key": "value"}
# filter by individual fields and do advanced queries on timestamps
filter = {'key': 'value'}
# send a bare series(e.g. XBU) to nearest expiring contract in that series
# you can also send a timeframe, e.g. XBU:monthly
# timeframes: daily, weekly, monthly, quarterly, and biquarterly
market = self.market(symbol)
request = {
'symbol': market['id'],
'binSize': self.timeframes[timeframe],
'partial': True, # True == include yet-incomplete current bins
# 'filter': filter, # filter by individual fields and do advanced queries
# 'columns': [], # will return all columns if omitted
# 'start': 0, # starting point for results(wtf?)
# 'reverse': False, # True == newest first
# 'endTime': '', # ending date filter for results
}
if since:
request['startTime'] = since # starting date filter for results
if limit:
request['count'] = limit # default 100
response = self.publicGetTradeBucketed(self.extend(request, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def parse_trade(self, trade, market=None):
timestamp = self.parse8601(trade['timestamp'])
symbol = None
if not market:
if 'symbol' in trade:
market = self.markets_by_id[trade['symbol']]
return {
'id': trade['trdMatchID'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': None,
'type': None,
'side': trade['side'].lower(),
'price': trade['price'],
'amount': trade['size'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTrade(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'symbol': self.market_id(symbol),
'side': self.capitalize(side),
'orderQty': amount,
'ordType': self.capitalize(type),
}
if type == 'limit':
order['rate'] = price
response = self.privatePostOrder(self.extend(order, params))
return {
'info': response,
'id': response['orderID'],
}
def cancel_order(self, id):
self.load_markets()
return self.privateDeleteOrder({'orderID': id})
def isFiat(self, currency):
if currency == 'EUR':
return True
if currency == 'PLN':
return True
return False
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
if currency != 'BTC':
raise ExchangeError(self.id + ' supoprts BTC withdrawals only, other currencies coming soon...')
request = {
'currency': 'XBt', # temporarily
'amount': amount,
'address': address,
# 'otpToken': '123456', # requires if two-factor auth(OTP) is enabled
# 'fee': 0.001, # bitcoin network fee
}
response = self.privatePostUserRequestWithdrawal(self.extend(request, params))
return {
'info': response,
'id': response['transactID'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
query = '/api' + '/' + self.version + '/' + path
if params:
query += '?' + self.urlencode(params)
url = self.urls['api'] + query
if api == 'private':
nonce = str(self.nonce())
if method == 'POST':
if params:
body = self.json(params)
request = ''.join([method, query, nonce, body or ''])
headers = {
'Content-Type': 'application/json',
'api-nonce': nonce,
'api-key': self.apiKey,
'api-signature': self.hmac(self.encode(request), self.encode(self.secret)),
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class bitso (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitso',
'name': 'Bitso',
'countries': 'MX', # Mexico
'rateLimit': 2000, # 30 requests per minute
'version': 'v3',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766335-715ce7aa-5ed5-11e7-88a8-173a27bb30fe.jpg',
'api': 'https://api.bitso.com',
'www': 'https://bitso.com',
'doc': 'https://bitso.com/api_info',
},
'api': {
'public': {
'get': [
'available_books',
'ticker',
'order_book',
'trades',
],
},
'private': {
'get': [
'account_status',
'balance',
'fees',
'fundings',
'fundings/{fid}',
'funding_destination',
'kyc_documents',
'ledger',
'ledger/trades',
'ledger/fees',
'ledger/fundings',
'ledger/withdrawals',
'mx_bank_codes',
'open_orders',
'order_trades/{oid}',
'orders/{oid}',
'user_trades',
'user_trades/{tid}',
'withdrawals/',
'withdrawals/{wid}',
],
'post': [
'bitcoin_withdrawal',
'debit_card_withdrawal',
'ether_withdrawal',
'orders',
'phone_number',
'phone_verification',
'phone_withdrawal',
'spei_withdrawal',
],
'delete': [
'orders/{oid}',
'orders/all',
],
}
},
}
params.update(config)
super(bitso, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetAvailableBooks()
result = []
for p in range(0, len(markets['payload'])):
market = markets['payload'][p]
id = market['book']
symbol = id.upper().replace('_', '/')
base, quote = symbol.split('/')
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetBalance()
balances = response['payload']['balances']
result = {'info': response}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency'].upper()
account = {
'free': float(balance['available']),
'used': float(balance['locked']),
'total': float(balance['total']),
}
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
response = self.publicGetOrderBook(self.extend({
'book': self.market_id(symbol),
}, params))
orderbook = response['payload']
timestamp = self.parse8601(orderbook['updated_at'])
return self.parse_order_book(orderbook, timestamp, 'bids', 'asks', 'price', 'amount')
def fetch_ticker(self, symbol):
self.load_markets()
response = self.publicGetTicker({
'book': self.market_id(symbol),
})
ticker = response['payload']
timestamp = self.parse8601(ticker['created_at'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': float(ticker['vwap']),
'open': None,
'close': None,
'first': None,
'last': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market=None):
timestamp = self.parse8601(trade['created_at'])
symbol = None
if not market:
if 'book' in trade:
market = self.markets_by_id[trade['book']]
return {
'id': str(trade['tid']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': None,
'type': None,
'side': trade['maker_side'],
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTrades(self.extend({
'book': self.market_id(market),
}, params))
return self.parse_trades(response['payload'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'book': self.market_id(symbol),
'side': side,
'type': type,
'major': amount,
}
if type == 'limit':
order['price'] = price
response = self.privatePostOrders(self.extend(order, params))
return {
'info': response,
'id': response['payload']['oid'],
}
def cancel_order(self, id):
self.load_markets()
return self.privateDeleteOrders({'oid': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
query = '/' + self.version + '/' + self.implode_params(path, params)
url = self.urls['api'] + query
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
if params:
body = self.json(params)
nonce = str(self.nonce())
request = ''.join([nonce, method, query, body or ''])
signature = self.hmac(self.encode(request), self.encode(self.secret))
auth = self.apiKey + ':' + nonce + ':' + signature
headers = {'Authorization': "Bitso " + auth}
response = self.fetch(url, method, headers, body)
if 'success' in response:
if response['success']:
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class bitstamp1 (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitstamp1',
'name': 'Bitstamp v1',
'countries': 'GB',
'rateLimit': 1000,
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27786377-8c8ab57e-5fe9-11e7-8ea4-2b05b6bcceec.jpg',
'api': 'https://www.bitstamp.net/api',
'www': 'https://www.bitstamp.net',
'doc': 'https://www.bitstamp.net/api',
},
'api': {
'public': {
'get': [
'ticker',
'ticker_hour',
'order_book',
'transactions',
'eur_usd',
],
},
'private': {
'post': [
'balance',
'user_transactions',
'open_orders',
'order_status',
'cancel_order',
'cancel_all_orders',
'buy',
'sell',
'bitcoin_deposit_address',
'unconfirmed_btc',
'ripple_withdrawal',
'ripple_address',
'withdrawal_requests',
'bitcoin_withdrawal',
],
},
},
'markets': {
'BTC/USD': {'id': 'btcusd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'BTC/EUR': {'id': 'btceur', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
'EUR/USD': {'id': 'eurusd', 'symbol': 'EUR/USD', 'base': 'EUR', 'quote': 'USD'},
'XRP/USD': {'id': 'xrpusd', 'symbol': 'XRP/USD', 'base': 'XRP', 'quote': 'USD'},
'XRP/EUR': {'id': 'xrpeur', 'symbol': 'XRP/EUR', 'base': 'XRP', 'quote': 'EUR'},
'XRP/BTC': {'id': 'xrpbtc', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC'},
'LTC/USD': {'id': 'ltcusd', 'symbol': 'LTC/USD', 'base': 'LTC', 'quote': 'USD'},
'LTC/EUR': {'id': 'ltceur', 'symbol': 'LTC/EUR', 'base': 'LTC', 'quote': 'EUR'},
'LTC/BTC': {'id': 'ltcbtc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'ETH/USD': {'id': 'ethusd', 'symbol': 'ETH/USD', 'base': 'ETH', 'quote': 'USD'},
'ETH/EUR': {'id': 'etheur', 'symbol': 'ETH/EUR', 'base': 'ETH', 'quote': 'EUR'},
'ETH/BTC': {'id': 'ethbtc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
},
}
params.update(config)
super(bitstamp1, self).__init__(params)
def fetch_order_book(self, symbol, params={}):
if symbol != 'BTC/USD':
raise ExchangeError(self.id + ' ' + self.version + " fetchOrderBook doesn't support " + symbol + ', use it for BTC/USD only')
orderbook = self.publicGetOrderBook(params)
timestamp = int(orderbook['timestamp']) * 1000
return self.parse_order_book(orderbook, timestamp)
def fetch_ticker(self, symbol):
if symbol != 'BTC/USD':
raise ExchangeError(self.id + ' ' + self.version + " fetchTicker doesn't support " + symbol + ', use it for BTC/USD only')
ticker = self.publicGetTicker()
timestamp = int(ticker['timestamp']) * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': float(ticker['vwap']),
'open': float(ticker['open']),
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market=None):
timestamp = None
if 'date' in trade:
timestamp = int(trade['date'])
elif 'datetime' in trade:
# timestamp = self.parse8601(trade['datetime'])
timestamp = int(trade['datetime'])
side = 'buy' if(trade['type'] == 0) else 'sell'
order = None
if 'order_id' in trade:
order = str(trade['order_id'])
if 'currency_pair' in trade:
if trade['currency_pair'] in self.markets_by_id:
market = self.markets_by_id[trade['currency_pair']]
return {
'id': str(trade['tid']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': order,
'type': None,
'side': side,
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
if symbol != 'BTC/USD':
raise ExchangeError(self.id + ' ' + self.version + " fetchTrades doesn't support " + symbol + ', use it for BTC/USD only')
market = self.market(symbol)
response = self.publicGetTransactions(self.extend({
'time': 'minute',
}, params))
return self.parse_trades(response, market)
def fetch_balance(self, params={}):
balance = self.privatePostBalance()
result = {'info': balance}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
total = lowercase + '_balance'
free = lowercase + '_available'
used = lowercase + '_reserved'
account = self.account()
account['free'] = self.safe_float(balance, free, 0.0)
account['used'] = self.safe_float(balance, used, 0.0)
account['total'] = self.safe_float(balance, total, 0.0)
result[currency] = account
return result
def create_order(self, symbol, type, side, amount, price=None, params={}):
if type != 'limit':
raise ExchangeError(self.id + ' ' + self.version + ' accepts limit orders only')
method = 'privatePost' + self.capitalize(side)
order = {
'id': self.market_id(symbol),
'amount': amount,
'price': price,
}
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id):
return self.privatePostCancelOrder({'id': id})
def parse_orderStatus(self, order):
if(order['status'] == 'Queue') or(order['status'] == 'Open'):
return 'open'
if order['status'] == 'Finished':
return 'closed'
return order['status']
def fetch_order_status(self, id, symbol=None):
self.load_markets()
response = self.privatePostOrderStatus({'id': id})
return self.parseOrderStatus(response)
def fetch_my_trades(self, symbol=None, params={}):
self.load_markets()
market = None
if symbol:
market = self.market(symbol)
pair = market['id'] if market else 'all'
request = self.extend({'id': pair}, params)
response = self.privatePostOpenOrdersId(request)
result = self.parse_trades(response, market)
def fetch_order(self, id):
raise NotSupported(self.id + ' fetchOrder is not implemented yet')
self.load_markets()
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
if not self.uid:
raise AuthenticationError(self.id + ' requires `' + self.id + '.uid` property for authentication')
nonce = str(self.nonce())
auth = nonce + self.uid + self.apiKey
signature = self.encode(self.hmac(self.encode(auth), self.encode(self.secret)))
query = self.extend({
'key': self.apiKey,
'signature': signature.upper(),
'nonce': nonce,
}, query)
body = self.urlencode(query)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
response = self.fetch(url, method, headers, body)
if 'status' in response:
if response['status'] == 'error':
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class bitstamp (Exchange):
def __init__(self, config={}):
params = {
'id': 'bitstamp',
'name': 'Bitstamp',
'countries': 'GB',
'rateLimit': 1000,
'version': 'v2',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27786377-8c8ab57e-5fe9-11e7-8ea4-2b05b6bcceec.jpg',
'api': 'https://www.bitstamp.net/api',
'www': 'https://www.bitstamp.net',
'doc': 'https://www.bitstamp.net/api',
},
'api': {
'public': {
'get': [
'order_book/{pair}/',
'ticker_hour/{pair}/',
'ticker/{pair}/',
'transactions/{pair}/',
],
},
'private': {
'post': [
'balance/',
'balance/{pair}/',
'user_transactions/',
'user_transactions/{pair}/',
'open_orders/all/',
'open_orders/{pair}',
'cancel_order/',
'buy/{pair}/',
'buy/market/{pair}/',
'sell/{pair}/',
'sell/market/{pair}/',
'ltc_withdrawal',
'ltc_address',
'eth_withdrawal',
'eth_address',
'transfer-to-main/',
'transfer-from-main/',
'xrp_withdrawal/',
'xrp_address/',
'withdrawal/open/',
'withdrawal/status/',
'withdrawal/cancel/',
'liquidation_address/new/',
'liquidation_address/info/',
],
},
},
'markets': {
'BTC/USD': {'id': 'btcusd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'BTC/EUR': {'id': 'btceur', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
'EUR/USD': {'id': 'eurusd', 'symbol': 'EUR/USD', 'base': 'EUR', 'quote': 'USD'},
'XRP/USD': {'id': 'xrpusd', 'symbol': 'XRP/USD', 'base': 'XRP', 'quote': 'USD'},
'XRP/EUR': {'id': 'xrpeur', 'symbol': 'XRP/EUR', 'base': 'XRP', 'quote': 'EUR'},
'XRP/BTC': {'id': 'xrpbtc', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC'},
'LTC/USD': {'id': 'ltcusd', 'symbol': 'LTC/USD', 'base': 'LTC', 'quote': 'USD'},
'LTC/EUR': {'id': 'ltceur', 'symbol': 'LTC/EUR', 'base': 'LTC', 'quote': 'EUR'},
'LTC/BTC': {'id': 'ltcbtc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'ETH/USD': {'id': 'ethusd', 'symbol': 'ETH/USD', 'base': 'ETH', 'quote': 'USD'},
'ETH/EUR': {'id': 'etheur', 'symbol': 'ETH/EUR', 'base': 'ETH', 'quote': 'EUR'},
'ETH/BTC': {'id': 'ethbtc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
},
}
params.update(config)
super(bitstamp, self).__init__(params)
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetOrderBookPair(self.extend({
'pair': self.market_id(symbol),
}, params))
timestamp = int(orderbook['timestamp']) * 1000
return self.parse_order_book(orderbook, timestamp)
def fetch_ticker(self, symbol):
ticker = self.publicGetTickerPair({
'pair': self.market_id(symbol),
})
timestamp = int(ticker['timestamp']) * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': float(ticker['vwap']),
'open': float(ticker['open']),
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market=None):
timestamp = None
if 'date' in trade:
timestamp = int(trade['date'])
elif 'datetime' in trade:
# timestamp = self.parse8601(trade['datetime'])
timestamp = int(trade['datetime'])
side = 'buy' if(trade['type'] == 0) else 'sell'
order = None
if 'order_id' in trade:
order = str(trade['order_id'])
if 'currency_pair' in trade:
if trade['currency_pair'] in self.markets_by_id:
market = self.markets_by_id[trade['currency_pair']]
return {
'id': str(trade['tid']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': order,
'type': None,
'side': side,
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTransactionsPair(self.extend({
'pair': market['id'],
'time': 'minute',
}, params))
return self.parse_trades(response, market)
def fetch_balance(self, params={}):
balance = self.privatePostBalance()
result = {'info': balance}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
total = lowercase + '_balance'
free = lowercase + '_available'
used = lowercase + '_reserved'
account = self.account()
if free in balance:
account['free'] = float(balance[free])
if used in balance:
account['used'] = float(balance[used])
if total in balance:
account['total'] = float(balance[total])
result[currency] = account
return result
def create_order(self, symbol, type, side, amount, price=None, params={}):
method = 'privatePost' + self.capitalize(side)
order = {
'pair': self.market_id(symbol),
'amount': amount,
}
if type == 'market':
method += 'Market'
else:
order['price'] = price
method += 'Pair'
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id):
return self.privatePostCancelOrder({'id': id})
def parse_orderStatus(self, order):
if(order['status'] == 'Queue') or(order['status'] == 'Open'):
return 'open'
if order['status'] == 'Finished':
return 'closed'
return order['status']
def fetch_order_status(self, id, symbol=None):
self.load_markets()
response = self.privatePostOrderStatus({'id': id})
return self.parseOrderStatus(response)
def fetch_my_trades(self, symbol=None, params={}):
self.load_markets()
market = None
if symbol:
market = self.market(symbol)
pair = market['id'] if market else 'all'
request = self.extend({'pair': pair}, params)
response = self.privatePostOpenOrdersPair(request)
result = self.parse_trades(response, market)
def fetch_order(self, id):
raise NotSupported(self.id + ' fetchOrder is not implemented yet')
self.load_markets()
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
if not self.uid:
raise AuthenticationError(self.id + ' requires `' + self.id + '.uid` property for authentication')
nonce = str(self.nonce())
auth = nonce + self.uid + self.apiKey
signature = self.encode(self.hmac(self.encode(auth), self.encode(self.secret)))
query = self.extend({
'key': self.apiKey,
'signature': signature.upper(),
'nonce': nonce,
}, query)
body = self.urlencode(query)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
response = self.fetch(url, method, headers, body)
if 'status' in response:
if response['status'] == 'error':
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class bittrex (Exchange):
def __init__(self, config={}):
params = {
'id': 'bittrex',
'name': 'Bittrex',
'countries': 'US',
'version': 'v1.1',
'rateLimit': 1500,
'hasFetchTickers': True,
'hasFetchOHLCV': True,
'hasFetchOrders': True,
'hasFetchOpenOrders': True,
'timeframes': {
'1m': 'oneMin',
'5m': 'fiveMin',
'30m': 'thirtyMin',
'1h': 'hour',
'1d': 'day',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766352-cf0b3c26-5ed5-11e7-82b7-f3826b7a97d8.jpg',
'api': {
'public': 'https://bittrex.com/api',
'account': 'https://bittrex.com/api',
'market': 'https://bittrex.com/api',
'v2': 'https://bittrex.com/api/v2.0/pub',
},
'www': 'https://bittrex.com',
'doc': [
'https://bittrex.com/Home/Api',
'https://www.npmjs.org/package/node.bittrex.api',
],
},
'api': {
'v2': {
'get': [
'currencies/GetBTCPrice',
'market/GetTicks',
'market/GetLatestTick',
'Markets/GetMarketSummaries',
'market/GetLatestTick',
],
},
'public': {
'get': [
'currencies',
'markethistory',
'markets',
'marketsummaries',
'marketsummary',
'orderbook',
'ticker',
],
},
'account': {
'get': [
'balance',
'balances',
'depositaddress',
'deposithistory',
'order',
'orderhistory',
'withdrawalhistory',
'withdraw',
],
},
'market': {
'get': [
'buylimit',
'buymarket',
'cancel',
'openorders',
'selllimit',
'sellmarket',
],
},
},
}
params.update(config)
super(bittrex, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetMarkets()
result = []
for p in range(0, len(markets['result'])):
market = markets['result'][p]
id = market['MarketName']
base = market['MarketCurrency']
quote = market['BaseCurrency']
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.accountGetBalances()
balances = response['result']
result = {'info': balances}
indexed = self.index_by(balances, 'Currency')
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in indexed:
balance = indexed[currency]
account['free'] = balance['Available']
account['used'] = balance['Balance'] - balance['Available']
account['total'] = balance['Balance']
result[currency] = account
return result
def fetch_order_book(self, market, params={}):
self.load_markets()
response = self.publicGetOrderbook(self.extend({
'market': self.market_id(market),
'type': 'both',
'depth': 50,
}, params))
orderbook = response['result']
return self.parse_order_book(orderbook, None, 'buy', 'sell', 'Rate', 'Quantity')
def parse_ticker(self, ticker, market):
timestamp = self.parse8601(ticker['TimeStamp'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['High']),
'low': float(ticker['Low']),
'bid': float(ticker['Bid']),
'ask': float(ticker['Ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['Last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['BaseVolume']),
'quoteVolume': float(ticker['Volume']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
response = self.publicGetMarketsummaries()
tickers = response['result']
result = {}
for t in range(0, len(tickers)):
ticker = tickers[t]
id = ticker['MarketName']
market = None
symbol = id
if id in self.markets_by_id:
market = self.markets_by_id[id]
symbol = market['symbol']
else:
quote, base = id.split('-')
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
response = self.publicGetMarketsummary({
'market': market['id'],
})
ticker = response['result'][0]
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market=None):
timestamp = self.parse8601(trade['TimeStamp'])
side = None
if trade['OrderType'] == 'BUY':
side = 'buy'
elif trade['OrderType'] == 'SELL':
side = 'sell'
type = None
id = None
if 'Id' in trade:
id = str(trade['Id'])
return {
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': trade['Price'],
'amount': trade['Quantity'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetMarkethistory(self.extend({
'market': market['id'],
}, params))
return self.parse_trades(response['result'], market)
def parse_ohlcv(self, ohlcv, market=None, timeframe='1d', since=None, limit=None):
timestamp = self.parse8601(ohlcv['T'])
return [
timestamp,
ohlcv['O'],
ohlcv['H'],
ohlcv['L'],
ohlcv['C'],
ohlcv['V'],
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'tickInterval': self.timeframes[timeframe],
'marketName': market['id'],
}
response = self.v2GetMarketGetTicks(self.extend(request, params))
return self.parse_ohlcvs(response['result'], market, timeframe, since, limit)
def fetch_open_orders(self, symbol=None, params={}):
self.load_markets()
request = {}
market = None
if symbol:
market = self.market(symbol)
request['market'] = market['id']
response = self.marketGetOpenorders(self.extend(request, params))
return self.parse_orders(response['result'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
method = 'marketGet' + self.capitalize(side) + type
order = {
'market': self.market_id(symbol),
'quantity': amount,
}
if type == 'limit':
order['rate'] = price
response = getattr(self, method)(self.extend(order, params))
result = {
'info': response,
'id': response['result']['uuid'],
}
return result
def cancel_order(self, id):
self.load_markets()
return self.marketGetCancel({'uuid': id})
def parse_order(self, order, market=None):
side = None
if 'OrderType' in order:
side = 'buy' if(order['OrderType'] == 'LIMIT_BUY') else 'sell'
if 'Type' in order:
side = 'buy' if(order['Type'] == 'LIMIT_BUY') else 'sell'
status = 'open'
if order['Closed']:
status = 'closed'
elif order['CancelInitiated']:
status = 'canceled'
symbol = None
if market:
symbol = market['symbol']
else:
exchange = order['Exchange']
if exchange in self.markets_by_id:
market = self.markets_by_id[exchange]
symbol = market['symbol']
timestamp = None
if 'Opened' in order:
timestamp = self.parse8601(order['Opened'])
if 'TimeStamp' in order:
timestamp = self.parse8601(order['TimeStamp'])
amount = order['Quantity']
remaining = order['QuantityRemaining']
filled = amount - remaining
result = {
'info': order,
'id': order['OrderUuid'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'type': 'limit',
'side': side,
'price': order['Price'],
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
}
return result
def fetch_order(self, id):
self.load_markets()
response = self.accountGetOrder({'uuid': id})
return self.parse_order(response['result'])
def fetch_orders(self, params={}):
self.load_markets()
response = self.accountGetOrderhistory(params)
return self.parse_orders(response['result'])
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
response = self.accountGetWithdraw(self.extend({
'currency': currency,
'quantity': amount,
'address': address,
}, params))
return {
'info': response,
'id': response['result']['uuid'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api] + '/'
if api != 'v2':
url += self.version + '/'
if api == 'public':
url += api + '/' + method.lower() + path
if params:
url += '?' + self.urlencode(params)
elif api == 'v2':
url += path
if params:
url += '?' + self.urlencode(params)
else:
nonce = self.nonce()
url += api + '/'
if((api == 'account') and(path != 'withdraw')) or(path == 'openorders'):
url += method.lower()
url += path + '?' + self.urlencode(self.extend({
'nonce': nonce,
'apikey': self.apiKey,
}, params))
signature = self.hmac(self.encode(url), self.encode(self.secret), hashlib.sha512)
headers = {'apisign': signature}
response = self.fetch(url, method, headers, body)
if 'success' in response:
if response['success']:
return response
if 'message' in response:
if response['message'] == "INSUFFICIENT_FUNDS":
raise InsufficientFunds(self.id + ' ' + self.json(response))
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class blinktrade (Exchange):
def __init__(self, config={}):
params = {
'id': 'blinktrade',
'name': 'BlinkTrade',
'countries': ['US', 'VE', 'VN', 'BR', 'PK', 'CL'],
'rateLimit': 1000,
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27990968-75d9c884-6470-11e7-9073-46756c8e7e8c.jpg',
'api': {
'public': 'https://api.blinktrade.com/api',
'private': 'https://api.blinktrade.com/tapi',
},
'www': 'https://blinktrade.com',
'doc': 'https://blinktrade.com/docs',
},
'api': {
'public': {
'get': [
'{currency}/ticker', # ?crypto_currency=BTC
'{currency}/orderbook', # ?crypto_currency=BTC
'{currency}/trades', # ?crypto_currency=BTC&since=<TIMESTAMP>&limit=<NUMBER>
],
},
'private': {
'post': [
'D', # order
'F', # cancel order
'U2', # balance
'U4', # my orders
'U6', # withdraw
'U18', # deposit
'U24', # confirm withdrawal
'U26', # list withdrawals
'U30', # list deposits
'U34', # ledger
'U70', # cancel withdrawal
],
},
},
'markets': {
'BTC/VEF': {'id': 'BTCVEF', 'symbol': 'BTC/VEF', 'base': 'BTC', 'quote': 'VEF', 'brokerId': 1, 'broker': 'SurBitcoin'},
'BTC/VND': {'id': 'BTCVND', 'symbol': 'BTC/VND', 'base': 'BTC', 'quote': 'VND', 'brokerId': 3, 'broker': 'VBTC'},
'BTC/BRL': {'id': 'BTCBRL', 'symbol': 'BTC/BRL', 'base': 'BTC', 'quote': 'BRL', 'brokerId': 4, 'broker': 'FoxBit'},
'BTC/PKR': {'id': 'BTCPKR', 'symbol': 'BTC/PKR', 'base': 'BTC', 'quote': 'PKR', 'brokerId': 8, 'broker': 'UrduBit'},
'BTC/CLP': {'id': 'BTCCLP', 'symbol': 'BTC/CLP', 'base': 'BTC', 'quote': 'CLP', 'brokerId': 9, 'broker': 'ChileBit'},
},
}
params.update(config)
super(blinktrade, self).__init__(params)
def fetch_balance(self, params={}):
return self.privatePostU2({
'BalanceReqID': self.nonce(),
})
def fetch_order_book(self, symbol, params={}):
market = self.market(symbol)
orderbook = self.publicGetCurrencyOrderbook(self.extend({
'currency': market['quote'],
'crypto_currency': market['base'],
}, params))
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
market = self.market(symbol)
ticker = self.publicGetCurrencyTicker({
'currency': market['quote'],
'crypto_currency': market['base'],
})
timestamp = self.milliseconds()
lowercaseQuote = market['quote'].lower()
quoteVolume = 'vol_' + lowercaseQuote
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['vol']),
'quoteVolume': float(ticker[quoteVolume]),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['date'] * 1000
return {
'id': trade['tid'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['side'],
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetCurrencyTrades(self.extend({
'currency': market['quote'],
'crypto_currency': market['base'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
market = self.market(symbol)
order = {
'ClOrdID': self.nonce(),
'Symbol': market['id'],
'Side': self.capitalize(side),
'OrdType': '2',
'Price': price,
'OrderQty': amount,
'BrokerID': market['brokerId'],
}
response = self.privatePostD(self.extend(order, params))
indexed = self.index_by(response['Responses'], 'MsgType')
execution = indexed['8']
return {
'info': response,
'id': execution['OrderID'],
}
def cancel_order(self, id, params={}):
return self.privatePostF(self.extend({
'ClOrdID': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api] + '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = str(self.nonce())
request = self.extend({'MsgType': path}, query)
body = self.json(request)
headers = {
'APIKey': self.apiKey,
'Nonce': nonce,
'Signature': self.hmac(self.encode(nonce), self.encode(self.secret)),
'Content-Type': 'application/json',
}
response = self.fetch(url, method, headers, body)
if 'Status' in response:
if response['Status'] != 200:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class bl3p (Exchange):
def __init__(self, config={}):
params = {
'id': 'bl3p',
'name': 'BL3P',
'countries': ['NL', 'EU'], # Netherlands, EU
'rateLimit': 1000,
'version': '1',
'comment': 'An exchange market by BitonicNL',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28501752-60c21b82-6feb-11e7-818b-055ee6d0e754.jpg',
'api': 'https://api.bl3p.eu',
'www': [
'https://bl3p.eu',
'https://bitonic.nl',
],
'doc': [
'https://github.com/BitonicNL/bl3p-api/tree/master/docs',
'https://bl3p.eu/api',
'https://bitonic.nl/en/api',
],
},
'api': {
'public': {
'get': [
'{market}/ticker',
'{market}/orderbook',
'{market}/trades',
],
},
'private': {
'post': [
'{market}/money/depth/full',
'{market}/money/order/add',
'{market}/money/order/cancel',
'{market}/money/order/result',
'{market}/money/orders',
'{market}/money/orders/history',
'{market}/money/trades/fetch',
'GENMKT/money/info',
'GENMKT/money/deposit_address',
'GENMKT/money/new_deposit_address',
'GENMKT/money/wallet/history',
'GENMKT/money/withdraw',
],
},
},
'markets': {
'BTC/EUR': {'id': 'BTCEUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
'LTC/EUR': {'id': 'LTCEUR', 'symbol': 'LTC/EUR', 'base': 'LTC', 'quote': 'EUR'},
},
}
params.update(config)
super(bl3p, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostGENMKTMoneyInfo()
data = response['data']
balance = data['wallets']
result = {'info': data}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in balance:
if 'available' in balance[currency]:
account['free'] = float(balance[currency]['available']['value'])
if currency in balance:
if 'balance' in balance[currency]:
account['total'] = float(balance[currency]['balance']['value'])
if account['total']:
if account['free']:
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def parse_bidask(self, bidask, priceKey=0, amountKey=0):
return [
bidask['price_int'] / 100000.0,
bidask['amount_int'] / 100000000.0,
]
def fetch_order_book(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetMarketOrderbook(self.extend({
'market': market['id'],
}, params))
orderbook = response['data']
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
ticker = self.publicGetMarketTicker({
'market': self.market_id(symbol),
})
timestamp = ticker['timestamp'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']['24h']),
'info': ticker,
}
def parse_trade(self, trade, market):
return {
'id': trade['trade_id'],
'info': trade,
'timestamp': trade['date'],
'datetime': self.iso8601(trade['date']),
'symbol': market['symbol'],
'type': None,
'side': None,
'price': trade['price_int'] / 100000.0,
'amount': trade['amount_int'] / 100000000.0,
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetMarketTrades(self.extend({
'market': market['id'],
}, params))
result = self.parse_trades(response['data']['trades'], market)
return result
def create_order(self, symbol, type, side, amount, price=None, params={}):
market = self.market(symbol)
order = {
'market': market['id'],
'amount_int': amount,
'fee_currency': market['quote'],
'type': 'bid' if(side == 'buy') else 'ask',
}
if type == 'limit':
order['price_int'] = price
response = self.privatePostMarketMoneyOrderAdd(self.extend(order, params))
return {
'info': response,
'id': str(response['order_id']),
}
def cancel_order(self, id):
return self.privatePostMarketMoneyOrderCancel({'order_id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
request = self.implode_params(path, params)
url = self.urls['api'] + '/' + self.version + '/' + request
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
body = self.urlencode(self.extend({'nonce': nonce}, query))
secret = base64.b64decode(self.secret)
auth = request + "\0" + body
signature = self.hmac(self.encode(auth), secret, hashlib.sha512, 'base64')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': len(body),
'Rest-Key': self.apiKey,
'Rest-Sign': signature,
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class bleutrade (bittrex):
def __init__(self, config={}):
params = {
'id': 'bleutrade',
'name': 'Bleutrade',
'countries': 'BR', # Brazil
'rateLimit': 1000,
'version': 'v2',
'hasFetchTickers': True,
'hasFetchOHLCV': False,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/30303000-b602dbe6-976d-11e7-956d-36c5049c01e7.jpg',
'api': {
'public': 'https://bleutrade.com/api',
'account': 'https://bleutrade.com/api',
'market': 'https://bleutrade.com/api',
},
'www': 'https://bleutrade.com',
'doc': 'https://bleutrade.com/help/API',
},
}
params.update(config)
super(bleutrade, self).__init__(params)
def fetch_order_book(self, market, params={}):
self.load_markets()
response = self.publicGetOrderbook(self.extend({
'market': self.market_id(market),
'type': 'ALL',
'depth': 50,
}, params))
orderbook = response['result']
return self.parse_order_book(orderbook, None, 'buy', 'sell', 'Rate', 'Quantity')
#------------------------------------------------------------------------------
class btcchina (Exchange):
def __init__(self, config={}):
params = {
'id': 'btcchina',
'name': 'BTCChina',
'countries': 'CN',
'rateLimit': 1500,
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766368-465b3286-5ed6-11e7-9a11-0f6467e1d82b.jpg',
'api': {
'plus': 'https://plus-api.btcchina.com/market',
'public': 'https://data.btcchina.com/data',
'private': 'https://api.btcchina.com/api_trade_v1.php',
},
'www': 'https://www.btcchina.com',
'doc': 'https://www.btcchina.com/apidocs'
},
'api': {
'plus': {
'get': [
'orderbook',
'ticker',
'trade',
],
},
'public': {
'get': [
'historydata',
'orderbook',
'ticker',
'trades',
],
},
'private': {
'post': [
'BuyIcebergOrder',
'BuyOrder',
'BuyOrder2',
'BuyStopOrder',
'CancelIcebergOrder',
'CancelOrder',
'CancelStopOrder',
'GetAccountInfo',
'getArchivedOrder',
'getArchivedOrders',
'GetDeposits',
'GetIcebergOrder',
'GetIcebergOrders',
'GetMarketDepth',
'GetMarketDepth2',
'GetOrder',
'GetOrders',
'GetStopOrder',
'GetStopOrders',
'GetTransactions',
'GetWithdrawal',
'GetWithdrawals',
'RequestWithdrawal',
'SellIcebergOrder',
'SellOrder',
'SellOrder2',
'SellStopOrder',
],
},
},
'markets': {
'BTC/CNY': {'id': 'btccny', 'symbol': 'BTC/CNY', 'base': 'BTC', 'quote': 'CNY', 'api': 'public', 'plus': False},
'LTC/CNY': {'id': 'ltccny', 'symbol': 'LTC/CNY', 'base': 'LTC', 'quote': 'CNY', 'api': 'public', 'plus': False},
'LTC/BTC': {'id': 'ltcbtc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC', 'api': 'public', 'plus': False},
'BCH/CNY': {'id': 'bcccny', 'symbol': 'BCH/CNY', 'base': 'BCH', 'quote': 'CNY', 'api': 'plus', 'plus': True},
'ETH/CNY': {'id': 'ethcny', 'symbol': 'ETH/CNY', 'base': 'ETH', 'quote': 'CNY', 'api': 'plus', 'plus': True},
},
}
params.update(config)
super(btcchina, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetTicker({
'market': 'all',
})
result = []
keys = list(markets.keys())
for p in range(0, len(keys)):
key = keys[p]
market = markets[key]
parts = key.split('_')
id = parts[1]
base = id[0:3]
quote = id[3:6]
base = base.upper()
quote = quote.upper()
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostGetAccountInfo()
balances = response['result']
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = self.account()
if lowercase in balances['balance']:
account['total'] = float(balances['balance'][lowercase]['amount'])
if lowercase in balances['frozen']:
account['used'] = float(balances['frozen'][lowercase]['amount'])
account['free'] = account['total'] - account['used']
result[currency] = account
return result
def createMarketRequest(self, market):
request = {}
field = 'symbol' if(market['plus']) else 'market'
request[field] = market['id']
return request
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
method = market['api'] + 'GetOrderbook'
request = self.createMarketRequest(market)
orderbook = getattr(self, method)(self.extend(request, params))
timestamp = orderbook['date'] * 1000
result = self.parse_order_book(orderbook, timestamp)
result['asks'] = self.sort_by(result['asks'], 0)
return result
def parse_ticker(self, ticker, market):
timestamp = ticker['date'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': float(ticker['vwap']),
'open': float(ticker['open']),
'close': float(ticker['prev_close']),
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['vol']),
'quoteVolume': None,
'info': ticker,
}
def parse_tickerPlus(self, ticker, market):
timestamp = ticker['Timestamp']
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['High']),
'low': float(ticker['Low']),
'bid': float(ticker['BidPrice']),
'ask': float(ticker['AskPrice']),
'vwap': None,
'open': float(ticker['Open']),
'close': float(ticker['PrevCls']),
'first': None,
'last': float(ticker['Last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['Volume24H']),
'quoteVolume': None,
'info': ticker,
}
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
method = market['api'] + 'GetTicker'
request = self.createMarketRequest(market)
tickers = getattr(self, method)(request)
ticker = tickers['ticker']
if market['plus']:
return self.parseTickerPlus(ticker, market)
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = int(trade['date']) * 1000
return {
'id': trade['tid'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': None,
'price': trade['price'],
'amount': trade['amount'],
}
def parse_tradePlus(self, trade, market):
timestamp = self.parse8601(trade['timestamp'])
return {
'id': None,
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['side'].lower(),
'price': trade['price'],
'amount': trade['size'],
}
def parse_tradesPlus(self, trades, market=None):
result = []
for i in range(0, len(trades)):
result.append(self.parseTradePlus(trades[i], market))
return result
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
method = market['api'] + 'GetTrade'
request = self.createMarketRequest(market)
if market['plus']:
now = self.milliseconds()
request['start_time'] = now - 86400 * 1000
request['end_time'] = now
else:
method += 's' # trades vs trade
response = getattr(self, method)(self.extend(request, params))
if market['plus']:
return self.parseTradesPlus(response['trades'], market)
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
method = 'privatePost' + self.capitalize(side) + 'Order2'
order = {}
id = market['id'].upper()
if type == 'market':
order['params'] = [None, amount, id]
else:
order['params'] = [price, amount, id]
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id, params={}):
self.load_markets()
market = params['market'] # TODO fixme
return self.privatePostCancelOrder(self.extend({
'params': [id, market],
}, params))
def nonce(self):
return self.microseconds()
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api] + '/' + path
if api == 'private':
if not self.apiKey:
raise AuthenticationError(self.id + ' requires `' + self.id + '.apiKey` property for authentication')
if not self.secret:
raise AuthenticationError(self.id + ' requires `' + self.id + '.secret` property for authentication')
p = []
if 'params' in params:
p = params['params']
nonce = self.nonce()
request = {
'method': path,
'id': nonce,
'params': p,
}
p = ','.join(p)
body = self.json(request)
query = (
'tonce=' + nonce +
'&accesskey=' + self.apiKey +
'&requestmethod=' + method.lower() +
'&id=' + nonce +
'&method=' + path +
'¶ms=' + p
)
signature = self.hmac(self.encode(query), self.encode(self.secret), hashlib.sha1)
auth = self.apiKey + ':' + signature
headers = {
'Content-Length': len(body),
'Authorization': 'Basic ' + base64.b64encode(auth),
'Json-Rpc-Tonce': nonce,
}
else:
if params:
url += '?' + self.urlencode(params)
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class btcmarkets (Exchange):
def __init__(self, config={}):
params = {
'id': 'btcmarkets',
'name': 'BTC Markets',
'countries': 'AU', # Australia
'rateLimit': 1000, # market data cached for 1 second (trades cached for 2 seconds)
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/29142911-0e1acfc2-7d5c-11e7-98c4-07d9532b29d7.jpg',
'api': 'https://api.btcmarkets.net',
'www': 'https://btcmarkets.net/',
'doc': 'https://github.com/BTCMarkets/API',
},
'api': {
'public': {
'get': [
'market/{id}/tick',
'market/{id}/orderbook',
'market/{id}/trades',
],
},
'private': {
'get': [
'account/balance',
'account/{id}/tradingfee',
],
'post': [
'fundtransfer/withdrawCrypto',
'fundtransfer/withdrawEFT',
'order/create',
'order/cancel',
'order/history',
'order/open',
'order/trade/history',
'order/createBatch', # they promise it's coming soon...
'order/detail',
],
},
},
'markets': {
'BTC/AUD': {'id': 'BTC/AUD', 'symbol': 'BTC/AUD', 'base': 'BTC', 'quote': 'AUD'},
'LTC/AUD': {'id': 'LTC/AUD', 'symbol': 'LTC/AUD', 'base': 'LTC', 'quote': 'AUD'},
'ETH/AUD': {'id': 'ETH/AUD', 'symbol': 'ETH/AUD', 'base': 'ETH', 'quote': 'AUD'},
'ETC/AUD': {'id': 'ETC/AUD', 'symbol': 'ETC/AUD', 'base': 'ETC', 'quote': 'AUD'},
'XRP/AUD': {'id': 'XRP/AUD', 'symbol': 'XRP/AUD', 'base': 'XRP', 'quote': 'AUD'},
'BCH/AUD': {'id': 'BCH/AUD', 'symbol': 'BCH/AUD', 'base': 'BCH', 'quote': 'AUD'},
'LTC/BTC': {'id': 'LTC/BTC', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'ETH/BTC': {'id': 'ETH/BTC', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
'ETC/BTC': {'id': 'ETC/BTC', 'symbol': 'ETC/BTC', 'base': 'ETC', 'quote': 'BTC'},
'XRP/BTC': {'id': 'XRP/BTC', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC'},
'BCH/BTC': {'id': 'BCH/BTC', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC'},
},
}
params.update(config)
super(btcmarkets, self).__init__(params)
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privateGetAccountBalance()
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
multiplier = 100000000
free = float(balance['balance'] / multiplier)
used = float(balance['pendingFunds'] / multiplier)
account = {
'free': free,
'used': used,
'total': self.sum(free, used),
}
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
orderbook = self.publicGetMarketIdOrderbook(self.extend({
'id': market['id'],
}, params))
timestamp = orderbook['timestamp'] * 1000
return self.parse_order_book(orderbook, timestamp)
def parse_ticker(self, ticker, market):
timestamp = ticker['timestamp'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': float(ticker['bestBid']),
'ask': float(ticker['bestAsk']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['lastPrice']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume24h']),
'info': ticker,
}
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetMarketIdTick({
'id': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = trade['date'] * 1000
return {
'info': trade,
'id': str(trade['tid']),
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': None,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetMarketIdTrades(self.extend({
# 'since': 59868345231,
'id': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
multiplier = 100000000 # for price and volume
# does BTC Markets support market orders at all?
orderSide = 'Bid' if(side == 'buy') else 'Ask'
order = self.ordered({
'currency': market['quote'],
'instrument': market['base'],
'price': price * multiplier,
'volume': amount * multiplier,
'orderSide': orderSide,
'ordertype': self.capitalize(type),
'clientRequestId': str(self.nonce()),
})
response = self.privatePostOrderCreate(self.extend(order, params))
return {
'info': response,
'id': str(response['id']),
}
def cancel_orders(self, ids):
self.load_markets()
return self.privatePostOrderCancel({'order_ids': ids})
def cancel_order(self, id):
self.load_markets()
return self.cancelOrders([id])
def nonce(self):
return self.milliseconds()
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
uri = '/' + self.implode_params(path, params)
url = self.urls['api'] + uri
query = self.omit(params, self.extract_params(path))
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
nonce = str(self.nonce())
auth = uri + "\n" + nonce + "\n"
headers = {
'Content-Type': 'application/json',
'apikey': self.apiKey,
'timestamp': nonce,
}
if method == 'POST':
body = self.urlencode(query)
auth += body
secret = base64.b64decode(self.secret)
signature = self.hmac(self.encode(auth), secret, hashlib.sha512, 'base64')
headers['signature'] = self.decode(signature)
response = self.fetch(url, method, headers, body)
if api == 'private':
if 'success' in response:
if not response['success']:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
return response
#------------------------------------------------------------------------------
class btctrader (Exchange):
def __init__(self, config={}):
params = {
'id': 'btctrader',
'name': 'BTCTrader',
'countries': ['TR', 'GR', 'PH'], # Turkey, Greece, Philippines
'rateLimit': 1000,
'hasFetchOHLCV': True,
'timeframes': {
'1d': '1d',
},
'comment': 'base API for BTCExchange, BTCTurk',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27992404-cda1e386-649c-11e7-8dc1-40bbd2897768.jpg',
'api': 'https://www.btctrader.com/api',
'www': 'https://www.btctrader.com',
'doc': 'https://github.com/BTCTrader/broker-api-docs',
},
'api': {
'public': {
'get': [
'ohlcdata', # ?last=COUNT
'orderbook',
'ticker',
'trades', # ?last=COUNT (max 50)
],
},
'private': {
'get': [
'balance',
'openOrders',
'userTransactions', # ?offset=0&limit=25&sort=asc
],
'post': [
'buy',
'cancelOrder',
'sell',
],
},
},
}
params.update(config)
super(btctrader, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privateGetBalance()
result = {'info': response}
base = {
'free': response['bitcoin_available'],
'used': response['bitcoin_reserved'],
'total': response['bitcoin_balance'],
}
quote = {
'free': response['money_available'],
'used': response['money_reserved'],
'total': response['money_balance'],
}
symbol = self.symbols[0]
market = self.markets[symbol]
result[market['base']] = base
result[market['quote']] = quote
return result
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetOrderbook(params)
timestamp = int(orderbook['timestamp'] * 1000)
return self.parse_order_book(orderbook, timestamp)
def fetch_ticker(self, symbol):
ticker = self.publicGetTicker()
timestamp = int(ticker['timestamp'] * 1000)
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': float(ticker['open']),
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': float(ticker['average']),
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['date'] * 1000
return {
'id': trade['tid'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': None,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
maxCount = 50
response = self.publicGetTrades(params)
return self.parse_trades(response, market)
def parse_ohlcv(self, ohlcv, market=None, timeframe='1d', since=None, limit=None):
timestamp = self.parse8601(ohlcv['Date'])
return [
timestamp,
ohlcv['Open'],
ohlcv['High'],
ohlcv['Low'],
ohlcv['Close'],
ohlcv['Volume'],
]
def fetch_ohlcv(self, symbol, timeframe='1d', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {}
if limit:
request['last'] = limit
response = self.publicGetOhlcdata(self.extend(request, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
method = 'privatePost' + self.capitalize(side)
order = {
'Type': 'BuyBtc' if(side == 'buy') else 'SelBtc',
'IsMarketOrder': 1 if(type == 'market') else 0,
}
if type == 'market':
if side == 'buy':
order['Total'] = amount
else:
order['Amount'] = amount
else:
order['Price'] = price
order['Amount'] = amount
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id):
return self.privatePostCancelOrder({'id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
if self.id == 'btctrader':
raise ExchangeError(self.id + ' is an abstract base API for BTCExchange, BTCTurk')
url = self.urls['api'] + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
nonce = self.nonce().toString
body = self.urlencode(params)
secret = self.base64ToString(self.secret)
auth = self.apiKey + nonce
headers = {
'X-PCK': self.apiKey,
'X-Stamp': str(nonce),
'X-Signature': self.hmac(self.encode(auth), secret, hashlib.sha256, 'base64'),
'Content-Type': 'application/x-www-form-urlencoded',
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class btcexchange (btctrader):
def __init__(self, config={}):
params = {
'id': 'btcexchange',
'name': 'BTCExchange',
'countries': 'PH', # Philippines
'rateLimit': 1500,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27993052-4c92911a-64aa-11e7-96d8-ec6ac3435757.jpg',
'api': 'https://www.btcexchange.ph/api',
'www': 'https://www.btcexchange.ph',
'doc': 'https://github.com/BTCTrader/broker-api-docs',
},
'markets': {
'BTC/PHP': {'id': 'BTC/PHP', 'symbol': 'BTC/PHP', 'base': 'BTC', 'quote': 'PHP'},
},
}
params.update(config)
super(btcexchange, self).__init__(params)
#------------------------------------------------------------------------------
class btctradeua (Exchange):
def __init__(self, config={}):
params = {
'id': 'btctradeua',
'name': 'BTC Trade UA',
'countries': 'UA', # Ukraine,
'rateLimit': 3000,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27941483-79fc7350-62d9-11e7-9f61-ac47f28fcd96.jpg',
'api': 'https://btc-trade.com.ua/api',
'www': 'https://btc-trade.com.ua',
'doc': 'https://docs.google.com/document/d/1ocYA0yMy_RXd561sfG3qEPZ80kyll36HUxvCRe5GbhE/edit',
},
'api': {
'public': {
'get': [
'deals/{symbol}',
'trades/sell/{symbol}',
'trades/buy/{symbol}',
'japan_stat/high/{symbol}',
],
},
'private': {
'post': [
'auth',
'ask/{symbol}',
'balance',
'bid/{symbol}',
'buy/{symbol}',
'my_orders/{symbol}',
'order/status/{id}',
'remove/order/{id}',
'sell/{symbol}',
],
},
},
'markets': {
'BTC/UAH': {'id': 'btc_uah', 'symbol': 'BTC/UAH', 'base': 'BTC', 'quote': 'UAH'},
'ETH/UAH': {'id': 'eth_uah', 'symbol': 'ETH/UAH', 'base': 'ETH', 'quote': 'UAH'},
'LTC/UAH': {'id': 'ltc_uah', 'symbol': 'LTC/UAH', 'base': 'LTC', 'quote': 'UAH'},
'DOGE/UAH': {'id': 'doge_uah', 'symbol': 'DOGE/UAH', 'base': 'DOGE', 'quote': 'UAH'},
'DASH/UAH': {'id': 'dash_uah', 'symbol': 'DASH/UAH', 'base': 'DASH', 'quote': 'UAH'},
'SIB/UAH': {'id': 'sib_uah', 'symbol': 'SIB/UAH', 'base': 'SIB', 'quote': 'UAH'},
'KRB/UAH': {'id': 'krb_uah', 'symbol': 'KRB/UAH', 'base': 'KRB', 'quote': 'UAH'},
'NVC/UAH': {'id': 'nvc_uah', 'symbol': 'NVC/UAH', 'base': 'NVC', 'quote': 'UAH'},
'LTC/BTC': {'id': 'ltc_btc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'NVC/BTC': {'id': 'nvc_btc', 'symbol': 'NVC/BTC', 'base': 'NVC', 'quote': 'BTC'},
'ITI/UAH': {'id': 'iti_uah', 'symbol': 'ITI/UAH', 'base': 'ITI', 'quote': 'UAH'},
'DOGE/BTC': {'id': 'doge_btc', 'symbol': 'DOGE/BTC', 'base': 'DOGE', 'quote': 'BTC'},
'DASH/BTC': {'id': 'dash_btc', 'symbol': 'DASH/BTC', 'base': 'DASH', 'quote': 'BTC'},
},
}
params.update(config)
super(btctradeua, self).__init__(params)
def sign_in(self):
return self.privatePostAuth()
def fetch_balance(self, params={}):
response = self.privatePostBalance()
result = {'info': response}
if 'accounts' in result:
accounts = response['accounts']
for b in range(0, len(accounts)):
account = accounts[b]
currency = account['currency']
balance = float(account['balance'])
result[currency] = {
'free': balance,
'used': 0.0,
'total': balance,
}
return result
def fetch_order_book(self, symbol, params={}):
market = self.market(symbol)
bids = self.publicGetTradesBuySymbol(self.extend({
'symbol': market['id'],
}, params))
asks = self.publicGetTradesSellSymbol(self.extend({
'symbol': market['id'],
}, params))
orderbook = {
'bids': [],
'asks': [],
}
if bids:
if 'list' in bids:
orderbook['bids'] = bids['list']
if asks:
if 'list' in asks:
orderbook['asks'] = asks['list']
return self.parse_order_book(orderbook, None, 'bids', 'asks', 'price', 'currency_trade')
def fetch_ticker(self, symbol):
response = self.publicGetJapanStatHighSymbol({
'symbol': self.market_id(symbol),
})
ticker = response['trades']
timestamp = self.milliseconds()
result = {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': None,
'ask': None,
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': None,
'info': ticker,
}
tickerLength = len(ticker)
if tickerLength > 0:
start = max(tickerLength - 48, 0)
for t in range(start, len(ticker)):
candle = ticker[t]
if result['open'] is None:
result['open'] = candle[1]
if(result['high'] is None) or(result['high'] < candle[2]):
result['high'] = candle[2]
if(result['low'] is None) or(result['low'] > candle[3]):
result['low'] = candle[3]
if result['quoteVolume'] is None:
result['quoteVolume'] = -candle[5]
else:
result['quoteVolume'] -= candle[5]
last = tickerLength - 1
result['close'] = ticker[last][4]
result['quoteVolume'] = -1 * result['quoteVolume']
return result
def parse_trade(self, trade, market):
timestamp = self.milliseconds() # until we have a better solution for python
return {
'id': str(trade['id']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['type'],
'price': float(trade['price']),
'amount': float(trade['amnt_base']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetDealsSymbol(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
market = self.market(symbol)
method = 'privatePost' + self.capitalize(side) + 'Id'
order = {
'count': amount,
'currency1': market['quote'],
'currency': market['base'],
'price': price,
}
return getattr(self, method)(self.extend(order, params))
def cancel_order(self, id):
return self.privatePostRemoveOrderId({'id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += self.implode_params(path, query)
else:
nonce = self.nonce()
body = self.urlencode(self.extend({
'out_order_id': nonce,
'nonce': nonce,
}, query))
auth = body + self.secret
headers = {
'public-key': self.apiKey,
'api-sign': self.hash(self.encode(auth), 'sha256'),
'Content-Type': 'application/x-www-form-urlencoded',
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class btcturk (btctrader):
def __init__(self, config={}):
params = {
'id': 'btcturk',
'name': 'BTCTurk',
'countries': 'TR', # Turkey
'rateLimit': 1000,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27992709-18e15646-64a3-11e7-9fa2-b0950ec7712f.jpg',
'api': 'https://www.btcturk.com/api',
'www': 'https://www.btcturk.com',
'doc': 'https://github.com/BTCTrader/broker-api-docs',
},
'markets': {
'BTC/TRY': {'id': 'BTC/TRY', 'symbol': 'BTC/TRY', 'base': 'BTC', 'quote': 'TRY'},
},
}
params.update(config)
super(btcturk, self).__init__(params)
#------------------------------------------------------------------------------
class btcx (Exchange):
def __init__(self, config={}):
params = {
'id': 'btcx',
'name': 'BTCX',
'countries': ['IS', 'US', 'EU'],
'rateLimit': 1500, # support in english is very poor, unable to tell rate limits
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766385-9fdcc98c-5ed6-11e7-8f14-66d5e5cd47e6.jpg',
'api': 'https://btc-x.is/api',
'www': 'https://btc-x.is',
'doc': 'https://btc-x.is/custom/api-document.html',
},
'api': {
'public': {
'get': [
'depth/{id}/{limit}',
'ticker/{id}',
'trade/{id}/{limit}',
],
},
'private': {
'post': [
'balance',
'cancel',
'history',
'order',
'redeem',
'trade',
'withdraw',
],
},
},
'markets': {
'BTC/USD': {'id': 'btc/usd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'BTC/EUR': {'id': 'btc/eur', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
},
}
params.update(config)
super(btcx, self).__init__(params)
def fetch_balance(self, params={}):
balances = self.privatePostBalance()
result = {'info': balances}
currencies = list(balances.keys())
for c in range(0, len(currencies)):
currency = currencies[c]
uppercase = currency.upper()
account = {
'free': balances[currency],
'used': 0.0,
'total': balances[currency],
}
result[uppercase] = account
return result
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetDepthIdLimit(self.extend({
'id': self.market_id(symbol),
'limit': 1000,
}, params))
return self.parse_order_book(orderbook, None, 'bids', 'asks', 'price', 'amount')
def fetch_ticker(self, symbol):
ticker = self.publicGetTickerId({
'id': self.market_id(symbol),
})
timestamp = ticker['time'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['sell']),
'ask': float(ticker['buy']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = int(trade['date']) * 1000
side = 'sell' if(trade['type'] == 'ask') else 'buy'
return {
'id': trade['id'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTradeIdLimit(self.extend({
'id': market['id'],
'limit': 1000,
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
response = self.privatePostTrade(self.extend({
'type': side.upper(),
'market': self.market_id(symbol),
'amount': amount,
'price': price,
}, params))
return {
'info': response,
'id': response['order']['id'],
}
def cancel_order(self, id):
return self.privatePostCancel({'order': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/'
if api == 'public':
url += self.implode_params(path, params)
else:
nonce = self.nonce()
url += api
body = self.urlencode(self.extend({
'Method': path.upper(),
'Nonce': nonce,
}, params))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': self.apiKey,
'Signature': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
response = self.fetch(url, method, headers, body)
if 'error' in response:
raise ExchangeError(self.id + ' ' + self.json(response['error']))
return response
#------------------------------------------------------------------------------
class bter (Exchange):
def __init__(self, config={}):
params = {
'id': 'bter',
'name': 'Bter',
'countries': ['VG', 'CN'], # British Virgin Islands, China
'version': '2',
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27980479-cfa3188c-6387-11e7-8191-93fc4184ba5c.jpg',
'api': {
'public': 'https://data.bter.com/api',
'private': 'https://api.bter.com/api',
},
'www': 'https://bter.com',
'doc': 'https://bter.com/api2',
},
'api': {
'public': {
'get': [
'pairs',
'marketinfo',
'marketlist',
'tickers',
'ticker/{id}',
'orderBook/{id}',
'trade/{id}',
'tradeHistory/{id}',
'tradeHistory/{id}/{tid}',
],
},
'private': {
'post': [
'balances',
'depositAddress',
'newAddress',
'depositsWithdrawals',
'buy',
'sell',
'cancelOrder',
'cancelAllOrders',
'getOrder',
'openOrders',
'tradeHistory',
'withdraw',
],
},
},
}
params.update(config)
super(bter, self).__init__(params)
def fetch_markets(self):
response = self.publicGetMarketlist()
markets = response['data']
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['pair']
base = market['curr_a']
quote = market['curr_b']
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balance = self.privatePostBalances()
result = {'info': balance}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
code = self.commonCurrencyCode(currency)
account = self.account()
if 'available' in balance:
if currency in balance['available']:
account['free'] = float(balance['available'][currency])
if 'locked' in balance:
if currency in balance['locked']:
account['used'] = float(balance['locked'][currency])
account['total'] = self.sum(account['free'], account['used'])
result[code] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetOrderBookId(self.extend({
'id': self.market_id(symbol),
}, params))
result = self.parse_order_book(orderbook)
result['asks'] = self.sort_by(result['asks'], 0)
return result
def parse_ticker(self, ticker, market=None):
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high24hr']),
'low': float(ticker['low24hr']),
'bid': float(ticker['highestBid']),
'ask': float(ticker['lowestAsk']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': float(ticker['percentChange']),
'percentage': None,
'average': None,
'baseVolume': float(ticker['baseVolume']),
'quoteVolume': float(ticker['quoteVolume']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGetTickers()
result = {}
ids = list(tickers.keys())
for i in range(0, len(ids)):
id = ids[i]
baseId, quoteId = id.split('_')
base = baseId.upper()
quote = quoteId.upper()
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
ticker = tickers[id]
market = None
if symbol in self.markets:
market = self.markets[symbol]
if id in self.markets_by_id:
market = self.markets_by_id[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetTickerId({
'id': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = int(trade['timestamp']) * 1000
return {
'id': trade['tradeID'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['type'],
'price': trade['rate'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
self.load_markets()
response = self.publicGetTradeHistoryId(self.extend({
'id': market['id'],
}, params))
return self.parse_trades(response['data'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
self.load_markets()
method = 'privatePost' + self.capitalize(side)
order = {
'currencyPair': self.market_id(symbol),
'rate': price,
'amount': amount,
}
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': response['orderNumber'],
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostCancelOrder({'orderNumber': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
prefix = (api + '/') if(api == 'private') else ''
url = self.urls['api'][api] + self.version + '/1/' + prefix + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
request = {'nonce': nonce}
body = self.urlencode(self.extend(request, query))
signature = self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512)
headers = {
'Key': self.apiKey,
'Sign': signature,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': str(len(body)),
}
response = self.fetch(url, method, headers, body)
if 'result' in response:
if response['result'] != 'true':
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class bxinth (Exchange):
def __init__(self, config={}):
params = {
'id': 'bxinth',
'name': 'BX.in.th',
'countries': 'TH', # Thailand
'rateLimit': 1500,
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766412-567b1eb4-5ed7-11e7-94a8-ff6a3884f6c5.jpg',
'api': 'https://bx.in.th/api',
'www': 'https://bx.in.th',
'doc': 'https://bx.in.th/info/api',
},
'api': {
'public': {
'get': [
'', # ticker
'options',
'optionbook',
'orderbook',
'pairing',
'trade',
'tradehistory',
],
},
'private': {
'post': [
'balance',
'biller',
'billgroup',
'billpay',
'cancel',
'deposit',
'getorders',
'history',
'option-issue',
'option-bid',
'option-sell',
'option-myissue',
'option-mybid',
'option-myoptions',
'option-exercise',
'option-cancel',
'option-history',
'order',
'withdrawal',
'withdrawal-history',
],
},
},
}
params.update(config)
super(bxinth, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetPairing()
keys = list(markets.keys())
result = []
for p in range(0, len(keys)):
market = markets[keys[p]]
id = str(market['pairing_id'])
base = market['primary_currency']
quote = market['secondary_currency']
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def commonCurrencyCode(self, currency):
# why would they use three letters instead of four for currency codes
if currency == 'DAS':
return 'DASH'
if currency == 'DOG':
return 'DOGE'
return currency
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostBalance()
balance = response['balance']
result = {'info': balance}
currencies = list(balance.keys())
for c in range(0, len(currencies)):
currency = currencies[c]
code = self.commonCurrencyCode(currency)
account = {
'free': float(balance[currency]['available']),
'used': 0.0,
'total': float(balance[currency]['total']),
}
account['used'] = account['total'] - account['free']
result[code] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetOrderbook(self.extend({
'pairing': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook)
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': float(ticker['orderbook']['bids']['highbid']),
'ask': float(ticker['orderbook']['asks']['highbid']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last_price']),
'change': float(ticker['change']),
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume_24hours']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGet()
result = {}
ids = list(tickers.keys())
for i in range(0, len(ids)):
id = ids[i]
ticker = tickers[id]
market = self.markets_by_id[id]
symbol = market['symbol']
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
tickers = self.publicGet({'pairing': market['id']})
id = str(market['id'])
ticker = tickers[id]
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = self.parse8601(trade['trade_date'])
return {
'id': trade['trade_id'],
'info': trade,
'order': trade['order_id'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['trade_type'],
'price': float(trade['rate']),
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTrade(self.extend({
'pairing': market['id'],
}, params))
return self.parse_trades(response['trades'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
response = self.privatePostOrder(self.extend({
'pairing': self.market_id(symbol),
'type': side,
'amount': amount,
'rate': price,
}, params))
return {
'info': response,
'id': str(response['order_id']),
}
def cancel_order(self, id):
self.load_markets()
pairing = None # TODO fixme
return self.privatePostCancel({
'order_id': id,
'pairing': pairing,
})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/'
if path:
url += path + '/'
if params:
url += '?' + self.urlencode(params)
if api == 'private':
nonce = self.nonce()
auth = self.apiKey + str(nonce) + self.secret
signature = self.hash(self.encode(auth), 'sha256')
body = self.urlencode(self.extend({
'key': self.apiKey,
'nonce': nonce,
'signature': signature,
# twofa: self.twofa,
}, params))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
response = self.fetch(url, method, headers, body)
if api == 'public':
return response
if 'success' in response:
if response['success']:
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class ccex (Exchange):
def __init__(self, config={}):
params = {
'id': 'ccex',
'name': 'C-CEX',
'countries': ['DE', 'EU'],
'rateLimit': 1500,
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766433-16881f90-5ed8-11e7-92f8-3d92cc747a6c.jpg',
'api': {
'tickers': 'https://c-cex.com/t',
'public': 'https://c-cex.com/t/api_pub.html',
'private': 'https://c-cex.com/t/api.html',
},
'www': 'https://c-cex.com',
'doc': 'https://c-cex.com/?id=api',
},
'api': {
'tickers': {
'get': [
'coinnames',
'{market}',
'pairs',
'prices',
'volume_{coin}',
],
},
'public': {
'get': [
'balancedistribution',
'markethistory',
'markets',
'marketsummaries',
'orderbook',
],
},
'private': {
'get': [
'buylimit',
'cancel',
'getbalance',
'getbalances',
'getopenorders',
'getorder',
'getorderhistory',
'mytrades',
'selllimit',
],
},
},
}
params.update(config)
super(ccex, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetMarkets()
result = []
for p in range(0, len(markets['result'])):
market = markets['result'][p]
id = market['MarketName']
base = market['MarketCurrency']
quote = market['BaseCurrency']
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetBalances()
balances = response['result']
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['Currency']
account = {
'free': balance['Available'],
'used': balance['Pending'],
'total': balance['Balance'],
}
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
response = self.publicGetOrderbook(self.extend({
'market': self.market_id(symbol),
'type': 'both',
'depth': 100,
}, params))
orderbook = response['result']
return self.parse_order_book(orderbook, None, 'buy', 'sell', 'Rate', 'Quantity')
def parse_ticker(self, ticker, market=None):
timestamp = ticker['updated'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['lastprice']),
'change': None,
'percentage': None,
'average': float(ticker['avg']),
'baseVolume': None,
'quoteVolume': self.safe_float(ticker, 'buysupport'),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.tickersGetPrices()
result = {'info': tickers}
ids = list(tickers.keys())
for i in range(0, len(ids)):
id = ids[i]
ticker = tickers[id]
uppercase = id.upper()
market = None
symbol = None
if uppercase in self.markets_by_id:
market = self.markets_by_id[uppercase]
symbol = market['symbol']
else:
base, quote = uppercase.split('-')
symbol = base + '/' + quote
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
response = self.tickersGetMarket({
'market': market['id'].lower(),
})
ticker = response['ticker']
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = self.parse8601(trade['TimeStamp'])
return {
'id': trade['Id'],
'info': trade,
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['OrderType'].lower(),
'price': trade['Price'],
'amount': trade['Quantity'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetMarkethistory(self.extend({
'market': self.market_id(market),
'type': 'both',
'depth': 100,
}, params))
return self.parse_trades(response['result'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
method = 'privateGet' + self.capitalize(side) + type
response = getattr(self, method)(self.extend({
'market': self.market_id(symbol),
'quantity': amount,
'rate': price,
}, params))
return {
'info': response,
'id': response['result']['uuid'],
}
def cancel_order(self, id):
self.load_markets()
return self.privateGetCancel({'uuid': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
if api == 'private':
nonce = str(self.nonce())
query = self.keysort(self.extend({
'a': path,
'apikey': self.apiKey,
'nonce': nonce,
}, params))
url += '?' + self.urlencode(query)
headers = {'apisign': self.hmac(self.encode(url), self.encode(self.secret), hashlib.sha512)}
elif api == 'public':
url += '?' + self.urlencode(self.extend({
'a': 'get' + path,
}, params))
else:
url += '/' + self.implode_params(path, params) + '.json'
response = self.fetch(url, method, headers, body)
if api == 'tickers':
return response
if 'success' in response:
if response['success']:
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class cex (Exchange):
def __init__(self, config={}):
params = {
'id': 'cex',
'name': 'CEX.IO',
'countries': ['GB', 'EU', 'CY', 'RU'],
'rateLimit': 1500,
'hasFetchTickers': False,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766442-8ddc33b0-5ed8-11e7-8b98-f786aef0f3c9.jpg',
'api': 'https://cex.io/api',
'www': 'https://cex.io',
'doc': 'https://cex.io/cex-api',
},
'api': {
'public': {
'get': [
'currency_limits',
'last_price/{pair}',
'last_prices/{currencies}',
'ohlcv/hd/{yyyymmdd}/{pair}',
'order_book/{pair}',
'ticker/{pair}',
'tickers/{currencies}',
'trade_history/{pair}',
],
'post': [
'convert/{pair}',
'price_stats/{pair}',
],
},
'private': {
'post': [
'active_orders_status/',
'archived_orders/{pair}',
'balance/',
'cancel_order/',
'cancel_orders/{pair}',
'cancel_replace_order/{pair}',
'close_position/{pair}',
'get_address/',
'get_myfee/',
'get_order/',
'get_order_tx/',
'open_orders/{pair}',
'open_orders/',
'open_position/{pair}',
'open_positions/{pair}',
'place_order/{pair}',
'place_order/{pair}',
],
}
},
}
params.update(config)
super(cex, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetCurrencyLimits()
result = []
for p in range(0, len(markets['data']['pairs'])):
market = markets['data']['pairs'][p]
id = market['symbol1'] + '/' + market['symbol2']
symbol = id
base, quote = symbol.split('/')
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privatePostBalance()
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = {
'free': float(balances[currency]['available']),
'used': float(balances[currency]['orders']),
'total': 0.0,
}
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetOrderBookPair(self.extend({
'pair': self.market_id(symbol),
}, params))
timestamp = orderbook['timestamp'] * 1000
return self.parse_order_book(orderbook, timestamp)
def parse_ticker(self, ticker, market):
timestamp = None
iso8601 = None
if 'timestamp' in ticker:
timestamp = int(ticker['timestamp']) * 1000
iso8601 = self.iso8601(timestamp)
volume = self.safe_float(ticker, 'volume')
high = self.safe_float(ticker, 'high')
low = self.safe_float(ticker, 'low')
bid = self.safe_float(ticker, 'bid')
ask = self.safe_float(ticker, 'ask')
last = self.safe_float(ticker, 'last')
return {
'timestamp': timestamp,
'datetime': iso8601,
'high': high,
'low': low,
'bid': bid,
'ask': ask,
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': last,
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': volume,
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
currencies = '/'.join(self.currencies)
response = self.publicGetTickersCurrencies({
'currencies': currencies,
})
tickers = response['data']
result = {}
for t in range(0, len(tickers)):
ticker = tickers[t]
symbol = ticker['pair'].replace(':', '/')
market = self.markets[symbol]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetTickerPair({
'pair': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market=None):
timestamp = int(trade['date']) * 1000
return {
'info': trade,
'id': trade['tid'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['type'],
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTradeHistoryPair(self.extend({
'pair': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'pair': self.market_id(symbol),
'type': side,
'amount': amount,
}
if type == 'limit':
order['price'] = price
else:
order['order_type'] = type
response = self.privatePostPlaceOrderPair(self.extend(order, params))
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostCancelOrder({'id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
if not self.uid:
raise AuthenticationError(self.id + ' requires `' + self.id + '.uid` property for authentication')
nonce = str(self.nonce())
auth = nonce + self.uid + self.apiKey
signature = self.hmac(self.encode(auth), self.encode(self.secret))
body = self.urlencode(self.extend({
'key': self.apiKey,
'signature': signature.upper(),
'nonce': nonce,
}, query))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
response = self.fetch(url, method, headers, body)
if 'e' in response:
if 'ok' in response:
if response['ok'] == 'ok':
return response
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class chbtc (Exchange):
def __init__(self, config={}):
params = {
'id': 'chbtc',
'name': 'CHBTC',
'countries': 'CN',
'rateLimit': 1000,
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28555659-f0040dc2-7109-11e7-9d99-688a438bf9f4.jpg',
'api': {
'public': 'http://api.chbtc.com/data', # no https for public API
'private': 'https://trade.chbtc.com/api',
},
'www': 'https://trade.chbtc.com/api',
'doc': 'https://www.chbtc.com/i/developer',
},
'api': {
'public': {
'get': [
'ticker',
'depth',
'trades',
'kline',
],
},
'private': {
'post': [
'order',
'cancelOrder',
'getOrder',
'getOrders',
'getOrdersNew',
'getOrdersIgnoreTradeType',
'getUnfinishedOrdersIgnoreTradeType',
'getAccountInfo',
'getUserAddress',
'getWithdrawAddress',
'getWithdrawRecord',
'getChargeRecord',
'getCnyWithdrawRecord',
'getCnyChargeRecord',
'withdraw',
],
},
},
'markets': {
'BTC/CNY': {'id': 'btc_cny', 'symbol': 'BTC/CNY', 'base': 'BTC', 'quote': 'CNY'},
'LTC/CNY': {'id': 'ltc_cny', 'symbol': 'LTC/CNY', 'base': 'LTC', 'quote': 'CNY'},
'ETH/CNY': {'id': 'eth_cny', 'symbol': 'ETH/CNY', 'base': 'ETH', 'quote': 'CNY'},
'ETC/CNY': {'id': 'etc_cny', 'symbol': 'ETC/CNY', 'base': 'ETC', 'quote': 'CNY'},
'BTS/CNY': {'id': 'bts_cny', 'symbol': 'BTS/CNY', 'base': 'BTS', 'quote': 'CNY'},
# 'EOS/CNY': {'id': 'eos_cny', 'symbol': 'EOS/CNY', 'base': 'EOS', 'quote': 'CNY'},
'BCH/CNY': {'id': 'bcc_cny', 'symbol': 'BCH/CNY', 'base': 'BCH', 'quote': 'CNY'},
'HSR/CNY': {'id': 'hsr_cny', 'symbol': 'HSR/CNY', 'base': 'HSR', 'quote': 'CNY'},
'QTUM/CNY': {'id': 'qtum_cny', 'symbol': 'QTUM/CNY', 'base': 'QTUM', 'quote': 'CNY'},
},
}
params.update(config)
super(chbtc, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostGetAccountInfo()
balances = response['result']
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in balances['balance']:
account['free'] = float(balances['balance'][currency]['amount'])
if currency in balances['frozen']:
account['used'] = float(balances['frozen'][currency]['amount'])
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
market = self.market(symbol)
orderbook = self.publicGetDepth(self.extend({
'currency': market['id'],
}, params))
timestamp = self.milliseconds()
bids = None
asks = None
if 'bids' in orderbook:
bids = orderbook['bids']
if 'asks' in orderbook:
asks = orderbook['asks']
result = {
'bids': bids,
'asks': asks,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
}
if result['bids']:
result['bids'] = self.sort_by(result['bids'], 0, True)
if result['asks']:
result['asks'] = self.sort_by(result['asks'], 0)
return result
def fetch_ticker(self, symbol):
response = self.publicGetTicker({
'currency': self.market_id(symbol),
})
ticker = response['ticker']
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['vol']),
'info': ticker,
}
def parse_trade(self, trade, market=None):
timestamp = trade['date'] * 1000
side = 'buy' if(trade['trade_type'] == 'bid') else 'sell'
return {
'info': trade,
'id': str(trade['tid']),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTrades(self.extend({
'currency': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
paramString = '&price=' + str(price)
paramString += '&amount=' + str(amount)
tradeType = '1' if(side == 'buy') else '0'
paramString += '&tradeType=' + tradeType
paramString += '¤cy=' + self.market_id(symbol)
response = self.privatePostOrder(paramString)
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id, params={}):
paramString = '&id=' + str(id)
if 'currency' in params:
paramString += '¤cy=' + params['currency']
return self.privatePostCancelOrder(paramString)
def fetch_order(self, id, params={}):
paramString = '&id=' + str(id)
if 'currency' in params:
paramString += '¤cy=' + params['currency']
return self.privatePostGetOrder(paramString)
def nonce(self):
return self.milliseconds()
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
if api == 'public':
url += '/' + self.version + '/' + path
if params:
url += '?' + self.urlencode(params)
else:
paramsLength = len(params) # params should be a string here
nonce = self.nonce()
auth = 'method=' + path
auth += '&accesskey=' + self.apiKey
auth += params if paramsLength else ''
secret = self.hash(self.encode(self.secret), 'sha1')
signature = self.hmac(self.encode(auth), self.encode(secret), hashlib.md5)
suffix = 'sign=' + signature + '&reqTime=' + str(nonce)
url += '/' + path + '?' + auth + '&' + suffix
response = self.fetch(url, method, headers, body)
if api == 'private':
if 'code' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class chilebit (blinktrade):
def __init__(self, config={}):
params = {
'id': 'chilebit',
'name': 'ChileBit',
'countries': 'CL',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27991414-1298f0d8-647f-11e7-9c40-d56409266336.jpg',
'api': {
'public': 'https://api.blinktrade.com/api',
'private': 'https://api.blinktrade.com/tapi',
},
'www': 'https://chilebit.net',
'doc': 'https://blinktrade.com/docs',
},
'comment': 'Blinktrade API',
'markets': {
'BTC/CLP': {'id': 'BTCCLP', 'symbol': 'BTC/CLP', 'base': 'BTC', 'quote': 'CLP', 'brokerId': 9, 'broker': 'ChileBit'},
},
}
params.update(config)
super(chilebit, self).__init__(params)
#------------------------------------------------------------------------------
class coincheck (Exchange):
def __init__(self, config={}):
params = {
'id': 'coincheck',
'name': 'coincheck',
'countries': ['JP', 'ID'],
'rateLimit': 1500,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766464-3b5c3c74-5ed9-11e7-840e-31b32968e1da.jpg',
'api': 'https://coincheck.com/api',
'www': 'https://coincheck.com',
'doc': 'https://coincheck.com/documents/exchange/api',
},
'api': {
'public': {
'get': [
'exchange/orders/rate',
'order_books',
'rate/{pair}',
'ticker',
'trades',
],
},
'private': {
'get': [
'accounts',
'accounts/balance',
'accounts/leverage_balance',
'bank_accounts',
'deposit_money',
'exchange/orders/opens',
'exchange/orders/transactions',
'exchange/orders/transactions_pagination',
'exchange/leverage/positions',
'lending/borrows/matches',
'send_money',
'withdraws',
],
'post': [
'bank_accounts',
'deposit_money/{id}/fast',
'exchange/orders',
'exchange/transfers/to_leverage',
'exchange/transfers/from_leverage',
'lending/borrows',
'lending/borrows/{id}/repay',
'send_money',
'withdraws',
],
'delete': [
'bank_accounts/{id}',
'exchange/orders/{id}',
'withdraws/{id}',
],
},
},
'markets': {
'BTC/JPY': {'id': 'btc_jpy', 'symbol': 'BTC/JPY', 'base': 'BTC', 'quote': 'JPY'}, # the only real pair
'ETH/JPY': {'id': 'eth_jpy', 'symbol': 'ETH/JPY', 'base': 'ETH', 'quote': 'JPY'},
'ETC/JPY': {'id': 'etc_jpy', 'symbol': 'ETC/JPY', 'base': 'ETC', 'quote': 'JPY'},
'DAO/JPY': {'id': 'dao_jpy', 'symbol': 'DAO/JPY', 'base': 'DAO', 'quote': 'JPY'},
'LSK/JPY': {'id': 'lsk_jpy', 'symbol': 'LSK/JPY', 'base': 'LSK', 'quote': 'JPY'},
'FCT/JPY': {'id': 'fct_jpy', 'symbol': 'FCT/JPY', 'base': 'FCT', 'quote': 'JPY'},
'XMR/JPY': {'id': 'xmr_jpy', 'symbol': 'XMR/JPY', 'base': 'XMR', 'quote': 'JPY'},
'REP/JPY': {'id': 'rep_jpy', 'symbol': 'REP/JPY', 'base': 'REP', 'quote': 'JPY'},
'XRP/JPY': {'id': 'xrp_jpy', 'symbol': 'XRP/JPY', 'base': 'XRP', 'quote': 'JPY'},
'ZEC/JPY': {'id': 'zec_jpy', 'symbol': 'ZEC/JPY', 'base': 'ZEC', 'quote': 'JPY'},
'XEM/JPY': {'id': 'xem_jpy', 'symbol': 'XEM/JPY', 'base': 'XEM', 'quote': 'JPY'},
'LTC/JPY': {'id': 'ltc_jpy', 'symbol': 'LTC/JPY', 'base': 'LTC', 'quote': 'JPY'},
'DASH/JPY': {'id': 'dash_jpy', 'symbol': 'DASH/JPY', 'base': 'DASH', 'quote': 'JPY'},
'ETH/BTC': {'id': 'eth_btc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
'ETC/BTC': {'id': 'etc_btc', 'symbol': 'ETC/BTC', 'base': 'ETC', 'quote': 'BTC'},
'LSK/BTC': {'id': 'lsk_btc', 'symbol': 'LSK/BTC', 'base': 'LSK', 'quote': 'BTC'},
'FCT/BTC': {'id': 'fct_btc', 'symbol': 'FCT/BTC', 'base': 'FCT', 'quote': 'BTC'},
'XMR/BTC': {'id': 'xmr_btc', 'symbol': 'XMR/BTC', 'base': 'XMR', 'quote': 'BTC'},
'REP/BTC': {'id': 'rep_btc', 'symbol': 'REP/BTC', 'base': 'REP', 'quote': 'BTC'},
'XRP/BTC': {'id': 'xrp_btc', 'symbol': 'XRP/BTC', 'base': 'XRP', 'quote': 'BTC'},
'ZEC/BTC': {'id': 'zec_btc', 'symbol': 'ZEC/BTC', 'base': 'ZEC', 'quote': 'BTC'},
'XEM/BTC': {'id': 'xem_btc', 'symbol': 'XEM/BTC', 'base': 'XEM', 'quote': 'BTC'},
'LTC/BTC': {'id': 'ltc_btc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'DASH/BTC': {'id': 'dash_btc', 'symbol': 'DASH/BTC', 'base': 'DASH', 'quote': 'BTC'},
},
}
params.update(config)
super(coincheck, self).__init__(params)
self.fetch_market_data()
self.fetch_my_balance()
self.pre_order_id = self.fetch_pre_order_id()
self.min_lot_digit = 4
self.min_lot = 0.005
def fetch_pre_order_id(self):
while True:
trade_histry = self.privateGetExchangeOrdersTransactions()
if trade_histry['success']:
if len(trade_histry['transactions']) == 0:
return None
else:
return trade_histry['transactions'][0]['order_id']
sleep(1)
def update_pre_order_id(self, order_id):
self.pre_order_id = order_id
def create_arb_market_buy_order(self, symbol, amount, params={}, price_buff=50000):
c_rt = self.create_limit_buy_order(symbol, amount, int(self.best_ask_price) + price_buff, params)
self.update_pre_order_id(c_rt['info']['id'])
return c_rt
def create_arb_market_sell_order(self, symbol, amount, params={}):
c_rt = self.create_order(symbol, 'market', 'sell', amount, None, params)
self.update_pre_order_id(c_rt['info']['id'])
return c_rt
def fetch_open_orders(self):
response = self.privateGetExchangeOrdersOpens()
if response['success']:
return response['orders']
else:
# エラー処理を追加
pass
def fetch_balance(self, params={}):
balances = self.privateGetAccountsBalance()
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = self.account()
if lowercase in balances:
account['free'] = float(balances[lowercase])
reserved = lowercase + '_reserved'
if reserved in balances:
account['used'] = float(balances[reserved])
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetOrderBooks(params)
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
ticker = self.publicGetTicker()
timestamp = ticker['timestamp'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = self.parse8601(trade['created_at'])
return {
'id': str(trade['id']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['order_type'],
'price': float(trade['rate']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTrades(params)
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
prefix = ''
order = {
'pair': self.market_id(symbol),
}
if type == 'market':
order_type = type + '_' + side
order['order_type'] = order_type
prefix = (order_type + '_') if(side == 'buy') else ''
order[prefix + 'amount'] = amount
else:
order['order_type'] = side
order['rate'] = price
order['amount'] = amount
response = self.privatePostExchangeOrders(self.extend(order, params))
return {
'info': response,
'id': str(response['id']),
}
def cancel_order(self, id):
return self.privateDeleteExchangeOrdersId({'id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = str(self.nonce())
length = 0
if query:
body = self.urlencode(self.keysort(query))
length = len(body)
auth = nonce + url + (body or '')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'ACCESS-KEY': self.apiKey,
'ACCESS-NONCE': nonce,
'ACCESS-SIGNATURE': self.hmac(self.encode(auth), self.encode(self.secret)),
}
response = self.fetch(url, method, headers, body)
if api == 'public':
return response
if 'success' in response:
if response['success']:
return response
raise ExchangeError(self.id, self.id + ' ' + self.json(response))
def handle_rest_errors(self, exception, http_status_code, response, url, method='GET'):
import re
error = None
details = response if response else None
# response_dict = json.loads(response)
if http_status_code == 429:
error = DDoSProtection
elif http_status_code in [404, 409, 422, 500, 501, 502, 520, 521, 522, 525]:
details = exception.read().decode('utf-8', 'ignore') if exception else (str(http_status_code) + ' ' + response)
error = ExchangeNotAvailable
elif http_status_code in [400, 403, 405, 503]:
reason = exception.read().decode('utf-8', 'ignore') if exception else response
if http_status_code == 400 and 'Amount btc の所持金額が足りません' in reason:
error = InsufficientFunds
details = reason
elif http_status_code == 400 and 'Amount 量が最低量(0.005 BTC)を下回っています' in reason:
error = ExchangeError
details = reason
elif http_status_code == 403 and 'This api is not permitted' in reason:
error = AuthenticationError
details = reason
else:
# special case to detect ddos protection
ddos_protection = re.search('(cloudflare|incapsula)', reason, flags=re.IGNORECASE)
if ddos_protection:
error = DDoSProtection
else:
error = ExchangeNotAvailable
details = '(possible reasons: ' + ', '.join([
'invalid API keys',
'bad or old nonce',
'exchange is down or offline',
'on maintenance',
'DDoS protection',
'rate-limiting',
reason,
]) + ')'
elif http_status_code in [408, 504]:
error = RequestTimeout
elif http_status_code in [401, 511]:
details = exception.read().decode('utf-8')
if http_status_code == 401 and 'Nonce must be incremented' in details:
error = ApiNonceError
else:
error = AuthenticationError
if error:
self.raise_error(error, url, method, exception if exception else str(http_status_code), details)
#------------------------------------------------------------------------------
class coinfloor (Exchange):
def __init__(self, config={}):
params = {
'id': 'coinfloor',
'name': 'coinfloor',
'rateLimit': 1000,
'countries': 'UK',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28246081-623fc164-6a1c-11e7-913f-bac0d5576c90.jpg',
'api': 'https://webapi.coinfloor.co.uk:8090/bist',
'www': 'https://www.coinfloor.co.uk',
'doc': [
'https://github.com/coinfloor/api',
'https://www.coinfloor.co.uk/api',
],
},
'api': {
'public': {
'get': [
'{id}/ticker/',
'{id}/order_book/',
'{id}/transactions/',
],
},
'private': {
'post': [
'{id}/balance/',
'{id}/user_transactions/',
'{id}/open_orders/',
'{id}/cancel_order/',
'{id}/buy/',
'{id}/sell/',
'{id}/buy_market/',
'{id}/sell_market/',
'{id}/estimate_sell_market/',
'{id}/estimate_buy_market/',
],
},
},
'markets': {
'BTC/GBP': {'id': 'XBT/GBP', 'symbol': 'BTC/GBP', 'base': 'BTC', 'quote': 'GBP'},
'BTC/EUR': {'id': 'XBT/EUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
'BTC/USD': {'id': 'XBT/USD', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'BTC/PLN': {'id': 'XBT/PLN', 'symbol': 'BTC/PLN', 'base': 'BTC', 'quote': 'PLN'},
'BCH/GBP': {'id': 'BCH/GBP', 'symbol': 'BCH/GBP', 'base': 'BCH', 'quote': 'GBP'},
},
}
params.update(config)
super(coinfloor, self).__init__(params)
def fetch_balance(self, params={}):
symbol = None
if 'symbol' in params:
symbol = params['symbol']
if 'id' in params:
symbol = params['id']
if not symbol:
raise ExchangeError(self.id + ' fetchBalance requires a symbol param')
return self.privatePostIdBalance({
'id': self.market_id(symbol),
})
def fetch_order_book(self, symbol):
orderbook = self.publicGetIdOrderBook({
'id': self.market_id(symbol),
})
return self.parse_order_book(orderbook)
def parse_ticker(self, ticker, market):
# rewrite to get the timestamp from HTTP headers
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': self.safe_float(ticker, 'vwap'),
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def fetch_ticker(self, symbol):
market = self.market(symbol)
ticker = self.publicGetIdTicker({
'id': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = trade['date'] * 1000
return {
'info': trade,
'id': str(trade['tid']),
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': None,
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetIdTransactions(self.extend({
'id': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
order = {'id': self.market_id(symbol)}
method = 'privatePostId' + self.capitalize(side)
if type == 'market':
order['quantity'] = amount
method += 'Market'
else:
order['price'] = price
order['amount'] = amount
return getattr(self, method)(self.extend(order, params))
def cancel_order(self, id):
return self.privatePostIdCancelOrder({'id': id})
def request(self, path, type='public', method='GET', params={}, headers=None, body=None):
# curl -k -u '[User ID]/[API key]:[Passphrase]' https://webapi.coinfloor.co.uk:8090/bist/XBT/GBP/balance/
url = self.urls['api'] + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if type == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
body = self.urlencode(self.extend({'nonce': nonce}, query))
auth = self.uid + '/' + self.apiKey + ':' + self.password
signature = base64.b64encode(auth)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': len(body),
'Authorization': 'Basic ' + signature,
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class coingi (Exchange):
def __init__(self, config={}):
params = {
'id': 'coingi',
'name': 'Coingi',
'rateLimit': 1000,
'countries': ['PA', 'BG', 'CN', 'US'], # Panama, Bulgaria, China, US
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28619707-5c9232a8-7212-11e7-86d6-98fe5d15cc6e.jpg',
'api': 'https://api.coingi.com',
'www': 'https://coingi.com',
'doc': 'http://docs.coingi.apiary.io/',
},
'api': {
'current': {
'get': [
'order-book/{pair}/{askCount}/{bidCount}/{depth}',
'transactions/{pair}/{maxCount}',
'24hour-rolling-aggregation',
],
},
'user': {
'post': [
'balance',
'add-order',
'cancel-order',
'orders',
'transactions',
'create-crypto-withdrawal',
],
},
},
'markets': {
'LTC/BTC': {'id': 'ltc-btc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
'PPC/BTC': {'id': 'ppc-btc', 'symbol': 'PPC/BTC', 'base': 'PPC', 'quote': 'BTC'},
'DOGE/BTC': {'id': 'doge-btc', 'symbol': 'DOGE/BTC', 'base': 'DOGE', 'quote': 'BTC'},
'VTC/BTC': {'id': 'vtc-btc', 'symbol': 'VTC/BTC', 'base': 'VTC', 'quote': 'BTC'},
'FTC/BTC': {'id': 'ftc-btc', 'symbol': 'FTC/BTC', 'base': 'FTC', 'quote': 'BTC'},
'NMC/BTC': {'id': 'nmc-btc', 'symbol': 'NMC/BTC', 'base': 'NMC', 'quote': 'BTC'},
'DASH/BTC': {'id': 'dash-btc', 'symbol': 'DASH/BTC', 'base': 'DASH', 'quote': 'BTC'},
},
}
params.update(config)
super(coingi, self).__init__(params)
def fetch_balance(self, params={}):
currencies = []
for c in range(0, len(self.currencies)):
currency = self.currencies[c].lower()
currencies.append(currency)
balances = self.userPostBalance({
'currencies': ','.join(currencies)
})
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']['name']
currency = currency.upper()
account = {
'free': balance['available'],
'used': balance['blocked'] + balance['inOrders'] + balance['withdrawing'],
'total': 0.0,
}
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
market = self.market(symbol)
orderbook = self.currentGetOrderBookPairAskCountBidCountDepth(self.extend({
'pair': market['id'],
'askCount': 512, # maximum returned number of asks 1-512
'bidCount': 512, # maximum returned number of bids 1-512
'depth': 32, # maximum number of depth range steps 1-32
}, params))
return self.parse_order_book(orderbook, None, 'bids', 'asks', 'price', 'baseAmount')
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': ticker['high'],
'low': ticker['low'],
'bid': ticker['highestBid'],
'ask': ticker['lowestAsk'],
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': ticker['baseVolume'],
'quoteVolume': ticker['counterVolume'],
'info': ticker,
}
return ticker
def fetch_tickers(self, symbols=None):
response = self.currentGet24hourRollingAggregation()
result = {}
for t in range(0, len(response)):
ticker = response[t]
base = ticker['currencyPair']['base'].upper()
quote = ticker['currencyPair']['counter'].upper()
symbol = base + '/' + quote
market = self.markets[symbol]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
tickers = self.fetchTickers(symbol)
return tickers[symbol]
def parse_trade(self, trade, market=None):
if not market:
market = self.markets_by_id[trade['currencyPair']]
return {
'id': trade['id'],
'info': trade,
'timestamp': trade['timestamp'],
'datetime': self.iso8601(trade['timestamp']),
'symbol': market['symbol'],
'type': None,
'side': None, # type
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.currentGetTransactionsPairMaxCount(self.extend({
'pair': market['id'],
'maxCount': 128,
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
order = {
'currencyPair': self.market_id(symbol),
'volume': amount,
'price': price,
'orderType': 0 if(side == 'buy') else 1,
}
response = self.userPostAddOrder(self.extend(order, params))
return {
'info': response,
'id': response['result'],
}
def cancel_order(self, id):
return self.userPostCancelOrder({'orderId': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + api + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'current':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
request = self.extend({
'token': self.apiKey,
'nonce': nonce,
}, query)
auth = str(nonce) + '$' + self.apiKey
request['signature'] = self.hmac(self.encode(auth), self.encode(self.secret))
body = self.json(request)
headers = {
'Content-Type': 'application/json',
}
response = self.fetch(url, method, headers, body)
if 'errors' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class coinmarketcap (Exchange):
def __init__(self, config={}):
params = {
'id': 'coinmarketcap',
'name': 'CoinMarketCap',
'rateLimit': 10000,
'version': 'v1',
'countries': 'US',
'hasPrivateAPI': False,
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28244244-9be6312a-69ed-11e7-99c1-7c1797275265.jpg',
'api': 'https://api.coinmarketcap.com',
'www': 'https://coinmarketcap.com',
'doc': 'https://coinmarketcap.com/api',
},
'api': {
'public': {
'get': [
'ticker/',
'ticker/{id}/',
'global/',
],
},
},
'currencies': [
'AUD',
'BRL',
'CAD',
'CHF',
'CNY',
'EUR',
'GBP',
'HKD',
'IDR',
'INR',
'JPY',
'KRW',
'MXN',
'RUB',
'USD',
],
}
params.update(config)
super(coinmarketcap, self).__init__(params)
def fetch_order_book(self, market, params={}):
raise ExchangeError('Fetching order books is not supported by the API of ' + self.id)
def fetch_markets(self):
markets = self.publicGetTicker()
result = []
for p in range(0, len(markets)):
market = markets[p]
for c in range(0, len(self.currencies)):
base = market['symbol']
baseId = market['id']
quote = self.currencies[c]
quoteId = quote.lower()
symbol = base + '/' + quote
id = baseId + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'info': market,
})
return result
def fetchGlobal(self, currency='USD'):
self.load_markets()
request = {}
if currency:
request['convert'] = currency
return self.publicGetGlobal(request)
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
if 'last_updated' in ticker:
if ticker['last_updated']:
timestamp = int(ticker['last_updated']) * 1000
volume = None
volumeKey = '24h_volume_' + market['quoteId']
if ticker[volumeKey]:
volume = float(ticker[volumeKey])
price = 'price_' + market['quoteId']
change = None
changeKey = 'percent_change_24h'
if ticker[changeKey]:
change = float(ticker[changeKey])
last = None
if price in ticker:
if ticker[price]:
last = float(ticker[price])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': None,
'ask': None,
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': last,
'change': change,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': volume,
'info': ticker,
}
def fetch_tickers(self, currency='USD'):
self.load_markets()
request = {}
if currency:
request['convert'] = currency
response = self.publicGetTicker(request)
tickers = {}
for t in range(0, len(response)):
ticker = response[t]
id = ticker['id'] + '/' + currency
market = self.markets_by_id[id]
symbol = market['symbol']
tickers[symbol] = self.parse_ticker(ticker, market)
return tickers
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
request = {
'convert': market['quote'],
'id': market['baseId'],
}
response = self.publicGetTickerId(request)
ticker = response[0]
return self.parse_ticker(ticker, market)
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if query:
url += '?' + self.urlencode(query)
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class coinmate (Exchange):
def __init__(self, config={}):
params = {
'id': 'coinmate',
'name': 'CoinMate',
'countries': ['GB', 'CZ'], # UK, Czech Republic
'rateLimit': 1000,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27811229-c1efb510-606c-11e7-9a36-84ba2ce412d8.jpg',
'api': 'https://coinmate.io/api',
'www': 'https://coinmate.io',
'doc': [
'http://docs.coinmate.apiary.io',
'https://coinmate.io/developers',
],
},
'api': {
'public': {
'get': [
'orderBook',
'ticker',
'transactions',
],
},
'private': {
'post': [
'balances',
'bitcoinWithdrawal',
'bitcoinDepositAddresses',
'buyInstant',
'buyLimit',
'cancelOrder',
'cancelOrderWithInfo',
'createVoucher',
'openOrders',
'redeemVoucher',
'sellInstant',
'sellLimit',
'transactionHistory',
'unconfirmedBitcoinDeposits',
],
},
},
'markets': {
'BTC/EUR': {'id': 'BTC_EUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
'BTC/CZK': {'id': 'BTC_CZK', 'symbol': 'BTC/CZK', 'base': 'BTC', 'quote': 'CZK'},
},
}
params.update(config)
super(coinmate, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostBalances()
balances = response['data']
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in balances:
account['free'] = balances[currency]['available']
account['used'] = balances[currency]['reserved']
account['total'] = balances[currency]['balance']
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
response = self.publicGetOrderBook(self.extend({
'currencyPair': self.market_id(symbol),
'groupByPriceLimit': 'False',
}, params))
orderbook = response['data']
timestamp = orderbook['timestamp'] * 1000
return self.parse_order_book(orderbook, timestamp, 'bids', 'asks', 'price', 'amount')
def fetch_ticker(self, symbol):
response = self.publicGetTicker({
'currencyPair': self.market_id(symbol),
})
ticker = response['data']
timestamp = ticker['timestamp'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['amount']),
'info': ticker,
}
def parse_trade(self, trade, market=None):
timestamp = trade['timestamp'] * 1000
if not market:
market = self.markets_by_id[trade['currencyPair']]
return {
'id': trade['transactionId'],
'info': trade,
'timestamp': trade['timestamp'],
'datetime': self.iso8601(trade['timestamp']),
'symbol': market['symbol'],
'type': None,
'side': None,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTransactions(self.extend({
'currencyPair': market['id'],
'minutesIntoHistory': 10,
}, params))
return self.parse_trades(response['data'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
method = 'privatePost' + self.capitalize(side)
order = {
'currencyPair': self.market_id(symbol),
}
if type == 'market':
if side == 'buy':
order['total'] = amount # amount in fiat
else:
order['amount'] = amount # amount in fiat
method += 'Instant'
else:
order['amount'] = amount # amount in crypto
order['price'] = price
method += self.capitalize(type)
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': str(response['data']),
}
def cancel_order(self, id):
return self.privatePostCancelOrder({'orderId': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
if not self.uid:
raise AuthenticationError(self.id + ' requires `' + self.id + '.uid` property for authentication')
nonce = str(self.nonce())
auth = nonce + self.uid + self.apiKey
signature = self.hmac(self.encode(auth), self.encode(self.secret))
body = self.urlencode(self.extend({
'clientId': self.uid,
'nonce': nonce,
'publicKey': self.apiKey,
'signature': signature.upper(),
}, params))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
response = self.fetch(url, method, headers, body)
if 'error' in response:
if response['error']:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class coinsecure (Exchange):
def __init__(self, config={}):
params = {
'id': 'coinsecure',
'name': 'Coinsecure',
'countries': 'IN', # India
'rateLimit': 1000,
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766472-9cbd200a-5ed9-11e7-9551-2267ad7bac08.jpg',
'api': 'https://api.coinsecure.in',
'www': 'https://coinsecure.in',
'doc': [
'https://api.coinsecure.in',
'https://github.com/coinsecure/plugins',
],
},
'api': {
'public': {
'get': [
'bitcoin/search/confirmation/{txid}',
'exchange/ask/low',
'exchange/ask/orders',
'exchange/bid/high',
'exchange/bid/orders',
'exchange/lastTrade',
'exchange/max24Hr',
'exchange/min24Hr',
'exchange/ticker',
'exchange/trades',
],
},
'private': {
'get': [
'mfa/authy/call',
'mfa/authy/sms',
'netki/search/{netkiName}',
'user/bank/otp/{number}',
'user/kyc/otp/{number}',
'user/profile/phone/otp/{number}',
'user/wallet/coin/address/{id}',
'user/wallet/coin/deposit/confirmed/all',
'user/wallet/coin/deposit/confirmed/{id}',
'user/wallet/coin/deposit/unconfirmed/all',
'user/wallet/coin/deposit/unconfirmed/{id}',
'user/wallet/coin/wallets',
'user/exchange/bank/fiat/accounts',
'user/exchange/bank/fiat/balance/available',
'user/exchange/bank/fiat/balance/pending',
'user/exchange/bank/fiat/balance/total',
'user/exchange/bank/fiat/deposit/cancelled',
'user/exchange/bank/fiat/deposit/unverified',
'user/exchange/bank/fiat/deposit/verified',
'user/exchange/bank/fiat/withdraw/cancelled',
'user/exchange/bank/fiat/withdraw/completed',
'user/exchange/bank/fiat/withdraw/unverified',
'user/exchange/bank/fiat/withdraw/verified',
'user/exchange/ask/cancelled',
'user/exchange/ask/completed',
'user/exchange/ask/pending',
'user/exchange/bid/cancelled',
'user/exchange/bid/completed',
'user/exchange/bid/pending',
'user/exchange/bank/coin/addresses',
'user/exchange/bank/coin/balance/available',
'user/exchange/bank/coin/balance/pending',
'user/exchange/bank/coin/balance/total',
'user/exchange/bank/coin/deposit/cancelled',
'user/exchange/bank/coin/deposit/unverified',
'user/exchange/bank/coin/deposit/verified',
'user/exchange/bank/coin/withdraw/cancelled',
'user/exchange/bank/coin/withdraw/completed',
'user/exchange/bank/coin/withdraw/unverified',
'user/exchange/bank/coin/withdraw/verified',
'user/exchange/bank/summary',
'user/exchange/coin/fee',
'user/exchange/fiat/fee',
'user/exchange/kycs',
'user/exchange/referral/coin/paid',
'user/exchange/referral/coin/successful',
'user/exchange/referral/fiat/paid',
'user/exchange/referrals',
'user/exchange/trade/summary',
'user/login/token/{token}',
'user/summary',
'user/wallet/summary',
'wallet/coin/withdraw/cancelled',
'wallet/coin/withdraw/completed',
'wallet/coin/withdraw/unverified',
'wallet/coin/withdraw/verified',
],
'post': [
'login',
'login/initiate',
'login/password/forgot',
'mfa/authy/initiate',
'mfa/ga/initiate',
'signup',
'user/netki/update',
'user/profile/image/update',
'user/exchange/bank/coin/withdraw/initiate',
'user/exchange/bank/coin/withdraw/newVerifycode',
'user/exchange/bank/fiat/withdraw/initiate',
'user/exchange/bank/fiat/withdraw/newVerifycode',
'user/password/change',
'user/password/reset',
'user/wallet/coin/withdraw/initiate',
'wallet/coin/withdraw/newVerifycode',
],
'put': [
'signup/verify/{token}',
'user/exchange/kyc',
'user/exchange/bank/fiat/deposit/new',
'user/exchange/ask/new',
'user/exchange/bid/new',
'user/exchange/instant/buy',
'user/exchange/instant/sell',
'user/exchange/bank/coin/withdraw/verify',
'user/exchange/bank/fiat/account/new',
'user/exchange/bank/fiat/withdraw/verify',
'user/mfa/authy/initiate/enable',
'user/mfa/ga/initiate/enable',
'user/netki/create',
'user/profile/phone/new',
'user/wallet/coin/address/new',
'user/wallet/coin/new',
'user/wallet/coin/withdraw/sendToExchange',
'user/wallet/coin/withdraw/verify',
],
'delete': [
'user/gcm/{code}',
'user/logout',
'user/exchange/bank/coin/withdraw/unverified/cancel/{withdrawID}',
'user/exchange/bank/fiat/deposit/cancel/{depositID}',
'user/exchange/ask/cancel/{orderID}',
'user/exchange/bid/cancel/{orderID}',
'user/exchange/bank/fiat/withdraw/unverified/cancel/{withdrawID}',
'user/mfa/authy/disable/{code}',
'user/mfa/ga/disable/{code}',
'user/profile/phone/delete',
'user/profile/image/delete/{netkiName}',
'user/wallet/coin/withdraw/unverified/cancel/{withdrawID}',
],
},
},
'markets': {
'BTC/INR': {'id': 'BTC/INR', 'symbol': 'BTC/INR', 'base': 'BTC', 'quote': 'INR'},
},
}
params.update(config)
super(coinsecure, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privateGetUserExchangeBankSummary()
balance = response['message']
coin = {
'free': balance['availableCoinBalance'],
'used': balance['pendingCoinBalance'],
'total': balance['totalCoinBalance'],
}
fiat = {
'free': balance['availableFiatBalance'],
'used': balance['pendingFiatBalance'],
'total': balance['totalFiatBalance'],
}
result = {
'info': balance,
'BTC': coin,
'INR': fiat,
}
return result
def fetch_order_book(self, market, params={}):
bids = self.publicGetExchangeBidOrders(params)
asks = self.publicGetExchangeAskOrders(params)
orderbook = {
'bids': bids['message'],
'asks': asks['message'],
}
return self.parse_order_book(orderbook, None, 'bids', 'asks', 'rate', 'vol')
def fetch_ticker(self, market):
response = self.publicGetExchangeTicker()
ticker = response['message']
timestamp = ticker['timestamp']
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': float(ticker['open']),
'close': None,
'first': None,
'last': float(ticker['lastPrice']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['coinvolume']),
'quoteVolume': float(ticker['fiatvolume']),
'info': ticker,
}
def fetch_trades(self, market, params={}):
return self.publicGetExchangeTrades(params)
def create_order(self, market, type, side, amount, price=None, params={}):
method = 'privatePutUserExchange'
order = {}
if type == 'market':
method += 'Instant' + self.capitalize(side)
if side == 'buy':
order['maxFiat'] = amount
else:
order['maxVol'] = amount
else:
direction = 'Bid' if(side == 'buy') else 'Ask'
method += direction + 'New'
order['rate'] = price
order['vol'] = amount
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': response['message']['orderID'],
}
def cancel_order(self, id):
raise ExchangeError(self.id + ' cancelOrder() is not fully implemented yet')
method = 'privateDeleteUserExchangeAskCancelOrderId' # TODO fixme, have to specify order side here
return getattr(self, method)({'orderID': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'private':
headers = {'Authorization': self.apiKey}
if query:
body = self.json(query)
headers['Content-Type'] = 'application/json'
response = self.fetch(url, method, headers, body)
if 'success' in response:
if response['success']:
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class coinspot (Exchange):
def __init__(self, config={}):
params = {
'id': 'coinspot',
'name': 'CoinSpot',
'countries': 'AU', # Australia
'rateLimit': 1000,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28208429-3cacdf9a-6896-11e7-854e-4c79a772a30f.jpg',
'api': {
'public': 'https://www.coinspot.com.au/pubapi',
'private': 'https://www.coinspot.com.au/api',
},
'www': 'https://www.coinspot.com.au',
'doc': 'https://www.coinspot.com.au/api',
},
'api': {
'public': {
'get': [
'latest',
],
},
'private': {
'post': [
'orders',
'orders/history',
'my/coin/deposit',
'my/coin/send',
'quote/buy',
'quote/sell',
'my/balances',
'my/orders',
'my/buy',
'my/sell',
'my/buy/cancel',
'my/sell/cancel',
],
},
},
'markets': {
'BTC/AUD': {'id': 'BTC', 'symbol': 'BTC/AUD', 'base': 'BTC', 'quote': 'AUD'},
'LTC/AUD': {'id': 'LTC', 'symbol': 'LTC/AUD', 'base': 'LTC', 'quote': 'AUD'},
'DOGE/AUD': {'id': 'DOGE', 'symbol': 'DOGE/AUD', 'base': 'DOGE', 'quote': 'AUD'},
},
}
params.update(config)
super(coinspot, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostMyBalances()
result = {'info': response}
if 'balance' in response:
balances = response['balance']
currencies = list(balances.keys())
for c in range(0, len(currencies)):
currency = currencies[c]
uppercase = currency.upper()
account = {
'free': balances[currency],
'used': 0.0,
'total': balances[currency],
}
if uppercase == 'DRK':
uppercase = 'DASH'
result[uppercase] = account
return result
def fetch_order_book(self, symbol, params={}):
market = self.market(symbol)
orderbook = self.privatePostOrders(self.extend({
'cointype': market['id'],
}, params))
timestamp = self.milliseconds()
result = self.parse_order_book(orderbook, None, 'buyorders', 'sellorders', 'rate', 'amount')
result['bids'] = self.sort_by(result['bids'], 0, True)
result['asks'] = self.sort_by(result['asks'], 0)
return result
def fetch_ticker(self, market):
response = self.publicGetLatest()
id = self.market_id(market)
id = id.lower()
ticker = response['prices'][id]
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': None,
'info': ticker,
}
def fetch_trades(self, market, params={}):
return self.privatePostOrdersHistory(self.extend({
'cointype': self.market_id(market),
}, params))
def create_order(self, market, type, side, amount, price=None, params={}):
method = 'privatePostMy' + self.capitalize(side)
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
order = {
'cointype': self.market_id(market),
'amount': amount,
'rate': price,
}
return getattr(self, method)(self.extend(order, params))
def cancel_order(self, id, params={}):
raise ExchangeError(self.id + ' cancelOrder() is not fully implemented yet')
method = 'privatePostMyBuy'
return getattr(self, method)({'id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
if not self.apiKey:
raise AuthenticationError(self.id + ' requires apiKey for all requests')
url = self.urls['api'][api] + '/' + path
if api == 'private':
nonce = self.nonce()
body = self.json(self.extend({'nonce': nonce}, params))
headers = {
'Content-Type': 'application/json',
'key': self.apiKey,
'sign': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class cryptopia (Exchange):
def __init__(self, config={}):
params = {
'id': 'cryptopia',
'name': 'Cryptopia',
'rateLimit': 1500,
'countries': 'NZ', # New Zealand
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/29484394-7b4ea6e2-84c6-11e7-83e5-1fccf4b2dc81.jpg',
'api': 'https://www.cryptopia.co.nz/api',
'www': 'https://www.cryptopia.co.nz',
'doc': [
'https://www.cryptopia.co.nz/Forum/Thread/255',
'https://www.cryptopia.co.nz/Forum/Thread/256',
],
},
'api': {
'public': {
'get': [
'GetCurrencies',
'GetTradePairs',
'GetMarkets',
'GetMarkets/{id}',
'GetMarkets/{hours}',
'GetMarkets/{id}/{hours}',
'GetMarket/{id}',
'GetMarket/{id}/{hours}',
'GetMarketHistory/{id}',
'GetMarketHistory/{id}/{hours}',
'GetMarketOrders/{id}',
'GetMarketOrders/{id}/{count}',
'GetMarketOrderGroups/{ids}/{count}',
],
},
'private': {
'post': [
'CancelTrade',
'GetBalance',
'GetDepositAddress',
'GetOpenOrders',
'GetTradeHistory',
'GetTransactions',
'SubmitTip',
'SubmitTrade',
'SubmitTransfer',
'SubmitWithdraw',
],
},
},
}
params.update(config)
super(cryptopia, self).__init__(params)
def fetch_markets(self):
response = self.publicGetMarkets()
result = []
markets = response['Data']
for i in range(0, len(markets)):
market = markets[i]
id = market['TradePairId']
symbol = market['Label']
base, quote = symbol.split('/')
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_order_book(self, market, params={}):
self.load_markets()
response = self.publicGetMarketOrdersId(self.extend({
'id': self.market_id(market),
}, params))
orderbook = response['Data']
return self.parse_order_book(orderbook, None, 'Buy', 'Sell', 'Price', 'Volume')
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
return {
'info': ticker,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['High']),
'low': float(ticker['Low']),
'bid': float(ticker['BidPrice']),
'ask': float(ticker['AskPrice']),
'vwap': None,
'open': float(ticker['Open']),
'close': float(ticker['Close']),
'first': None,
'last': float(ticker['LastPrice']),
'change': float(ticker['Change']),
'percentage': None,
'average': None,
'baseVolume': float(ticker['BaseVolume']),
'quoteVolume': float(ticker['Volume']),
}
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
response = self.publicGetMarketId({
'id': market['id'],
})
ticker = response['Data']
return self.parse_ticker(ticker, market)
def fetch_tickers(self):
self.load_markets()
response = self.publicGetMarkets()
result = {}
tickers = response['Data']
for i in range(0, len(tickers)):
ticker = tickers[i]
id = ticker['TradePairId']
market = self.markets_by_id[id]
symbol = market['symbol']
result[symbol] = self.parse_ticker(ticker, market)
return result
def parse_trade(self, trade, market):
timestamp = trade['Timestamp'] * 1000
return {
'id': None,
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['Type'].lower(),
'price': trade['Price'],
'amount': trade['Amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetMarketHistoryIdHours(self.extend({
'id': market['id'],
'hours': 24, # default
}, params))
trades = response['Data']
return self.parse_trades(trades, market)
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostGetBalance()
balances = response['Data']
result = {'info': response}
for i in range(0, len(balances)):
balance = balances[i]
currency = balance['Symbol']
account = {
'free': balance['Available'],
'used': 0.0,
'total': balance['Total'],
}
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def create_order(self, market, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'TradePairId': self.market_id(market),
'Type': self.capitalize(side),
'Rate': price,
'Amount': amount,
}
response = self.privatePostSubmitTrade(self.extend(order, params))
return {
'info': response,
'id': str(response['Data']['OrderId']),
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostCancelTrade({
'Type': 'Trade',
'OrderId': id,
})
def parse_order(self, order, market=None):
symbol = None
if market:
symbol = market['symbol']
elif 'Market' in order:
id = order['Market']
if id in self.markets_by_id:
market = self.markets_by_id[id]
symbol = market['symbol']
timestamp = self.parse8601(order['TimeStamp'])
amount = order['Amount']
remaining = order['Remaining']
filled = amount - remaining
return {
'id': str(order['OrderId']),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'status': order['status'],
'symbol': symbol,
'type': 'limit',
'side': order['Type'].lower(),
'price': order['Rate'],
'amount': amount,
'filled': filled,
'remaining': remaining,
# 'trades': self.parse_trades(order['trades'], market),
}
def fetch_open_orders(self, symbol=None, params={}):
if not symbol:
raise ExchangeError(self.id + ' fetchOpenOrders requires a symbol param')
self.load_markets()
market = self.market(symbol)
response = self.privatePostGetOpenOrders({
# 'Market': market['id'],
'TradePairId': market['id'], # Cryptopia identifier(not required if 'Market' supplied)
# 'Count': 100, # default = 100
}, params)
orders = response['Data']
result = []
for i in range(0, len(orders)):
order = orders[i]
result.append(self.extend(order, {'status': 'open'}))
return self.parse_orders(result, market)
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
response = self.privatePostSubmitWithdraw(self.extend({
'Currency': currency,
'Amount': amount,
'Address': address, # Address must exist in you AddressBook in security settings
}, params))
return {
'info': response,
'id': response['Data'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = str(self.nonce())
body = self.json(query)
hash = self.hash(self.encode(body), 'md5', 'base64')
secret = base64.b64decode(self.secret)
uri = self.encode_uri_component(url)
lowercase = uri.lower()
payload = self.apiKey + method + lowercase + nonce + self.binary_to_string(hash)
signature = self.hmac(self.encode(payload), secret, hashlib.sha256, 'base64')
auth = 'amx ' + self.apiKey + ':' + self.binary_to_string(signature) + ':' + nonce
headers = {
'Content-Type': 'application/json',
'Authorization': auth,
}
response = self.fetch(url, method, headers, body)
if response:
if 'Success' in response:
if response['Success']:
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class dsx (Exchange):
def __init__(self, config={}):
params = {
'id': 'dsx',
'name': 'DSX',
'countries': 'UK',
'rateLimit': 1500,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27990275-1413158a-645a-11e7-931c-94717f7510e3.jpg',
'api': {
'mapi': 'https://dsx.uk/mapi', # market data
'tapi': 'https://dsx.uk/tapi', # trading
'dwapi': 'https://dsx.uk/dwapi', # deposit/withdraw
},
'www': 'https://dsx.uk',
'doc': [
'https://api.dsx.uk',
'https://dsx.uk/api_docs/public',
'https://dsx.uk/api_docs/private',
'',
],
},
'api': {
# market data (public)
'mapi': {
'get': [
'barsFromMoment/{id}/{period}/{start}', # empty reply :\
'depth/{id}',
'info',
'lastBars/{id}/{period}/{amount}', # period is (m, h or d)
'periodBars/{id}/{period}/{start}/{end}',
'ticker/{id}',
'trades/{id}',
],
},
# trading (private)
'tapi': {
'post': [
'getInfo',
'TransHistory',
'TradeHistory',
'OrderHistory',
'ActiveOrders',
'Trade',
'CancelOrder',
],
},
# deposit / withdraw (private)
'dwapi': {
'post': [
'getCryptoDepositAddress',
'cryptoWithdraw',
'fiatWithdraw',
'getTransactionStatus',
'getTransactions',
],
},
},
}
params.update(config)
super(dsx, self).__init__(params)
def fetch_markets(self):
response = self.mapiGetInfo()
keys = list(response['pairs'].keys())
result = []
for p in range(0, len(keys)):
id = keys[p]
market = response['pairs'][id]
base = id[0:3]
quote = id[3:6]
base = base.upper()
quote = quote.upper()
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.tapiPostGetInfo()
balances = response['return']
result = {'info': balances}
currencies = list(balances['total'].keys())
for c in range(0, len(currencies)):
currency = currencies[c]
account = {
'free': balances['funds'][currency],
'used': 0.0,
'total': balances['total'][currency],
}
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.mapiGetDepthId(self.extend({
'id': market['id'],
}, params))
orderbook = response[market['id']]
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
response = self.mapiGetTickerId({
'id': market['id'],
})
ticker = response[market['id']]
timestamp = ticker['updated'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': float(ticker['avg']),
'baseVolume': float(ticker['vol']),
'quoteVolume': float(ticker['vol_cur']),
'info': ticker,
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
return self.mapiGetTradesId(self.extend({
'id': self.market_id(symbol),
}, params))
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
order = {
'pair': self.market_id(symbol),
'type': side,
'rate': price,
'amount': amount,
}
response = self.tapiPostTrade(self.extend(order, params))
return {
'info': response,
'id': str(response['return']['orderId']),
}
def cancel_order(self, id):
self.load_markets()
return self.tapiPostCancelOrder({'orderId': id})
def request(self, path, api='mapi', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
if(api == 'mapi') or(api == 'dwapi'):
url += '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'mapi':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
body = self.urlencode(self.extend({
'method': path,
'nonce': nonce,
}, query))
signature = self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512, 'base64')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': self.apiKey,
'Sign': self.decode(signature),
}
response = self.fetch(url, method, headers, body)
if api == 'mapi':
return response
if 'success' in response:
if response['success']:
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class exmo (Exchange):
def __init__(self, config={}):
params = {
'id': 'exmo',
'name': 'EXMO',
'countries': ['ES', 'RU'], # Spain, Russia
'rateLimit': 1000, # once every 350 ms ≈ 180 requests per minute ≈ 3 requests per second
'version': 'v1',
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766491-1b0ea956-5eda-11e7-9225-40d67b481b8d.jpg',
'api': 'https://api.exmo.com',
'www': 'https://exmo.me',
'doc': [
'https://exmo.me/ru/api_doc',
'https://github.com/exmo-dev/exmo_api_lib/tree/master/nodejs',
],
},
'api': {
'public': {
'get': [
'currency',
'order_book',
'pair_settings',
'ticker',
'trades',
],
},
'private': {
'post': [
'user_info',
'order_create',
'order_cancel',
'user_open_orders',
'user_trades',
'user_cancelled_orders',
'order_trades',
'required_amount',
'deposit_address',
'withdraw_crypt',
'withdraw_get_txid',
'excode_create',
'excode_load',
'wallet_history',
],
},
},
}
params.update(config)
super(exmo, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetPairSettings()
keys = list(markets.keys())
result = []
for p in range(0, len(keys)):
id = keys[p]
market = markets[id]
symbol = id.replace('_', '/')
base, quote = symbol.split('/')
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostUserInfo()
result = {'info': response}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
account = self.account()
if currency in response['balances']:
account['free'] = float(response['balances'][currency])
if currency in response['reserved']:
account['used'] = float(response['reserved'][currency])
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetOrderBook(self.extend({
'pair': market['id'],
}, params))
orderbook = response[market['id']]
return self.parse_order_book(orderbook, None, 'bid', 'ask')
def parse_ticker(self, ticker, market):
timestamp = ticker['updated'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy_price']),
'ask': float(ticker['sell_price']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last_trade']),
'change': None,
'percentage': None,
'average': float(ticker['avg']),
'baseVolume': float(ticker['vol']),
'quoteVolume': float(ticker['vol_curr']),
'info': ticker,
}
def fetch_tickers(self, currency='USD'):
self.load_markets()
response = self.publicGetTicker()
result = {}
ids = list(response.keys())
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = response[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
response = self.publicGetTicker()
market = self.market(symbol)
return self.parse_ticker(response[market['id']], market)
def parse_trade(self, trade, market):
timestamp = trade['date'] * 1000
return {
'id': str(trade['trade_id']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': None,
'type': None,
'side': trade['type'],
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTrades(self.extend({
'pair': market['id'],
}, params))
return self.parse_trades(response[market['id']], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
prefix = ''
if type == 'market':
prefix = 'market_'
order = {
'pair': self.market_id(symbol),
'quantity': amount,
'price': price or 0,
'type': prefix + side,
}
response = self.privatePostOrderCreate(self.extend(order, params))
return {
'info': response,
'id': str(response['order_id']),
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostOrderCancel({'order_id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
nonce = self.nonce()
body = self.urlencode(self.extend({'nonce': nonce}, params))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': len(body),
'Key': self.apiKey,
'Sign': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
response = self.fetch(url, method, headers, body)
if 'result' in response:
if response['result']:
return response
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class flowbtc (Exchange):
def __init__(self, config={}):
params = {
'id': 'flowbtc',
'name': 'flowBTC',
'countries': 'BR', # Brazil
'version': 'v1',
'rateLimit': 1000,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28162465-cd815d4c-67cf-11e7-8e57-438bea0523a2.jpg',
'api': 'https://api.flowbtc.com:8400/ajax',
'www': 'https://trader.flowbtc.com',
'doc': 'http://www.flowbtc.com.br/api/',
},
'api': {
'public': {
'post': [
'GetTicker',
'GetTrades',
'GetTradesByDate',
'GetOrderBook',
'GetProductPairs',
'GetProducts',
],
},
'private': {
'post': [
'CreateAccount',
'GetUserInfo',
'SetUserInfo',
'GetAccountInfo',
'GetAccountTrades',
'GetDepositAddresses',
'Withdraw',
'CreateOrder',
'ModifyOrder',
'CancelOrder',
'CancelAllOrders',
'GetAccountOpenOrders',
'GetOrderFee',
],
},
},
}
params.update(config)
super(flowbtc, self).__init__(params)
def fetch_markets(self):
response = self.publicPostGetProductPairs()
markets = response['productPairs']
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['name']
base = market['product1Label']
quote = market['product2Label']
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostGetAccountInfo()
balances = response['currencies']
result = {'info': response}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['name']
account = {
'free': balance['balance'],
'used': balance['hold'],
'total': 0.0,
}
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
orderbook = self.publicPostGetOrderBook(self.extend({
'productPair': market['id'],
}, params))
return self.parse_order_book(orderbook, None, 'bids', 'asks', 'px', 'qty')
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicPostGetTicker({
'productPair': market['id'],
})
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['volume24hr']),
'quoteVolume': float(ticker['volume24hrProduct2']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['unixtime'] * 1000
side = 'buy' if(trade['incomingOrderSide'] == 0) else 'sell'
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'id': str(trade['tid']),
'order': None,
'type': None,
'side': side,
'price': trade['px'],
'amount': trade['qty'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicPostGetTrades(self.extend({
'ins': market['id'],
'startIndex': -1,
}, params))
return self.parse_trades(response['trades'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
orderType = 1 if(type == 'market') else 0
order = {
'ins': self.market_id(symbol),
'side': side,
'orderType': orderType,
'qty': amount,
'px': price,
}
response = self.privatePostCreateOrder(self.extend(order, params))
return {
'info': response,
'id': response['serverOrderId'],
}
def cancel_order(self, id, params={}):
self.load_markets()
if 'ins' in params:
return self.privatePostCancelOrder(self.extend({
'serverOrderId': id,
}, params))
raise ExchangeError(self.id + ' requires `ins` symbol parameter for cancelling an order')
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + path
if api == 'public':
if params:
body = self.json(params)
else:
if not self.uid:
raise AuthenticationError(self.id + ' requires `' + self.id + '.uid` property for authentication')
nonce = self.nonce()
auth = str(nonce) + self.uid + self.apiKey
signature = self.hmac(self.encode(auth), self.encode(self.secret))
body = self.json(self.extend({
'apiKey': self.apiKey,
'apiNonce': nonce,
'apiSig': signature.upper(),
}, params))
headers = {
'Content-Type': 'application/json',
}
response = self.fetch(url, method, headers, body)
if 'isAccepted' in response:
if response['isAccepted']:
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class foxbit (blinktrade):
def __init__(self, config={}):
params = {
'id': 'foxbit',
'name': 'FoxBit',
'countries': 'BR',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27991413-11b40d42-647f-11e7-91ee-78ced874dd09.jpg',
'api': {
'public': 'https://api.blinktrade.com/api',
'private': 'https://api.blinktrade.com/tapi',
},
'www': 'https://foxbit.exchange',
'doc': 'https://blinktrade.com/docs',
},
'comment': 'Blinktrade API',
'markets': {
'BTC/BRL': {'id': 'BTCBRL', 'symbol': 'BTC/BRL', 'base': 'BTC', 'quote': 'BRL', 'brokerId': 4, 'broker': 'FoxBit'},
},
}
params.update(config)
super(foxbit, self).__init__(params)
#------------------------------------------------------------------------------
class fyb (Exchange):
def __init__(self, config={}):
params = {
'rateLimit': 1500,
'api': {
'public': {
'get': [
'ticker',
'tickerdetailed',
'orderbook',
'trades',
],
},
'private': {
'post': [
'test',
'getaccinfo',
'getpendingorders',
'getorderhistory',
'cancelpendingorder',
'placeorder',
'withdraw',
],
},
},
}
params.update(config)
super(fyb, self).__init__(params)
def fetch_balance(self, params={}):
balance = self.privatePostGetaccinfo()
btc = float(balance['btcBal'])
symbol = self.symbols[0]
quote = self.markets[symbol]['quote']
lowercase = quote.lower() + 'Bal'
fiat = float(balance[lowercase])
crypto = {
'free': btc,
'used': 0.0,
'total': btc,
}
accounts = {'BTC': crypto}
accounts[quote] = {
'free': fiat,
'used': 0.0,
'total': fiat,
}
accounts['info'] = balance
return accounts
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetOrderbook(params)
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
ticker = self.publicGetTickerdetailed()
timestamp = self.milliseconds()
last = None
volume = None
if 'last' in ticker:
last = float(ticker['last'])
if 'vol' in ticker:
volume = float(ticker['vol'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': last,
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': volume,
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = int(trade['date']) * 1000
return {
'info': trade,
'id': str(trade['tid']),
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': None,
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTrades(params)
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
response = self.privatePostPlaceorder(self.extend({
'qty': amount,
'price': price,
'type': side[0].upper()
}, params))
return {
'info': response,
'id': response['pending_oid'],
}
def cancel_order(self, id):
return self.privatePostCancelpendingorder({'orderNo': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + path
if api == 'public':
url += '.json'
else:
nonce = self.nonce()
body = self.urlencode(self.extend({'timestamp': nonce}, params))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'key': self.apiKey,
'sig': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha1)
}
response = self.fetch(url, method, headers, body)
if api == 'private':
if 'error' in response:
if response['error']:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class fybse (fyb):
def __init__(self, config={}):
params = {
'id': 'fybse',
'name': 'FYB-SE',
'countries': 'SE', # Sweden
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766512-31019772-5edb-11e7-8241-2e675e6797f1.jpg',
'api': 'https://www.fybse.se/api/SEK',
'www': 'https://www.fybse.se',
'doc': 'http://docs.fyb.apiary.io',
},
'markets': {
'BTC/SEK': {'id': 'SEK', 'symbol': 'BTC/SEK', 'base': 'BTC', 'quote': 'SEK'},
},
}
params.update(config)
super(fybse, self).__init__(params)
#------------------------------------------------------------------------------
class fybsg (fyb):
def __init__(self, config={}):
params = {
'id': 'fybsg',
'name': 'FYB-SG',
'countries': 'SG', # Singapore
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766513-3364d56a-5edb-11e7-9e6b-d5898bb89c81.jpg',
'api': 'https://www.fybsg.com/api/SGD',
'www': 'https://www.fybsg.com',
'doc': 'http://docs.fyb.apiary.io',
},
'markets': {
'BTC/SGD': {'id': 'SGD', 'symbol': 'BTC/SGD', 'base': 'BTC', 'quote': 'SGD'},
},
}
params.update(config)
super(fybsg, self).__init__(params)
#------------------------------------------------------------------------------
class gatecoin (Exchange):
def __init__(self, config={}):
params = {
'id': 'gatecoin',
'name': 'Gatecoin',
'rateLimit': 2000,
'countries': 'HK', # Hong Kong
'comment': 'a regulated/licensed exchange',
'hasFetchTickers': True,
'hasFetchOHLCV': True,
'timeframes': {
'1m': '1m',
'15m': '15m',
'1h': '1h',
'6h': '6h',
'1d': '24h',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28646817-508457f2-726c-11e7-9eeb-3528d2413a58.jpg',
'api': 'https://api.gatecoin.com',
'www': 'https://gatecoin.com',
'doc': [
'https://gatecoin.com/api',
'https://github.com/Gatecoin/RESTful-API-Implementation',
'https://api.gatecoin.com/swagger-ui/index.html',
],
},
'api': {
'public': {
'get': [
'Public/ExchangeRate', # Get the exchange rates
'Public/LiveTicker', # Get live ticker for all currency
'Public/LiveTicker/{CurrencyPair}', # Get live ticker by currency
'Public/LiveTickers', # Get live ticker for all currency
'Public/MarketDepth/{CurrencyPair}', # Gets prices and market depth for the currency pair.
'Public/NetworkStatistics/{DigiCurrency}', # Get the network status of a specific digital currency
'Public/StatisticHistory/{DigiCurrency}/{Typeofdata}', # Get the historical data of a specific digital currency
'Public/TickerHistory/{CurrencyPair}/{Timeframe}', # Get ticker history
'Public/Transactions/{CurrencyPair}', # Gets recent transactions
'Public/TransactionsHistory/{CurrencyPair}', # Gets all transactions
'Reference/BusinessNatureList', # Get the business nature list.
'Reference/Countries', # Get the country list.
'Reference/Currencies', # Get the currency list.
'Reference/CurrencyPairs', # Get the currency pair list.
'Reference/CurrentStatusList', # Get the current status list.
'Reference/IdentydocumentTypes', # Get the different types of identity documents possible.
'Reference/IncomeRangeList', # Get the income range list.
'Reference/IncomeSourceList', # Get the income source list.
'Reference/VerificationLevelList', # Get the verif level list.
'Stream/PublicChannel', # Get the public pubnub channel list
],
'post': [
'Export/Transactions', # Request a export of all trades from based on currencypair, start date and end date
'Ping', # Post a string, then get it back.
'Public/Unsubscribe/{EmailCode}', # Lets the user unsubscribe from emails
'RegisterUser', # Initial trader registration.
],
},
'private': {
'get': [
'Account/CorporateData', # Get corporate account data
'Account/DocumentAddress', # Check if residence proof uploaded
'Account/DocumentCorporation', # Check if registered document uploaded
'Account/DocumentID', # Check if ID document copy uploaded
'Account/DocumentInformation', # Get Step3 Data
'Account/Email', # Get user email
'Account/FeeRate', # Get fee rate of logged in user
'Account/Level', # Get verif level of logged in user
'Account/PersonalInformation', # Get Step1 Data
'Account/Phone', # Get user phone number
'Account/Profile', # Get trader profile
'Account/Questionnaire', # Fill the questionnaire
'Account/Referral', # Get referral information
'Account/ReferralCode', # Get the referral code of the logged in user
'Account/ReferralNames', # Get names of referred traders
'Account/ReferralReward', # Get referral reward information
'Account/ReferredCode', # Get referral code
'Account/ResidentInformation', # Get Step2 Data
'Account/SecuritySettings', # Get verif details of logged in user
'Account/User', # Get all user info
'APIKey/APIKey', # Get API Key for logged in user
'Auth/ConnectionHistory', # Gets connection history of logged in user
'Balance/Balances', # Gets the available balance for each currency for the logged in account.
'Balance/Balances/{Currency}', # Gets the available balance for s currency for the logged in account.
'Balance/Deposits', # Get all account deposits, including wire and digital currency, of the logged in user
'Balance/Withdrawals', # Get all account withdrawals, including wire and digital currency, of the logged in user
'Bank/Accounts/{Currency}/{Location}', # Get internal bank account for deposit
'Bank/Transactions', # Get all account transactions of the logged in user
'Bank/UserAccounts', # Gets all the bank accounts related to the logged in user.
'Bank/UserAccounts/{Currency}', # Gets all the bank accounts related to the logged in user.
'ElectronicWallet/DepositWallets', # Gets all crypto currency addresses related deposits to the logged in user.
'ElectronicWallet/DepositWallets/{DigiCurrency}', # Gets all crypto currency addresses related deposits to the logged in user by currency.
'ElectronicWallet/Transactions', # Get all digital currency transactions of the logged in user
'ElectronicWallet/Transactions/{DigiCurrency}', # Get all digital currency transactions of the logged in user
'ElectronicWallet/UserWallets', # Gets all external digital currency addresses related to the logged in user.
'ElectronicWallet/UserWallets/{DigiCurrency}', # Gets all external digital currency addresses related to the logged in user by currency.
'Info/ReferenceCurrency', # Get user's reference currency
'Info/ReferenceLanguage', # Get user's reference language
'Notification/Messages', # Get from oldest unread + 3 read message to newest messages
'Trade/Orders', # Gets open orders for the logged in trader.
'Trade/Orders/{OrderID}', # Gets an order for the logged in trader.
'Trade/StopOrders', # Gets all stop orders for the logged in trader. Max 1000 record.
'Trade/StopOrdersHistory', # Gets all stop orders for the logged in trader. Max 1000 record.
'Trade/Trades', # Gets all transactions of logged in user
'Trade/UserTrades', # Gets all transactions of logged in user
],
'post': [
'Account/DocumentAddress', # Upload address proof document
'Account/DocumentCorporation', # Upload registered document document
'Account/DocumentID', # Upload ID document copy
'Account/Email/RequestVerify', # Request for verification email
'Account/Email/Verify', # Verification email
'Account/GoogleAuth', # Enable google auth
'Account/Level', # Request verif level of logged in user
'Account/Questionnaire', # Fill the questionnaire
'Account/Referral', # Post a referral email
'APIKey/APIKey', # Create a new API key for logged in user
'Auth/ChangePassword', # Change password.
'Auth/ForgotPassword', # Request reset password
'Auth/ForgotUserID', # Request user id
'Auth/Login', # Trader session log in.
'Auth/Logout', # Logout from the current session.
'Auth/LogoutOtherSessions', # Logout other sessions.
'Auth/ResetPassword', # Reset password
'Bank/Transactions', # Request a transfer from the traders account of the logged in user. This is only available for bank account
'Bank/UserAccounts', # Add an account the logged in user
'ElectronicWallet/DepositWallets/{DigiCurrency}', # Add an digital currency addresses to the logged in user.
'ElectronicWallet/Transactions/Deposits/{DigiCurrency}', # Get all internal digital currency transactions of the logged in user
'ElectronicWallet/Transactions/Withdrawals/{DigiCurrency}', # Get all external digital currency transactions of the logged in user
'ElectronicWallet/UserWallets/{DigiCurrency}', # Add an external digital currency addresses to the logged in user.
'ElectronicWallet/Withdrawals/{DigiCurrency}', # Request a transfer from the traders account to an external address. This is only available for crypto currencies.
'Notification/Messages', # Mark all as read
'Notification/Messages/{ID}', # Mark as read
'Trade/Orders', # Place an order at the exchange.
'Trade/StopOrders', # Place a stop order at the exchange.
],
'put': [
'Account/CorporateData', # Update user company data for corporate account
'Account/DocumentID', # Update ID document meta data
'Account/DocumentInformation', # Update Step3 Data
'Account/Email', # Update user email
'Account/PersonalInformation', # Update Step1 Data
'Account/Phone', # Update user phone number
'Account/Questionnaire', # update the questionnaire
'Account/ReferredCode', # Update referral code
'Account/ResidentInformation', # Update Step2 Data
'Account/SecuritySettings', # Update verif details of logged in user
'Account/User', # Update all user info
'Bank/UserAccounts', # Update the label of existing user bank accounnt
'ElectronicWallet/DepositWallets/{DigiCurrency}/{AddressName}', # Update the name of an address
'ElectronicWallet/UserWallets/{DigiCurrency}', # Update the name of an external address
'Info/ReferenceCurrency', # User's reference currency
'Info/ReferenceLanguage', # Update user's reference language
],
'delete': [
'APIKey/APIKey/{PublicKey}', # Remove an API key
'Bank/Transactions/{RequestID}', # Delete pending account withdraw of the logged in user
'Bank/UserAccounts/{Currency}/{Label}', # Delete an account of the logged in user
'ElectronicWallet/DepositWallets/{DigiCurrency}/{AddressName}', # Delete an digital currency addresses related to the logged in user.
'ElectronicWallet/UserWallets/{DigiCurrency}/{AddressName}', # Delete an external digital currency addresses related to the logged in user.
'Trade/Orders', # Cancels all existing order
'Trade/Orders/{OrderID}', # Cancels an existing order
'Trade/StopOrders', # Cancels all existing stop orders
'Trade/StopOrders/{ID}', # Cancels an existing stop order
],
},
},
}
params.update(config)
super(gatecoin, self).__init__(params)
def fetch_markets(self):
response = self.publicGetPublicLiveTickers()
markets = response['tickers']
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['currencyPair']
base = id[0:3]
quote = id[3:6]
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetBalanceBalances()
balances = response['balances']
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
account = {
'free': balance['availableBalance'],
'used': self.sum(
balance['pendingIncoming'],
balance['pendingOutgoing'],
balance['openOrder']),
'total': balance['balance'],
}
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
orderbook = self.publicGetPublicMarketDepthCurrencyPair(self.extend({
'CurrencyPair': market['id'],
}, params))
return self.parse_order_book(orderbook, None, 'bids', 'asks', 'price', 'volume')
def parse_ticker(self, ticker, market):
timestamp = int(ticker['createDateTime']) * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': float(ticker['vwap']),
'open': float(ticker['open']),
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
response = self.publicGetPublicLiveTickers()
tickers = response['tickers']
result = {}
for t in range(0, len(tickers)):
ticker = tickers[t]
id = ticker['currencyPair']
market = self.markets_by_id[id]
symbol = market['symbol']
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
response = self.publicGetPublicLiveTickerCurrencyPair({
'CurrencyPair': market['id'],
})
ticker = response['ticker']
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market=None):
side = None
order = None
if 'way' in trade:
side = 'buy' if(trade['way'] == 'bid') else 'sell'
orderId = trade['way'] + 'OrderId'
order = trade[orderId]
timestamp = int(trade['transactionTime']) * 1000
if not market:
market = self.markets_by_id[trade['currencyPair']]
return {
'info': trade,
'id': str(trade['transactionId']),
'order': order,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['quantity'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetPublicTransactionsCurrencyPair(self.extend({
'CurrencyPair': market['id'],
}, params))
return self.parse_trades(response['transactions'], market)
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
return [
int(ohlcv['createDateTime']) * 1000,
ohlcv['open'],
ohlcv['high'],
ohlcv['low'],
None,
ohlcv['volume'],
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'CurrencyPair': market['id'],
'Timeframe': self.timeframes[timeframe],
}
if limit:
request['Count'] = limit
request = self.extend(request, params)
response = self.publicGetPublicTickerHistoryCurrencyPairTimeframe(request)
return self.parse_ohlcvs(response['tickers'], market, timeframe, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'Code': self.market_id(symbol),
'Way': 'Bid' if(side == 'buy') else 'Ask',
'Amount': amount,
}
if type == 'limit':
order['Price'] = price
if self.twofa:
if 'ValidationCode' in params:
order['ValidationCode'] = params['ValidationCode']
else:
raise AuthenticationError(self.id + ' two-factor authentication requires a missing ValidationCode parameter')
response = self.privatePostTradeOrders(self.extend(order, params))
return {
'info': response,
'id': response['clOrderId'],
}
def cancel_order(self, id):
self.load_markets()
return self.privateDeleteTradeOrdersOrderID({'OrderID': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
contentType = '' if(method == 'GET') else 'application/json'
auth = method + url + contentType + str(nonce)
auth = auth.lower()
signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256, 'base64')
headers = {
'API_PUBLIC_KEY': self.apiKey,
'API_REQUEST_SIGNATURE': signature,
'API_REQUEST_DATE': nonce,
}
if method != 'GET':
headers['Content-Type'] = contentType
body = self.json(self.extend({'nonce': nonce}, params))
response = self.fetch(url, method, headers, body)
if 'responseStatus' in response:
if 'message' in response['responseStatus']:
if response['responseStatus']['message'] == 'OK':
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class gdax (Exchange):
def __init__(self, config={}):
params = {
'id': 'gdax',
'name': 'GDAX',
'countries': 'US',
'rateLimit': 1000,
'hasFetchOHLCV': True,
'timeframes': {
'1m': 60,
'5m': 300,
'15m': 900,
'30m': 1800,
'1h': 3600,
'2h': 7200,
'4h': 14400,
'12h': 43200,
'1d': 86400,
'1w': 604800,
'1M': 2592000,
'1y': 31536000,
},
'urls': {
'test': 'https://api-public.sandbox.gdax.com',
'logo': 'https://user-images.githubusercontent.com/1294454/27766527-b1be41c6-5edb-11e7-95f6-5b496c469e2c.jpg',
'api': 'https://api.gdax.com',
'www': 'https://www.gdax.com',
'doc': 'https://docs.gdax.com',
},
'api': {
'public': {
'get': [
'currencies',
'products',
'products/{id}/book',
'products/{id}/candles',
'products/{id}/stats',
'products/{id}/ticker',
'products/{id}/trades',
'time',
],
},
'private': {
'get': [
'accounts',
'accounts/{id}',
'accounts/{id}/holds',
'accounts/{id}/ledger',
'coinbase-accounts',
'fills',
'funding',
'orders',
'orders/{id}',
'payment-methods',
'position',
'reports/{id}',
'users/self/trailing-volume',
],
'post': [
'deposits/coinbase-account',
'deposits/payment-method',
'funding/repay',
'orders',
'position/close',
'profiles/margin-transfer',
'reports',
'withdrawals/coinbase',
'withdrawals/crypto',
'withdrawals/payment-method',
],
'delete': [
'orders',
'orders/{id}',
],
},
},
}
params.update(config)
super(gdax, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetProducts()
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['id']
base = market['base_currency']
quote = market['quote_currency']
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privateGetAccounts()
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
account = {
'free': float(balance['available']),
'used': float(balance['hold']),
'total': float(balance['balance']),
}
result[currency] = account
return result
def fetch_order_book(self, market, params={}):
self.load_markets()
orderbook = self.publicGetProductsIdBook(self.extend({
'id': self.market_id(market),
'level': 2, # 1 best bidask, 2 aggregated, 3 full
}, params))
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetProductsIdTicker({
'id': market['id'],
})
quote = self.publicGetProductsIdStats({
'id': market['id'],
})
timestamp = self.parse8601(ticker['time'])
bid = None
ask = None
if 'bid' in ticker:
bid = float(ticker['bid'])
if 'ask' in ticker:
ask = float(ticker['ask'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(quote['high']),
'low': float(quote['low']),
'bid': bid,
'ask': ask,
'vwap': None,
'open': float(quote['open']),
'close': None,
'first': None,
'last': float(quote['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = self.parse8601(['time'])
type = None
return {
'id': str(trade['trade_id']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['side'],
'price': float(trade['price']),
'amount': float(trade['size']),
}
def fetch_trades(self, market, params={}):
self.load_markets()
return self.publicGetProductsIdTrades(self.extend({
'id': self.market_id(market), # fixes issue #2
}, params))
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
return [
ohlcv[0] * 1000,
ohlcv[3],
ohlcv[2],
ohlcv[1],
ohlcv[4],
ohlcv[5],
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
granularity = self.timeframes[timeframe]
if not limit:
limit = 200 # max = 200
end = self.milliseconds()
start = end - limit * granularity * 1000
request = {
'id': market['id'],
'granularity': granularity,
'start': self.iso8601(start),
'end': self.iso8601(end),
}
response = self.publicGetProductsIdCandles(self.extend(request, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def fetchTime(self):
response = self.publicGetTime()
return self.parse8601(response['iso'])
def create_order(self, market, type, side, amount, price=None, params={}):
self.load_markets()
oid = str(self.nonce())
order = {
'product_id': self.market_id(market),
'side': side,
'size': amount,
'type': type,
}
if type == 'limit':
order['price'] = price
response = self.privatePostOrders(self.extend(order, params))
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id):
self.load_markets()
return self.privateDeleteOrdersId({'id': id})
def getPaymentMethods(self):
response = self.privateGetPaymentMethods()
return response
def withdraw(self, currency, amount, address, params={}):
if 'payment_method_id' in params:
self.load_markets()
response = self.privatePostWithdraw(self.extend({
'currency': currency,
'amount': amount,
# 'address': address, # they don't allow withdrawals to direct addresses
}, params))
return {
'info': response,
'id': response['result'],
}
raise ExchangeError(self.id + " withdraw requires a 'payment_method_id' parameter")
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
request = '/' + self.implode_params(path, params)
url = self.urls['api'] + request
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
if not self.apiKey:
raise AuthenticationError(self.id + ' requires apiKey property for authentication and trading')
if not self.secret:
raise AuthenticationError(self.id + ' requires secret property for authentication and trading')
if not self.password:
raise AuthenticationError(self.id + ' requires password property for authentication and trading')
nonce = str(self.nonce())
if query:
body = self.json(query)
what = nonce + method + request + (body or '')
secret = base64.b64decode(self.secret)
signature = self.hmac(self.encode(what), secret, hashlib.sha256, 'base64')
headers = {
'CB-ACCESS-KEY': self.apiKey,
'CB-ACCESS-SIGN': self.decode(signature),
'CB-ACCESS-TIMESTAMP': nonce,
'CB-ACCESS-PASSPHRASE': self.password,
'Content-Type': 'application/json',
}
response = self.fetch(url, method, headers, body)
if 'message' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class gemini (Exchange):
def __init__(self, config={}):
params = {
'id': 'gemini',
'name': 'Gemini',
'countries': 'US',
'rateLimit': 1500, # 200 for private API
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27816857-ce7be644-6096-11e7-82d6-3c257263229c.jpg',
'api': 'https://api.gemini.com',
'www': 'https://gemini.com',
'doc': 'https://docs.gemini.com/rest-api',
},
'api': {
'public': {
'get': [
'symbols',
'pubticker/{symbol}',
'book/{symbol}',
'trades/{symbol}',
'auction/{symbol}',
'auction/{symbol}/history',
],
},
'private': {
'post': [
'order/new',
'order/cancel',
'order/cancel/session',
'order/cancel/all',
'order/status',
'orders',
'mytrades',
'tradevolume',
'balances',
'deposit/{currency}/newAddress',
'withdraw/{currency}',
'heartbeat',
],
},
},
}
params.update(config)
super(gemini, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetSymbols()
result = []
for p in range(0, len(markets)):
id = markets[p]
market = id
uppercase = market.upper()
base = uppercase[0:3]
quote = uppercase[3:6]
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_order_book(self, market, params={}):
self.load_markets()
orderbook = self.publicGetBookSymbol(self.extend({
'symbol': self.market_id(market),
}, params))
return self.parse_order_book(orderbook, None, 'bids', 'asks', 'price', 'amount')
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetPubtickerSymbol({
'symbol': market['id'],
})
timestamp = ticker['volume']['timestamp']
baseVolume = market['base']
quoteVolume = market['quote']
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['volume'][baseVolume]),
'quoteVolume': float(ticker['volume'][quoteVolume]),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['timestampms']
return {
'id': str(trade['tid']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['type'],
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTradesSymbol(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response, market)
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privatePostBalances()
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
account = {
'free': float(balance['available']),
'used': 0.0,
'total': float(balance['amount']),
}
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
order = {
'client_order_id': self.nonce(),
'symbol': self.market_id(symbol),
'amount': str(amount),
'price': str(price),
'side': side,
'type': 'exchange limit', # gemini allows limit orders only
}
response = self.privatePostOrderNew(self.extend(order, params))
return {
'info': response,
'id': response['order_id'],
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostCancelOrder({'order_id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
request = self.extend({
'request': url,
'nonce': nonce,
}, query)
payload = self.json(request)
payload = base64.b64encode(self.encode(payload))
signature = self.hmac(payload, self.encode(self.secret), hashlib.sha384)
headers = {
'Content-Type': 'text/plain',
'Content-Length': 0,
'X-GEMINI-APIKEY': self.apiKey,
'X-GEMINI-PAYLOAD': payload,
'X-GEMINI-SIGNATURE': signature,
}
url = self.urls['api'] + url
response = self.fetch(url, method, headers, body)
if 'result' in response:
if response['result'] == 'error':
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class hitbtc (Exchange):
def __init__(self, config={}):
params = {
'id': 'hitbtc',
'name': 'HitBTC',
'countries': 'HK', # Hong Kong
'rateLimit': 1500,
'version': '1',
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
'api': 'http://api.hitbtc.com',
'www': 'https://hitbtc.com',
'doc': [
'https://hitbtc.com/api',
'http://hitbtc-com.github.io/hitbtc-api',
'http://jsfiddle.net/bmknight/RqbYB',
],
},
'api': {
'public': {
'get': [
'{symbol}/orderbook',
'{symbol}/ticker',
'{symbol}/trades',
'{symbol}/trades/recent',
'symbols',
'ticker',
'time,'
],
},
'trading': {
'get': [
'balance',
'orders/active',
'orders/recent',
'order',
'trades/by/order',
'trades',
],
'post': [
'new_order',
'cancel_order',
'cancel_orders',
],
},
'payment': {
'get': [
'balance',
'address/{currency}',
'transactions',
'transactions/{transaction}',
],
'post': [
'transfer_to_trading',
'transfer_to_main',
'address/{currency}',
'payout',
],
}
},
}
params.update(config)
super(hitbtc, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetSymbols()
result = []
for p in range(0, len(markets['symbols'])):
market = markets['symbols'][p]
id = market['symbol']
base = market['commodity']
quote = market['currency']
lot = float(market['lot'])
step = float(market['step'])
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'lot': lot,
'step': step,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.tradingGetBalance()
balances = response['balance']
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
code = balance['currency_code']
currency = self.commonCurrencyCode(code)
account = {
'free': float(balance['cash']),
'used': float(balance['reserved']),
'total': 0.0,
}
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetSymbolOrderbook(self.extend({
'symbol': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook)
def parse_ticker(self, ticker, market):
timestamp = ticker['timestamp']
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': float(ticker['open']),
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['volume']),
'quoteVolume': float(ticker['volume_quote']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGetTicker()
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetSymbolTicker({
'symbol': market['id'],
})
if 'message' in ticker:
raise ExchangeError(self.id + ' ' + ticker['message'])
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market=None):
return {
'info': trade,
'id': trade[0],
'timestamp': trade[3],
'datetime': self.iso8601(trade[3]),
'symbol': market['symbol'],
'type': None,
'side': trade[4],
'price': float(trade[1]),
'amount': float(trade[2]),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetSymbolTrades(self.extend({
'symbol': market['id'],
# 'from': 0,
# 'till': 100,
# 'by': 'ts', # or by trade_id
# 'sort': 'desc', # or asc
# 'start_index': 0,
# 'max_results': 1000,
# 'format_item': 'object',
# 'format_price': 'number',
# 'format_amount': 'number',
# 'format_tid': 'string',
# 'format_timestamp': 'millisecond',
# 'format_wrap': False,
'side': 'true',
}, params))
return self.parse_trades(response['trades'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
# check if amount can be evenly divided into lots
# they want integer quantity in lot units
quantity = float(amount) / market['lot']
wholeLots = int(round(quantity))
difference = quantity - wholeLots
if abs(difference) > market['step']:
raise ExchangeError(self.id + ' order amount should be evenly divisible by lot unit size of ' + str(market['lot']))
clientOrderId = self.milliseconds()
order = {
'clientOrderId': str(clientOrderId),
'symbol': market['id'],
'side': side,
'quantity': str(wholeLots), # quantity in integer lot units
'type': type,
}
if type == 'limit':
order['price'] = '{:.10f}'.format(price)
response = self.tradingPostNewOrder(self.extend(order, params))
return {
'info': response,
'id': response['ExecutionReport']['clientOrderId'],
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.tradingPostCancelOrder(self.extend({
'clientOrderId': id,
}, params))
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
response = self.paymentPostPayout(self.extend({
'currency_code': currency,
'amount': amount,
'address': address,
}, params))
return {
'info': response,
'id': response['transaction'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/' + 'api' + '/' + self.version + '/' + api + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
query = self.extend({'nonce': nonce, 'apikey': self.apiKey}, query)
if method == 'POST':
if query:
body = self.urlencode(query)
url += '?' + self.urlencode(query)
auth = url + (body or '')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Signature': self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha512).lower(),
}
url = self.urls['api'] + url
response = self.fetch(url, method, headers, body)
if 'code' in response:
if 'ExecutionReport' in response:
if response['ExecutionReport']['orderRejectReason'] == 'orderExceedsLimit':
raise InsufficientFunds(self.id + ' ' + self.json(response))
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class hitbtc2 (hitbtc):
def __init__(self, config={}):
params = {
'id': 'hitbtc2',
'name': 'HitBTC v2',
'countries': 'HK', # Hong Kong
'rateLimit': 1500,
'version': '2',
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
'api': 'https://api.hitbtc.com',
'www': 'https://hitbtc.com',
'doc': [
'https://api.hitbtc.com/api/2/explore',
'https://github.com/hitbtc-com/hitbtc-api/blob/master/APIv2.md',
],
},
'api': {
'public': {
'get': [
'symbol', # Available Currency Symbols
'symbol/{symbol}', # Get symbol info
'currency', # Available Currencies
'currency/{currency}', # Get currency info
'ticker', # Ticker list for all symbols
'ticker/{symbol}', # Ticker for symbol
'trades/{symbol}', # Trades
'orderbook/{symbol}', # Orderbook
],
},
'private': {
'get': [
'order', # List your current open orders
'order/{clientOrderId}', # Get a single order by clientOrderId
'trading/balance', # Get trading balance
'trading/fee/{symbol}', # Get trading fee rate
'history/trades', # Get historical trades
'history/order', # Get historical orders
'history/order/{id}/trades', # Get historical trades by specified order
'account/balance', # Get main acccount balance
'account/transactions', # Get account transactions
'account/transactions/{id}', # Get account transaction by id
'account/crypto/address/{currency}', # Get deposit crypro address
],
'post': [
'order', # Create new order
'account/crypto/withdraw', # Withdraw crypro
'account/crypto/address/{currency}', # Create new deposit crypro address
'account/transfer', # Transfer amount to trading
],
'put': [
'order/{clientOrderId}', # Create new order
'account/crypto/withdraw/{id}', # Commit withdraw crypro
],
'delete': [
'order', # Cancel all open orders
'order/{clientOrderId}', # Cancel order
'account/crypto/withdraw/{id}', # Rollback withdraw crypro
],
'patch': [
'order/{clientOrderId}', # Cancel Replace order
],
},
},
}
params.update(config)
super(hitbtc2, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetSymbol()
result = []
for i in range(0, len(markets)):
market = markets[i]
id = market['id']
base = market['baseCurrency']
quote = market['quoteCurrency']
lot = market['quantityIncrement']
step = market['tickSize']
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'lot': lot,
'step': step,
'info': market,
})
return result
def fetch_balance(self):
self.load_markets()
balances = self.privateGetTradingBalance()
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
code = balance['currency']
currency = self.commonCurrencyCode(code)
account = {
'free': float(balance['available']),
'used': float(balance['reserved']),
'total': 0.0,
}
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetOrderbookSymbol(self.extend({
'symbol': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook, None, 'bid', 'ask', 'price', 'size')
def parse_ticker(self, ticker, market):
timestamp = self.parse8601(ticker['timestamp'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_float(ticker, 'high'),
'low': self.safe_float(ticker, 'low'),
'bid': self.safe_float(ticker, 'bid'),
'ask': self.safe_float(ticker, 'ask'),
'vwap': None,
'open': self.safe_float(ticker, 'open'),
'close': self.safe_float(ticker, 'close'),
'first': None,
'last': self.safe_float(ticker, 'last'),
'change': None,
'percentage': None,
'average': None,
'baseVolume': self.safe_float(ticker, 'volume'),
'quoteVolume': self.safe_float(ticker, 'quoteVolume'),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGetTicker()
result = {}
for i in range(0, len(tickers)):
ticker = tickers[i]
id = ticker['symbol']
market = self.markets_by_id[id]
symbol = market['symbol']
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetTickerSymbol({
'symbol': market['id'],
})
if 'message' in ticker:
raise ExchangeError(self.id + ' ' + ticker['message'])
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market=None):
timestamp = self.parse8601(trade['timestamp'])
return {
'info': trade,
'id': str(trade['id']),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['side'],
'price': float(trade['price']),
'amount': float(trade['quantity']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTradesSymbol(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
clientOrderId = self.milliseconds()
amount = float(amount)
order = {
'clientOrderId': str(clientOrderId),
'symbol': market['id'],
'side': side,
'quantity': str(amount),
'type': type,
}
if type == 'limit':
price = float(price)
order['price'] = '{:.10f}'.format(price)
response = self.privatePostOrder(self.extend(order, params))
return {
'info': response,
'id': response['clientOrderId'],
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privateDeleteOrderClientOrderId(self.extend({
'clientOrderId': id,
}, params))
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
amount = float(amount)
response = self.privatePostAccountCryptoWithdraw(self.extend({
'currency': currency,
'amount': str(amount),
'address': address,
}, params))
return {
'info': response,
'id': response['id'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/api' + '/' + self.version + '/'
query = self.omit(params, self.extract_params(path))
if api == 'public':
url += api + '/' + self.implode_params(path, params)
if query:
url += '?' + self.urlencode(query)
else:
url += self.implode_params(path, params) + '?' + self.urlencode(query)
if method != 'GET':
if query:
body = self.json(query)
payload = self.encode(self.apiKey + ':' + self.secret)
auth = base64.b64encode(payload)
headers = {
'Authorization': "Basic " + self.decode(auth),
'Content-Type': 'application/json',
}
url = self.urls['api'] + url
response = self.fetch(url, method, headers, body)
if 'error' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class huobi1 (Exchange):
def __init__(self, config={}):
params = {
'id': 'huobi1',
'name': 'Huobi v1',
'countries': 'CN',
'rateLimit': 2000,
'version': 'v1',
'hasFetchOHLCV': True,
'accounts': None,
'accountsById': None,
'timeframes': {
'1m': '1min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '60min',
'1d': '1day',
'1w': '1week',
'1M': '1mon',
'1y': '1year',
},
'api': {
'market': {
'get': [
'history/kline', # 获取K线数据
'detail/merged', # 获取聚合行情(Ticker)
'depth', # 获取 Market Depth 数据
'trade', # 获取 Trade Detail 数据
'history/trade', # 批量获取最近的交易记录
'detail', # 获取 Market Detail 24小时成交量数据
],
},
'public': {
'get': [
'common/symbols', # 查询系统支持的所有交易对
'common/currencys', # 查询系统支持的所有币种
'common/timestamp', # 查询系统当前时间
],
},
'private': {
'get': [
'account/accounts', # 查询当前用户的所有账户(即account-id)
'account/accounts/{id}/balance', # 查询指定账户的余额
'order/orders/{id}', # 查询某个订单详情
'order/orders/{id}/matchresults', # 查询某个订单的成交明细
'order/orders', # 查询当前委托、历史委托
'order/matchresults', # 查询当前成交、历史成交
'dw/withdraw-virtual/addresses', # 查询虚拟币提现地址
],
'post': [
'order/orders/place', # 创建并执行一个新订单 (一步下单, 推荐使用)
'order/orders', # 创建一个新的订单请求 (仅创建订单,不执行下单)
'order/orders/{id}/place', # 执行一个订单 (仅执行已创建的订单)
'order/orders/{id}/submitcancel', # 申请撤销一个订单请求
'order/orders/batchcancel', # 批量撤销订单
'dw/balance/transfer', # 资产划转
'dw/withdraw-virtual/create', # 申请提现虚拟币
'dw/withdraw-virtual/{id}/place', # 确认申请虚拟币提现
'dw/withdraw-virtual/{id}/cancel', # 申请取消提现虚拟币
],
},
},
}
params.update(config)
super(huobi1, self).__init__(params)
def fetch_markets(self):
response = self.publicGetCommonSymbols()
markets = response['data']
numMarkets = len(markets)
if numMarkets < 1:
raise ExchangeError(self.id + ' publicGetCommonSymbols returned empty response: ' + self.json(response))
result = []
for i in range(0, len(markets)):
market = markets[i]
baseId = market['base-currency']
quoteId = market['quote-currency']
base = baseId.upper()
quote = quoteId.upper()
id = baseId + quoteId
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def parse_ticker(self, ticker, market):
last = None
if 'last' in ticker:
last = ticker['last']
return {
'timestamp': ticker['ts'],
'datetime': self.iso8601(ticker['ts']),
'high': ticker['high'],
'low': ticker['low'],
'bid': ticker['bid'][0],
'ask': ticker['ask'][0],
'vwap': None,
'open': ticker['open'],
'close': ticker['close'],
'first': None,
'last': last,
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['amount']),
'quoteVolume': ticker['vol'],
'info': ticker,
}
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.marketGetDepth(self.extend({
'symbol': market['id'],
'type': 'step0',
}, params))
return self.parse_order_book(response['tick'], response['tick']['ts'])
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
response = self.marketGetDetailMerged({'symbol': market['id']})
return self.parse_ticker(response['tick'], market)
def parse_trade(self, trade, market):
timestamp = trade['ts']
return {
'info': trade,
'id': str(trade['id']),
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['direction'],
'price': trade['price'],
'amount': trade['amount'],
}
def parse_trades_data(self, data, market):
result = []
for i in range(0, len(data)):
trades = self.parse_trades(data[i]['data'], market)
for k in range(0, len(trades)):
result.append(trades[k])
return result
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.marketGetHistoryTrade(self.extend({
'symbol': market['id'],
'size': 2000,
}, params))
return self.parse_trades_data(response['data'], market)
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
return [
ohlcv['id'] * 1000,
ohlcv['open'],
ohlcv['high'],
ohlcv['low'],
ohlcv['close'],
ohlcv['vol'],
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
response = self.marketGetHistoryKline(self.extend({
'symbol': market['id'],
'period': self.timeframes[timeframe],
'size': 2000, # max = 2000
}, params))
return self.parse_ohlcvs(response['data'], market, timeframe, since, limit)
def loadAccounts(self, reload=False):
if reload:
self.accounts = self.fetchAccounts()
else:
if self.accounts:
return self.accounts
else:
self.accounts = self.fetchAccounts()
self.accountsById = self.index_by(self.accounts, 'id')
return self.accounts
def fetchAccounts(self):
self.load_markets()
response = self.privateGetAccountAccounts()
return response['data']
def fetch_balance(self, params={}):
self.load_markets()
self.loadAccounts()
response = self.privateGetAccountAccountsIdBalance(self.extend({
'id': self.accounts[0]['id'],
}, params))
balances = response['data']['list']
result = {'info': response}
for i in range(0, len(balances)):
balance = balances[i]
uppercase = balance['currency'].upper()
currency = self.commonCurrencyCode(uppercase)
account = self.account()
account['free'] = float(balance['balance'])
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
self.loadAccounts()
market = self.market(symbol)
order = {
'account-id': self.accounts[0]['id'],
'amount': '{:.10f}'.format(amount),
'symbol': market['id'],
'type': side + '-' + type,
}
if type == 'limit':
order['price'] = '{:.10f}'.format(price)
response = self.privatePostOrderOrdersPlace(self.extend(order, params))
return {
'info': response,
'id': response['data'],
}
def cancel_order(self, id):
return self.privatePostOrderOrdersIdSubmitcancel({'id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/'
if api == 'market':
url += api
else:
url += self.version
url += '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'private':
timestamp = self.YmdHMS(self.milliseconds(), 'T')
request = self.keysort(self.extend({
'SignatureMethod': 'HmacSHA256',
'SignatureVersion': '2',
'AccessKeyId': self.apiKey,
'Timestamp': timestamp,
}, query))
auth = self.urlencode(request)
payload = "\n".join([method, self.hostname, url, auth])
signature = self.hmac(self.encode(payload), self.encode(self.secret), hashlib.sha256, 'base64')
auth += '&' + self.urlencode({'Signature': signature})
if method == 'GET':
url += '?' + auth
else:
body = self.json(query)
headers = {
'Content-Type': 'application/json',
}
else:
if params:
url += '?' + self.urlencode(params)
url = self.urls['api'] + url
response = self.fetch(url, method, headers, body)
if 'status' in response:
if response['status'] == 'error':
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class huobicny (huobi1):
def __init__(self, config={}):
params = {
'id': 'huobicny',
'name': 'Huobi CNY',
'hostname': 'be.huobi.com',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766569-15aa7b9a-5edd-11e7-9e7f-44791f4ee49c.jpg',
'api': 'https://be.huobi.com',
'www': 'https://www.huobi.com',
'doc': 'https://github.com/huobiapi/API_Docs/wiki/REST_api_reference',
},
# 'markets': {
# 'ETH/CNY': {'id': 'ethcny', 'symbol': 'ETH/CNY', 'base': 'ETH', 'quote': 'CNY'},
# 'ETC/CNY': {'id': 'etccny', 'symbol': 'ETC/CNY', 'base': 'ETC', 'quote': 'CNY'},
# 'BCH/CNY': {'id': 'bcccny', 'symbol': 'BCH/CNY', 'base': 'BCH', 'quote': 'CNY'},
#},
}
params.update(config)
super(huobicny, self).__init__(params)
#------------------------------------------------------------------------------
class huobipro (huobi1):
def __init__(self, config={}):
params = {
'id': 'huobipro',
'name': 'Huobi Pro',
'hostname': 'api.huobi.pro',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766569-15aa7b9a-5edd-11e7-9e7f-44791f4ee49c.jpg',
'api': 'https://api.huobi.pro',
'www': 'https://www.huobi.pro',
'doc': 'https://github.com/huobiapi/API_Docs/wiki/REST_api_reference',
},
# 'markets': {
# 'ETH/BTC': {'id': 'ethbtc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
# 'ETC/BTC': {'id': 'etccny', 'symbol': 'ETC/BTC', 'base': 'ETC', 'quote': 'BTC'},
# 'LTC/BTC': {'id': 'ltcbtc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
# 'BCH/BTC': {'id': 'bcccny', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC'},
#},
}
params.update(config)
super(huobipro, self).__init__(params)
#------------------------------------------------------------------------------
class huobi (Exchange):
def __init__(self, config={}):
params = {
'id': 'huobi',
'name': 'Huobi',
'countries': 'CN',
'rateLimit': 2000,
'version': 'v3',
'hasFetchOHLCV': True,
'timeframes': {
'1m': '001',
'5m': '005',
'15m': '015',
'30m': '030',
'1h': '060',
'1d': '100',
'1w': '200',
'1M': '300',
'1y': '400',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766569-15aa7b9a-5edd-11e7-9e7f-44791f4ee49c.jpg',
'api': 'http://api.huobi.com',
'www': 'https://www.huobi.com',
'doc': 'https://github.com/huobiapi/API_Docs_en/wiki',
},
'api': {
'staticmarket': {
'get': [
'{id}_kline_{period}',
'ticker_{id}',
'depth_{id}',
'depth_{id}_{length}',
'detail_{id}',
],
},
'usdmarket': {
'get': [
'{id}_kline_{period}',
'ticker_{id}',
'depth_{id}',
'depth_{id}_{length}',
'detail_{id}',
],
},
'trade': {
'post': [
'get_account_info',
'get_orders',
'order_info',
'buy',
'sell',
'buy_market',
'sell_market',
'cancel_order',
'get_new_deal_orders',
'get_order_id_by_trade_id',
'withdraw_coin',
'cancel_withdraw_coin',
'get_withdraw_coin_result',
'transfer',
'loan',
'repayment',
'get_loan_available',
'get_loans',
],
},
},
'markets': {
'BTC/CNY': {'id': 'btc', 'symbol': 'BTC/CNY', 'base': 'BTC', 'quote': 'CNY', 'type': 'staticmarket', 'coinType': 1},
'LTC/CNY': {'id': 'ltc', 'symbol': 'LTC/CNY', 'base': 'LTC', 'quote': 'CNY', 'type': 'staticmarket', 'coinType': 2},
# 'BTC/USD': {'id': 'btc', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD', 'type': 'usdmarket', 'coinType': 1},
},
}
params.update(config)
super(huobi, self).__init__(params)
def fetch_balance(self, params={}):
balances = self.tradePostGetAccountInfo()
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = self.account()
available = 'available_' + lowercase + '_display'
frozen = 'frozen_' + lowercase + '_display'
loan = 'loan_' + lowercase + '_display'
if available in balances:
account['free'] = float(balances[available])
if frozen in balances:
account['used'] = float(balances[frozen])
if loan in balances:
account['used'] = self.sum(account['used'], float(balances[loan]))
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
market = self.market(symbol)
method = market['type'] + 'GetDepthId'
orderbook = getattr(self, method)(self.extend({'id': market['id']}, params))
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
market = self.market(symbol)
method = market['type'] + 'GetTickerId'
response = getattr(self, method)({'id': market['id']})
ticker = response['ticker']
timestamp = int(response['time']) * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': float(ticker['open']),
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['vol']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['ts']
return {
'info': trade,
'id': str(trade['id']),
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['direction'],
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
method = market['type'] + 'GetDetailId'
response = getattr(self, method)(self.extend({
'id': market['id'],
}, params))
return self.parse_trades(response['trades'], market)
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
# not implemented yet
return [
ohlcv[0],
ohlcv[1],
ohlcv[2],
ohlcv[3],
ohlcv[4],
ohlcv[6],
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
market = self.market(symbol)
method = market['type'] + 'GetIdKlinePeriod'
ohlcvs = getattr(self, method)(self.extend({
'id': market['id'],
'period': self.timeframes[timeframe],
}, params))
return ohlcvs
# return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
market = self.market(symbol)
method = 'tradePost' + self.capitalize(side)
order = {
'coin_type': market['coinType'],
'amount': amount,
'market': market['quote'].lower(),
}
if type == 'limit':
order['price'] = price
else:
method += self.capitalize(type)
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id):
return self.tradePostCancelOrder({'id': id})
def request(self, path, api='trade', method='GET', params={}, headers=None, body=None):
url = self.urls['api']
if api == 'trade':
url += '/api' + self.version
query = self.keysort(self.extend({
'method': path,
'access_key': self.apiKey,
'created': self.nonce(),
}, params))
queryString = self.urlencode(self.omit(query, 'market'))
# secret key must be appended to the query before signing
queryString += '&secret_key=' + self.secret
query['sign'] = self.hash(self.encode(queryString))
body = self.urlencode(query)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
else:
url += '/' + api + '/' + self.implode_params(path, params) + '_json.js'
query = self.omit(params, self.extract_params(path))
if query:
url += '?' + self.urlencode(query)
response = self.fetch(url, method, headers, body)
if 'status' in response:
if response['status'] == 'error':
raise ExchangeError(self.id + ' ' + self.json(response))
if 'code' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class independentreserve (Exchange):
def __init__(self, config={}):
params = {
'id': 'independentreserve',
'name': 'Independent Reserve',
'countries': ['AU', 'NZ'], # Australia, New Zealand
'rateLimit': 1000,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/30521662-cf3f477c-9bcb-11e7-89bc-d1ac85012eda.jpg',
'api': {
'public': 'https://api.independentreserve.com/Public',
'private': 'https://api.independentreserve.com/Private',
},
'www': 'https://www.independentreserve.com',
'doc': 'https://www.independentreserve.com/API',
},
'api': {
'public': {
'get': [
'GetValidPrimaryCurrencyCodes',
'GetValidSecondaryCurrencyCodes',
'GetValidLimitOrderTypes',
'GetValidMarketOrderTypes',
'GetValidOrderTypes',
'GetValidTransactionTypes',
'GetMarketSummary',
'GetOrderBook',
'GetTradeHistorySummary',
'GetRecentTrades',
'GetFxRates',
],
},
'private': {
'post': [
'PlaceLimitOrder',
'PlaceMarketOrder',
'CancelOrder',
'GetOpenOrders',
'GetClosedOrders',
'GetClosedFilledOrders',
'GetOrderDetails',
'GetAccounts',
'GetTransactions',
'GetDigitalCurrencyDepositAddress',
'GetDigitalCurrencyDepositAddresses',
'SynchDigitalCurrencyDepositAddressWithBlockchain',
'WithdrawDigitalCurrency',
'RequestFiatWithdrawal',
'GetTrades',
],
},
},
}
params.update(config)
super(independentreserve, self).__init__(params)
def fetch_markets(self):
baseCurrencies = self.publicGetValidPrimaryCurrencyCodes()
quoteCurrencies = self.publicGetValidSecondaryCurrencyCodes()
result = []
for i in range(0, len(baseCurrencies)):
baseId = baseCurrencies[i]
baseIdUppercase = baseId.upper()
base = self.commonCurrencyCode(baseIdUppercase)
for j in range(0, len(quoteCurrencies)):
quoteId = quoteCurrencies[j]
quoteIdUppercase = quoteId.upper()
quote = self.commonCurrencyCode(quoteIdUppercase)
id = baseId + '/' + quoteId
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'info': id,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privatePostGetAccounts()
result = {'info': balances}
for i in range(0, len(balances)):
balance = balances[i]
currencyCode = balance['CurrencyCode']
uppercase = currencyCode.upper()
currency = self.commonCurrencyCode(uppercase)
account = self.account()
account['free'] = balance['AvailableBalance']
account['total'] = balance['TotalBalance']
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetOrderBook(self.extend({
'primaryCurrencyCode': market['baseId'],
'secondaryCurrencyCode': market['quoteId'],
}, params))
timestamp = self.parse8601(response['CreatedTimestampUtc'])
return self.parse_order_book(response, timestamp, 'BuyOrders', 'SellOrders', 'Price', 'Volume')
def parse_ticker(self, ticker, market):
timestamp = self.parse8601(ticker['CreatedTimestampUtc'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': ticker['DayHighestPrice'],
'low': ticker['DayLowestPrice'],
'bid': ticker['CurrentHighestBidPrice'],
'ask': ticker['CurrentLowestOfferPrice'],
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': ticker['LastPrice'],
'change': None,
'percentage': None,
'average': ticker['DayAvgPrice'],
'baseVolume': ticker['DayVolumeXbt'],
'quoteVolume': ticker['DayVolumeXbtInSecondaryCurrrency'],
'info': ticker,
}
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
response = self.publicGetMarketSummary({
'primaryCurrencyCode': market['baseId'],
'secondaryCurrencyCode': market['quoteId'],
})
return self.parse_ticker(response, market)
def parse_trade(self, trade, market):
timestamp = self.parse8601(trade['TradeTimestampUtc'])
return {
'id': None,
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': None,
'type': None,
'side': None,
'price': trade['SecondaryCurrencyTradePrice'],
'amount': trade['PrimaryCurrencyAmount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetRecentTrades(self.extend({
'primaryCurrencyCode': market['baseId'],
'secondaryCurrencyCode': market['quoteId'],
'numberOfRecentTradesToRetrieve': 50, # max = 50
}, params))
return self.parse_trades(response['Trades'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
capitalizedOrderType = self.capitalize(type)
method = 'Place' + capitalizedOrderType + 'Order'
orderType = capitalizedOrderType
orderType += 'Offer' if(side == 'sell') else 'Bid'
order = self.ordered({
'primaryCurrencyCode': market['baseId'],
'secondaryCurrencyCode': market['quoteId'],
'orderType': orderType,
})
if type == 'limit':
order['price'] = price
order['volume'] = amount
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': response['OrderGuid'],
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostCancelOrder({'orderGuid': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api] + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
nonce = self.nonce()
auth = [
url,
'apiKey=' + self.apiKey,
'nonce=' + str(nonce),
]
keysorted = self.keysort(params)
keys = list(params.keys())
for i in range(0, len(keys)):
key = keys[i]
auth.append(key + '=' + params[key])
message = ','.join(auth)
signature = self.hmac(self.encode(message), self.encode(self.secret))
query = self.keysort(self.extend({
'apiKey': self.apiKey,
'nonce': nonce,
'signature': signature,
}, params))
body = self.json(query)
headers = {'Content-Type': 'application/json'}
response = self.fetch(url, method, headers, body)
# todo error handling
return response
#------------------------------------------------------------------------------
class itbit (Exchange):
def __init__(self, config={}):
params = {
'id': 'itbit',
'name': 'itBit',
'countries': 'US',
'rateLimit': 2000,
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27822159-66153620-60ad-11e7-89e7-005f6d7f3de0.jpg',
'api': 'https://api.itbit.com',
'www': 'https://www.itbit.com',
'doc': [
'https://api.itbit.com/docs',
'https://www.itbit.com/api',
],
},
'api': {
'public': {
'get': [
'markets/{symbol}/ticker',
'markets/{symbol}/order_book',
'markets/{symbol}/trades',
],
},
'private': {
'get': [
'wallets',
'wallets/{walletId}',
'wallets/{walletId}/balances/{currencyCode}',
'wallets/{walletId}/funding_history',
'wallets/{walletId}/trades',
'wallets/{walletId}/orders/{id}',
],
'post': [
'wallet_transfers',
'wallets',
'wallets/{walletId}/cryptocurrency_deposits',
'wallets/{walletId}/cryptocurrency_withdrawals',
'wallets/{walletId}/orders',
'wire_withdrawal',
],
'delete': [
'wallets/{walletId}/orders/{id}',
],
},
},
'markets': {
'BTC/USD': {'id': 'XBTUSD', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'BTC/SGD': {'id': 'XBTSGD', 'symbol': 'BTC/SGD', 'base': 'BTC', 'quote': 'SGD'},
'BTC/EUR': {'id': 'XBTEUR', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
},
}
params.update(config)
super(itbit, self).__init__(params)
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetMarketsSymbolOrderBook(self.extend({
'symbol': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
ticker = self.publicGetMarketsSymbolTicker({
'symbol': self.market_id(symbol),
})
timestamp = self.parse8601(ticker['serverTimeUTC'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high24h']),
'low': float(ticker['low24h']),
'bid': self.safe_float(ticker, 'bid'),
'ask': self.safe_float(ticker, 'ask'),
'vwap': float(ticker['vwap24h']),
'open': float(ticker['openToday']),
'close': None,
'first': None,
'last': float(ticker['lastPrice']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume24h']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = self.parse8601(trade['timestamp'])
id = str(trade['matchNumber'])
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'id': id,
'order': id,
'type': None,
'side': None,
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetMarketsSymbolTrades(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response['recentTrades'], market)
def fetch_balance(self, params={}):
response = self.privateGetBalances()
balances = response['balances']
result = {'info': response}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
account = {
'free': float(balance['availableBalance']),
'used': 0.0,
'total': float(balance['totalBalance']),
}
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def fetchWallets(self):
return self.privateGetWallets()
def nonce(self):
return self.milliseconds()
def create_order(self, symbol, type, side, amount, price=None, params={}):
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
walletIdInParams = ('walletId' in list(params.keys()))
if not walletIdInParams:
raise ExchangeError(self.id + ' createOrder requires a walletId parameter')
amount = str(amount)
price = str(price)
market = self.market(symbol)
order = {
'side': side,
'type': type,
'currency': market['base'],
'amount': amount,
'display': amount,
'price': price,
'instrument': market['id'],
}
response = self.privatePostTradeAdd(self.extend(order, params))
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id, params={}):
walletIdInParams = ('walletId' in list(params.keys()))
if not walletIdInParams:
raise ExchangeError(self.id + ' cancelOrder requires a walletId parameter')
return self.privateDeleteWalletsWalletIdOrdersId(self.extend({
'id': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
if query:
body = self.json(query)
else:
body = ''
nonce = str(self.nonce())
timestamp = nonce
auth = [method, url, body, nonce, timestamp]
message = nonce + self.json(auth)
hash = self.hash(self.encode(message), 'sha256', 'binary')
binhash = self.binary_concat(url, hash)
signature = self.hmac(binhash, self.encode(self.secret), hashlib.sha512, 'base64')
headers = {
'Authorization': self.apiKey + ':' + signature,
'Content-Type': 'application/json',
'X-Auth-Timestamp': timestamp,
'X-Auth-Nonce': nonce,
}
response = self.fetch(url, method, headers, body)
if 'code' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class jubi (Exchange):
def __init__(self, config={}):
params = {
'id': 'jubi',
'name': 'jubi.com',
'countries': 'CN',
'rateLimit': 1500,
'version': 'v1',
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766581-9d397d9a-5edd-11e7-8fb9-5d8236c0e692.jpg',
'api': 'https://www.jubi.com/api',
'www': 'https://www.jubi.com',
'doc': 'https://www.jubi.com/help/api.html',
},
'api': {
'public': {
'get': [
'depth',
'orders',
'ticker',
'allticker',
],
},
'private': {
'post': [
'balance',
'trade_add',
'trade_cancel',
'trade_list',
'trade_view',
'wallet',
],
},
},
}
params.update(config)
super(jubi, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetAllticker()
keys = list(markets.keys())
result = []
for p in range(0, len(keys)):
id = keys[p]
base = id.upper()
quote = 'CNY'
symbol = base + '/' + quote
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': id,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privatePostBalance()
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
if lowercase == 'dash':
lowercase = 'drk'
account = self.account()
free = lowercase + '_balance'
used = lowercase + '_lock'
if free in balances:
account['free'] = float(balances[free])
if used in balances:
account['used'] = float(balances[used])
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetDepth(self.extend({
'coin': self.market_id(symbol),
}, params))
result = self.parse_order_book(orderbook)
result['asks'] = self.sort_by(result['asks'], 0)
return result
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['vol']),
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGetAllticker()
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetTicker({
'coin': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = int(trade['date']) * 1000
return {
'info': trade,
'id': trade['tid'],
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['type'],
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetOrders(self.extend({
'coin': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
response = self.privatePostTradeAdd(self.extend({
'amount': amount,
'price': price,
'type': side,
'coin': self.market_id(symbol),
}, params))
return {
'info': response,
'id': response['id'],
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privatePostTradeCancel(self.extend({
'id': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
nonce = str(self.nonce())
query = self.extend({
'key': self.apiKey,
'nonce': nonce,
}, params)
request = self.urlencode(query)
secret = self.hash(self.encode(self.secret))
query['signature'] = self.hmac(self.encode(request), self.encode(secret))
body = self.urlencode(query)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
response = self.fetch(url, method, headers, body)
if 'result' in response:
if not response['result']:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class kraken (Exchange):
def __init__(self, config={}):
params = {
'id': 'kraken',
'name': 'Kraken',
'countries': 'US',
'version': '0',
'rateLimit': 1500,
'hasFetchTickers': True,
'hasFetchOHLCV': True,
'marketsByAltname': {},
'timeframes': {
'1m': '1',
'5m': '5',
'15m': '15',
'30m': '30',
'1h': '60',
'4h': '240',
'1d': '1440',
'1w': '10080',
'2w': '21600',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766599-22709304-5ede-11e7-9de1-9f33732e1509.jpg',
'api': 'https://api.kraken.com',
'www': 'https://www.kraken.com',
'doc': [
'https://www.kraken.com/en-us/help/api',
'https://github.com/nothingisdead/npm-kraken-api',
],
},
'api': {
'public': {
'get': [
'Assets',
'AssetPairs',
'Depth',
'OHLC',
'Spread',
'Ticker',
'Time',
'Trades',
],
},
'private': {
'post': [
'AddOrder',
'Balance',
'CancelOrder',
'ClosedOrders',
'DepositAddresses',
'DepositMethods',
'DepositStatus',
'Ledgers',
'OpenOrders',
'OpenPositions',
'QueryLedgers',
'QueryOrders',
'QueryTrades',
'TradeBalance',
'TradesHistory',
'TradeVolume',
'Withdraw',
'WithdrawCancel',
'WithdrawInfo',
'WithdrawStatus',
],
},
},
}
params.update(config)
super(kraken, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetAssetPairs()
keys = list(markets['result'].keys())
result = []
for p in range(0, len(keys)):
id = keys[p]
market = markets['result'][id]
base = market['base']
quote = market['quote']
if(base[0] == 'X') or(base[0] == 'Z'):
base = base[1:]
if(quote[0] == 'X') or(quote[0] == 'Z'):
quote = quote[1:]
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
darkpool = id.find('.d') >= 0
symbol = market['altname'] if darkpool else(base + '/' + quote)
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'darkpool': darkpool,
'info': market,
'altname': market['altname'],
})
self.marketsByAltname = self.index_by(result, 'altname')
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
darkpool = symbol.find('.d') >= 0
if darkpool:
raise ExchangeError(self.id + ' does not provide an order book for darkpool symbol ' + symbol)
market = self.market(symbol)
response = self.publicGetDepth(self.extend({
'pair': market['id'],
}, params))
orderbook = response['result'][market['id']]
return self.parse_order_book(orderbook)
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['h'][1]),
'low': float(ticker['l'][1]),
'bid': float(ticker['b'][0]),
'ask': float(ticker['a'][0]),
'vwap': float(ticker['p'][1]),
'open': float(ticker['o']),
'close': None,
'first': None,
'last': float(ticker['c'][0]),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['v'][1]),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
pairs = []
for s in range(0, len(self.symbols)):
symbol = self.symbols[s]
market = self.markets[symbol]
if not market['darkpool']:
pairs.append(market['id'])
filter = ','.join(pairs)
response = self.publicGetTicker({
'pair': filter,
})
tickers = response['result']
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
darkpool = symbol.find('.d') >= 0
if darkpool:
raise ExchangeError(self.id + ' does not provide a ticker for darkpool symbol ' + symbol)
market = self.market(symbol)
response = self.publicGetTicker({
'pair': market['id'],
})
ticker = response['result'][market['id']]
return self.parse_ticker(ticker, market)
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
return [
ohlcv[0] * 1000,
float(ohlcv[1]),
float(ohlcv[2]),
float(ohlcv[3]),
float(ohlcv[4]),
float(ohlcv[6]),
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
request = {
'pair': market['id'],
'interval': self.timeframes[timeframe],
}
if since:
request['since'] = since
response = self.publicGetOHLC(self.extend(request, params))
ohlcvs = response['result'][market['id']]
return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)
def parse_trade(self, trade, market):
timestamp = int(trade[2] * 1000)
side = 'sell' if(trade[3] == 's') else 'buy'
type = 'limit' if(trade[4] == 'l') else 'market'
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': type,
'side': side,
'price': float(trade[0]),
'amount': float(trade[1]),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
id = market['id']
response = self.publicGetTrades(self.extend({
'pair': id,
}, params))
trades = response['result'][id]
return self.parse_trades(trades, market)
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostBalance()
balances = response['result']
result = {'info': balances}
currencies = list(balances.keys())
for c in range(0, len(currencies)):
currency = currencies[c]
code = currency
# X-ISO4217-A3 standard currency codes
if code[0] == 'X':
code = code[1:]
elif code[0] == 'Z':
code = code[1:]
code = self.commonCurrencyCode(code)
balance = float(balances[currency])
account = {
'free': balance,
'used': 0.0,
'total': balance,
}
result[code] = account
return result
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'pair': self.market_id(symbol),
'type': side,
'ordertype': type,
'volume': amount,
}
if type == 'limit':
order['price'] = price
response = self.privatePostAddOrder(self.extend(order, params))
length = len(response['result']['txid'])
id = response['result']['txid'] if(length > 1) else response['result']['txid'][0]
return {
'info': response,
'id': id,
}
def parse_order(self, order, market=None):
description = order['descr']
side = description['type']
type = description['ordertype']
symbol = None
if not market:
pair = description['pair']
if pair in self.marketsByAltname:
market = self.marketsByAltname[pair]
elif pair in self.markets_by_id:
market = self.markets_by_id[pair]
if market:
symbol = market['symbol']
timestamp = int(order['opentm'] * 1000)
amount = float(order['vol'])
filled = float(order['vol_exec'])
remaining = amount - filled
return {
'id': order['id'],
'info': order,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'status': order['status'],
'symbol': symbol,
'type': type,
'side': side,
'price': float(order['price']),
'amount': amount,
'filled': filled,
'remaining': remaining,
# 'trades': self.parse_trades(order['trades'], market),
}
def parse_orders(self, orders, market=None):
result = []
ids = list(orders.keys())
for i in range(0, len(ids)):
id = ids[i]
order = self.extend({'id': id}, orders[id])
result.append(self.parse_order(order, market))
return result
def fetch_order(self, id, params={}):
self.load_markets()
response = self.privatePostQueryOrders(self.extend({
'trades': True, # whether or not to include trades in output(optional, default False)
'txid': id, # comma delimited list of transaction ids to query info about(20 maximum)
# 'userref': 'optional', # restrict results to given user reference id(optional)
}, params))
orders = response['result']
order = self.parse_order(orders[id])
return self.extend({'info': response}, order)
def cancel_order(self, id):
self.load_markets()
return self.privatePostCancelOrder({'txid': id})
def withdraw(self, currency, amount, address, params={}):
if 'key' in params:
self.load_markets()
response = self.privatePostWithdraw(self.extend({
'asset': currency,
'amount': amount,
# 'address': address, # they don't allow withdrawals to direct addresses
}, params))
return {
'info': response,
'id': response['result'],
}
raise ExchangeError(self.id + " withdraw requires a 'key' parameter(withdrawal key name, as set up on your account)")
def fetch_open_orders(self, symbol=None, params={}):
self.load_markets()
market = None
if symbol:
market = self.market_id(symbol)
response = self.privatePostOpenOrders(params)
return self.parse_orders(response['result']['open'], market)
def fetchClosedOrders(self, symbol=None, params={}):
self.load_markets()
market = None
if symbol:
market = self.market_id(symbol)
response = self.privatePostClosedOrders(params)
return self.parse_orders(response['result']['closed'], market)
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/' + self.version + '/' + api + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
nonce = str(self.nonce())
body = self.urlencode(self.extend({'nonce': nonce}, params))
auth = self.encode(nonce + body)
hash = self.hash(auth, 'sha256', 'binary')
binary = self.encode(url)
binhash = self.binary_concat(binary, hash)
secret = base64.b64decode(self.secret)
signature = self.hmac(binhash, secret, hashlib.sha512, 'base64')
headers = {
'API-Key': self.apiKey,
'API-Sign': self.decode(signature),
'Content-Type': 'application/x-www-form-urlencoded',
}
url = self.urls['api'] + url
response = self.fetch(url, method, headers, body)
if 'error' in response:
numErrors = len(response['error'])
if numErrors:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class lakebtc (Exchange):
def __init__(self, config={}):
params = {
'id': 'lakebtc',
'name': 'LakeBTC',
'countries': 'US',
'version': 'api_v2',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28074120-72b7c38a-6660-11e7-92d9-d9027502281d.jpg',
'api': 'https://api.lakebtc.com',
'www': 'https://www.lakebtc.com',
'doc': [
'https://www.lakebtc.com/s/api_v2',
'https://www.lakebtc.com/s/api',
],
},
'api': {
'public': {
'get': [
'bcorderbook',
'bctrades',
'ticker',
],
},
'private': {
'post': [
'buyOrder',
'cancelOrders',
'getAccountInfo',
'getExternalAccounts',
'getOrders',
'getTrades',
'openOrders',
'sellOrder',
],
},
},
}
params.update(config)
super(lakebtc, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetTicker()
result = []
keys = list(markets.keys())
for k in range(0, len(keys)):
id = keys[k]
market = markets[id]
base = id[0:3]
quote = id[3:6]
base = base.upper()
quote = quote.upper()
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostGetAccountInfo()
balances = response['balance']
result = {'info': response}
currencies = list(balances.keys())
for c in range(0, len(currencies)):
currency = currencies[c]
balance = float(balances[currency])
account = {
'free': balance,
'used': 0.0,
'total': balance,
}
result[currency] = account
return result
def fetch_order_book(self, market, params={}):
self.load_markets()
orderbook = self.publicGetBcorderbook(self.extend({
'symbol': self.market_id(market),
}, params))
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
tickers = self.publicGetTicker({
'symbol': market['id'],
})
ticker = tickers[market['id']]
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_float(ticker, 'high'),
'low': self.safe_float(ticker, 'low'),
'bid': self.safe_float(ticker, 'bid'),
'ask': self.safe_float(ticker, 'ask'),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': self.safe_float(ticker, 'last'),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': self.safe_float(ticker, 'volume'),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['date'] * 1000
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'id': str(trade['tid']),
'order': None,
'type': None,
'side': None,
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetBctrades(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, market, type, side, amount, price=None, params={}):
self.load_markets()
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
method = 'privatePost' + self.capitalize(side) + 'Order'
marketId = self.market_id(market)
order = {
'params': [price, amount, marketId],
}
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': str(response['id']),
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostCancelOrder({'params': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version
if api == 'public':
url += '/' + path
if params:
url += '?' + self.urlencode(params)
else:
nonce = self.nonce()
if params:
params = ','.join(params)
else:
params = ''
query = self.urlencode({
'tonce': nonce,
'accesskey': self.apiKey,
'requestmethod': method.lower(),
'id': nonce,
'method': path,
'params': params,
})
body = self.json({
'method': path,
'params': params,
'id': nonce,
})
signature = self.hmac(self.encode(query), self.secret, hashlib.sha1, 'base64')
headers = {
'Json-Rpc-Tonce': nonce,
'Authorization': "Basic " + self.apiKey + ':' + signature,
'Content-Length': len(body),
'Content-Type': 'application/json',
}
response = self.fetch(url, method, headers, body)
if 'error' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class livecoin (Exchange):
def __init__(self, config={}):
params = {
'id': 'livecoin',
'name': 'LiveCoin',
'countries': ['US', 'UK', 'RU'],
'rateLimit': 1000,
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27980768-f22fc424-638a-11e7-89c9-6010a54ff9be.jpg',
'api': 'https://api.livecoin.net',
'www': 'https://www.livecoin.net',
'doc': 'https://www.livecoin.net/api?lang=en',
},
'api': {
'public': {
'get': [
'exchange/all/order_book',
'exchange/last_trades',
'exchange/maxbid_minask',
'exchange/order_book',
'exchange/restrictions',
'exchange/ticker', # omit params to get all tickers at once
'info/coinInfo',
],
},
'private': {
'get': [
'exchange/client_orders',
'exchange/order',
'exchange/trades',
'exchange/commission',
'exchange/commissionCommonInfo',
'payment/balances',
'payment/balance',
'payment/get/address',
'payment/history/size',
'payment/history/transactions',
],
'post': [
'exchange/buylimit',
'exchange/buymarket',
'exchange/cancellimit',
'exchange/selllimit',
'exchange/sellmarket',
'payment/out/capitalist',
'payment/out/card',
'payment/out/coin',
'payment/out/okpay',
'payment/out/payeer',
'payment/out/perfectmoney',
'payment/voucher/amount',
'payment/voucher/make',
'payment/voucher/redeem',
],
},
},
}
params.update(config)
super(livecoin, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetExchangeTicker()
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['symbol']
symbol = id
base, quote = symbol.split('/')
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privateGetPaymentBalances()
result = {'info': balances}
for b in range(0, len(self.currencies)):
balance = balances[b]
currency = balance['currency']
account = None
if currency in result:
account = result[currency]
else:
account = self.account()
if balance['type'] == 'total':
account['total'] = float(balance['value'])
if balance['type'] == 'available':
account['free'] = float(balance['value'])
if balance['type'] == 'trade':
account['used'] = float(balance['value'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetExchangeOrderBook(self.extend({
'currencyPair': self.market_id(symbol),
'groupByPrice': 'false',
'depth': 100,
}, params))
timestamp = orderbook['timestamp']
return self.parse_order_book(orderbook, timestamp)
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['best_bid']),
'ask': float(ticker['best_ask']),
'vwap': float(ticker['vwap']),
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
response = self.publicGetExchangeTicker()
tickers = self.index_by(response, 'symbol')
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetExchangeTicker({
'currencyPair': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = trade['time'] * 1000
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'id': str(trade['id']),
'order': None,
'type': None,
'side': trade['type'].lower(),
'price': trade['price'],
'amount': trade['quantity'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetExchangeLastTrades(self.extend({
'currencyPair': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
method = 'privatePostExchange' + self.capitalize(side) + type
order = {
'currencyPair': self.market_id(symbol),
'quantity': amount,
}
if type == 'limit':
order['price'] = price
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': str(response['id']),
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privatePostExchangeCancellimit(self.extend({
'orderId': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
query = self.urlencode(self.keysort(params))
if method == 'GET':
if query:
url += '?' + query
else:
if query:
body = query
signature = self.hmac(self.encode(query), self.encode(self.secret), hashlib.sha256)
headers = {
'Api-Key': self.apiKey,
'Sign': signature.upper(),
'Content-Type': 'application/x-www-form-urlencoded',
}
response = self.fetch(url, method, headers, body)
if 'success' in response:
if not response['success']:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class liqui (Exchange):
def __init__(self, config={}):
params = {
'id': 'liqui',
'name': 'Liqui',
'countries': 'UA',
'rateLimit': 1000,
'version': '3',
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27982022-75aea828-63a0-11e7-9511-ca584a8edd74.jpg',
'api': {
'public': 'https://api.liqui.io/api',
'private': 'https://api.liqui.io/tapi',
},
'www': 'https://liqui.io',
'doc': 'https://liqui.io/api',
},
'api': {
'public': {
'get': [
'info',
'ticker/{pair}',
'depth/{pair}',
'trades/{pair}',
],
},
'private': {
'post': [
'getInfo',
'Trade',
'ActiveOrders',
'OrderInfo',
'CancelOrder',
'TradeHistory',
'TransHistory',
'CoinDepositAddress',
'WithdrawCoin',
'CreateCoupon',
'RedeemCoupon',
],
}
},
}
params.update(config)
super(liqui, self).__init__(params)
def fetch_markets(self):
response = self.publicGetInfo()
markets = response['pairs']
keys = list(markets.keys())
result = []
for p in range(0, len(keys)):
id = keys[p]
market = markets[id]
base, quote = id.split('_')
base = base.upper()
quote = quote.upper()
if base == 'DSH':
base = 'DASH'
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostGetInfo()
balances = response['return']
result = {'info': balances}
funds = balances['funds']
currencies = list(funds.keys())
for c in range(0, len(currencies)):
currency = currencies[c]
uppercase = currency.upper()
# they misspell DASH as dsh :/
if uppercase == 'DSH':
uppercase = 'DASH'
account = {
'free': funds[currency],
'used': 0.0,
'total': funds[currency],
}
result[uppercase] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetDepthPair(self.extend({
'pair': market['id'],
}, params))
if market['id'] in response:
orderbook = response[market['id']]
result = self.parse_order_book(orderbook)
result['bids'] = self.sort_by(result['bids'], 0, True)
result['asks'] = self.sort_by(result['asks'], 0)
return result
raise ExchangeError(self.id + ' ' + market['symbol'] + ' order book is empty or not available')
def parse_ticker(self, ticker, market=None):
timestamp = ticker['updated'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_float(ticker, 'high'),
'low': self.safe_float(ticker, 'low'),
'bid': self.safe_float(ticker, 'buy'),
'ask': self.safe_float(ticker, 'sell'),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': self.safe_float(ticker, 'last'),
'change': None,
'percentage': None,
'average': self.safe_float(ticker, 'avg'),
'baseVolume': self.safe_float(ticker, 'vol_cur'),
'quoteVolume': self.safe_float(ticker, 'vol'),
'info': ticker,
}
def fetch_tickers(self, symbols=None):
self.load_markets()
ids = self.market_ids(symbols) if(symbols) else self.ids
tickers = self.publicGetTickerPair({
'pair': '-'.join(ids),
})
result = {}
keys = list(tickers.keys())
for k in range(0, len(keys)):
id = keys[k]
ticker = tickers[id]
market = self.markets_by_id[id]
symbol = market['symbol']
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
id = market['id']
tickers = self.fetchTickers([id])
return tickers[symbol]
def parse_trade(self, trade, market):
timestamp = trade['timestamp'] * 1000
side = 'sell' if(trade['type'] == 'ask') else 'buy'
return {
'id': trade['tid'],
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
id = market['id']
response = self.publicGetTradesPair(self.extend({
'pair': id,
}, params))
return self.parse_trades(response[id], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'pair': self.market_id(symbol),
'type': side,
'amount': amount,
'rate': price,
}
response = self.privatePostTrade(self.extend(order, params))
return {
'info': response,
'id': response['return']['order_id'],
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostCancelOrder({'order_id': id})
def parse_order(self, order):
statusCode = order['status']
status = None
if statusCode == 0:
status = 'open'
elif(statusCode == 2) or(statusCode == 3):
status = 'canceled'
else:
status = 'closed'
timestamp = order['timestamp_created'] * 1000
market = self.markets_by_id[order['pair']]
result = {
'info': order,
'id': order['id'],
'symbol': market['symbol'],
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'type': 'limit',
'side': order['type'],
'price': order['rate'],
'amount': order['start_amount'],
'remaining': order['amount'],
'status': status,
}
return result
def parse_orders(self, orders, market=None):
ids = list(orders.keys())
result = []
for i in range(0, len(ids)):
id = ids[i]
order = orders[id]
extended = self.extend(order, {'id': id})
result.append(self.parse_order(extended, market))
return result
def fetch_order(self, id):
self.load_markets()
response = self.privatePostOrderInfo({'order_id': id})
order = response['return'][id]
return self.parse_order(self.extend({'id': id}, order))
def fetch_open_orders(self, symbol=None, params={}):
if not symbol:
raise ExchangeError(self.id + ' requires a symbol')
self.load_markets()
market = self.market(symbol)
request = {
'pair': market['id'],
}
response = self.privatePostActiveOrders(self.extend(request, params))
return self.parse_orders(response['return'], market)
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
response = self.privatePostWithdrawCoin(self.extend({
'coinName': currency,
'amount': float(amount),
'address': address,
}, params))
return {
'info': response,
'id': response['return']['tId'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
query = self.omit(params, self.extract_params(path))
if api == 'public':
url += '/' + self.version + '/' + self.implode_params(path, params)
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
body = self.urlencode(self.extend({
'nonce': nonce,
'method': path,
}, query))
signature = self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': str(len(body)),
'Key': self.apiKey,
'Sign': signature,
}
response = self.fetch(url, method, headers, body)
if 'success' in response:
if not response['success']:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class luno (Exchange):
def __init__(self, config={}):
params = {
'id': 'luno',
'name': 'luno',
'countries': ['GB', 'SG', 'ZA'],
'rateLimit': 3000,
'version': '1',
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766607-8c1a69d8-5ede-11e7-930c-540b5eb9be24.jpg',
'api': 'https://api.mybitx.com/api',
'www': 'https://www.luno.com',
'doc': [
'https://www.luno.com/en/api',
'https://npmjs.org/package/bitx',
'https://github.com/bausmeier/node-bitx',
],
},
'api': {
'public': {
'get': [
'orderbook',
'ticker',
'tickers',
'trades',
],
},
'private': {
'get': [
'accounts/{id}/pending',
'accounts/{id}/transactions',
'balance',
'fee_info',
'funding_address',
'listorders',
'listtrades',
'orders/{id}',
'quotes/{id}',
'withdrawals',
'withdrawals/{id}',
],
'post': [
'accounts',
'postorder',
'marketorder',
'stoporder',
'funding_address',
'withdrawals',
'send',
'quotes',
'oauth2/grant',
],
'put': [
'quotes/{id}',
],
'delete': [
'quotes/{id}',
'withdrawals/{id}',
],
},
},
}
params.update(config)
super(luno, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetTickers()
result = []
for p in range(0, len(markets['tickers'])):
market = markets['tickers'][p]
id = market['pair']
base = id[0:3]
quote = id[3:6]
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetBalance()
balances = response['balance']
result = {'info': response}
for b in range(0, len(balances)):
balance = balances[b]
currency = self.commonCurrencyCode(balance['asset'])
reserved = float(balance['reserved'])
unconfirmed = float(balance['unconfirmed'])
account = {
'free': float(balance['balance']),
'used': self.sum(reserved, unconfirmed),
'total': 0.0,
}
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetOrderbook(self.extend({
'pair': self.market_id(symbol),
}, params))
timestamp = orderbook['timestamp']
return self.parse_order_book(orderbook, timestamp, 'bids', 'asks', 'price', 'volume')
def parse_ticker(self, ticker, market):
timestamp = ticker['timestamp']
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last_trade']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['rolling_24_hour_volume']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
response = self.publicGetTickers()
tickers = self.index_by(response['tickers'], 'pair')
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetTicker({
'pair': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
side = 'buy' if(trade['is_buy']) else 'sell'
return {
'info': trade,
'id': None,
'order': None,
'timestamp': trade['timestamp'],
'datetime': self.iso8601(trade['timestamp']),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': float(trade['price']),
'amount': float(trade['volume']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTrades(self.extend({
'pair': market['id'],
}, params))
return self.parse_trades(response['trades'], market)
def create_order(self, market, type, side, amount, price=None, params={}):
self.load_markets()
method = 'privatePost'
order = {'pair': self.market_id(market)}
if type == 'market':
method += 'Marketorder'
order['type'] = side.upper()
if side == 'buy':
order['counter_volume'] = amount
else:
order['base_volume'] = amount
else:
method += 'Order'
order['volume'] = amount
order['price'] = price
if side == 'buy':
order['type'] = 'BID'
else:
order['type'] = 'ASK'
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': response['order_id'],
}
def cancel_order(self, id):
self.load_markets()
return self.privatePostStoporder({'order_id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if query:
url += '?' + self.urlencode(query)
if api == 'private':
auth = self.encode(self.apiKey + ':' + self.secret)
auth = base64.b64encode(auth)
headers = {'Authorization': 'Basic ' + self.decode(auth)}
response = self.fetch(url, method, headers, body)
if 'error' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class mercado (Exchange):
def __init__(self, config={}):
params = {
'id': 'mercado',
'name': 'Mercado Bitcoin',
'countries': 'BR', # Brazil
'rateLimit': 1000,
'version': 'v3',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27837060-e7c58714-60ea-11e7-9192-f05e86adb83f.jpg',
'api': {
'public': 'https://www.mercadobitcoin.net/api',
'private': 'https://www.mercadobitcoin.net/tapi',
},
'www': 'https://www.mercadobitcoin.com.br',
'doc': [
'https://www.mercadobitcoin.com.br/api-doc',
'https://www.mercadobitcoin.com.br/trade-api',
],
},
'api': {
'public': {
'get': [# last slash critical
'orderbook/',
'orderbook_litecoin/',
'ticker/',
'ticker_litecoin/',
'trades/',
'trades_litecoin/',
'v2/ticker/',
'v2/ticker_litecoin/',
],
},
'private': {
'post': [
'cancel_order',
'get_account_info',
'get_order',
'get_withdrawal',
'list_system_messages',
'list_orders',
'list_orderbook',
'place_buy_order',
'place_sell_order',
'withdraw_coin',
],
},
},
'markets': {
'BTC/BRL': {'id': 'BRLBTC', 'symbol': 'BTC/BRL', 'base': 'BTC', 'quote': 'BRL', 'suffix': ''},
'LTC/BRL': {'id': 'BRLLTC', 'symbol': 'LTC/BRL', 'base': 'LTC', 'quote': 'BRL', 'suffix': 'Litecoin'},
},
}
params.update(config)
super(mercado, self).__init__(params)
def fetch_order_book(self, symbol, params={}):
market = self.market(symbol)
method = 'publicGetOrderbook' + self.capitalize(market['suffix'])
orderbook = getattr(self, method)(params)
return self.parse_order_book(orderbook)
def fetch_ticker(self, symbol):
market = self.market(symbol)
method = 'publicGetV2Ticker' + self.capitalize(market['suffix'])
response = getattr(self, method)()
ticker = response['ticker']
timestamp = int(ticker['date']) * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['vol']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['date'] * 1000
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'id': str(trade['tid']),
'order': None,
'type': None,
'side': trade['type'],
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
method = 'publicGetTrades' + self.capitalize(market['suffix'])
response = getattr(self, method)(params)
return self.parse_trades(response, market)
def fetch_balance(self, params={}):
response = self.privatePostGetAccountInfo()
balances = response['balance']
result = {'info': response}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = self.account()
if lowercase in balances:
account['free'] = float(balances[lowercase]['available'])
account['total'] = float(balances[lowercase]['total'])
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def create_order(self, symbol, type, side, amount, price=None, params={}):
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
method = 'privatePostPlace' + self.capitalize(side) + 'Order'
order = {
'coin_pair': self.market_id(symbol),
'quantity': amount,
'limit_price': price,
}
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': str(response['response_data']['order']['order_id']),
}
def cancel_order(self, id, params={}):
return self.privatePostCancelOrder(self.extend({
'order_id': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api] + '/'
if api == 'public':
url += path
else:
url += self.version + '/'
nonce = self.nonce()
body = self.urlencode(self.extend({
'tapi_method': path,
'tapi_nonce': nonce,
}, params))
auth = '/tapi/' + self.version + '/' + '?' + body
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'TAPI-ID': self.apiKey,
'TAPI-MAC': self.hmac(self.encode(auth), self.secret, hashlib.sha512),
}
response = self.fetch(url, method, headers, body)
if 'error_message' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class mixcoins (Exchange):
def __init__(self, config={}):
params = {
'id': 'mixcoins',
'name': 'MixCoins',
'countries': ['GB', 'HK'],
'rateLimit': 1500,
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/30237212-ed29303c-9535-11e7-8af8-fcd381cfa20c.jpg',
'api': 'https://mixcoins.com/api',
'www': 'https://mixcoins.com',
'doc': 'https://mixcoins.com/help/api/',
},
'api': {
'public': {
'get': [
'ticker',
'trades',
'depth',
],
},
'private': {
'post': [
'cancel',
'info',
'orders',
'order',
'transactions',
'trade',
],
},
},
'markets': {
'BTC/USD': {'id': 'btc_usd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'ETH/BTC': {'id': 'eth_btc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
'BCH/BTC': {'id': 'bcc_btc', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC'},
'LSK/BTC': {'id': 'lsk_btc', 'symbol': 'LSK/BTC', 'base': 'LSK', 'quote': 'BTC'},
'BCH/USD': {'id': 'bcc_usd', 'symbol': 'BCH/USD', 'base': 'BCH', 'quote': 'USD'},
'ETH/USD': {'id': 'eth_usd', 'symbol': 'ETH/USD', 'base': 'ETH', 'quote': 'USD'},
},
}
params.update(config)
super(mixcoins, self).__init__(params)
def fetch_balance(self, params={}):
response = self.privatePostInfo()
balance = response['result']['wallet']
result = {'info': balance}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = self.account()
if lowercase in balance:
account['free'] = float(balance[lowercase]['avail'])
account['used'] = float(balance[lowercase]['lock'])
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
response = self.publicGetDepth(self.extend({
'market': self.market_id(symbol),
}, params))
orderbook = response['result']
return self.parse_order_book(response['result'])
def fetch_ticker(self, symbol):
response = self.publicGetTicker({
'market': self.market_id(symbol),
})
ticker = response['result']
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['vol']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = int(trade['date']) * 1000
return {
'id': str(trade['id']),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': None,
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTrades(self.extend({
'market': market['id'],
}, params))
return self.parse_trades(response['result'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
order = {
'market': self.market_id(symbol),
'op': side,
'amount': amount,
}
if type == 'market':
order['order_type'] = 1
order['price'] = price
else:
order['order_type'] = 0
response = self.privatePostTrade(self.extend(order, params))
return {
'info': response,
'id': str(response['result']['id']),
}
def cancel_order(self, id):
return self.privatePostCancel({'id': id})
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + path
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
nonce = self.nonce()
body = self.urlencode(self.extend({
'nonce': nonce,
}, params))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': len(body),
'Key': self.apiKey,
'Sign': self.hmac(self.encode(body), self.secret, hashlib.sha512),
}
response = self.fetch(url, method, headers, body)
if 'status' in response:
if response['status'] == 200:
return response
raise ExchangeError(self.id + ' ' + self.json(response))
#------------------------------------------------------------------------------
class nova (Exchange):
def __init__(self, config={}):
params = {
'id': 'nova',
'name': 'Novaexchange',
'countries': 'TZ', # Tanzania
'rateLimit': 2000,
'version': 'v2',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/30518571-78ca0bca-9b8a-11e7-8840-64b83a4a94b2.jpg',
'api': 'https://novaexchange.com/remote',
'www': 'https://novaexchange.com',
'doc': 'https://novaexchange.com/remote/faq',
},
'api': {
'public': {
'get': [
'markets/',
'markets/{basecurrency}',
'market/info/{pair}/',
'market/orderhistory/{pair}/',
'market/openorders/{pair}/buy/',
'market/openorders/{pair}/sell/',
'market/openorders/{pair}/both/',
'market/openorders/{pair}/{ordertype}/',
],
},
'private': {
'post': [
'getbalances/',
'getbalance/{currency}/',
'getdeposits/',
'getwithdrawals/',
'getnewdepositaddress/{currency}/',
'getdepositaddress/{currency}/',
'myopenorders/',
'myopenorders_market/{pair}/',
'cancelorder/{orderid}/',
'withdraw/{currency}/',
'trade/{pair}/',
'tradehistory/',
'getdeposithistory/',
'getwithdrawalhistory/',
'walletstatus/',
'walletstatus/{currency}/',
],
},
},
}
params.update(config)
super(nova, self).__init__(params)
def fetch_markets(self):
response = self.publicGetMarkets()
markets = response['markets']
result = []
for i in range(0, len(markets)):
market = markets[i]
if not market['disabled']:
id = market['marketname']
quote, base = id.split('_')
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetMarketOpenordersPairBoth(self.extend({
'pair': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook, None, 'buyorders', 'sellorders', 'price', 'amount')
def fetch_ticker(self, symbol):
self.load_markets()
response = self.publicGetMarketInfoPair({
'pair': self.market_id(symbol),
})
ticker = response['markets'][0]
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high24h']),
'low': float(ticker['low24h']),
'bid': self.safe_float(ticker, 'bid'),
'ask': self.safe_float(ticker, 'ask'),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last_price']),
'change': float(ticker['change24h']),
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume24h']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = trade['unix_t_datestamp'] * 1000
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'id': None,
'order': None,
'type': None,
'side': trade['tradetype'].lower(),
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetMarketOrderhistoryPair(self.extend({
'pair': market['id'],
}, params))
return self.parse_trades(response['items'], market)
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostGetbalances()
balances = response['balances']
result = {'info': response}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
lockbox = float(balance['amount_lockbox'])
trades = float(balance['amount_trades'])
account = {
'free': float(balance['amount']),
'used': self.sum(lockbox, trades),
'total': float(balance['amount_total']),
}
result[currency] = account
return result
def create_order(self, symbol, type, side, amount, price=None, params={}):
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
self.load_markets()
amount = str(amount)
price = str(price)
market = self.market(symbol)
order = {
'tradetype': side.upper(),
'tradeamount': amount,
'tradeprice': price,
'tradebase': 1,
'pair': market['id'],
}
response = self.privatePostTradePair(self.extend(order, params))
return {
'info': response,
'id': None,
}
def cancel_order(self, id, params={}):
return self.privatePostCancelorder(self.extend({
'orderid': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/'
if api == 'private':
url += api + '/'
url += self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = str(self.nonce())
url += '?' + self.urlencode({'nonce': nonce})
signature = self.hmac(self.encode(url), self.encode(self.secret), hashlib.sha512, 'base64')
body = self.urlencode(self.extend({
'apikey': self.apiKey,
'signature': signature,
}, query))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
response = self.fetch(url, method, headers, body)
if 'status' in response:
if response['status'] != 'success':
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class okcoin (Exchange):
def __init__(self, config={}):
params = {
'version': 'v1',
'rateLimit': 1000, # up to 3000 requests per 5 minutes ≈ 600 requests per minute ≈ 10 requests per second ≈ 100 ms
'hasFetchOHLCV': True,
'timeframes': {
'1m': '1min',
'3m': '3min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '1hour',
'2h': '2hour',
'4h': '4hour',
'6h': '6hour',
'12h': '12hour',
'1d': '1day',
'3d': '3day',
'1w': '1week',
},
'api': {
'public': {
'get': [
'depth',
'exchange_rate',
'future_depth',
'future_estimated_price',
'future_hold_amount',
'future_index',
'future_kline',
'future_price_limit',
'future_ticker',
'future_trades',
'kline',
'otcs',
'ticker',
'trades',
],
},
'private': {
'post': [
'account_records',
'batch_trade',
'borrow_money',
'borrow_order_info',
'borrows_info',
'cancel_borrow',
'cancel_order',
'cancel_otc_order',
'cancel_withdraw',
'future_batch_trade',
'future_cancel',
'future_devolve',
'future_explosive',
'future_order_info',
'future_orders_info',
'future_position',
'future_position_4fix',
'future_trade',
'future_trades_history',
'future_userinfo',
'future_userinfo_4fix',
'lend_depth',
'order_fee',
'order_history',
'order_info',
'orders_info',
'otc_order_history',
'otc_order_info',
'repayment',
'submit_otc_order',
'trade',
'trade_history',
'trade_otc_order',
'withdraw',
'withdraw_info',
'unrepayments_info',
'userinfo',
],
},
},
}
params.update(config)
super(okcoin, self).__init__(params)
def fetch_order_book(self, market, params={}):
orderbook = self.publicGetDepth(self.extend({
'symbol': self.market_id(market),
}, params))
timestamp = self.milliseconds()
return {
'bids': orderbook['bids'],
'asks': self.sort_by(orderbook['asks'], 0),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
}
def parse_ticker(self, ticker, market):
timestamp = ticker['timestamp']
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['vol']),
'info': ticker,
}
def fetch_ticker(self, symbol):
market = self.market(symbol)
response = self.publicGetTicker({
'symbol': market['id'],
})
timestamp = int(response['date']) * 1000
ticker = self.extend(response['ticker'], {'timestamp': timestamp})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market=None):
symbol = None
if market:
symbol = market['symbol']
return {
'info': trade,
'timestamp': trade['date_ms'],
'datetime': self.iso8601(trade['date_ms']),
'symbol': symbol,
'id': trade['tid'],
'order': None,
'type': None,
'side': trade['type'],
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTrades(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response, market)
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=1440, params={}):
market = self.market(symbol)
request = {
'symbol': market['id'],
'type': self.timeframes[timeframe],
}
if limit:
request['size'] = int(limit)
if since:
request['since'] = since
else:
request['since'] = self.milliseconds() - 86400000 # last 24 hours
response = self.publicGetKline(self.extend(request, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def fetch_balance(self, params={}):
response = self.privatePostUserinfo()
balances = response['info']['funds']
result = {'info': response}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = self.account()
if lowercase in balances['free']:
account['free'] = float(balances['free'][lowercase])
if lowercase in balances['freezed']:
account['used'] = float(balances['freezed'][lowercase])
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def create_order(self, market, type, side, amount, price=None, params={}):
order = {
'symbol': self.market_id(market),
'type': side,
}
if type == 'limit':
order['price'] = price
order['amount'] = amount
else:
if side == 'buy':
order['price'] = params
else:
order['amount'] = amount
order['type'] += '_market'
response = self.privatePostTrade(self.extend(order, params))
return {
'info': response,
'id': str(response['order_id']),
}
def cancel_order(self, id, params={}):
return self.privatePostCancelOrder(self.extend({
'order_id': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/' + 'api' + '/' + self.version + '/' + path + '.do'
if api == 'public':
if params:
url += '?' + self.urlencode(params)
else:
query = self.keysort(self.extend({
'api_key': self.apiKey,
}, params))
# secret key must be at the end of query
queryString = self.urlencode(query) + '&secret_key=' + self.secret
query['sign'] = self.hash(self.encode(queryString)).upper()
body = self.urlencode(query)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
url = self.urls['api'] + url
response = self.fetch(url, method, headers, body)
if 'result' in response:
if not response['result']:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class okcoincny (okcoin):
def __init__(self, config={}):
params = {
'id': 'okcoincny',
'name': 'OKCoin CNY',
'countries': 'CN',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766792-8be9157a-5ee5-11e7-926c-6d69b8d3378d.jpg',
'api': 'https://www.okcoin.cn',
'www': 'https://www.okcoin.cn',
'doc': 'https://www.okcoin.cn/rest_getStarted.html',
},
'markets': {
'BTC/CNY': {'id': 'btc_cny', 'symbol': 'BTC/CNY', 'base': 'BTC', 'quote': 'CNY'},
'LTC/CNY': {'id': 'ltc_cny', 'symbol': 'LTC/CNY', 'base': 'LTC', 'quote': 'CNY'},
'ETH/CNY': {'id': 'eth_cny', 'symbol': 'ETH/CNY', 'base': 'ETH', 'quote': 'CNY'},
'ETC/CNY': {'id': 'etc_cny', 'symbol': 'ETC/CNY', 'base': 'ETC', 'quote': 'CNY'},
'BCH/CNY': {'id': 'bcc_cny', 'symbol': 'BCH/CNY', 'base': 'BCH', 'quote': 'CNY'},
},
}
params.update(config)
super(okcoincny, self).__init__(params)
#------------------------------------------------------------------------------
class okcoinusd (okcoin):
def __init__(self, config={}):
params = {
'id': 'okcoinusd',
'name': 'OKCoin USD',
'countries': ['CN', 'US'],
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766791-89ffb502-5ee5-11e7-8a5b-c5950b68ac65.jpg',
'api': 'https://www.okcoin.com',
'www': 'https://www.okcoin.com',
'doc': [
'https://www.okcoin.com/rest_getStarted.html',
'https://www.npmjs.com/package/okcoin.com',
],
},
'markets': {
'BTC/USD': {'id': 'btc_usd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'LTC/USD': {'id': 'ltc_usd', 'symbol': 'LTC/USD', 'base': 'LTC', 'quote': 'USD'},
'ETH/USD': {'id': 'eth_usd', 'symbol': 'ETH/USD', 'base': 'ETH', 'quote': 'USD'},
'ETC/USD': {'id': 'etc_usd', 'symbol': 'ETC/USD', 'base': 'ETC', 'quote': 'USD'},
},
}
params.update(config)
super(okcoinusd, self).__init__(params)
#------------------------------------------------------------------------------
class okex (okcoin):
def __init__(self, config={}):
params = {
'id': 'okex',
'name': 'OKEX',
'countries': ['CN', 'US'],
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/29562593-9038a9bc-8742-11e7-91cc-8201f845bfc1.jpg',
'api': 'https://www.okex.com',
'www': 'https://www.okex.com',
'doc': 'https://www.okex.com/rest_getStarted.html',
},
'markets': {
'BTC/USD': {'id': 'btc_usd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'LTC/USD': {'id': 'ltc_usd', 'symbol': 'LTC/USD', 'base': 'LTC', 'quote': 'USD'},
# 'LTC/BTC': {'id': 'ltc_btc', 'symbol': 'LTC/BTC', 'base': 'LTC', 'quote': 'BTC'},
# 'ETH/BTC': {'id': 'eth_btc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
# 'ETC/BTC': {'id': 'etc_btc', 'symbol': 'ETC/BTC', 'base': 'ETC', 'quote': 'BTC'},
# 'BCH/BTC': {'id': 'bcc_btc', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC'},
},
}
params.update(config)
super(okex, self).__init__(params)
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetFutureDepth(self.extend({
'symbol': self.market_id(symbol),
'contract_type': 'this_week', # next_week, quarter
}, params))
timestamp = self.milliseconds()
return {
'bids': orderbook['bids'],
'asks': self.sort_by(orderbook['asks'], 0),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
}
def fetch_ticker(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetFutureTicker(self.extend({
'symbol': market['id'],
'contract_type': 'this_week', # next_week, quarter
}, params))
timestamp = int(response['date']) * 1000
ticker = self.extend(response['ticker'], {'timestamp': timestamp})
return self.parse_ticker(ticker, market)
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetFutureTrades(self.extend({
'symbol': market['id'],
'contract_type': 'this_week', # next_week, quarter
}, params))
return self.parse_trades(response, market)
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
market = self.market(symbol)
request = {
'symbol': market['id'],
'contract_type': 'this_week', # next_week, quarter
'type': self.timeframes[timeframe],
'since': since,
}
if limit:
request['size'] = int(limit)
if since:
request['since'] = since
else:
request['since'] = self.milliseconds() - 86400000 # last 24 hours
response = self.publicGetFutureKline(self.extend(request, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
orderType = '1' if(side == 'buy') else '2'
order = {
'symbol': self.market_id(symbol),
'type': orderType,
'contract_type': 'this_week', # next_week, quarter
'match_price': 0, # match best counter party price? 0 or 1, ignores price if 1
'lever_rate': 10, # leverage rate value: 10 or 20(10 by default)
'price': price,
'amount': amount,
}
response = self.privatePostFutureTrade(self.extend(order, params))
return {
'info': response,
'id': str(response['order_id']),
}
def cancel_order(self, id, params={}):
return self.privatePostFutureCancel(self.extend({
'order_id': id,
}, params))
#------------------------------------------------------------------------------
class paymium (Exchange):
def __init__(self, config={}):
params = {
'id': 'paymium',
'name': 'Paymium',
'countries': ['FR', 'EU'],
'rateLimit': 2000,
'version': 'v1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27790564-a945a9d4-5ff9-11e7-9d2d-b635763f2f24.jpg',
'api': 'https://paymium.com/api',
'www': 'https://www.paymium.com',
'doc': [
'https://github.com/Paymium/api-documentation',
'https://www.paymium.com/page/developers',
],
},
'api': {
'public': {
'get': [
'countries',
'data/{id}/ticker',
'data/{id}/trades',
'data/{id}/depth',
'bitcoin_charts/{id}/trades',
'bitcoin_charts/{id}/depth',
],
},
'private': {
'get': [
'merchant/get_payment/{UUID}',
'user',
'user/addresses',
'user/addresses/{btc_address}',
'user/orders',
'user/orders/{UUID}',
'user/price_alerts',
],
'post': [
'user/orders',
'user/addresses',
'user/payment_requests',
'user/price_alerts',
'merchant/create_payment',
],
'delete': [
'user/orders/{UUID}/cancel',
'user/price_alerts/{id}',
],
},
},
'markets': {
'BTC/EUR': {'id': 'eur', 'symbol': 'BTC/EUR', 'base': 'BTC', 'quote': 'EUR'},
},
}
params.update(config)
super(paymium, self).__init__(params)
def fetch_balance(self, params={}):
balances = self.privateGetUser()
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = self.account()
balance = 'balance_' + lowercase
locked = 'locked_' + lowercase
if balance in balances:
account['free'] = balances[balance]
if locked in balances:
account['used'] = balances[locked]
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, market, params={}):
orderbook = self.publicGetDataIdDepth(self.extend({
'id': self.market_id(market),
}, params))
result = self.parse_order_book(orderbook, None, 'bids', 'asks', 'price', 'amount')
result['bids'] = self.sort_by(result['bids'], 0, True)
return result
def fetch_ticker(self, market):
ticker = self.publicGetDataIdTicker({
'id': self.market_id(market),
})
timestamp = ticker['at'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': float(ticker['vwap']),
'open': float(ticker['open']),
'close': None,
'first': None,
'last': float(ticker['price']),
'change': None,
'percentage': float(ticker['variation']),
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = int(trade['created_at_int']) * 1000
volume = 'traded_' + market['base'].lower()
return {
'info': trade,
'id': trade['uuid'],
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['side'],
'price': trade['price'],
'amount': trade[volume],
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetDataIdTrades(self.extend({
'id': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, market, type, side, amount, price=None, params={}):
order = {
'type': self.capitalize(type) + 'Order',
'currency': self.market_id(market),
'direction': side,
'amount': amount,
}
if type == 'market':
order['price'] = price
response = self.privatePostUserOrders(self.extend(order, params))
return {
'info': response,
'id': response['uuid'],
}
def cancel_order(self, id, params={}):
return self.privatePostCancelOrder(self.extend({
'orderNumber': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
body = self.json(params)
nonce = str(self.nonce())
auth = nonce + url + body
headers = {
'Api-Key': self.apiKey,
'Api-Signature': self.hmac(self.encode(auth), self.secret),
'Api-Nonce': nonce,
'Content-Type': 'application/json',
}
response = self.fetch(url, method, headers, body)
if 'errors' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class poloniex (Exchange):
def __init__(self, config={}):
params = {
'id': 'poloniex',
'name': 'Poloniex',
'countries': 'US',
'rateLimit': 500, # 6 calls per second
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766817-e9456312-5ee6-11e7-9b3c-b628ca5626a5.jpg',
'api': {
'public': 'https://poloniex.com/public',
'private': 'https://poloniex.com/tradingApi',
},
'www': 'https://poloniex.com',
'doc': [
'https://poloniex.com/support/api/',
'http://pastebin.com/dMX7mZE0',
],
},
'api': {
'public': {
'get': [
'return24hVolume',
'returnChartData',
'returnCurrencies',
'returnLoanOrders',
'returnOrderBook',
'returnTicker',
'returnTradeHistory',
],
},
'private': {
'post': [
'buy',
'cancelLoanOffer',
'cancelOrder',
'closeMarginPosition',
'createLoanOffer',
'generateNewAddress',
'getMarginPosition',
'marginBuy',
'marginSell',
'moveOrder',
'returnActiveLoans',
'returnAvailableAccountBalances',
'returnBalances',
'returnCompleteBalances',
'returnDepositAddresses',
'returnDepositsWithdrawals',
'returnFeeInfo',
'returnLendingHistory',
'returnMarginAccountSummary',
'returnOpenLoanOffers',
'returnOpenOrders',
'returnOrderTrades',
'returnTradableBalances',
'returnTradeHistory',
'sell',
'toggleAutoRenew',
'transferBalance',
'withdraw',
],
},
},
}
params.update(config)
super(poloniex, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetReturnTicker()
keys = list(markets.keys())
result = []
for p in range(0, len(keys)):
id = keys[p]
market = markets[id]
quote, base = id.split('_')
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privatePostReturnCompleteBalances({
'account': 'all',
})
result = {'info': balances}
currencies = list(balances.keys())
for c in range(0, len(currencies)):
currency = currencies[c]
balance = balances[currency]
account = {
'free': float(balance['available']),
'used': float(balance['onOrders']),
'total': 0.0,
}
account['total'] = self.sum(account['free'], account['used'])
result[currency] = account
return result
def fetch_order_book(self, market, params={}):
self.load_markets()
orderbook = self.publicGetReturnOrderBook(self.extend({
'currencyPair': self.market_id(market),
}, params))
return self.parse_order_book(orderbook)
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high24hr']),
'low': float(ticker['low24hr']),
'bid': float(ticker['highestBid']),
'ask': float(ticker['lowestAsk']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': float(ticker['percentChange']),
'percentage': None,
'average': None,
'baseVolume': float(ticker['baseVolume']),
'quoteVolume': float(ticker['quoteVolume']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGetReturnTicker()
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
tickers = self.publicGetReturnTicker()
ticker = tickers[market['id']]
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market=None):
timestamp = self.parse8601(trade['date'])
id = None
order = None
symbol = None
if market:
symbol = market['symbol']
elif 'currencyPair' in trade:
marketId = trade['currencyPair']
symbol = self.markets_by_id[marketId]['symbol']
if 'tradeID' in trade:
id = trade['tradeID']
if 'orderNumber' in trade:
order = trade['orderNumber']
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'id': id,
'order': order,
'type': None,
'side': trade['type'],
'price': float(trade['rate']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
trades = self.publicGetReturnTradeHistory(self.extend({
'currencyPair': market['id'],
'end': self.seconds(), # last 50000 trades by default
}, params))
return self.parse_trades(trades, market)
def fetch_my_trades(self, symbol=None, params={}):
self.load_markets()
market = None
if symbol:
market = self.market(symbol)
pair = market['id'] if market else 'all'
request = self.extend({
'currencyPair': pair,
'end': self.seconds(), # last 50000 trades by default
}, params)
response = self.privatePostReturnTradeHistory(request)
result = None
if market:
result = self.parse_trades(response, market)
else:
result = {'info': response}
ids = list(response.keys())
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
result[symbol] = self.parse_trades(response[id], market)
return result
def parse_order(self, order, market):
trades = None
if 'resultingTrades' in order:
trades = self.parse_trades(order['resultingTrades'], market)
return {
'info': order,
'id': order['orderNumber'],
'timestamp': order['timestamp'],
'datetime': self.iso8601(order['timestamp']),
'status': order['status'],
'symbol': market['symbol'],
'type': order['type'],
'side': order['side'],
'price': float(order['price']),
'amount': float(order['amount']),
'trades': trades,
}
def parseOpenOrders(self, orders, market, result=[]):
for i in range(0, len(orders)):
order = orders[i]
timestamp = self.parse8601(order['date'])
extended = self.extend(order, {
'timestamp': timestamp,
'status': 'open',
'type': 'limit',
'side': order['type'],
'price': order['rate'],
})
result.append(self.parse_order(extended, market))
return result
def fetch_open_orders(self, symbol=None, params={}):
self.load_markets()
market = None
if symbol:
market = self.market(symbol)
pair = market['id'] if market else 'all'
response = self.privatePostReturnOpenOrders(self.extend({
'currencyPair': pair,
}))
if market:
return self.parseOpenOrders(response, market)
ids = list(response.keys())
result = []
for i in range(0, len(ids)):
id = ids[i]
orders = response[id]
market = self.markets_by_id[id]
symbol = market['symbol']
self.parseOpenOrders(orders, market, result)
return result
def fetch_order_status(self, id, market=None):
self.load_markets()
orders = self.fetch_open_orders(market)
indexed = self.index_by(orders, 'id')
return 'open' if(id in list(indexed.keys())) else 'closed'
def create_order(self, symbol, type, side, amount, price=None, params={}):
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
self.load_markets()
method = 'privatePost' + self.capitalize(side)
market = self.market(symbol)
response = getattr(self, method)(self.extend({
'currencyPair': market['id'],
'rate': price,
'amount': amount,
}, params))
timestamp = self.milliseconds()
order = self.parse_order(self.extend({
'timestamp': timestamp,
'status': 'open',
'type': type,
'side': side,
'price': float(price),
'amount': float(amount),
}, response), market)
id = order['id']
self.orders[id] = order
return self.extend({'info': response}, order)
def fetch_order(self, id):
self.load_markets()
orders = self.fetch_open_orders()
index = self.index_by(orders, 'id')
if id in index:
self.orders[id] = index[id]
return index[id]
elif id in self.orders:
self.orders[id]['status'] = 'closed'
return self.orders[id]
raise ExchangeError(self.id + ' order ' + id + ' not found')
def fetch_order_trades(self, id, params={}):
self.load_markets()
trades = self.privatePostReturnOrderTrades(self.extend({
'orderNumber': id,
}, params))
return self.parse_trades(trades)
def cancel_order(self, id, params={}):
self.load_markets()
return self.privatePostCancelOrder(self.extend({
'orderNumber': id,
}, params))
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
result = self.privatePostWithdraw(self.extend({
'currency': currency,
'amount': amount,
'address': address,
}, params))
return {
'info': result,
'id': result['response'],
}
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
query = self.extend({'command': path}, params)
if api == 'public':
url += '?' + self.urlencode(query)
else:
query['nonce'] = self.nonce()
body = self.urlencode(query)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': self.apiKey,
'Sign': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
response = self.fetch(url, method, headers, body)
if 'error' in response:
error = self.id + ' ' + self.json(response)
failed = response['error'].find('Not enough') >= 0
if failed:
raise InsufficientFunds(error)
raise ExchangeError(error)
return response
#------------------------------------------------------------------------------
class quadrigacx (Exchange):
def __init__(self, config={}):
params = {
'id': 'quadrigacx',
'name': 'QuadrigaCX',
'countries': 'CA',
'rateLimit': 1000,
'version': 'v2',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766825-98a6d0de-5ee7-11e7-9fa4-38e11a2c6f52.jpg',
'api': 'https://api.quadrigacx.com',
'www': 'https://www.quadrigacx.com',
'doc': 'https://www.quadrigacx.com/api_info',
},
'api': {
'public': {
'get': [
'order_book',
'ticker',
'transactions',
],
},
'private': {
'post': [
'balance',
'bitcoin_deposit_address',
'bitcoin_withdrawal',
'buy',
'cancel_order',
'ether_deposit_address',
'ether_withdrawal',
'lookup_order',
'open_orders',
'sell',
'user_transactions',
],
},
},
'markets': {
'BTC/CAD': {'id': 'btc_cad', 'symbol': 'BTC/CAD', 'base': 'BTC', 'quote': 'CAD'},
'BTC/USD': {'id': 'btc_usd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD'},
'ETH/BTC': {'id': 'eth_btc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC'},
'ETH/CAD': {'id': 'eth_cad', 'symbol': 'ETH/CAD', 'base': 'ETH', 'quote': 'CAD'},
},
}
params.update(config)
super(quadrigacx, self).__init__(params)
def fetch_balance(self, params={}):
balances = self.privatePostBalance()
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = {
'free': float(balances[lowercase + '_available']),
'used': float(balances[lowercase + '_reserved']),
'total': float(balances[lowercase + '_balance']),
}
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
orderbook = self.publicGetOrderBook(self.extend({
'book': self.market_id(symbol),
}, params))
timestamp = int(orderbook['timestamp']) * 1000
return self.parse_order_book(orderbook, timestamp)
def fetch_ticker(self, symbol):
ticker = self.publicGetTicker({
'book': self.market_id(symbol),
})
timestamp = int(ticker['timestamp']) * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': float(ticker['vwap']),
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = int(trade['date']) * 1000
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'id': str(trade['tid']),
'order': None,
'type': None,
'side': trade['side'],
'price': float(trade['price']),
'amount': float(trade['amount']),
}
def fetch_trades(self, symbol, params={}):
market = self.market(symbol)
response = self.publicGetTransactions(self.extend({
'book': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
method = 'privatePost' + self.capitalize(side)
order = {
'amount': amount,
'book': self.market_id(symbol),
}
if type == 'limit':
order['price'] = price
response = getattr(self, method)(self.extend(order, params))
return {
'info': response,
'id': str(response['id']),
}
def cancel_order(self, id, params={}):
return self.privatePostCancelOrder(self.extend({
'id': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + path
if api == 'public':
url += '?' + self.urlencode(params)
else:
if not self.uid:
raise AuthenticationError(self.id + ' requires `' + self.id + '.uid` property for authentication')
nonce = self.nonce()
request = ''.join([str(nonce), self.uid, self.apiKey])
signature = self.hmac(self.encode(request), self.encode(self.secret))
query = self.extend({
'key': self.apiKey,
'nonce': nonce,
'signature': signature,
}, params)
body = self.json(query)
headers = {
'Content-Type': 'application/json',
}
response = self.fetch(url, method, headers, body)
if 'error' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class quoine (Exchange):
def __init__(self, config={}):
params = {
'id': 'quoine',
'name': 'QUOINE',
'countries': ['JP', 'SG', 'VN'],
'version': '2',
'rateLimit': 1000,
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766844-9615a4e8-5ee8-11e7-8814-fcd004db8cdd.jpg',
'api': 'https://api.quoine.com',
'www': 'https://www.quoine.com',
'doc': 'https://developers.quoine.com',
},
'api': {
'public': {
'get': [
'products',
'products/{id}',
'products/{id}/price_levels',
'executions',
'ir_ladders/{currency}',
],
},
'private': {
'get': [
'accounts/balance',
'crypto_accounts',
'executions/me',
'fiat_accounts',
'loan_bids',
'loans',
'orders',
'orders/{id}',
'orders/{id}/trades',
'trades',
'trades/{id}/loans',
'trading_accounts',
'trading_accounts/{id}',
],
'post': [
'fiat_accounts',
'loan_bids',
'orders',
],
'put': [
'loan_bids/{id}/close',
'loans/{id}',
'orders/{id}',
'orders/{id}/cancel',
'trades/{id}',
'trades/{id}/close',
'trades/close_all',
'trading_accounts/{id}',
],
},
},
}
params.update(config)
super(quoine, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetProducts()
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['id']
base = market['base_currency']
quote = market['quoted_currency']
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privateGetAccountsBalance()
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
total = float(balance['balance'])
account = {
'free': total,
'used': 0.0,
'total': total,
}
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetProductsIdPriceLevels(self.extend({
'id': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook, None, 'buy_price_levels', 'sell_price_levels')
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
last = None
if 'last_traded_price' in ticker:
if ticker['last_traded_price']:
length = len(ticker['last_traded_price'])
if length > 0:
last = float(ticker['last_traded_price'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high_market_ask']),
'low': float(ticker['low_market_bid']),
'bid': float(ticker['market_bid']),
'ask': float(ticker['market_ask']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': last,
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['volume_24h']),
'quoteVolume': None,
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGetProducts()
result = {}
for t in range(0, len(tickers)):
ticker = tickers[t]
base = ticker['base_currency']
quote = ticker['quoted_currency']
symbol = base + '/' + quote
market = self.markets[symbol]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetProductsId({
'id': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = trade['created_at'] * 1000
return {
'info': trade,
'id': str(trade['id']),
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['taker_side'],
'price': float(trade['price']),
'amount': float(trade['quantity']),
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetExecutions(self.extend({
'product_id': market['id'],
}, params))
return self.parse_trades(response['models'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'order_type': type,
'product_id': self.market_id(symbol),
'side': side,
'quantity': amount,
}
if type == 'limit':
order['price'] = price
response = self.privatePostOrders(self.extend({
'order': order,
}, params))
return {
'info': response,
'id': str(response['id']),
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privatePutOrdersIdCancel(self.extend({
'id': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
headers = {
'X-Quoine-API-Version': self.version,
'Content-Type': 'application/json',
}
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
request = {
'path': url,
'nonce': nonce,
'token_id': self.apiKey,
'iat': int(math.floor(nonce / 1000)), # issued at
}
if query:
body = self.json(query)
headers['X-Quoine-Auth'] = self.jwt(request, self.secret)
response = self.fetch(self.urls['api'] + url, method, headers, body)
if 'message' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class southxchange (Exchange):
def __init__(self, config={}):
params = {
'id': 'southxchange',
'name': 'SouthXchange',
'countries': 'AR', # Argentina
'rateLimit': 1000,
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27838912-4f94ec8a-60f6-11e7-9e5d-bbf9bd50a559.jpg',
'api': 'https://www.southxchange.com/api',
'www': 'https://www.southxchange.com',
'doc': 'https://www.southxchange.com/Home/Api',
},
'api': {
'public': {
'get': [
'markets',
'price/{symbol}',
'prices',
'book/{symbol}',
'trades/{symbol}',
],
},
'private': {
'post': [
'cancelMarketOrders',
'cancelOrder',
'generatenewaddress',
'listOrders',
'listBalances',
'placeOrder',
'withdraw',
],
},
},
}
params.update(config)
super(southxchange, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetMarkets()
result = []
for p in range(0, len(markets)):
market = markets[p]
base = market[0]
quote = market[1]
symbol = base + '/' + quote
id = symbol
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privatePostListBalances()
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['Currency']
uppercase = currency.uppercase
free = float(balance['Available'])
used = float(balance['Unconfirmed'])
total = self.sum(free, used)
account = {
'free': free,
'used': used,
'total': total,
}
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetBookSymbol(self.extend({
'symbol': self.market_id(symbol),
}, params))
return self.parse_order_book(orderbook, None, 'BuyOrders', 'SellOrders', 'Price', 'Amount')
def parse_ticker(self, ticker, market):
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': None,
'low': None,
'bid': self.safe_float(ticker, 'Bid'),
'ask': self.safe_float(ticker, 'Ask'),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': self.safe_float(ticker, 'Last'),
'change': self.safe_float(ticker, 'Variation24Hr'),
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': self.safe_float(ticker, 'Volume24Hr'),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
response = self.publicGetPrices()
tickers = self.index_by(response, 'Market')
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetPriceSymbol({
'symbol': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market):
timestamp = trade['At'] * 1000
return {
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'id': None,
'order': None,
'type': None,
'side': trade['Type'],
'price': trade['Price'],
'amount': trade['Amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTradesSymbol(self.extend({
'symbol': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
order = {
'listingCurrency': market['base'],
'referenceCurrency': market['quote'],
'type': side,
'amount': amount,
}
if type == 'limit':
order['limitPrice'] = price
response = self.privatePostPlaceOrder(self.extend(order, params))
return {
'info': response,
'id': str(response),
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privatePostCancelOrder(self.extend({
'orderCode': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'private':
nonce = self.nonce()
query = self.extend({
'key': self.apiKey,
'nonce': nonce,
}, query)
body = self.json(query)
headers = {
'Content-Type': 'application/json',
'Hash': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
response = self.fetch(url, method, headers, body)
# if not response:
# raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class surbitcoin (blinktrade):
def __init__(self, config={}):
params = {
'id': 'surbitcoin',
'name': 'SurBitcoin',
'countries': 'VE',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27991511-f0a50194-6481-11e7-99b5-8f02932424cc.jpg',
'api': {
'public': 'https://api.blinktrade.com/api',
'private': 'https://api.blinktrade.com/tapi',
},
'www': 'https://surbitcoin.com',
'doc': 'https://blinktrade.com/docs',
},
'comment': 'Blinktrade API',
'markets': {
'BTC/VEF': {'id': 'BTCVEF', 'symbol': 'BTC/VEF', 'base': 'BTC', 'quote': 'VEF', 'brokerId': 1, 'broker': 'SurBitcoin'},
},
}
params.update(config)
super(surbitcoin, self).__init__(params)
#------------------------------------------------------------------------------
class therock (Exchange):
def __init__(self, config={}):
params = {
'id': 'therock',
'name': 'TheRockTrading',
'countries': 'MT',
'rateLimit': 1000,
'version': 'v1',
'hasFetchTickers': True,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766869-75057fa2-5ee9-11e7-9a6f-13e641fa4707.jpg',
'api': 'https://api.therocktrading.com',
'www': 'https://therocktrading.com',
'doc': [
'https://api.therocktrading.com/doc/v1/index.html',
'https://api.therocktrading.com/doc/',
],
},
'api': {
'public': {
'get': [
'funds/{id}/orderbook',
'funds/{id}/ticker',
'funds/{id}/trades',
'funds/tickers',
],
},
'private': {
'get': [
'balances',
'balances/{id}',
'discounts',
'discounts/{id}',
'funds',
'funds/{id}',
'funds/{id}/trades',
'funds/{fund_id}/orders',
'funds/{fund_id}/orders/{id}',
'funds/{fund_id}/position_balances',
'funds/{fund_id}/positions',
'funds/{fund_id}/positions/{id}',
'transactions',
'transactions/{id}',
'withdraw_limits/{id}',
'withdraw_limits',
],
'post': [
'atms/withdraw',
'funds/{fund_id}/orders',
],
'delete': [
'funds/{fund_id}/orders/{id}',
'funds/{fund_id}/orders/remove_all',
],
},
},
}
params.update(config)
super(therock, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetFundsTickers()
result = []
for p in range(0, len(markets['tickers'])):
market = markets['tickers'][p]
id = market['fund_id']
base = id[0:3]
quote = id[3:6]
symbol = base + '/' + quote
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetBalances()
balances = response['balances']
result = {'info': response}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
free = balance['trading_balance']
total = balance['balance']
used = total - free
account = {
'free': free,
'used': used,
'total': total,
}
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
orderbook = self.publicGetFundsIdOrderbook(self.extend({
'id': self.market_id(symbol),
}, params))
timestamp = self.parse8601(orderbook['date'])
return self.parse_order_book(orderbook, timestamp, 'bids', 'asks', 'price', 'amount')
def parse_ticker(self, ticker, market):
timestamp = self.parse8601(ticker['date'])
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['bid']),
'ask': float(ticker['ask']),
'vwap': None,
'open': float(ticker['open']),
'close': float(ticker['close']),
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['volume_traded']),
'quoteVolume': float(ticker['volume']),
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
response = self.publicGetFundsTickers()
tickers = self.index_by(response['tickers'], 'fund_id')
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = self.markets_by_id[id]
symbol = market['symbol']
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
ticker = self.publicGetFundsIdTicker({
'id': market['id'],
})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market=None):
if not market:
market = self.markets_by_id[trade['fund_id']]
timestamp = self.parse8601(trade['date'])
return {
'info': trade,
'id': str(trade['id']),
'order': None,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': trade['side'],
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetFundsIdTrades(self.extend({
'id': market['id'],
}, params))
return self.parse_trades(response['trades'], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
response = self.privatePostFundsFundIdOrders(self.extend({
'fund_id': self.market_id(symbol),
'side': side,
'amount': amount,
'price': price,
}, params))
return {
'info': response,
'id': str(response['id']),
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privateDeleteFundsFundIdOrdersId(self.extend({
'id': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'private':
nonce = str(self.nonce())
auth = nonce + url
headers = {
'X-TRT-KEY': self.apiKey,
'X-TRT-NONCE': nonce,
'X-TRT-SIGN': self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha512),
}
if query:
body = self.json(query)
headers['Content-Type'] = 'application/json'
response = self.fetch(url, method, headers, body)
if 'errors' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class urdubit (blinktrade):
def __init__(self, config={}):
params = {
'id': 'urdubit',
'name': 'UrduBit',
'countries': 'PK',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27991453-156bf3ae-6480-11e7-82eb-7295fe1b5bb4.jpg',
'api': {
'public': 'https://api.blinktrade.com/api',
'private': 'https://api.blinktrade.com/tapi',
},
'www': 'https://urdubit.com',
'doc': 'https://blinktrade.com/docs',
},
'comment': 'Blinktrade API',
'markets': {
'BTC/PKR': {'id': 'BTCPKR', 'symbol': 'BTC/PKR', 'base': 'BTC', 'quote': 'PKR', 'brokerId': 8, 'broker': 'UrduBit'},
},
}
params.update(config)
super(urdubit, self).__init__(params)
#------------------------------------------------------------------------------
class vaultoro (Exchange):
def __init__(self, config={}):
params = {
'id': 'vaultoro',
'name': 'Vaultoro',
'countries': 'CH',
'rateLimit': 1000,
'version': '1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766880-f205e870-5ee9-11e7-8fe2-0d5b15880752.jpg',
'api': 'https://api.vaultoro.com',
'www': 'https://www.vaultoro.com',
'doc': 'https://api.vaultoro.com',
},
'api': {
'public': {
'get': [
'bidandask',
'buyorders',
'latest',
'latesttrades',
'markets',
'orderbook',
'sellorders',
'transactions/day',
'transactions/hour',
'transactions/month',
],
},
'private': {
'get': [
'balance',
'mytrades',
'orders',
],
'post': [
'buy/{symbol}/{type}',
'cancel/{id}',
'sell/{symbol}/{type}',
'withdraw',
],
},
},
}
params.update(config)
super(vaultoro, self).__init__(params)
def fetch_markets(self):
result = []
markets = self.publicGetMarkets()
market = markets['data']
base = market['BaseCurrency']
quote = market['MarketCurrency']
symbol = base + '/' + quote
baseId = base
quoteId = quote
id = market['MarketName']
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privateGetBalance()
balances = response['data']
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency_code']
uppercase = currency.upper()
free = balance['cash']
used = balance['reserved']
total = self.sum(free, used)
account = {
'free': free,
'used': used,
'total': total,
}
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
response = self.publicGetOrderbook(params)
orderbook = {
'bids': response['data'][0]['b'],
'asks': response['data'][1]['s'],
}
result = self.parse_order_book(orderbook, None, 'bids', 'asks', 'Gold_Price', 'Gold_Amount')
result['bids'] = self.sort_by(result['bids'], 0, True)
return result
def fetch_ticker(self, symbol):
self.load_markets()
quote = self.publicGetBidandask()
bidsLength = len(quote['bids'])
bid = quote['bids'][bidsLength - 1]
ask = quote['asks'][0]
response = self.publicGetMarkets()
ticker = response['data']
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['24hHigh']),
'low': float(ticker['24hLow']),
'bid': bid[0],
'ask': ask[0],
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['LastPrice']),
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': float(ticker['24hVolume']),
'info': ticker,
}
def parse_trade(self, trade, market):
timestamp = self.parse8601(trade['Time'])
return {
'id': None,
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'order': None,
'type': None,
'side': None,
'price': trade['Gold_Price'],
'amount': trade['Gold_Amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTransactionsDay(params)
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
method = 'privatePost' + self.capitalize(side) + 'SymbolType'
response = getattr(self, method)(self.extend({
'symbol': market['quoteId'].lower(),
'type': type,
'gld': amount,
'price': price or 1,
}, params))
return {
'info': response,
'id': response['data']['Order_ID'],
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privatePostCancelId(self.extend({
'id': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/'
if api == 'public':
url += path
else:
nonce = self.nonce()
url += self.version + '/' + self.implode_params(path, params)
query = self.extend({
'nonce': nonce,
'apikey': self.apiKey,
}, self.omit(params, self.extract_params(path)))
url += '?' + self.urlencode(query)
headers = {
'Content-Type': 'application/json',
'X-Signature': self.hmac(self.encode(url), self.encode(self.secret))
}
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class vbtc (blinktrade):
def __init__(self, config={}):
params = {
'id': 'vbtc',
'name': 'VBTC',
'countries': 'VN',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27991481-1f53d1d8-6481-11e7-884e-21d17e7939db.jpg',
'api': {
'public': 'https://api.blinktrade.com/api',
'private': 'https://api.blinktrade.com/tapi',
},
'www': 'https://vbtc.exchange',
'doc': 'https://blinktrade.com/docs',
},
'comment': 'Blinktrade API',
'markets': {
'BTC/VND': {'id': 'BTCVND', 'symbol': 'BTC/VND', 'base': 'BTC', 'quote': 'VND', 'brokerId': 3, 'broker': 'VBTC'},
},
}
params.update(config)
super(vbtc, self).__init__(params)
#------------------------------------------------------------------------------
class virwox (Exchange):
def __init__(self, config={}):
params = {
'id': 'virwox',
'name': 'VirWoX',
'countries': ['AT', 'EU'],
'rateLimit': 1000,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766894-6da9d360-5eea-11e7-90aa-41f2711b7405.jpg',
'api': {
'public': 'http://api.virwox.com/api/json.php',
'private': 'https://www.virwox.com/api/trading.php',
},
'www': 'https://www.virwox.com',
'doc': 'https://www.virwox.com/developers.php',
},
'api': {
'public': {
'get': [
'getInstruments',
'getBestPrices',
'getMarketDepth',
'estimateMarketOrder',
'getTradedPriceVolume',
'getRawTradeData',
'getStatistics',
'getTerminalList',
'getGridList',
'getGridStatistics',
],
'post': [
'getInstruments',
'getBestPrices',
'getMarketDepth',
'estimateMarketOrder',
'getTradedPriceVolume',
'getRawTradeData',
'getStatistics',
'getTerminalList',
'getGridList',
'getGridStatistics',
],
},
'private': {
'get': [
'cancelOrder',
'getBalances',
'getCommissionDiscount',
'getOrders',
'getTransactions',
'placeOrder',
],
'post': [
'cancelOrder',
'getBalances',
'getCommissionDiscount',
'getOrders',
'getTransactions',
'placeOrder',
],
},
},
}
params.update(config)
super(virwox, self).__init__(params)
def fetch_markets(self):
markets = self.publicGetInstruments()
keys = list(markets['result'].keys())
result = []
for p in range(0, len(keys)):
market = markets['result'][keys[p]]
id = market['instrumentID']
symbol = market['symbol']
base = market['longCurrency']
quote = market['shortCurrency']
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostGetBalances()
balances = response['result']['accountList']
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['currency']
total = balance['balance']
account = {
'free': total,
'used': 0.0,
'total': total,
}
result[currency] = account
return result
def fetchBestPrices(self, symbol):
self.load_markets()
return self.publicPostGetBestPrices({
'symbols': [symbol],
})
def fetch_order_book(self, symbol, params={}):
self.load_markets()
response = self.publicPostGetMarketDepth(self.extend({
'symbols': [symbol],
'buyDepth': 100,
'sellDepth': 100,
}, params))
orderbook = response['result'][0]
return self.parse_order_book(orderbook, None, 'buy', 'sell', 'price', 'volume')
def fetch_ticker(self, symbol):
self.load_markets()
end = self.milliseconds()
start = end - 86400000
response = self.publicGetTradedPriceVolume({
'instrument': symbol,
'endDate': self.YmdHMS(end),
'startDate': self.YmdHMS(start),
'HLOC': 1,
})
tickers = response['result']['priceVolumeList']
keys = list(tickers.keys())
length = len(keys)
lastKey = keys[length - 1]
ticker = tickers[lastKey]
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': None,
'ask': None,
'vwap': None,
'open': float(ticker['open']),
'close': float(ticker['close']),
'first': None,
'last': None,
'change': None,
'percentage': None,
'average': None,
'baseVolume': float(ticker['longVolume']),
'quoteVolume': float(ticker['shortVolume']),
'info': ticker,
}
def fetch_trades(self, market, params={}):
self.load_markets()
return self.publicGetRawTradeData(self.extend({
'instrument': market,
'timespan': 3600,
}, params))
def create_order(self, market, type, side, amount, price=None, params={}):
self.load_markets()
order = {
'instrument': self.symbol(market),
'orderType': side.upper(),
'amount': amount,
}
if type == 'limit':
order['price'] = price
response = self.privatePostPlaceOrder(self.extend(order, params))
return {
'info': response,
'id': str(response['orderID']),
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privatePostCancelOrder(self.extend({
'orderID': id,
}, params))
def request(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = self.urls['api'][api]
auth = {}
if api == 'private':
auth['key'] = self.apiKey
auth['user'] = self.login
auth['pass'] = self.password
nonce = self.nonce()
if method == 'GET':
url += '?' + self.urlencode(self.extend({
'method': path,
'id': nonce,
}, auth, params))
else:
headers = {'Content-Type': 'application/json'}
body = self.json({
'method': path,
'params': self.extend(auth, params),
'id': nonce,
})
response = self.fetch(url, method, headers, body)
if 'error' in response:
if response['error']:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class xbtce (Exchange):
def __init__(self, config={}):
params = {
'id': 'xbtce',
'name': 'xBTCe',
'countries': 'RU',
'rateLimit': 2000, # responses are cached every 2 seconds
'version': 'v1',
'hasPublicAPI': False,
'hasFetchTickers': True,
'hasFetchOHLCV': False,
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28059414-e235970c-662c-11e7-8c3a-08e31f78684b.jpg',
'api': 'https://cryptottlivewebapi.xbtce.net:8443/api',
'www': 'https://www.xbtce.com',
'doc': [
'https://www.xbtce.com/tradeapi',
'https://support.xbtce.info/Knowledgebase/Article/View/52/25/xbtce-exchange-api',
],
},
'api': {
'public': {
'get': [
'currency',
'currency/{filter}',
'level2',
'level2/{filter}',
'quotehistory/{symbol}/{periodicity}/bars/ask',
'quotehistory/{symbol}/{periodicity}/bars/bid',
'quotehistory/{symbol}/level2',
'quotehistory/{symbol}/ticks',
'symbol',
'symbol/{filter}',
'tick',
'tick/{filter}',
'ticker',
'ticker/{filter}',
'tradesession',
],
},
'private': {
'get': [
'tradeserverinfo',
'tradesession',
'currency',
'currency/{filter}',
'level2',
'level2/{filter}',
'symbol',
'symbol/{filter}',
'tick',
'tick/{filter}',
'account',
'asset',
'asset/{id}',
'position',
'position/{id}',
'trade',
'trade/{id}',
'quotehistory/{symbol}/{periodicity}/bars/ask',
'quotehistory/{symbol}/{periodicity}/bars/ask/info',
'quotehistory/{symbol}/{periodicity}/bars/bid',
'quotehistory/{symbol}/{periodicity}/bars/bid/info',
'quotehistory/{symbol}/level2',
'quotehistory/{symbol}/level2/info',
'quotehistory/{symbol}/periodicities',
'quotehistory/{symbol}/ticks',
'quotehistory/{symbol}/ticks/info',
'quotehistory/cache/{symbol}/{periodicity}/bars/ask',
'quotehistory/cache/{symbol}/{periodicity}/bars/bid',
'quotehistory/cache/{symbol}/level2',
'quotehistory/cache/{symbol}/ticks',
'quotehistory/symbols',
'quotehistory/version',
],
'post': [
'trade',
'tradehistory',
],
'put': [
'trade',
],
'delete': [
'trade',
],
},
},
}
params.update(config)
super(xbtce, self).__init__(params)
def fetch_markets(self):
markets = self.privateGetSymbol()
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['Symbol']
base = market['MarginCurrency']
quote = market['ProfitCurrency']
if base == 'DSH':
base = 'DASH'
symbol = base + '/' + quote
symbol = symbol if market['IsTradeAllowed'] else id
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
balances = self.privateGetAsset()
result = {'info': balances}
for b in range(0, len(balances)):
balance = balances[b]
currency = balance['Currency']
uppercase = currency.upper()
# xbtce names DASH incorrectly as DSH
if uppercase == 'DSH':
uppercase = 'DASH'
total = balance['balance']
account = {
'free': balance['FreeAmount'],
'used': balance['LockedAmount'],
'total': balance['Amount'],
}
result[uppercase] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
orderbook = self.privateGetLevel2Filter(self.extend({
'filter': market['id'],
}, params))
orderbook = orderbook[0]
timestamp = orderbook['Timestamp']
return self.parse_order_book(orderbook, timestamp, 'Bids', 'Asks', 'Price', 'Volume')
def parse_ticker(self, ticker, market):
timestamp = 0
last = None
if 'LastBuyTimestamp' in ticker:
if timestamp < ticker['LastBuyTimestamp']:
timestamp = ticker['LastBuyTimestamp']
last = ticker['LastBuyPrice']
if 'LastSellTimestamp' in ticker:
if timestamp < ticker['LastSellTimestamp']:
timestamp = ticker['LastSellTimestamp']
last = ticker['LastSellPrice']
if not timestamp:
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': ticker['DailyBestBuyPrice'],
'low': ticker['DailyBestSellPrice'],
'bid': ticker['BestBid'],
'ask': ticker['BestAsk'],
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': last,
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': ticker['DailyTradedTotalVolume'],
'info': ticker,
}
def fetch_tickers(self):
self.load_markets()
tickers = self.publicGetTicker()
tickers = self.index_by(tickers, 'Symbol')
ids = list(tickers.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
market = None
symbol = None
if id in self.markets_by_id:
market = self.markets_by_id[id]
symbol = market['symbol']
else:
base = id[0:3]
quote = id[3:6]
if base == 'DSH':
base = 'DASH'
if quote == 'DSH':
quote = 'DASH'
symbol = base + '/' + quote
ticker = tickers[id]
result[symbol] = self.parse_ticker(ticker, market)
return result
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
tickers = self.publicGetTickerFilter({
'filter': market['id'],
})
length = len(tickers)
if length < 1:
raise ExchangeError(self.id + ' fetchTicker returned empty response, xBTCe public API error')
tickers = self.index_by(tickers, 'Symbol')
ticker = tickers[market['id']]
return self.parse_ticker(ticker, market)
def fetch_trades(self, symbol, params={}):
self.load_markets()
# no method for trades?
return self.privateGetTrade(params)
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
return [
ohlcv['Timestamp'],
ohlcv['Open'],
ohlcv['High'],
ohlcv['Low'],
ohlcv['Close'],
ohlcv['Volume'],
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
raise NotSupported(self.id + ' fetchOHLCV is disabled by the exchange')
minutes = int(timeframe / 60) # 1 minute by default
periodicity = str(minutes)
self.load_markets()
market = self.market(symbol)
if not since:
since = self.seconds() - 86400 * 7 # last day by defulat
if not limit:
limit = 1000 # default
response = self.privateGetQuotehistorySymbolPeriodicityBarsBid(self.extend({
'symbol': market['id'],
'periodicity': '5m', # periodicity,
'timestamp': since,
'count': limit,
}, params))
return self.parse_ohlcvs(response['Bars'], market, timeframe, since, limit)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
response = self.tapiPostTrade(self.extend({
'pair': self.market_id(symbol),
'type': side,
'amount': amount,
'rate': price,
}, params))
return {
'info': response,
'id': str(response['Id']),
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.privateDeleteTrade(self.extend({
'Type': 'Cancel',
'Id': id,
}, params))
def nonce(self):
return self.milliseconds()
def request(self, path, api='api', method='GET', params={}, headers=None, body=None):
if not self.apiKey:
raise AuthenticationError(self.id + ' requires apiKey for all requests, their public API is always busy')
if not self.uid:
raise AuthenticationError(self.id + ' requires uid property for authentication and trading')
url = self.urls['api'] + '/' + self.version
if api == 'public':
url += '/' + api
url += '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if api == 'public':
if query:
url += '?' + self.urlencode(query)
else:
headers = {'Accept-Encoding': 'gzip, deflate'}
nonce = str(self.nonce())
if method == 'POST':
if query:
headers['Content-Type'] = 'application/json'
body = self.json(query)
else:
url += '?' + self.urlencode(query)
auth = nonce + self.uid + self.apiKey + method + url
if body:
auth += body
signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256, 'base64')
credentials = self.uid + ':' + self.apiKey + ':' + nonce + ':' + self.binary_to_string(signature)
headers['Authorization'] = 'HMAC ' + credentials
return self.fetch(url, method, headers, body)
#------------------------------------------------------------------------------
class yobit (Exchange):
def __init__(self, config={}):
params = {
'id': 'yobit',
'name': 'YoBit',
'countries': 'RU',
'rateLimit': 2000, # responses are cached every 2 seconds
'version': '3',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766910-cdcbfdae-5eea-11e7-9859-03fea873272d.jpg',
'api': 'https://yobit.net',
'www': 'https://www.yobit.net',
'doc': 'https://www.yobit.net/en/api/',
},
'api': {
'api': {
'get': [
'depth/{pairs}',
'info',
'ticker/{pairs}',
'trades/{pairs}',
],
},
'tapi': {
'post': [
'ActiveOrders',
'CancelOrder',
'GetDepositAddress',
'getInfo',
'OrderInfo',
'Trade',
'TradeHistory',
'WithdrawCoinsToAddress',
],
},
},
}
params.update(config)
super(yobit, self).__init__(params)
def fetch_markets(self):
markets = self.apiGetInfo()
keys = list(markets['pairs'].keys())
result = []
for p in range(0, len(keys)):
id = keys[p]
market = markets['pairs'][id]
symbol = id.upper().replace('_', '/')
base, quote = symbol.split('/')
base = self.commonCurrencyCode(base)
quote = self.commonCurrencyCode(quote)
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.tapiPostGetInfo()
balances = response['return']
result = {'info': balances}
for c in range(0, len(self.currencies)):
currency = self.currencies[c]
lowercase = currency.lower()
account = self.account()
if 'funds' in balances:
if lowercase in balances['funds']:
account['free'] = balances['funds'][lowercase]
if 'funds_incl_orders' in balances:
if lowercase in balances['funds_incl_orders']:
account['total'] = balances['funds_incl_orders'][lowercase]
if account['total'] and account['free']:
account['used'] = account['total'] - account['free']
result[currency] = account
return result
def fetch_order_book(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.apiGetDepthPairs(self.extend({
'pairs': market['id'],
}, params))
orderbook = response[market['id']]
timestamp = self.milliseconds()
bids = orderbook['bids'] if('bids' in list(orderbook.keys())) else []
asks = orderbook['asks'] if('asks' in list(orderbook.keys())) else []
return {
'bids': bids,
'asks': asks,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
}
def fetch_ticker(self, symbol):
self.load_markets()
market = self.market(symbol)
tickers = self.apiGetTickerPairs({
'pairs': market['id'],
})
ticker = tickers[market['id']]
timestamp = ticker['updated'] * 1000
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': float(ticker['high']),
'low': float(ticker['low']),
'bid': float(ticker['buy']),
'ask': float(ticker['sell']),
'vwap': None,
'open': None,
'close': None,
'first': None,
'last': float(ticker['last']),
'change': None,
'percentage': None,
'average': float(ticker['avg']),
'baseVolume': float(ticker['vol_cur']),
'quoteVolume': float(ticker['vol']),
'info': ticker,
}
def parse_trade(self, trade, market=None):
timestamp = trade['timestamp'] * 1000
side = 'buy' if(trade['type'] == 'bid') else 'sell'
return {
'info': trade,
'id': str(trade['tid']),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.apiGetTradesPairs(self.extend({
'pairs': market['id'],
}, params))
return self.parse_trades(response[market['id']], market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
if type == 'market':
raise ExchangeError(self.id + ' allows limit orders only')
rate = str(price)
response = self.tapiPostTrade(self.extend({
'pair': self.market_id(symbol),
'type': side,
'amount': amount,
'rate': '{:.8f}'.format(price),
}, params))
return {
'info': response,
'id': str(response['return']['order_id']),
}
def cancel_order(self, id, params={}):
self.load_markets()
return self.tapiPostCancelOrder(self.extend({
'order_id': id,
}, params))
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
result = self.tapiPostWithdrawCoinsToAddress(self.extend({
'coinName': currency,
'amount': amount,
'address': address,
}, params))
return {
'info': result,
'id': None,
}
def request(self, path, api='api', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/' + api
if api == 'api':
url += '/' + self.version + '/' + self.implode_params(path, params)
query = self.omit(params, self.extract_params(path))
if query:
url += '?' + self.urlencode(query)
else:
nonce = self.nonce()
query = self.extend({'method': path, 'nonce': nonce}, params)
body = self.urlencode(query)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'key': self.apiKey,
'sign': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
response = self.fetch(url, method, headers, body)
if 'error' in response:
raise ExchangeError(self.id + ' ' + self.json(response))
return response
#------------------------------------------------------------------------------
class yunbi (acx):
def __init__(self, config={}):
params = {
'id': 'yunbi',
'name': 'YUNBI',
'countries': 'CN',
'rateLimit': 1000,
'version': 'v2',
'hasFetchTickers': True,
'hasFetchOHLCV': True,
'timeframes': {
'1m': '1',
'5m': '5',
'15m': '15',
'30m': '30',
'1h': '60',
'2h': '120',
'4h': '240',
'12h': '720',
'1d': '1440',
'3d': '4320',
'1w': '10080',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/28570548-4d646c40-7147-11e7-9cf6-839b93e6d622.jpg',
'api': 'https://yunbi.com',
'www': 'https://yunbi.com',
'doc': [
'https://yunbi.com/documents/api/guide',
'https://yunbi.com/swagger/',
],
},
'api': {
'public': {
'get': [
'tickers',
'tickers/{market}',
'markets',
'order_book',
'k',
'depth',
'trades',
'k_with_pending_trades',
'timestamp',
'addresses/{address}',
'partners/orders/{id}/trades',
],
},
'private': {
'get': [
'deposits',
'members/me',
'deposit',
'deposit_address',
'order',
'orders',
'trades/my',
],
'post': [
'order/delete',
'orders',
'orders/multi',
'orders/clear',
],
},
},
}
params.update(config)
super(yunbi, self).__init__(params)
#------------------------------------------------------------------------------
class zaif (Exchange):
def __init__(self, config={}):
params = {
'id': 'zaif',
'name': 'Zaif',
'countries': 'JP',
'rateLimit': 2000,
'version': '1',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766927-39ca2ada-5eeb-11e7-972f-1b4199518ca6.jpg',
'api': 'https://api.zaif.jp',
'www': 'https://zaif.jp',
'doc': [
'http://techbureau-api-document.readthedocs.io/ja/latest/index.html',
'https://corp.zaif.jp/api-docs',
'https://corp.zaif.jp/api-docs/api_links',
'https://www.npmjs.com/package/zaif.jp',
'https://github.com/you21979/node-zaif',
],
},
'api': {
'public': {
'get': [
'depth/{pair}',
'currencies/{pair}',
'currencies/all',
'currency_pairs/{pair}',
'currency_pairs/all',
'last_price/{pair}',
'ticker/{pair}',
'trades/{pair}',
],
},
'private': {
'post': [
'active_orders',
'cancel_order',
'deposit_history',
'get_id_info',
'get_info',
'get_info2',
'get_personal_info',
'trade',
'trade_history',
'withdraw',
'withdraw_history',
],
},
'ecapi': {
'post': [
'createInvoice',
'getInvoice',
'getInvoiceIdsByOrderNumber',
'cancelInvoice',
],
},
},
}
params.update(config)
super(zaif, self).__init__(params)
self.fetch_market_data()
self.fetch_my_balance()
self.pre_order_id = self.fetch_pre_order_id()
self.min_lot_digit = 4
self.min_lot = 0.0001
def create_z_my_order_id(self):
import time
from datetime import datetime
import uuid
dt = datetime.now()
unixtime_str = str(int(time.mktime(dt.timetuple()) * 1e5 + dt.microsecond))
mac_addr = hex(uuid.getnode()).replace('0x', '')
z_my_order_id = 'z_' + unixtime_str + mac_addr
return z_my_order_id
def fetch_pre_order_id(self):
while True:
trade_histry = self.privatePostTradeHistory({'count': 1})
if trade_histry['success']:
if len(trade_histry['return']) == 0:
return None
else:
for order_num in trade_histry['return'].keys():
return trade_histry['return'][order_num]['comment']
sleep(1)
def fetch_markets(self):
markets = self.publicGetCurrencyPairsAll()
result = []
for p in range(0, len(markets)):
market = markets[p]
id = market['currency_pair']
symbol = market['name']
base, quote = symbol.split('/')
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'info': market,
})
return result
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostGetInfo()
balances = response['return']
result = {'info': balances}
currencies = list(balances['funds'].keys())
for c in range(0, len(currencies)):
currency = currencies[c]
balance = balances['funds'][currency]
uppercase = currency.upper()
account = {
'free': balance,
'used': 0.0,
'total': balance,
}
if 'deposit' in balances:
if currency in balances['deposit']:
account['total'] = balances['deposit'][currency]
account['used'] = account['total'] - account['free']
result[uppercase] = account
return result
def fetch_order_book(self, market, params={}):
self.load_markets()
orderbook = self.publicGetDepthPair(self.extend({
'pair': self.market_id(market),
}, params))
return self.parse_order_book(orderbook)
def fetch_ticker(self, market):
self.load_markets()
ticker = self.publicGetTickerPair({
'pair': self.market_id(market),
})
timestamp = self.milliseconds()
return {
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': ticker['high'],
'low': ticker['low'],
'bid': ticker['bid'],
'ask': ticker['ask'],
'vwap': ticker['vwap'],
'open': None,
'close': None,
'first': None,
'last': ticker['last'],
'change': None,
'percentage': None,
'average': None,
'baseVolume': None,
'quoteVolume': ticker['volume'],
'info': ticker,
}
def parse_trade(self, trade, market=None):
side = 'buy' if(trade['trade_type'] == 'bid') else 'sell'
timestamp = trade['date'] * 1000
id = None
if 'id' in trade:
id = trade['id']
elif 'tid' in trade:
id = trade['tid']
if not market:
market = self.markets_by_id[trade['currency_pair']]
return {
'id': str(id),
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': market['symbol'],
'type': None,
'side': side,
'price': trade['price'],
'amount': trade['amount'],
}
def fetch_trades(self, symbol, params={}):
self.load_markets()
market = self.market(symbol)
response = self.publicGetTradesPair(self.extend({
'pair': market['id'],
}, params))
return self.parse_trades(response, market)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
if type == 'market':
raise ExchangeError(self.id, self.id + ' allows limit orders only')
response = self.privatePostTrade(self.extend({
'currency_pair': self.market_id(symbol),
'action': 'bid' if(side == 'buy') else 'ask',
'amount': amount,
'price': price,
}, params))
return {
'info': response,
'id': str(response['return']['order_id']),
}
def update_pre_order_id(self, order_id):
self.pre_order_id = order_id
def create_arb_market_buy_order(self, symbol, amount, params={}, price_buff=50000):
params['comment'] = self.create_z_my_order_id()
z_rt = self.create_limit_buy_order(symbol, amount, int(self.best_ask_price) + price_buff, params)
self.update_pre_order_id(params['comment'])
return z_rt
def create_arb_market_sell_order(self, symbol, amount, params={}, price_buff=50000):
params['comment'] = self.create_z_my_order_id()
z_rt = self.create_limit_sell_order(symbol, amount, int(self.best_bid_price) - price_buff, params)
self.update_pre_order_id(params['comment'])
return z_rt
def cancel_order(self, id, params={}):
self.load_markets()
return self.privatePostCancelOrder(self.extend({
'order_id': id,
}, params))
def parse_order(self, order, market=None):
side = 'buy' if(order['action'] == 'bid') else 'sell'
timestamp = int(order['timestamp']) * 1000
if not market:
market = self.markets_by_id[order['currency_pair']]
return {
'id': str(order['id']),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'status': 'open',
'symbol': market['symbol'],
'type': 'limit',
'side': side,
'price': order['price'],
'amount': order['amount'],
'trades': None,
}
def parse_orders(self, orders, market=None):
ids = list(orders.keys())
result = []
for i in range(0, len(ids)):
id = ids[i]
order = orders[id]
extended = self.extend(order, {'id': id})
result.append(self.parse_order(extended, market))
return result
def fetch_open_orders(self, symbol=None, params={}):
self.load_markets()
market = None
# request = {
# 'is_token': False,
# 'is_token_both': False,
#}
request = {}
if symbol:
market = self.market(symbol)
request['currency_pair'] = market['id']
response = self.privatePostActiveOrders(self.extend(request, params))
return self.parse_orders(response['return'], market)
def fetchClosedOrders(self, symbol=None, params={}):
self.load_markets()
market = None
# request = {
# 'from': 0,
# 'count': 1000,
# 'from_id': 0,
# 'end_id': 1000,
# 'order': 'DESC',
# 'since': 1503821051,
# 'end': 1503821051,
# 'is_token': False,
#}
request = {}
if symbol:
market = self.market(symbol)
request['currency_pair'] = market['id']
response = self.privatePostTradeHistory(self.extend(request, params))
return self.parse_orders(response['return'], market)
def withdraw(self, currency, amount, address, params={}):
self.load_markets()
if currency == 'JPY':
raise ExchangeError(self.id, self.id + ' does not allow ' + currency + ' withdrawals')
result = self.privatePostWithdraw(self.extend({
'currency': currency,
'amount': amount,
'address': address,
# 'message': 'Hinot ', # XEM only
# 'opt_fee': 0.003, # BTC and MONA only
}, params))
return {
'info': result,
'id': result['return']['txid'],
'fee': result['return']['fee'],
}
def request(self, path, api='api', method='GET', params={}, headers=None, body=None):
url = self.urls['api'] + '/'
if api == 'public':
url += 'api/' + self.version + '/' + self.implode_params(path, params)
else:
url += 'ecapi' if(api == 'ecapi') else 'tapi'
nonce = self.nonce()
body = self.urlencode(self.extend({
'method': path,
'nonce': nonce,
}, params))
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Key': self.apiKey,
'Sign': self.hmac(self.encode(body), self.encode(self.secret), hashlib.sha512),
}
response = self.fetch(url, method, headers, body)
if 'error' in response:
if 'time out' in response['error']:
raise RequestTimeout(self.id, self.id + ' ' + response['error'])
if 'time wait restriction, please try later' in response['error']:
raise ExchangeNotAvailable(self.id, self.id + ' ' + response['error'])
if 'trade temporarily unavailable' in response['error']:
raise ExchangeNotAvailable(self.id, self.id + ' ' + response['error'])
if 'insufficient funds' in response['error']:
raise InsufficientFunds(self.id, self.id + ' ' + response['error'])
if 'api key dont have' in response['error']:
raise AuthenticationError(self.id, self.id + ' ' + response['error'])
if 'nonce not incremented' in response['error']:
raise ApiNonceError(self.id, self.id + ' ' + response['error'])
if 'invalid amount parameter' in response['error']:
raise ExchangeError(self.id, self.id + ' ' + response['error'])
raise ExchangeError(self.id, self.id + ' ' + response['error'])
if 'success' in response:
if not response['success']:
raise ExchangeError(self.id, self.id + ' ' + self.json(response))
return response
| mit | -4,919,360,203,065,701,000 | 36.746573 | 211 | 0.461253 | false |
jwiggins/scikit-image | skimage/io/_plugins/freeimage_plugin.py | 26 | 27618 | import ctypes
import numpy
import sys
import os
import os.path
from numpy.compat import asbytes, asstr
def _generate_candidate_libs():
# look for likely library files in the following dirs:
lib_dirs = [os.path.dirname(__file__),
'/lib',
'/usr/lib',
'/usr/local/lib',
'/opt/local/lib',
os.path.join(sys.prefix, 'lib'),
os.path.join(sys.prefix, 'DLLs')
]
if 'HOME' in os.environ:
lib_dirs.append(os.path.join(os.environ['HOME'], 'lib'))
lib_dirs = [ld for ld in lib_dirs if os.path.exists(ld)]
lib_names = ['libfreeimage', 'freeimage'] # should be lower-case!
# Now attempt to find libraries of that name in the given directory
# (case-insensitive and without regard for extension)
lib_paths = []
for lib_dir in lib_dirs:
for lib_name in lib_names:
files = os.listdir(lib_dir)
lib_paths += [os.path.join(lib_dir, lib) for lib in files
if lib.lower().startswith(lib_name) and not
os.path.splitext(lib)[1] in ('.py', '.pyc', '.ini')]
lib_paths = [lp for lp in lib_paths if os.path.exists(lp)]
return lib_dirs, lib_paths
if sys.platform == 'win32':
LOADER = ctypes.windll
FUNCTYPE = ctypes.WINFUNCTYPE
else:
LOADER = ctypes.cdll
FUNCTYPE = ctypes.CFUNCTYPE
def handle_errors():
global FT_ERROR_STR
if FT_ERROR_STR:
tmp = FT_ERROR_STR
FT_ERROR_STR = None
raise RuntimeError(tmp)
FT_ERROR_STR = None
# This MUST happen in module scope, or the function pointer is garbage
# collected, leading to a segfault when error_handler is called.
@FUNCTYPE(None, ctypes.c_int, ctypes.c_char_p)
def c_error_handler(fif, message):
global FT_ERROR_STR
FT_ERROR_STR = 'FreeImage error: %s' % message
def load_freeimage():
freeimage = None
errors = []
# First try a few bare library names that ctypes might be able to find
# in the default locations for each platform. Win DLL names don't need the
# extension, but other platforms do.
bare_libs = ['FreeImage', 'libfreeimage.dylib', 'libfreeimage.so',
'libfreeimage.so.3']
lib_dirs, lib_paths = _generate_candidate_libs()
lib_paths = bare_libs + lib_paths
for lib in lib_paths:
try:
freeimage = LOADER.LoadLibrary(lib)
break
except Exception:
if lib not in bare_libs:
# Don't record errors when it couldn't load the library from
# a bare name -- this fails often, and doesn't provide any
# useful debugging information anyway, beyond "couldn't find
# library..."
# Get exception instance in Python 2.x/3.x compatible manner
e_type, e_value, e_tb = sys.exc_info()
del e_tb
errors.append((lib, e_value))
if freeimage is None:
if errors:
# No freeimage library loaded, and load-errors reported for some
# candidate libs
err_txt = ['%s:\n%s' % (l, str(e)) for l, e in errors]
raise RuntimeError('One or more FreeImage libraries were found, '
'but could not be loaded due to the following '
'errors:\n\n\n'.join(err_txt))
else:
# No errors, because no potential libraries found at all!
raise RuntimeError('Could not find a FreeImage library in any of:'
'\n\n'.join(lib_dirs))
# FreeImage found
freeimage.FreeImage_SetOutputMessage(c_error_handler)
return freeimage
_FI = load_freeimage()
API = {
# All we're doing here is telling ctypes that some of the FreeImage
# functions return pointers instead of integers. (On 64-bit systems,
# without this information the pointers get truncated and crashes result).
# There's no need to list functions that return ints, or the types of the
# parameters to these or other functions -- that's fine to do implicitly.
# Note that the ctypes immediately converts the returned void_p back to a
# python int again! This is really not helpful, because then passing it
# back to another library call will cause truncation-to-32-bits on 64-bit
# systems. Thanks, ctypes! So after these calls one must immediately
# re-wrap the int as a c_void_p if it is to be passed back into FreeImage.
'FreeImage_AllocateT': (ctypes.c_void_p, None),
'FreeImage_FindFirstMetadata': (ctypes.c_void_p, None),
'FreeImage_GetBits': (ctypes.c_void_p, None),
'FreeImage_GetPalette': (ctypes.c_void_p, None),
'FreeImage_GetTagKey': (ctypes.c_char_p, None),
'FreeImage_GetTagValue': (ctypes.c_void_p, None),
'FreeImage_Load': (ctypes.c_void_p, None),
'FreeImage_LockPage': (ctypes.c_void_p, None),
'FreeImage_OpenMultiBitmap': (ctypes.c_void_p, None)
}
# Albert's ctypes pattern
def register_api(lib, api):
for f, (restype, argtypes) in api.items():
func = getattr(lib, f)
func.restype = restype
func.argtypes = argtypes
register_api(_FI, API)
class FiTypes(object):
FIT_UNKNOWN = 0
FIT_BITMAP = 1
FIT_UINT16 = 2
FIT_INT16 = 3
FIT_UINT32 = 4
FIT_INT32 = 5
FIT_FLOAT = 6
FIT_DOUBLE = 7
FIT_COMPLEX = 8
FIT_RGB16 = 9
FIT_RGBA16 = 10
FIT_RGBF = 11
FIT_RGBAF = 12
dtypes = {FIT_BITMAP: numpy.uint8,
FIT_UINT16: numpy.uint16,
FIT_INT16: numpy.int16,
FIT_UINT32: numpy.uint32,
FIT_INT32: numpy.int32,
FIT_FLOAT: numpy.float32,
FIT_DOUBLE: numpy.float64,
FIT_COMPLEX: numpy.complex128,
FIT_RGB16: numpy.uint16,
FIT_RGBA16: numpy.uint16,
FIT_RGBF: numpy.float32,
FIT_RGBAF: numpy.float32,
}
fi_types = {(numpy.dtype('uint8'), 1): FIT_BITMAP,
(numpy.dtype('uint8'), 3): FIT_BITMAP,
(numpy.dtype('uint8'), 4): FIT_BITMAP,
(numpy.dtype('uint16'), 1): FIT_UINT16,
(numpy.dtype('int16'), 1): FIT_INT16,
(numpy.dtype('uint32'), 1): FIT_UINT32,
(numpy.dtype('int32'), 1): FIT_INT32,
(numpy.dtype('float32'), 1): FIT_FLOAT,
(numpy.dtype('float64'), 1): FIT_DOUBLE,
(numpy.dtype('complex128'), 1): FIT_COMPLEX,
(numpy.dtype('uint16'), 3): FIT_RGB16,
(numpy.dtype('uint16'), 4): FIT_RGBA16,
(numpy.dtype('float32'), 3): FIT_RGBF,
(numpy.dtype('float32'), 4): FIT_RGBAF,
}
extra_dims = {FIT_UINT16: [],
FIT_INT16: [],
FIT_UINT32: [],
FIT_INT32: [],
FIT_FLOAT: [],
FIT_DOUBLE: [],
FIT_COMPLEX: [],
FIT_RGB16: [3],
FIT_RGBA16: [4],
FIT_RGBF: [3],
FIT_RGBAF: [4],
}
@classmethod
def get_type_and_shape(cls, bitmap):
w = _FI.FreeImage_GetWidth(bitmap)
handle_errors()
h = _FI.FreeImage_GetHeight(bitmap)
handle_errors()
fi_type = _FI.FreeImage_GetImageType(bitmap)
handle_errors()
if not fi_type:
raise ValueError('Unknown image pixel type')
dtype = cls.dtypes[fi_type]
if fi_type == cls.FIT_BITMAP:
bpp = _FI.FreeImage_GetBPP(bitmap)
handle_errors()
if bpp == 8:
extra_dims = []
elif bpp == 24:
extra_dims = [3]
elif bpp == 32:
extra_dims = [4]
else:
raise ValueError('Cannot convert %d BPP bitmap' % bpp)
else:
extra_dims = cls.extra_dims[fi_type]
return numpy.dtype(dtype), extra_dims + [w, h]
class IoFlags(object):
# loading: load the image header only (not supported by all plugins)
FIF_LOAD_NOPIXELS = 0x8000
BMP_DEFAULT = 0
BMP_SAVE_RLE = 1
CUT_DEFAULT = 0
DDS_DEFAULT = 0
EXR_DEFAULT = 0 # save data as half with piz-based wavelet compression
EXR_FLOAT = 0x0001 # save data as float instead of half (not recommended)
EXR_NONE = 0x0002 # save with no compression
EXR_ZIP = 0x0004 # save with zlib compression, in blocks of 16 scan lines
EXR_PIZ = 0x0008 # save with piz-based wavelet compression
EXR_PXR24 = 0x0010 # save with lossy 24-bit float compression
# save with lossy 44% float compression (22% when combined with EXR_LC)
EXR_B44 = 0x0020
# one luminance and two chroma channels rather than as RGB (lossy)
EXR_LC = 0x0040
FAXG3_DEFAULT = 0
GIF_DEFAULT = 0
# Load as 256 color image with ununsed palette entries if 16 or 2 color
GIF_LOAD256 = 1
# 'Play' the GIF generating each frame (as 32bpp) instead of raw frame data
GIF_PLAYBACK = 2
HDR_DEFAULT = 0
ICO_DEFAULT = 0
# convert to 32bpp then add an alpha channel from the AND-mask when loading
ICO_MAKEALPHA = 1
IFF_DEFAULT = 0
J2K_DEFAULT = 0 # save with a 16:1 rate
JP2_DEFAULT = 0 # save with a 16:1 rate
# loading (see JPEG_FAST)
# saving (see JPEG_QUALITYGOOD|JPEG_SUBSAMPLING_420)
JPEG_DEFAULT = 0
# load the file as fast as possible, sacrificing some quality
JPEG_FAST = 0x0001
# load the file with the best quality, sacrificing some speed
JPEG_ACCURATE = 0x0002
# load separated CMYK "as is" (use | to combine with other load flags)
JPEG_CMYK = 0x0004
# load and rotate according to Exif 'Orientation' tag if available
JPEG_EXIFROTATE = 0x0008
JPEG_QUALITYSUPERB = 0x80 # save with superb quality (100:1)
JPEG_QUALITYGOOD = 0x0100 # save with good quality (75:1)
JPEG_QUALITYNORMAL = 0x0200 # save with normal quality (50:1)
JPEG_QUALITYAVERAGE = 0x0400 # save with average quality (25:1)
JPEG_QUALITYBAD = 0x0800 # save with bad quality (10:1)
# save as a progressive-JPEG (use | to combine with other save flags)
JPEG_PROGRESSIVE = 0x2000
# save with high 4x1 chroma subsampling (4:1:1)
JPEG_SUBSAMPLING_411 = 0x1000
# save with medium 2x2 medium chroma subsampling (4:2:0) - default value
JPEG_SUBSAMPLING_420 = 0x4000
# save with low 2x1 chroma subsampling (4:2:2)
JPEG_SUBSAMPLING_422 = 0x8000
JPEG_SUBSAMPLING_444 = 0x10000 # save with no chroma subsampling (4:4:4)
# compute optimal Huffman coding tables (can reduce file size a few %)
JPEG_OPTIMIZE = 0x20000 # on saving,
JPEG_BASELINE = 0x40000 # save basic JPEG, without metadata or any markers
KOALA_DEFAULT = 0
LBM_DEFAULT = 0
MNG_DEFAULT = 0
PCD_DEFAULT = 0
PCD_BASE = 1 # load the bitmap sized 768 x 512
PCD_BASEDIV4 = 2 # load the bitmap sized 384 x 256
PCD_BASEDIV16 = 3 # load the bitmap sized 192 x 128
PCX_DEFAULT = 0
PFM_DEFAULT = 0
PICT_DEFAULT = 0
PNG_DEFAULT = 0
PNG_IGNOREGAMMA = 1 # loading: avoid gamma correction
# save using ZLib level 1 compression flag (default value is 6)
PNG_Z_BEST_SPEED = 0x0001
# save using ZLib level 6 compression flag (default recommended value)
PNG_Z_DEFAULT_COMPRESSION = 0x0006
# save using ZLib level 9 compression flag (default value is 6)
PNG_Z_BEST_COMPRESSION = 0x0009
PNG_Z_NO_COMPRESSION = 0x0100 # save without ZLib compression
# save using Adam7 interlacing (use | to combine with other save flags)
PNG_INTERLACED = 0x0200
PNM_DEFAULT = 0
PNM_SAVE_RAW = 0 # Writer saves in RAW format (i.e. P4, P5 or P6)
PNM_SAVE_ASCII = 1 # Writer saves in ASCII format (i.e. P1, P2 or P3)
PSD_DEFAULT = 0
PSD_CMYK = 1 # reads tags for separated CMYK (default converts to RGB)
PSD_LAB = 2 # reads tags for CIELab (default is conversion to RGB)
RAS_DEFAULT = 0
RAW_DEFAULT = 0 # load the file as linear RGB 48-bit
# try to load embedded JPEG preview from Exif Data or default to RGB 24-bit
RAW_PREVIEW = 1
RAW_DISPLAY = 2 # load the file as RGB 24-bit
SGI_DEFAULT = 0
TARGA_DEFAULT = 0
TARGA_LOAD_RGB888 = 1 # Convert RGB555 and ARGB8888 -> RGB888.
TARGA_SAVE_RLE = 2 # Save with RLE compression
TIFF_DEFAULT = 0
# reads/stores tags for separated CMYK
# (use | to combine with compression flags)
TIFF_CMYK = 0x0001
TIFF_PACKBITS = 0x0100 # save using PACKBITS compression
TIFF_DEFLATE = 0x0200 # save using DEFLATE (a.k.a. ZLIB) compression
TIFF_ADOBE_DEFLATE = 0x0400 # save using ADOBE DEFLATE compression
TIFF_NONE = 0x0800 # save without any compression
TIFF_CCITTFAX3 = 0x1000 # save using CCITT Group 3 fax encoding
TIFF_CCITTFAX4 = 0x2000 # save using CCITT Group 4 fax encoding
TIFF_LZW = 0x4000 # save using LZW compression
TIFF_JPEG = 0x8000 # save using JPEG compression
TIFF_LOGLUV = 0x10000 # save using LogLuv compression
WBMP_DEFAULT = 0
XBM_DEFAULT = 0
XPM_DEFAULT = 0
class MetadataModels(object):
FIMD_COMMENTS = 0
FIMD_EXIF_MAIN = 1
FIMD_EXIF_EXIF = 2
FIMD_EXIF_GPS = 3
FIMD_EXIF_MAKERNOTE = 4
FIMD_EXIF_INTEROP = 5
FIMD_IPTC = 6
FIMD_XMP = 7
FIMD_GEOTIFF = 8
FIMD_ANIMATION = 9
class MetadataDatatype(object):
FIDT_BYTE = 1 # 8-bit unsigned integer
FIDT_ASCII = 2 # 8-bit bytes w/ last byte null
FIDT_SHORT = 3 # 16-bit unsigned integer
FIDT_LONG = 4 # 32-bit unsigned integer
FIDT_RATIONAL = 5 # 64-bit unsigned fraction
FIDT_SBYTE = 6 # 8-bit signed integer
FIDT_UNDEFINED = 7 # 8-bit untyped data
FIDT_SSHORT = 8 # 16-bit signed integer
FIDT_SLONG = 9 # 32-bit signed integer
FIDT_SRATIONAL = 10 # 64-bit signed fraction
FIDT_FLOAT = 11 # 32-bit IEEE floating point
FIDT_DOUBLE = 12 # 64-bit IEEE floating point
FIDT_IFD = 13 # 32-bit unsigned integer (offset)
FIDT_PALETTE = 14 # 32-bit RGBQUAD
FIDT_LONG8 = 16 # 64-bit unsigned integer
FIDT_SLONG8 = 17 # 64-bit signed integer
FIDT_IFD8 = 18 # 64-bit unsigned integer (offset)
dtypes = {FIDT_BYTE: numpy.uint8,
FIDT_SHORT: numpy.uint16,
FIDT_LONG: numpy.uint32,
FIDT_RATIONAL: [('numerator', numpy.uint32),
('denominator', numpy.uint32)],
FIDT_SBYTE: numpy.int8,
FIDT_UNDEFINED: numpy.uint8,
FIDT_SSHORT: numpy.int16,
FIDT_SLONG: numpy.int32,
FIDT_SRATIONAL: [('numerator', numpy.int32),
('denominator', numpy.int32)],
FIDT_FLOAT: numpy.float32,
FIDT_DOUBLE: numpy.float64,
FIDT_IFD: numpy.uint32,
FIDT_PALETTE: [('R', numpy.uint8), ('G', numpy.uint8),
('B', numpy.uint8), ('A', numpy.uint8)],
FIDT_LONG8: numpy.uint64,
FIDT_SLONG8: numpy.int64,
FIDT_IFD8: numpy.uint64,
}
def _process_bitmap(filename, flags, process_func):
filename = asbytes(filename)
ftype = _FI.FreeImage_GetFileType(filename, 0)
handle_errors()
if ftype == -1:
raise ValueError('Cannot determine type of file %s' % filename)
bitmap = _FI.FreeImage_Load(ftype, filename, flags)
handle_errors()
bitmap = ctypes.c_void_p(bitmap)
if not bitmap:
raise ValueError('Could not load file %s' % filename)
try:
return process_func(bitmap)
finally:
_FI.FreeImage_Unload(bitmap)
handle_errors()
def read(filename, flags=0):
"""Read an image to a numpy array of shape (height, width) for
greyscale images, or shape (height, width, nchannels) for RGB or
RGBA images.
The `flags` parameter should be one or more values from the IoFlags
class defined in this module, or-ed together with | as appropriate.
(See the source-code comments for more details.)
"""
return _process_bitmap(filename, flags, _array_from_bitmap)
def read_metadata(filename):
"""Return a dict containing all image metadata.
Returned dict maps (metadata_model, tag_name) keys to tag values, where
metadata_model is a string name based on the FreeImage "metadata models"
defined in the class MetadataModels.
"""
flags = IoFlags.FIF_LOAD_NOPIXELS
return _process_bitmap(filename, flags, _read_metadata)
def _process_multipage(filename, flags, process_func):
filename = asbytes(filename)
ftype = _FI.FreeImage_GetFileType(filename, 0)
handle_errors()
if ftype == -1:
raise ValueError('Cannot determine type of file %s' % filename)
create_new = False
read_only = True
keep_cache_in_memory = True
multibitmap = _FI.FreeImage_OpenMultiBitmap(
ftype, filename, create_new, read_only, keep_cache_in_memory, flags)
handle_errors()
multibitmap = ctypes.c_void_p(multibitmap)
if not multibitmap:
raise ValueError('Could not open %s as multi-page image.' % filename)
try:
pages = _FI.FreeImage_GetPageCount(multibitmap)
handle_errors()
out = []
for i in range(pages):
bitmap = _FI.FreeImage_LockPage(multibitmap, i)
handle_errors()
bitmap = ctypes.c_void_p(bitmap)
if not bitmap:
raise ValueError('Could not open %s as a multi-page image.'
% filename)
try:
out.append(process_func(bitmap))
finally:
_FI.FreeImage_UnlockPage(multibitmap, bitmap, False)
handle_errors()
return out
finally:
_FI.FreeImage_CloseMultiBitmap(multibitmap, 0)
handle_errors()
def read_multipage(filename, flags=0):
"""Read a multipage image to a list of numpy arrays, where each
array is of shape (height, width) for greyscale images, or shape
(height, width, nchannels) for RGB or RGBA images.
The `flags` parameter should be one or more values from the IoFlags
class defined in this module, or-ed together with | as appropriate.
(See the source-code comments for more details.)
"""
return _process_multipage(filename, flags, _array_from_bitmap)
def read_multipage_metadata(filename):
"""Read a multipage image to a list of metadata dicts, one dict for each
page. The dict format is as in read_metadata().
"""
flags = IoFlags.FIF_LOAD_NOPIXELS
return _process_multipage(filename, flags, _read_metadata)
def _wrap_bitmap_bits_in_array(bitmap, shape, dtype):
"""Return an ndarray view on the data in a FreeImage bitmap. Only
valid for as long as the bitmap is loaded (if single page) / locked
in memory (if multipage).
"""
pitch = _FI.FreeImage_GetPitch(bitmap)
handle_errors()
height = shape[-1]
byte_size = height * pitch
itemsize = dtype.itemsize
if len(shape) == 3:
strides = (itemsize, shape[0] * itemsize, pitch)
else:
strides = (itemsize, pitch)
bits = _FI.FreeImage_GetBits(bitmap)
handle_errors()
array = numpy.ndarray(
shape, dtype=dtype,
buffer=(ctypes.c_char * byte_size).from_address(bits), strides=strides)
return array
def _array_from_bitmap(bitmap):
"""Convert a FreeImage bitmap pointer to a numpy array.
"""
dtype, shape = FiTypes.get_type_and_shape(bitmap)
array = _wrap_bitmap_bits_in_array(bitmap, shape, dtype)
# swizzle the color components and flip the scanlines to go from
# FreeImage's BGR[A] and upside-down internal memory format to something
# more normal
def n(arr):
return arr[..., ::-1].T
if len(shape) == 3 and _FI.FreeImage_IsLittleEndian() and \
dtype.type == numpy.uint8:
b = n(array[0])
g = n(array[1])
r = n(array[2])
if shape[0] == 3:
handle_errors()
return numpy.dstack((r, g, b))
elif shape[0] == 4:
a = n(array[3])
return numpy.dstack((r, g, b, a))
else:
raise ValueError('Cannot handle images of shape %s' % shape)
# We need to copy because array does *not* own its memory
# after bitmap is freed.
return n(array).copy()
def _read_metadata(bitmap):
metadata = {}
models = [(name[5:], number) for name, number in
MetadataModels.__dict__.items() if name.startswith('FIMD_')]
tag = ctypes.c_void_p()
for model_name, number in models:
mdhandle = _FI.FreeImage_FindFirstMetadata(number, bitmap,
ctypes.byref(tag))
handle_errors()
mdhandle = ctypes.c_void_p(mdhandle)
if mdhandle:
more = True
while more:
tag_name = asstr(_FI.FreeImage_GetTagKey(tag))
tag_type = _FI.FreeImage_GetTagType(tag)
byte_size = _FI.FreeImage_GetTagLength(tag)
handle_errors()
char_ptr = ctypes.c_char * byte_size
tag_str = char_ptr.from_address(_FI.FreeImage_GetTagValue(tag))
handle_errors()
if tag_type == MetadataDatatype.FIDT_ASCII:
tag_val = asstr(tag_str.value)
else:
tag_val = numpy.fromstring(
tag_str, dtype=MetadataDatatype.dtypes[tag_type])
if len(tag_val) == 1:
tag_val = tag_val[0]
metadata[(model_name, tag_name)] = tag_val
more = _FI.FreeImage_FindNextMetadata(mdhandle,
ctypes.byref(tag))
handle_errors()
_FI.FreeImage_FindCloseMetadata(mdhandle)
handle_errors()
return metadata
def write(array, filename, flags=0):
"""Write a (height, width) or (height, width, nchannels) array to
a greyscale, RGB, or RGBA image, with file type deduced from the
filename.
The `flags` parameter should be one or more values from the IoFlags
class defined in this module, or-ed together with | as appropriate.
(See the source-code comments for more details.)
"""
array = numpy.asarray(array)
filename = asbytes(filename)
ftype = _FI.FreeImage_GetFIFFromFilename(filename)
handle_errors()
if ftype == -1:
raise ValueError('Cannot determine type for %s' % filename)
bitmap, fi_type = _array_to_bitmap(array)
try:
if fi_type == FiTypes.FIT_BITMAP:
can_write = _FI.FreeImage_FIFSupportsExportBPP(
ftype, _FI.FreeImage_GetBPP(bitmap))
handle_errors()
else:
can_write = _FI.FreeImage_FIFSupportsExportType(ftype, fi_type)
handle_errors()
if not can_write:
raise TypeError('Cannot save image of this format '
'to this file type')
res = _FI.FreeImage_Save(ftype, bitmap, filename, flags)
handle_errors()
if not res:
raise RuntimeError('Could not save image properly.')
finally:
_FI.FreeImage_Unload(bitmap)
handle_errors()
def write_multipage(arrays, filename, flags=0):
"""Write a list of (height, width) or (height, width, nchannels)
arrays to a multipage greyscale, RGB, or RGBA image, with file type
deduced from the filename.
The `flags` parameter should be one or more values from the IoFlags
class defined in this module, or-ed together with | as appropriate.
(See the source-code comments for more details.)
"""
filename = asbytes(filename)
ftype = _FI.FreeImage_GetFIFFromFilename(filename)
if ftype == -1:
raise ValueError('Cannot determine type of file %s' % filename)
create_new = True
read_only = False
keep_cache_in_memory = True
multibitmap = _FI.FreeImage_OpenMultiBitmap(ftype, filename,
create_new, read_only,
keep_cache_in_memory, 0)
multibitmap = ctypes.c_void_p(multibitmap)
if not multibitmap:
raise ValueError('Could not open %s for writing multi-page image.' %
filename)
try:
for array in arrays:
array = numpy.asarray(array)
bitmap, fi_type = _array_to_bitmap(array)
_FI.FreeImage_AppendPage(multibitmap, bitmap)
finally:
_FI.FreeImage_CloseMultiBitmap(multibitmap, flags)
# 4-byte quads of 0,v,v,v from 0,0,0,0 to 0,255,255,255
_GREY_PALETTE = numpy.arange(0, 0x01000000, 0x00010101, dtype=numpy.uint32)
def _array_to_bitmap(array):
"""Allocate a FreeImage bitmap and copy a numpy array into it.
"""
shape = array.shape
dtype = array.dtype
r, c = shape[:2]
if len(shape) == 2:
n_channels = 1
w_shape = (c, r)
elif len(shape) == 3:
n_channels = shape[2]
w_shape = (n_channels, c, r)
else:
n_channels = shape[0]
try:
fi_type = FiTypes.fi_types[(dtype, n_channels)]
except KeyError:
raise ValueError('Cannot write arrays of given type and shape.')
itemsize = array.dtype.itemsize
bpp = 8 * itemsize * n_channels
bitmap = _FI.FreeImage_AllocateT(fi_type, c, r, bpp, 0, 0, 0)
bitmap = ctypes.c_void_p(bitmap)
if not bitmap:
raise RuntimeError('Could not allocate image for storage')
try:
def n(arr): # normalise to freeimage's in-memory format
return arr.T[..., ::-1]
wrapped_array = _wrap_bitmap_bits_in_array(bitmap, w_shape, dtype)
# swizzle the color components and flip the scanlines to go to
# FreeImage's BGR[A] and upside-down internal memory format
if len(shape) == 3 and _FI.FreeImage_IsLittleEndian():
r = array[:, :, 0]
g = array[:, :, 1]
b = array[:, :, 2]
if dtype.type == numpy.uint8:
wrapped_array[0] = n(b)
wrapped_array[1] = n(g)
wrapped_array[2] = n(r)
elif dtype.type == numpy.uint16:
wrapped_array[0] = n(r)
wrapped_array[1] = n(g)
wrapped_array[2] = n(b)
if shape[2] == 4:
a = array[:, :, 3]
wrapped_array[3] = n(a)
else:
wrapped_array[:] = n(array)
if len(shape) == 2 and dtype.type == numpy.uint8:
palette = _FI.FreeImage_GetPalette(bitmap)
palette = ctypes.c_void_p(palette)
if not palette:
raise RuntimeError('Could not get image palette')
ctypes.memmove(palette, _GREY_PALETTE.ctypes.data, 1024)
return bitmap, fi_type
except:
_FI.FreeImage_Unload(bitmap)
raise
def imread(filename):
"""
img = imread(filename)
Reads an image from file `filename`
Parameters
----------
filename : file name
Returns
-------
img : ndarray
"""
img = read(filename)
return img
def imsave(filename, img):
'''
imsave(filename, img)
Save image to disk
Image type is inferred from filename
Parameters
----------
filename : file name
img : image to be saved as nd array
'''
write(img, filename)
| bsd-3-clause | -3,460,456,233,723,943,400 | 35.007823 | 79 | 0.597074 | false |
zas/picard | picard/ui/edittagdialog.py | 3 | 12144 | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2011-2014 Michael Wiencek
# Copyright (C) 2014 Sophist-UK
# Copyright (C) 2016-2017 Sambhav Kothari
# Copyright (C) 2017 Wieland Hoffmann
# Copyright (C) 2017-2018, 2020 Laurent Monin
# Copyright (C) 2018 Vishal Choudhary
# Copyright (C) 2019-2020 Philipp Wolfer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from PyQt5 import (
QtCore,
QtGui,
QtWidgets,
)
from picard.const import (
RELEASE_COUNTRIES,
RELEASE_FORMATS,
RELEASE_PRIMARY_GROUPS,
RELEASE_SECONDARY_GROUPS,
RELEASE_STATUS,
)
from picard.util.tags import TAG_NAMES
from picard.ui import PicardDialog
from picard.ui.ui_edittagdialog import Ui_EditTagDialog
AUTOCOMPLETE_RELEASE_TYPES = [s.lower() for s
in sorted(RELEASE_PRIMARY_GROUPS) + sorted(RELEASE_SECONDARY_GROUPS)]
AUTOCOMPLETE_RELEASE_STATUS = sorted([s.lower() for s in RELEASE_STATUS])
AUTOCOMPLETE_RELEASE_COUNTRIES = sorted(RELEASE_COUNTRIES, key=str.casefold)
AUTOCOMPLETE_RELEASE_FORMATS = sorted(RELEASE_FORMATS, key=str.casefold)
class TagEditorDelegate(QtWidgets.QItemDelegate):
def createEditor(self, parent, option, index):
if not index.isValid():
return None
tag = self.get_tag_name(index)
if tag.partition(':')[0] in ('comment', 'lyrics'):
editor = QtWidgets.QPlainTextEdit(parent)
editor.setFrameStyle(editor.style().styleHint(QtWidgets.QStyle.SH_ItemView_DrawDelegateFrame, None, editor))
editor.setMinimumSize(QtCore.QSize(0, 80))
else:
editor = super().createEditor(parent, option, index)
completer = None
if tag in ('date', 'originaldate'):
editor.setPlaceholderText(_('YYYY-MM-DD'))
elif tag == 'originalyear':
editor.setPlaceholderText(_('YYYY'))
elif tag == 'releasetype':
completer = QtWidgets.QCompleter(AUTOCOMPLETE_RELEASE_TYPES, editor)
elif tag == 'releasestatus':
completer = QtWidgets.QCompleter(AUTOCOMPLETE_RELEASE_STATUS, editor)
completer.setModelSorting(QtWidgets.QCompleter.CaseInsensitivelySortedModel)
elif tag == 'releasecountry':
completer = QtWidgets.QCompleter(AUTOCOMPLETE_RELEASE_COUNTRIES, editor)
completer.setModelSorting(QtWidgets.QCompleter.CaseInsensitivelySortedModel)
elif tag == 'media':
completer = QtWidgets.QCompleter(AUTOCOMPLETE_RELEASE_FORMATS, editor)
completer.setModelSorting(QtWidgets.QCompleter.CaseInsensitivelySortedModel)
if editor and completer:
completer.setCompletionMode(QtWidgets.QCompleter.UnfilteredPopupCompletion)
completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
editor.setCompleter(completer)
return editor
def get_tag_name(self, index):
return self.parent().tag
class EditTagDialog(PicardDialog):
def __init__(self, window, tag):
super().__init__(window)
self.ui = Ui_EditTagDialog()
self.ui.setupUi(self)
self.window = window
self.value_list = self.ui.value_list
self.metadata_box = window.metadata_box
self.tag = tag
self.modified_tags = {}
self.different = False
self.default_tags = sorted(
set(list(TAG_NAMES.keys()) + self.metadata_box.tag_diff.tag_names))
if len(self.metadata_box.files) == 1:
current_file = list(self.metadata_box.files)[0]
self.default_tags = list(filter(current_file.supports_tag, self.default_tags))
tag_names = self.ui.tag_names
tag_names.addItem("")
visible_tags = [tn for tn in self.default_tags if not tn.startswith("~")]
tag_names.addItems(visible_tags)
self.completer = QtWidgets.QCompleter(visible_tags, tag_names)
self.completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
tag_names.setCompleter(self.completer)
self.value_list.model().rowsInserted.connect(self.on_rows_inserted)
self.value_list.model().rowsRemoved.connect(self.on_rows_removed)
self.value_list.setItemDelegate(TagEditorDelegate(self))
self.tag_changed(tag)
self.value_selection_changed()
def keyPressEvent(self, event):
if event.modifiers() == QtCore.Qt.NoModifier and event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
self.add_or_edit_value()
event.accept()
elif event.matches(QtGui.QKeySequence.Delete):
self.remove_value()
elif event.key() == QtCore.Qt.Key_Insert:
self.add_value()
else:
super().keyPressEvent(event)
def tag_selected(self, index):
self.add_or_edit_value()
def edit_value(self):
item = self.value_list.currentItem()
if item:
# Do not initialize editing if editor is already active. Avoids flickering of the edit field
# when already in edit mode. `isPersistentEditorOpen` is only supported in Qt 5.10 and later.
if hasattr(self.value_list, 'isPersistentEditorOpen') and self.value_list.isPersistentEditorOpen(item):
return
self.value_list.editItem(item)
def add_value(self):
item = QtWidgets.QListWidgetItem()
item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable)
self.value_list.addItem(item)
self.value_list.setCurrentItem(item)
self.value_list.editItem(item)
def add_or_edit_value(self):
last_item = self.value_list.item(self.value_list.count() - 1)
# Edit the last item, if it is empty, or add a new empty item
if last_item and not last_item.text():
self.value_list.setCurrentItem(last_item)
self.edit_value()
else:
self.add_value()
def remove_value(self):
value_list = self.value_list
row = value_list.currentRow()
if row == 0 and self.different:
self.different = False
self.ui.add_value.setEnabled(True)
value_list.takeItem(row)
def on_rows_inserted(self, parent, first, last):
for row in range(first, last + 1):
item = self.value_list.item(row)
self._modified_tag().insert(row, item.text())
def on_rows_removed(self, parent, first, last):
for row in range(first, last + 1):
del self._modified_tag()[row]
def move_row_up(self):
row = self.value_list.currentRow()
if row > 0:
self._move_row(row, -1)
def move_row_down(self):
row = self.value_list.currentRow()
if row + 1 < self.value_list.count():
self._move_row(row, 1)
def _move_row(self, row, direction):
value_list = self.value_list
item = value_list.takeItem(row)
new_row = row + direction
value_list.insertItem(new_row, item)
value_list.setCurrentRow(new_row)
def disable_all(self):
self.value_list.clear()
self.value_list.setEnabled(False)
self.ui.add_value.setEnabled(False)
def enable_all(self):
self.value_list.setEnabled(True)
self.ui.add_value.setEnabled(True)
def tag_changed(self, tag):
tag_names = self.ui.tag_names
tag_names.editTextChanged.disconnect(self.tag_changed)
line_edit = tag_names.lineEdit()
cursor_pos = line_edit.cursorPosition()
flags = QtCore.Qt.MatchFixedString | QtCore.Qt.MatchCaseSensitive
# if the previous tag was new and has no value, remove it from the QComboBox.
# e.g. typing "XYZ" should not leave "X" or "XY" in the QComboBox.
if self.tag and self.tag not in self.default_tags and self._modified_tag() == [""]:
tag_names.removeItem(tag_names.findText(self.tag, flags))
row = tag_names.findText(tag, flags)
self.tag = tag
if row <= 0:
if tag:
# add custom tags to the QComboBox immediately
tag_names.addItem(tag)
tag_names.model().sort(0)
row = tag_names.findText(tag, flags)
else:
# the QLineEdit is empty, disable everything
self.disable_all()
tag_names.setCurrentIndex(0)
tag_names.editTextChanged.connect(self.tag_changed)
return
self.enable_all()
tag_names.setCurrentIndex(row)
line_edit.setCursorPosition(cursor_pos)
self.value_list.clear()
values = self.modified_tags.get(self.tag, None)
if values is None:
new_tags = self.metadata_box.tag_diff.new
display_value, self.different = new_tags.display_value(self.tag)
values = [display_value] if self.different else new_tags[self.tag]
self.ui.add_value.setEnabled(not self.different)
self.value_list.model().rowsInserted.disconnect(self.on_rows_inserted)
self._add_value_items(values)
self.value_list.model().rowsInserted.connect(self.on_rows_inserted)
self.value_list.setCurrentItem(self.value_list.item(0), QtCore.QItemSelectionModel.SelectCurrent)
tag_names.editTextChanged.connect(self.tag_changed)
def _add_value_items(self, values):
values = [v for v in values if v] or [""]
for value in values:
item = QtWidgets.QListWidgetItem(value)
item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsDragEnabled)
font = item.font()
font.setItalic(self.different)
item.setFont(font)
self.value_list.addItem(item)
def value_edited(self, item):
row = self.value_list.row(item)
value = item.text()
if row == 0 and self.different:
self.modified_tags[self.tag] = [value]
self.different = False
font = item.font()
font.setItalic(False)
item.setFont(font)
self.ui.add_value.setEnabled(True)
else:
self._modified_tag()[row] = value
# add tags to the completer model once they get values
cm = self.completer.model()
if self.tag not in cm.stringList():
cm.insertRows(0, 1)
cm.setData(cm.index(0, 0), self.tag)
cm.sort(0)
def value_selection_changed(self):
selection = len(self.value_list.selectedItems()) > 0
self.ui.edit_value.setEnabled(selection)
self.ui.remove_value.setEnabled(selection)
self.ui.move_value_up.setEnabled(selection)
self.ui.move_value_down.setEnabled(selection)
def _modified_tag(self):
return self.modified_tags.setdefault(self.tag,
list(self.metadata_box.tag_diff.new[self.tag]) or [""])
def accept(self):
with self.window.ignore_selection_changes:
for tag, values in self.modified_tags.items():
self.modified_tags[tag] = [v for v in values if v]
modified_tags = self.modified_tags.items()
for obj in self.metadata_box.objects:
for tag, values in modified_tags:
obj.metadata[tag] = list(values)
obj.update()
super().accept()
| gpl-2.0 | -4,111,216,551,356,728,300 | 39.751678 | 136 | 0.633976 | false |
google-research/football | gfootball/replay.py | 1 | 1265 | # coding=utf-8
# Copyright 2019 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.
"""Script allowing to replay a given trace file.
Example usage:
python replay.py --trace_file=/tmp/dumps/shutdown_20190521-165136974075.dump
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from gfootball.env import script_helpers
from absl import app
from absl import flags
FLAGS = flags.FLAGS
flags.DEFINE_string('trace_file', None, 'Trace file to replay')
flags.DEFINE_integer('fps', 10, 'How many frames per second to render')
flags.mark_flag_as_required('trace_file')
def main(_):
script_helpers.ScriptHelpers().replay(FLAGS.trace_file, FLAGS.fps)
if __name__ == '__main__':
app.run(main)
| apache-2.0 | -4,181,820,207,905,264,600 | 29.853659 | 79 | 0.744664 | false |
popazerty/obh-sh4 | lib/python/Screens/LocationBox.py | 25 | 16256 | #
# Generic Screen to select a path/filename combination
#
# GUI (Screens)
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Screens.InputBox import InputBox
from Screens.HelpMenu import HelpableScreen
from Screens.ChoiceBox import ChoiceBox
# Generic
from Tools.BoundFunction import boundFunction
from Tools.Directories import *
from Components.config import config
import os
# Quickselect
from Tools.NumericalTextInput import NumericalTextInput
# GUI (Components)
from Components.ActionMap import NumberActionMap, HelpableActionMap
from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.Button import Button
from Components.FileList import FileList
from Components.MenuList import MenuList
# Timer
from enigma import eTimer
defaultInhibitDirs = ["/bin", "/boot", "/dev", "/etc", "/lib", "/proc", "/sbin", "/sys", "/usr", "/var"]
class LocationBox(Screen, NumericalTextInput, HelpableScreen):
"""Simple Class similar to MessageBox / ChoiceBox but used to choose a folder/pathname combination"""
skin = """<screen name="LocationBox" position="100,75" size="540,460" >
<widget name="text" position="0,2" size="540,22" font="Regular;22" />
<widget name="target" position="0,23" size="540,22" valign="center" font="Regular;22" />
<widget name="filelist" position="0,55" zPosition="1" size="540,210" scrollbarMode="showOnDemand" selectionDisabled="1" />
<widget name="textbook" position="0,272" size="540,22" font="Regular;22" />
<widget name="booklist" position="5,302" zPosition="2" size="535,100" scrollbarMode="showOnDemand" />
<widget name="red" position="0,415" zPosition="1" size="135,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
<widget name="key_red" position="0,415" zPosition="2" size="135,40" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="green" position="135,415" zPosition="1" size="135,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
<widget name="key_green" position="135,415" zPosition="2" size="135,40" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="yellow" position="270,415" zPosition="1" size="135,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
<widget name="key_yellow" position="270,415" zPosition="2" size="135,40" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
<widget name="blue" position="405,415" zPosition="1" size="135,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
<widget name="key_blue" position="405,415" zPosition="2" size="135,40" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, text = "", filename = "", currDir = None, bookmarks = None, userMode = False, windowTitle = _("Select location"), minFree = None, autoAdd = False, editDir = False, inhibitDirs = [], inhibitMounts = []):
# Init parents
Screen.__init__(self, session)
NumericalTextInput.__init__(self, handleTimeout = False)
HelpableScreen.__init__(self)
# Set useable chars
self.setUseableChars(u'1234567890abcdefghijklmnopqrstuvwxyz')
# Quickselect Timer
self.qs_timer = eTimer()
self.qs_timer.callback.append(self.timeout)
self.qs_timer_type = 0
# Initialize Quickselect
self.curr_pos = -1
self.quickselect = ""
# Set Text
self["text"] = Label(text)
self["textbook"] = Label(_("Bookmarks"))
# Save parameters locally
self.text = text
self.filename = filename
self.minFree = minFree
self.realBookmarks = bookmarks
self.bookmarks = bookmarks and bookmarks.value[:] or []
self.userMode = userMode
self.autoAdd = autoAdd
self.editDir = editDir
self.inhibitDirs = inhibitDirs
# Initialize FileList
self["filelist"] = FileList(currDir, showDirectories = True, showFiles = False, inhibitMounts = inhibitMounts, inhibitDirs = inhibitDirs)
# Initialize BookList
self["booklist"] = MenuList(self.bookmarks)
# Buttons
self["key_green"] = Button(_("OK"))
self["key_yellow"] = Button(_("Rename"))
self["key_blue"] = Button(_("Remove bookmark"))
self["key_red"] = Button(_("Cancel"))
# Background for Buttons
self["green"] = Pixmap()
self["yellow"] = Pixmap()
self["blue"] = Pixmap()
self["red"] = Pixmap()
# Initialize Target
self["target"] = Label()
if self.userMode:
self.usermodeOn()
# Custom Action Handler
class LocationBoxActionMap(HelpableActionMap):
def __init__(self, parent, context, actions = { }, prio=0):
HelpableActionMap.__init__(self, parent, context, actions, prio)
self.box = parent
def action(self, contexts, action):
# Reset Quickselect
self.box.timeout(force = True)
return HelpableActionMap.action(self, contexts, action)
# Actions that will reset quickselect
self["WizardActions"] = LocationBoxActionMap(self, "WizardActions",
{
"left": self.left,
"right": self.right,
"up": self.up,
"down": self.down,
"ok": (self.ok, _("select")),
"back": (self.cancel, _("Cancel")),
}, -2)
self["ColorActions"] = LocationBoxActionMap(self, "ColorActions",
{
"red": self.cancel,
"green": self.select,
"yellow": self.changeName,
"blue": self.addRemoveBookmark,
}, -2)
self["EPGSelectActions"] = LocationBoxActionMap(self, "EPGSelectActions",
{
"prevBouquet": (self.switchToBookList, _("switch to bookmarks")),
"nextBouquet": (self.switchToFileList, _("switch to filelist")),
}, -2)
self["MenuActions"] = LocationBoxActionMap(self, "MenuActions",
{
"menu": (self.showMenu, _("menu")),
}, -2)
# Actions used by quickselect
self["NumberActions"] = NumberActionMap(["NumberActions"],
{
"1": self.keyNumberGlobal,
"2": self.keyNumberGlobal,
"3": self.keyNumberGlobal,
"4": self.keyNumberGlobal,
"5": self.keyNumberGlobal,
"6": self.keyNumberGlobal,
"7": self.keyNumberGlobal,
"8": self.keyNumberGlobal,
"9": self.keyNumberGlobal,
"0": self.keyNumberGlobal
})
# Run some functions when shown
self.onShown.extend((
boundFunction(self.setTitle, windowTitle),
self.updateTarget,
self.showHideRename,
))
self.onLayoutFinish.append(self.switchToFileListOnStart)
# Make sure we remove our callback
self.onClose.append(self.disableTimer)
def switchToFileListOnStart(self):
if self.realBookmarks and self.realBookmarks.value:
self.currList = "booklist"
currDir = self["filelist"].current_directory
if currDir in self.bookmarks:
self["booklist"].moveToIndex(self.bookmarks.index(currDir))
else:
self.switchToFileList()
def disableTimer(self):
self.qs_timer.callback.remove(self.timeout)
def showHideRename(self):
# Don't allow renaming when filename is empty
if self.filename == "":
self["key_yellow"].hide()
def switchToFileList(self):
if not self.userMode:
self.currList = "filelist"
self["filelist"].selectionEnabled(1)
self["booklist"].selectionEnabled(0)
self["key_blue"].text = _("Add bookmark")
self.updateTarget()
def switchToBookList(self):
self.currList = "booklist"
self["filelist"].selectionEnabled(0)
self["booklist"].selectionEnabled(1)
self["key_blue"].text = _("Remove bookmark")
self.updateTarget()
def addRemoveBookmark(self):
if self.currList == "filelist":
# add bookmark
folder = self["filelist"].getSelection()[0]
if folder is not None and not folder in self.bookmarks:
self.bookmarks.append(folder)
self.bookmarks.sort()
self["booklist"].setList(self.bookmarks)
else:
# remove bookmark
if not self.userMode:
name = self["booklist"].getCurrent()
self.session.openWithCallback(
boundFunction(self.removeBookmark, name),
MessageBox,
_("Do you really want to remove your bookmark of %s?") % (name),
)
def removeBookmark(self, name, ret):
if not ret:
return
if name in self.bookmarks:
self.bookmarks.remove(name)
self["booklist"].setList(self.bookmarks)
def createDir(self):
if self["filelist"].current_directory != None:
self.session.openWithCallback(
self.createDirCallback,
InputBox,
title = _("Please enter name of the new directory"),
text = ""
)
def createDirCallback(self, res):
if res:
path = os.path.join(self["filelist"].current_directory, res)
if not pathExists(path):
if not createDir(path):
self.session.open(
MessageBox,
_("Creating directory %s failed.") % (path),
type = MessageBox.TYPE_ERROR,
timeout = 5
)
self["filelist"].refresh()
else:
self.session.open(
MessageBox,
_("The path %s already exists.") % (path),
type = MessageBox.TYPE_ERROR,
timeout = 5
)
def removeDir(self):
sel = self["filelist"].getSelection()
if sel and pathExists(sel[0]):
self.session.openWithCallback(
boundFunction(self.removeDirCallback, sel[0]),
MessageBox,
_("Do you really want to remove directory %s from the disk?") % (sel[0]),
type = MessageBox.TYPE_YESNO
)
else:
self.session.open(
MessageBox,
_("Invalid directory selected: %s") % (sel[0]),
type = MessageBox.TYPE_ERROR,
timeout = 5
)
def removeDirCallback(self, name, res):
if res:
if not removeDir(name):
self.session.open(
MessageBox,
_("Removing directory %s failed. (Maybe not empty.)") % (name),
type = MessageBox.TYPE_ERROR,
timeout = 5
)
else:
self["filelist"].refresh()
self.removeBookmark(name, True)
val = self.realBookmarks and self.realBookmarks.value
if val and name in val:
val.remove(name)
self.realBookmarks.value = val
self.realBookmarks.save()
def up(self):
self[self.currList].up()
self.updateTarget()
def down(self):
self[self.currList].down()
self.updateTarget()
def left(self):
self[self.currList].pageUp()
self.updateTarget()
def right(self):
self[self.currList].pageDown()
self.updateTarget()
def ok(self):
if self.currList == "filelist":
if self["filelist"].canDescent():
self["filelist"].descent()
self.updateTarget()
else:
self.select()
def cancel(self):
self.close(None)
def getPreferredFolder(self):
if self.currList == "filelist":
# XXX: We might want to change this for parent folder...
return self["filelist"].getSelection()[0]
else:
return self["booklist"].getCurrent()
def selectConfirmed(self, ret):
if ret:
ret = ''.join((self.getPreferredFolder(), self.filename))
if self.realBookmarks:
if self.autoAdd and not ret in self.bookmarks:
self.bookmarks.append(self.getPreferredFolder())
self.bookmarks.sort()
if self.bookmarks != self.realBookmarks.value:
self.realBookmarks.value = self.bookmarks
self.realBookmarks.save()
self.close(ret)
def select(self):
currentFolder = self.getPreferredFolder()
# Do nothing unless current Directory is valid
if currentFolder is not None:
# Check if we need to have a minimum of free Space available
if self.minFree is not None:
# Try to read fs stats
try:
s = os.statvfs(currentFolder)
if (s.f_bavail * s.f_bsize) / 1000000 > self.minFree:
# Automatically confirm if we have enough free disk Space available
return self.selectConfirmed(True)
except OSError:
pass
# Ask User if he really wants to select this folder
self.session.openWithCallback(
self.selectConfirmed,
MessageBox,
_("There might not be enough Space on the selected Partition.\nDo you really want to continue?"),
type = MessageBox.TYPE_YESNO
)
# No minimum free Space means we can safely close
else:
self.selectConfirmed(True)
def changeName(self):
if self.filename != "":
# TODO: Add Information that changing extension is bad? disallow?
self.session.openWithCallback(
self.nameChanged,
InputBox,
title = _("Please enter a new filename"),
text = self.filename
)
def nameChanged(self, res):
if res is not None:
if len(res):
self.filename = res
self.updateTarget()
else:
self.session.open(
MessageBox,
_("An empty filename is illegal."),
type = MessageBox.TYPE_ERROR,
timeout = 5
)
def updateTarget(self):
# Write Combination of Folder & Filename when Folder is valid
currFolder = self.getPreferredFolder()
if currFolder is not None:
self["target"].setText(''.join((currFolder, self.filename)))
# Display a Warning otherwise
else:
self["target"].setText(_("Invalid location"))
def showMenu(self):
if not self.userMode and self.realBookmarks:
if self.currList == "filelist":
menu = [
(_("switch to bookmarks"), self.switchToBookList),
(_("add bookmark"), self.addRemoveBookmark)
]
if self.editDir:
menu.extend((
(_("create directory"), self.createDir),
(_("remove directory"), self.removeDir)
))
else:
menu = (
(_("switch to filelist"), self.switchToFileList),
(_("remove bookmark"), self.addRemoveBookmark)
)
self.session.openWithCallback(
self.menuCallback,
ChoiceBox,
title = "",
list = menu
)
def menuCallback(self, choice):
if choice:
choice[1]()
def usermodeOn(self):
self.switchToBookList()
self["filelist"].hide()
self["key_blue"].hide()
def keyNumberGlobal(self, number):
# Cancel Timeout
self.qs_timer.stop()
# See if another key was pressed before
if number != self.lastKey:
# Reset lastKey again so NumericalTextInput triggers its keychange
self.nextKey()
# Try to select what was typed
self.selectByStart()
# Increment position
self.curr_pos += 1
# Get char and append to text
char = self.getKey(number)
self.quickselect = self.quickselect[:self.curr_pos] + unicode(char)
# Start Timeout
self.qs_timer_type = 0
self.qs_timer.start(1000, 1)
def selectByStart(self):
# Don't do anything on initial call
if not self.quickselect:
return
# Don't select if no dir
if self["filelist"].getCurrentDirectory():
# TODO: implement proper method in Components.FileList
files = self["filelist"].getFileList()
# Initialize index
idx = 0
# We select by filename which is absolute
lookfor = self["filelist"].getCurrentDirectory() + self.quickselect
# Select file starting with generated text
for file in files:
if file[0][0] and file[0][0].lower().startswith(lookfor):
self["filelist"].instance.moveSelectionTo(idx)
break
idx += 1
def timeout(self, force = False):
# Timeout Key
if not force and self.qs_timer_type == 0:
# Try to select what was typed
self.selectByStart()
# Reset Key
self.lastKey = -1
# Change type
self.qs_timer_type = 1
# Start timeout again
self.qs_timer.start(1000, 1)
# Timeout Quickselect
else:
# Eventually stop Timer
self.qs_timer.stop()
# Invalidate
self.lastKey = -1
self.curr_pos = -1
self.quickselect = ""
def __repr__(self):
return str(type(self)) + "(" + self.text + ")"
def MovieLocationBox(session, text, dir, minFree = None):
return LocationBox(session, text = text, currDir = dir, bookmarks = config.movielist.videodirs, autoAdd = True, editDir = True, inhibitDirs = defaultInhibitDirs, minFree = minFree)
class TimeshiftLocationBox(LocationBox):
def __init__(self, session):
LocationBox.__init__(
self,
session,
text = _("Where to save temporary timeshift recordings?"),
currDir = config.usage.timeshift_path.value,
bookmarks = config.usage.allowed_timeshift_paths,
autoAdd = True,
editDir = True,
inhibitDirs = defaultInhibitDirs,
minFree = 1024 # the same requirement is hardcoded in servicedvb.cpp
)
self.skinName = "LocationBox"
def cancel(self):
config.usage.timeshift_path.cancel()
LocationBox.cancel(self)
def selectConfirmed(self, ret):
if ret:
config.usage.timeshift_path.value = self.getPreferredFolder()
config.usage.timeshift_path.save()
LocationBox.selectConfirmed(self, ret)
| gpl-2.0 | -846,379,975,282,609,700 | 29.159555 | 231 | 0.683501 | false |
jdm/gemrb | gemrb/GUIScripts/Spellbook.py | 1 | 22686 | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2011 The GemRB Project
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# a library of any functions for spell(book) managment
import GemRB
import CommonTables
import GameCheck
from GUIDefines import *
from ie_stats import *
from ie_action import ACT_LEFT, ACT_RIGHT
from ie_spells import *
from ie_restype import RES_2DA
#################################################################
# this is in the operator module of the standard python lib
def itemgetter(*items):
if len(items) == 1:
item = items[0]
def g(obj):
return obj[item]
else:
def g(obj):
return tuple(obj[item] for item in items)
return g
#################################################################
# routines for the actionbar spell access code
def GetUsableMemorizedSpells(actor, BookType):
memorizedSpells = []
spellResRefs = []
for level in range (20): # Saradas NPC teaches you a level 14 special ...
spellCount = GemRB.GetMemorizedSpellsCount (actor, BookType, level, False)
for i in range (spellCount):
Spell0 = GemRB.GetMemorizedSpell (actor, BookType, level, i)
if not Spell0["Flags"]:
# depleted, so skip
continue
if Spell0["SpellResRef"] in spellResRefs:
# add another one, so we can get the count more cheaply later
spellResRefs.append (Spell0["SpellResRef"])
continue
spellResRefs.append (Spell0["SpellResRef"])
Spell = GemRB.GetSpell(Spell0["SpellResRef"])
Spell['BookType'] = BookType # just another sorting key
Spell['SpellIndex'] = GemRB.GetSpelldataIndex (actor, Spell["SpellResRef"], 1<<BookType) # crucial!
if Spell['SpellIndex'] == -1:
print "Error, memorized spell not found!", Spell["SpellResRef"], 1<<BookType
Spell['SpellIndex'] += 1000 * 1<<BookType
memorizedSpells.append (Spell)
if not len(memorizedSpells):
return []
# count and remove the duplicates
memorizedSpells2 = []
for spell in memorizedSpells:
if spell["SpellResRef"] in spellResRefs:
spell['MemoCount'] = spellResRefs.count(spell["SpellResRef"])
while spell["SpellResRef"] in spellResRefs:
spellResRefs.remove(spell["SpellResRef"])
memorizedSpells2.append(spell)
return memorizedSpells2
def GetKnownSpells(actor, BookType):
knownSpells = []
spellResRefs = []
for level in range (9):
spellCount = GemRB.GetKnownSpellsCount (actor, BookType, level)
for i in range (spellCount):
Spell0 = GemRB.GetKnownSpell (actor, BookType, level, i)
if Spell0["SpellResRef"] in spellResRefs:
continue
spellResRefs.append (Spell0["SpellResRef"])
Spell = GemRB.GetSpell(Spell0["SpellResRef"])
Spell['BookType'] = BookType # just another sorting key
Spell['MemoCount'] = 0
Spell['SpellIndex'] = 1000 * 1<<BookType # this gets assigned properly later
knownSpells.append (Spell)
return knownSpells
def GetKnownSpellsLevel(actor, BookType, level):
knownSpells = []
spellResRefs = []
spellCount = GemRB.GetKnownSpellsCount (actor, BookType, level)
for i in range (spellCount):
Spell0 = GemRB.GetKnownSpell (actor, BookType, level, i)
if Spell0["SpellResRef"] in spellResRefs:
continue
spellResRefs.append (Spell0["SpellResRef"])
Spell = GemRB.GetSpell(Spell0["SpellResRef"])
Spell['BookType'] = BookType # just another sorting key
knownSpells.append (Spell)
return knownSpells
def index (list, value):
for i in range(len(list)):
if list[i]==value:
return i
return -1
def GetMemorizedSpells(actor, BookType, level):
memoSpells = []
spellResRefs = []
spellCount = GemRB.GetMemorizedSpellsCount (actor, BookType, level, False)
for i in range (spellCount):
Spell0 = GemRB.GetMemorizedSpell (actor, BookType, level, i)
pos = index(spellResRefs,Spell0["SpellResRef"])
if pos!=-1:
memoSpells[pos]['KnownCount']+=1
memoSpells[pos]['MemoCount']+=Spell0["Flags"]
continue
spellResRefs.append (Spell0["SpellResRef"])
Spell = GemRB.GetSpell(Spell0["SpellResRef"])
Spell['KnownCount'] = 1
Spell['MemoCount'] = Spell0["Flags"]
memoSpells.append (Spell)
return memoSpells
# direct access to the spellinfo struct
# SpellIndex is the index of the spell in the struct, but we add a thousandfold of the spell type for later use in SpellPressed
def GetSpellinfoSpells(actor, BookType):
memorizedSpells = []
spellResRefs = GemRB.GetSpelldata (actor)
i = 0
for resref in spellResRefs:
Spell = GemRB.GetSpell(resref)
Spell['BookType'] = BookType # just another sorting key
Spell['SpellIndex'] = i + 1000 * 255 # spoofing the type, so any table would work
Spell['MemoCount'] = 1
memorizedSpells.append (Spell)
i += 1
return memorizedSpells
def SortUsableSpells(memorizedSpells):
# sort it by using the spldisp.2da table
layout = CommonTables.SpellDisplay.GetValue ("USE_ROW", "ROWS")
layout = CommonTables.SpellDisplay.GetRowName (layout)
order = CommonTables.SpellDisplay.GetValue ("DESCENDING", "ROWS")
key1 = CommonTables.SpellDisplay.GetValue (layout, "KEY1")
key2 = CommonTables.SpellDisplay.GetValue (layout, "KEY2")
key3 = CommonTables.SpellDisplay.GetValue (layout, "KEY3")
if key1:
if key3 and key2:
memorizedSpells = sorted(memorizedSpells, key=itemgetter(key1, key2, key3), reverse=order)
elif key2:
memorizedSpells = sorted(memorizedSpells, key=itemgetter(key1, key2), reverse=order)
else:
memorizedSpells = sorted(memorizedSpells, key=itemgetter(key1), reverse=order)
return memorizedSpells
# Sets up all the (12) action buttons for a player character with different spell or innate icons.
# It also sets up the scroll buttons left and right if needed.
# If Start is supplied, it will skip the first few items (used when scrolling through the list)
# BookType is a spellbook type bitfield (1-mage, 2-priest, 4-innate and others in iwd2)
# Offset is a control ID offset here for iwd2 purposes
def SetupSpellIcons(Window, BookType, Start=0, Offset=0):
actor = GemRB.GameGetFirstSelectedActor ()
# check if we're dealing with a temporary spellbook
if GemRB.GetVar("ActionLevel") == 11:
allSpells = GetSpellinfoSpells (actor, BookType)
else:
# construct the spellbook of usable (not depleted) memorized spells
# the getters expect the BookType as: 0 priest, 1 mage, 2 innate
if BookType == -1:
# Nahal's reckless dweomer can use any known spell
allSpells = GetKnownSpells (actor, IE_SPELL_TYPE_WIZARD)
else:
allSpells = []
for i in range(16):
if BookType & (1<<i):
allSpells += GetUsableMemorizedSpells (actor, i)
if not len(allSpells):
raise AttributeError ("Error, unknown BookType passed to SetupSpellIcons: %d! Bailing out!" %(BookType))
return
if BookType == -1:
memorizedSpells = allSpells
# reset Type, so we can choose the surge spell instead of just getting a redraw of the action bar
GemRB.SetVar("Type", 3)
else:
memorizedSpells = SortUsableSpells(allSpells)
# start creating the controls
import GUICommonWindows
# TODO: ASCOL, ROWS
#AsCol = CommonTables.SpellDisplay.GetValue (layout, "AS_COL")
#Rows = CommonTables.SpellDisplay.GetValue (layout, "ROWS")
More = len(memorizedSpells) > 12 or Start > 0
# scroll left button
if More:
Button = Window.GetControl (Offset)
Button.SetText ("")
if Start:
GUICommonWindows.SetActionIconWorkaround (Button, ACT_LEFT, 0)
Button.SetState (IE_GUI_BUTTON_UNPRESSED)
else:
Button.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_SET)
Button.SetTooltip ("")
Button.SetState (IE_GUI_BUTTON_DISABLED)
# disable all spells if fx_disable_spellcasting was run with the same type
# but only if there are any spells of that type to disable
disabled_spellcasting = GemRB.GetPlayerStat(actor, IE_CASTING, 0)
actionLevel = GemRB.GetVar ("ActionLevel")
#order is: mage, cleric, innate, class, song, (defaults to 1, item)
spellSections = [2, 4, 8, 16, 16]
# create the spell icon buttons
buttonCount = 12 - More * 2 # GUIBT_COUNT in PCStatsStruct
for i in range (buttonCount):
Button = Window.GetControl (i+Offset+More)
Button.SetEvent (IE_GUI_BUTTON_ON_RIGHT_PRESS, None)
if i+Start >= len(memorizedSpells):
Button.SetState (IE_GUI_BUTTON_DISABLED)
Button.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_SET)
Button.SetText ("")
Button.SetTooltip ("")
continue
Spell = memorizedSpells[i+Start]
spellType = Spell['SpellType']
if spellType > 4:
spellType = 1
else:
spellType = spellSections[spellType]
if BookType == -1:
Button.SetVarAssoc ("Spell", Spell['SpellIndex']+i+Start)
else:
Button.SetVarAssoc ("Spell", Spell['SpellIndex'])
# disable spells that should be cast from the inventory or can't be cast while silenced or ...
# see splspec.2da for all the reasons; silence is handled elsewhere
specialSpell = GemRB.CheckSpecialSpell(actor, Spell['SpellResRef'])
specialSpell = (specialSpell & SP_IDENTIFY) or ((specialSpell & SP_SURGE) and actionLevel == 5)
if specialSpell & SP_SILENCE and Spell['HeaderFlags'] & 0x20000: # SF_IGNORES_SILENCE
specialSpell ^= SP_SILENCE
if specialSpell or (disabled_spellcasting&spellType):
Button.SetState (IE_GUI_BUTTON_DISABLED)
Button.EnableBorder(1, 0)
else:
Button.SetState (IE_GUI_BUTTON_UNPRESSED)
Button.SetEvent (IE_GUI_BUTTON_ON_PRESS, GUICommonWindows.SpellPressed)
Button.SetEvent (IE_GUI_BUTTON_ON_SHIFT_PRESS, GUICommonWindows.SpellShiftPressed)
if Spell['SpellResRef']:
Button.SetSprites ("guibtbut", 0, 0,1,2,3)
Button.SetSpellIcon (Spell['SpellResRef'], 1)
Button.SetFlags (IE_GUI_BUTTON_PICTURE|IE_GUI_BUTTON_ALIGN_BOTTOM|IE_GUI_BUTTON_ALIGN_RIGHT, OP_SET)
Button.SetTooltip (Spell['SpellName'])
if Spell['MemoCount'] > 0 and BookType != -1:
Button.SetText (str(Spell['MemoCount']))
else:
Button.SetText ("")
# scroll right button
if More:
Button = Window.GetControl (Offset+buttonCount+1)
GUICommonWindows.SetActionIconWorkaround (Button, ACT_RIGHT, buttonCount)
Button.SetText ("")
if len(memorizedSpells) - Start > 10:
Button.SetState (IE_GUI_BUTTON_UNPRESSED)
else:
Button.SetState (IE_GUI_BUTTON_DISABLED)
Button.SetFlags (IE_GUI_BUTTON_NO_IMAGE, OP_SET)
Button.SetTooltip ("")
#################################################################
# routines used during character generation and levelup
#################################################################
def GetMageSpells (Kit, Alignment, Level):
MageSpells = []
SpellType = 99
v = CommonTables.Aligns.FindValue (3, Alignment)
Usability = Kit | CommonTables.Aligns.GetValue(v, 5)
HokeyPokey = "MAGE"
WildMages = True
BadSchools = 0
if GameCheck.IsIWD2():
HokeyPokey = "WIZARD"
WildMages = False
# iwd2 has only per-kit exclusion, spells can't override it
ExclusionTable = GemRB.LoadTable ("magesch")
KitRow = ExclusionTable.FindValue ("KIT", Kit)
KitRow = ExclusionTable.GetRowName (KitRow)
BadSchools = ExclusionTable.GetValue (KitRow, "EXCLUSION")
if BadSchools == -1:
BadSchools = 0
SpellsTable = GemRB.LoadTable ("spells")
for i in range(SpellsTable.GetValue (HokeyPokey, str(Level), GTV_INT)):
SpellName = "SPWI%d%02d"%(Level,i+1)
ms = GemRB.GetSpell (SpellName, 1)
if ms == None:
continue
if Usability & ms['SpellExclusion']:
SpellType = 0
elif BadSchools & (1<<ms['SpellSchool']+5):
SpellType = 0
else:
SpellType = 1
if Kit & (1 << ms['SpellSchool']+5): # of matching specialist school
SpellType = 2
# Wild mage spells are of normal schools, so we have to find them
# separately. Generalists can learn any spell but the wild ones, so
# we check if the mage is wild and if a generalist wouldn't be able
# to learn the spell.
if WildMages and Kit == 0x8000 and (0x4000 & ms['SpellExclusion']):
SpellType = 2
MageSpells.append ([SpellName, SpellType])
return MageSpells
def GetLearnableMageSpells (Kit, Alignment, Level):
Learnable = []
for Spell in GetMageSpells (Kit, Alignment, Level):
if Spell[1]:
Learnable.append (Spell[0])
return Learnable
def GetLearnableDomainSpells (pc, Level):
import GUICommon
import GUICommonWindows
Learnable =[]
# only clerics have domains due to listdom.2da restrictions
# no need to double check, as we only call this for IE_IWD2_SPELL_CLERIC
BaseClassName = GUICommon.GetClassRowName (pc)
BaseClassIndex = CommonTables.Classes.GetRowIndex (BaseClassName)
# columns correspond to kits in the same order
KitIndex = GUICommonWindows.GetKitIndex (pc, BaseClassIndex)
if KitIndex == -1:
print "GetLearnableDomainSpells: couldn't determine the kit, bailing out!"
return Learnable
# calculate the offset from the first cleric kit
KitIndex -= CommonTables.Classes.FindValue ("CLASS", BaseClassIndex+1)
DomainSpellTable = GemRB.LoadTable ("listdomn")
# check everything in case someone wants to mod the spell amount
for i in range(DomainSpellTable.GetRowCount ()):
if DomainSpellTable.GetValue (i, KitIndex) == Level:
SpellName = DomainSpellTable.GetRowName (i)
SpellName = DomainSpellTable.GetValue (SpellName, "DOMAIN_RESREF")
Learnable.append (SpellName)
return Learnable
def GetLearnablePriestSpells (Class, Alignment, Level, booktype=0):
Learnable =[]
v = CommonTables.Aligns.FindValue(3, Alignment)
#usability is the bitset we look for
Usability = CommonTables.Aligns.GetValue(v, 5)
HolyMoly = "PRIEST"
SpellListTable = None
if GameCheck.IsIWD2():
HolyMoly = "CLERIC"
SpellListTable = GemRB.LoadTable ("listspll")
SpellsTable = GemRB.LoadTable ("spells")
for i in range(SpellsTable.GetValue (HolyMoly, str (Level), GTV_INT)):
SpellName = "SPPR%d%02d"%(Level,i+1)
ms = GemRB.GetSpell(SpellName, 1)
if ms == None:
continue
if Class & ms['SpellDivine']:
continue
if Usability & ms['SpellExclusion']:
continue
if SpellListTable:
idx = SpellListTable.FindValue ("SPELL_RES_REF", SpellName)
# columns are in the same order as booktypes
if SpellListTable.GetValue (idx, booktype) <= 0:
continue
Learnable.append (SpellName)
return Learnable
# there is no separate druid spell table in the originals
#FIXME: try to do this in a non-hard way?
def GetPriestSpellTable(tablename):
if GameCheck.IsIWD2():
return tablename # no need for this folly
if not GemRB.HasResource (tablename, RES_2DA):
if tablename == "MXSPLDRU":
return "MXSPLPRS"
return tablename
def SetupSpellLevels (pc, TableName, Type, Level):
#don't die on a missing reference
tmp = GetPriestSpellTable(TableName)
if tmp != TableName:
SetupSpellLevels (pc, tmp, Type, Level)
return
Table = GemRB.LoadTable (TableName)
kit = GemRB.GetPlayerStat (pc, IE_KIT)
for i in range(Table.GetColumnCount ()):
# do a string lookup since some tables don't have entries for all levels
value = Table.GetValue (str(Level), str(i+1), GTV_INT)
# specialist mages get an extra spell if they already know that level
# FIXME: get a general routine to find specialists
school = GemRB.GetVar("MAGESCHOOL")
if (Type == IE_SPELL_TYPE_WIZARD and school != 0) or \
(GameCheck.IsIWD2() and Type == IE_IWD2_SPELL_WIZARD and not (kit&0x4000)):
if value > 0:
value += 1
elif Type == IE_IWD2_SPELL_DOMAIN:
if value > 0:
value = 1 # since we're reusing the main cleric table
GemRB.SetMemorizableSpellsCount (pc, value, Type, i)
return
def UnsetupSpellLevels (pc, TableName, Type, Level):
#don't die on a missing reference
tmp = GetPriestSpellTable(TableName)
if tmp != TableName:
UnsetupSpellLevels (pc, tmp, Type, Level)
return
Table = GemRB.LoadTable (TableName)
for i in range(Table.GetColumnCount ()):
GemRB.SetMemorizableSpellsCount (pc, 0, Type, i)
return
# Returns -1 if not found; otherwise, the index of the spell
def HasSpell (Actor, SpellType, Level, Ref):
# loop through each spell in the spell level and check for a matching ref
for i in range (GemRB.GetKnownSpellsCount (Actor, SpellType, Level)):
Spell = GemRB.GetKnownSpell(Actor, SpellType, Level, i)
if Spell["SpellResRef"].upper() == Ref.upper(): # ensure case is the same
return i
# not found
return -1
def HasSorcererBook (pc):
import GUICommon
ClassName = GUICommon.GetClassRowName (pc)
SorcererBook = CommonTables.ClassSkills.GetValue (ClassName, "BOOKTYPE") & 2
return SorcererBook
def CannotLearnSlotSpell ():
pc = GemRB.GameGetSelectedPCSingle ()
# disqualify sorcerers immediately
if HasSorcererBook (pc):
return LSR_STAT
booktype = IE_SPELL_TYPE_WIZARD
if GameCheck.IsIWD2():
booktype = IE_IWD2_SPELL_WIZARD
if GameCheck.IsPST():
import GUIINV
slot, slot_item = GUIINV.ItemHash[GemRB.GetVar ('ItemButton')]
else:
slot_item = GemRB.GetSlotItem (pc, GemRB.GetVar ("ItemButton"))
spell_ref = GemRB.GetItem (slot_item['ItemResRef'], pc)['Spell']
spell = GemRB.GetSpell (spell_ref)
level = spell['SpellLevel']
# school conflicts are handled before this is called from inventory
# add them here if a need arises
# maybe she already knows this spell
if HasSpell (pc, booktype, level-1, spell_ref) != -1:
return LSR_KNOWN
# level check (needs enough intelligence for this level of spell)
dumbness = GemRB.GetPlayerStat (pc, IE_INT)
if level > GemRB.GetAbilityBonus (IE_INT, 1, dumbness):
return LSR_LEVEL
spell_count = GemRB.GetKnownSpellsCount (pc, booktype, level-1)
if spell_count > GemRB.GetAbilityBonus (IE_INT, 2, dumbness):
return LSR_FULL
return 0
def LearnPriestSpells (pc, level, mask):
"""Learns all the priest spells through the given spell level.
Mask distinguishes clerical and druidic spells."""
# make sure we don't have too high a level
booktype = IE_SPELL_TYPE_PRIEST
if GameCheck.IsIWD2():
level = min(9, level)
booktype = mask
mask = 0 # no classflags restrictions like in others (differentiating cleric/rangers)
else:
level = min(7, level)
# go through each level
alignment = GemRB.GetPlayerStat (pc, IE_ALIGNMENT)
for i in range (level):
if booktype == IE_IWD2_SPELL_DOMAIN:
learnable = GetLearnableDomainSpells (pc, i+1)
else:
learnable = GetLearnablePriestSpells (mask, alignment, i+1, booktype)
for spell in learnable:
# if the spell isn't learned, learn it
if HasSpell (pc, booktype, i, spell) < 0:
if GameCheck.IsIWD2():
if booktype == IE_IWD2_SPELL_DOMAIN:
GemRB.LearnSpell (pc, spell, 0, 1<<booktype, i)
else:
# perhaps forcing would be fine here too, but it's untested and
# iwd2 cleric schools grant certain spells at different levels
GemRB.LearnSpell (pc, spell, 0, 1<<booktype)
else:
GemRB.LearnSpell (pc, spell)
return
def RemoveKnownSpells (pc, type, level1=1, level2=1, noslots=0, kit=0):
"""Removes all known spells of a given type between two spell levels.
If noslots is true, all memorization counts are set to 0.
Kit is used to identify the priest spell mask of the spells to be removed;
this is only used when removing spells in a dualclass."""
# choose the correct limit based upon class type
if type == IE_SPELL_TYPE_WIZARD or GameCheck.IsIWD2():
limit = 9
elif type == IE_SPELL_TYPE_PRIEST:
limit = 7
# make sure that we get the original kit, if we have one
if kit:
originalkit = GetKitIndex (pc)
if originalkit: # kitted; find the class value
originalkit = CommonTables.KitList.GetValue (originalkit, 7)
else: # just get the class value
originalkit = GemRB.GetPlayerStat (pc, IE_CLASS)
originalkit = GUICommon.GetClassRowName (originalkit, "class")
# this is is specifically for dual-classes and will not work to remove only one
# spell type from a ranger/cleric multi-class
if CommonTables.ClassSkills.GetValue (originalkit, "DRUIDSPELL", GTV_STR) != "*": # knows druid spells
originalkit = 0x8000
elif CommonTables.ClassSkills.GetValue (originalkit, "CLERICSPELL", GTV_STR) != "*": # knows cleric spells
originalkit = 0x4000
else: # don't know any other spells
originalkit = 0
# don't know how this would happen, but better to be safe
if originalkit == kit:
originalkit = 0
elif type == IE_SPELL_TYPE_INNATE:
limit = 1
else: # can't do anything if an improper spell type is sent
return 0
if GameCheck.IsIWD2():
kit = 0 # just skip the dualclass logic
# make sure we're within parameters
if level1 < 1 or level2 > limit or level1 > level2:
return 0
# remove all spells for each level
for level in range (level1-1, level2):
# we need the count because we remove each spell in reverse order
count = GemRB.GetKnownSpellsCount (pc, type, level)
mod = count-1
for spell in range (count):
# see if we need to check for kit
if type == IE_SPELL_TYPE_PRIEST and kit:
# get the spell's ref data
ref = GemRB.GetKnownSpell (pc, type, level, mod-spell)
ref = GemRB.GetSpell (ref['SpellResRef'], 1)
# we have to look at the originalkit as well specifically for ranger/cleric dual-classes
# we wouldn't want to remove all cleric spells and druid spells if we lost our cleric class
# only the cleric ones
if kit&ref['SpellDivine'] or (originalkit and not originalkit&ref['SpellDivine']):
continue
# remove the spell
GemRB.RemoveSpell (pc, type, level, mod-spell)
# remove memorization counts if desired
if noslots:
GemRB.SetMemorizableSpellsCount (pc, 0, type, level)
# return success
return 1
# learning/memorization wrapper for when you want to give more than 1 instance
# learn a spell if we don't know it yet, otherwise just increase the memo count
def LearnSpell(pc, spellref, booktype, level, count, flags=0):
SpellIndex = HasSpell (pc, booktype, level, spellref)
if SpellIndex < 0:
ret = GemRB.LearnSpell (pc, spellref, flags)
if ret != LSR_OK and ret != LSR_KNOWN:
raise RuntimeError, "Failed learning spell: %s !" %(spellref)
return
SpellIndex = HasSpell (pc, booktype, level, spellref)
count -= 1
if count <= 0:
return
if SpellIndex == -1:
# should never happen
raise RuntimeError, "LearnSpell: Severe spellbook problems: %s !" %(spellref)
return
for j in range(count):
GemRB.MemorizeSpell (pc, booktype, level, SpellIndex, flags&LS_MEMO)
| gpl-2.0 | -4,937,222,554,928,820,000 | 34.009259 | 127 | 0.715772 | false |
loveshell/sleepy-puppy | sleepypuppy/api/views.py | 9 | 15763 | # Copyright 2015 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from flask.ext.restful import Resource, reqparse
from sqlalchemy.exc import IntegrityError
from sleepypuppy import db, app
from sleepypuppy.admin.puppyscript.models import Puppyscript
from sleepypuppy.admin.payload.models import Payload
from sleepypuppy.admin.capture.models import Capture
from sleepypuppy.admin.assessment.models import Assessment
from sleepypuppy.admin.access_log.models import AccessLog
from sleepypuppy.admin.collector.models import GenericCollector
# Request parser for API calls to Payload model
parser_payload = reqparse.RequestParser()
parser_payload.add_argument('assessments',
type=list,
required=False,
location='json')
parser_payload.add_argument('payload',
type=str,
required=False,
help="Payload Cannot Be Blank",
location='json')
parser_payload.add_argument('notes',
type=str,
location='json')
# Request parser for API calls to Assessment model
parser_assessment = reqparse.RequestParser()
parser_assessment.add_argument('name',
type=str,
required=False,
help="Assessment Name Cannot Be Blank",
location='json')
parser_assessment.add_argument('access_log_enabled',
type=bool,
required=False,
location='json')
parser_assessment.add_argument('snooze',
type=bool,
required=False,
location='json')
parser_assessment.add_argument('run_once',
type=bool,
required=False,
location='json')
# Request parser for API calls to Puppyscript model
parser_puppyscript = reqparse.RequestParser()
parser_puppyscript.add_argument('name',
type=str,
required=True,
help="Name Cannot Be Blank",
location='json')
parser_puppyscript.add_argument('code',
type=str,
required=True,
help="Code Cannot Be Blank",
location='json')
parser_puppyscript.add_argument('notes',
type=str,
required=False,
location='json')
parser_helper = reqparse.RequestParser()
parser_helper.add_argument('a',
type=str,
required=False)
class AssessmentView(Resource):
"""
API Provides CRUD operations for a specific Assessment based on id.
Methods:
GET
PUT
DELETE
"""
def get(self, id):
"""
Retrieve an assessment based on id.
"""
e = Assessment.query.filter(Assessment.id == id).first()
if e is not None:
return e.as_dict()
else:
return {}
def put(self, id):
"""
Update an assessment based on id.
"""
args = parser_assessment.parse_args()
e = Assessment.query.filter(Assessment.id == id).first()
if e is not None:
e.name = args["name"]
e.name = args["access_log_enabled"]
e.name = args["snooze"]
e.name = args["run_once"]
else:
return 'assessment not found!'
try:
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
return e.as_dict(), 201
def delete(self, id):
"""
Delete an assessment based on id.
"""
e = Assessment.query.filter(Assessment.id == id).first()
if e is not None:
try:
# Delete everything asssociated with Assessment
Capture.query.filter_by(assessment=e.name).delete()
AccessLog.query.filter_by(assessment=e.name).delete()
GenericCollector.query.filter_by(assessment=e.name).delete()
db.session.delete(e)
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
else:
return {}
return e.as_dict(), 204
class AssessmentViewList(Resource):
"""
API Provides CRUD operations for Assessments.
Methods:
GET
POST
"""
def get(self):
results = []
for row in Assessment.query.all():
results.append(row.as_dict())
return results
def post(self):
args = parser_assessment.parse_args()
o = Assessment()
o.name = args["name"]
o.access_log_enabled = args["access_log_enabled"]
o.snooze = args["snooze"]
o.run_once = args["run_once"]
try:
db.session.add(o)
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
return o.as_dict(), 201
class PayloadView(Resource):
"""
API Provides CRUD operations for Payloads based on id.
Methods:
GET
PUT
DELETE
"""
def get(self, id):
e = Payload.query.filter(Payload.id == id).first()
if e is not None:
return e.as_dict()
else:
return 'payload not found!'
def put(self, id):
args = parser_payload.parse_args()
e = Payload.query.filter(Payload.id == id).first()
if e is not None:
e.notes = args["notes"]
e.payload = args["payload"]
else:
return 'payload not found!'
try:
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
return e.as_dict(), 201
def delete(self, id):
e = Payload.query.filter(Payload.id == id).first()
if e is not None:
try:
db.session.delete(e)
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
else:
return {}
return e.as_dict(), 204
class PayloadViewList(Resource):
"""
API Provides CRUD operations for Payloads.
Methods:
GET
POST
"""
def get(self):
results = []
for row in Payload.query.all():
results.append(row.as_dict())
return results
def post(self):
args = parser_payload.parse_args()
o = Payload()
o.payload = args["payload"]
o.ordering = 1
o.notes = args["notes"]
try:
db.session.add(o)
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
return o.as_dict(), 201
class PuppyscriptAssociations(Resource):
"""
API Provides GET operations for retriving Puppyscripts associated with payload
Methods:
GET
"""
def get(self, id):
args = parser_helper.parse_args()
the_list = []
the_assessment = args['a']
the_payload = Payload.query.filter(Payload.id == id).first()
try:
if the_payload is not None:
for the_puppyscript in the_payload.ordering.split(','):
the_list.append(Puppyscript.query.filter_by(
id=int(the_puppyscript)).first().as_dict(the_payload.id, the_assessment))
return the_list
else:
return {}
except:
return {}
class AssessmentPayloads(Resource):
"""
API Provides GET operation for retriving Payloads associated with an Assessment
Methods:
GET
"""
def get(self, id):
the_list = []
assessment = Assessment.query.filter_by(id=id).first()
payloads = Payload.query.all()
try:
if assessment is not None:
for payload in payloads:
results = payload.payload.replace("$1",
"//{}/x?u={}&a={}".format(app.config['HOSTNAME'], str(payload.id), str(assessment.id)))
the_list.append(results)
return the_list
else:
return {}
except:
return {}
class PuppyscriptView(Resource):
"""
API Provides CRUD operations for Puppyscripts based on id.
Methods:
GET
PUT
DELETE
"""
def get(self, id):
e = Puppyscript.query.filter(Puppyscript.id == id).first()
if e is not None:
return e.as_dict()
else:
return {}
def put(self, id):
args = parser_puppyscript.parse_args()
e = Puppyscript.query.filter(Puppyscript.id == id).first()
if e is not None:
e.name = args["name"]
e.code = args["code"]
e.notes = args["notes"]
else:
return {'puppyscript not found!'}
try:
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
return e.as_dict(), 201
def delete(self, id):
result = Puppyscript.query.filter(Puppyscript.id == id).first()
if result is not None:
try:
payloads = Payload.query.all()
for payload in payloads:
if payload.ordering is not None:
payload.ordering = payload.ordering.replace(
str(result.id) + ",", "")
payload.ordering = payload.ordering.replace(
"," + str(result.id), "")
payload.ordering = payload.ordering.replace(
str(result.id), "")
db.session.add(payload)
db.session.commit()
except Exception as err:
app.logger.warn(err)
try:
db.session.delete(result)
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
else:
return {}
class PuppyscriptViewList(Resource):
"""
API Provides CRUD operations for Puppyscripts.
Methods:
GET
POST
"""
def get(self):
results = []
for row in Puppyscript.query.all():
results.append(row.as_dict())
return results
def post(self):
args = parser_puppyscript.parse_args()
o = Puppyscript()
o.name = args["name"]
o.code = args["code"]
o.notes = args["notes"]
try:
db.session.add(o)
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
return o.as_dict(), 201
class CaptureView(Resource):
"""
API Provides CRUD operations for Captures based on id.
Methods:
GET
DELETE
Captures should be immutable so no PUT operations are permitted.
"""
def get(self, id):
e = Capture.query.filter(Capture.id == id).first()
if e is not None:
return e.as_dict()
else:
return {}
def delete(self, id):
capture = Capture.query.filter(Capture.id == id).first()
if capture is not None:
try:
os.remove("uploads/{}.png".format(capture.screenshot))
os.remove("uploads/small_{}.png".format(capture.screenshot))
except:
pass
try:
db.session.delete(capture)
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
else:
return {}
return capture.as_dict(), 204
class CaptureViewList(Resource):
"""
API Provides CRUD operations for Captures.
Methods:
GET
"""
def get(self):
results = []
for row in Capture.query.all():
results.append(row.as_dict())
return results
class GenericCollectorView(Resource):
"""
API Provides CRUD operations for Captures based on id.
Methods:
GET
DELETE
Captures should be immutable so no PUT operations are permitted.
"""
def get(self, id):
e = GenericCollector.query.filter(GenericCollector.id == id).first()
if e is not None:
return e.as_dict()
else:
return {}
def delete(self, id):
capture = GenericCollector.query.filter(
GenericCollector.id == id).first()
if capture is not None:
try:
db.session.delete(capture)
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
else:
return {}
return capture.as_dict(), 204
class GenericCollectorViewList(Resource):
"""
API Provides CRUD operations for Captures.
Methods:
GET
"""
def get(self):
results = []
for row in GenericCollector.query.all():
results.append(row.as_dict())
return results
class AccessLogView(Resource):
"""
API Provides CRUD operations for AccessLog based on id.
Methods:
GET
DELETE
Captures should be immutable so no PUT operations are permitted.
"""
def get(self, id):
e = AccessLog.query.filter(AccessLog.id == id).first()
if e is not None:
return e.as_dict()
else:
return {}
def delete(self, id):
access_log = AccessLog.query.filter(AccessLog.id == id).first()
if access_log is not None:
try:
db.session.delete(access_log)
db.session.commit()
except IntegrityError, exc:
app.logger.warn(exc.message)
return {"error": exc.message}, 500
else:
return {}
return access_log.as_dict(), 204
class AccessLogViewList(Resource):
"""
API Provides CRUD operations for Access Log.
Methods:
GET
"""
def get(self):
results = []
for row in AccessLog.query.all():
results.append(row.as_dict())
return results
| apache-2.0 | 3,686,837,271,280,829,000 | 26.702988 | 141 | 0.526232 | false |
open-switch/ops-quagga | ops-tests/component/zebra/test_zebra_ct_connected_routes.py | 2 | 173308 | # -*- coding: utf-8 -*-
#
# (c)Copyright 2015 Hewlett Packard Enterprise Development LP
#
# GNU Zebra 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, or (at your option) any
# later version.
#
# GNU Zebra is distributed in the hope that it will be useful, but
# WITHoutput ANY WARRANTY; withoutput 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 GNU Zebra; see the file COPYING. If not, write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.from re import match
# Topology definition. the topology contains two back to back switches
# having four links between them.
from helpers_routing import (
ZEBRA_TEST_SLEEP_TIME,
ZEBRA_INIT_SLEEP_TIME,
verify_show_ip_route,
verify_show_ipv6_route,
verify_show_rib
)
from time import sleep
zebra_stop_command_string = "systemctl stop ops-zebra"
zebra_start_command_string = "systemctl start ops-zebra"
TOPOLOGY = """
# +-------+ +-------+
# | <----> |
# | <----> |
# | sw1 | | sw2 |
# | <----> |
# | <----> |
# +-------+ +-------+
# Nodes
[type=openswitch name="Switch 1"] sw1
[type=openswitch name="Switch 2"] sw2
# Links
sw1:if01 -- sw2:if01
sw1:if02 -- sw2:if02
sw1:if03 -- sw2:if03
sw1:if04 -- sw2:if04
"""
"""
Format of the route dictionary used for component test verification
data keys
Route - string set to route which is of the format
"Prefix/Masklen"
NumberNexthops - string set to the number of next-hops
of the route
Next-hop - string set to the next-hop port or IP/IPv6
address as the key and a dictionary as value
data keys
Distance - String whose numeric value is the administration
distance of the next-hop
Metric - String whose numeric value is the metric of the
next-hop
RouteType - String which is the route type of the next-hop
"""
# This test configures IPv4 and IPv6 interface addresses on different interface
# types and check if the corresponding connected routes have been programmed in FIB
# by looking into the output of "show ip/ipv6 route/show rib".
def configure_layer3_interfaces(sw1, sw2, step):
# Configure physical layer-3 interface
sw1_interface = sw1.ports["if0{}".format(1)]
sw1("configure terminal")
sw1("interface {}".format(sw1_interface))
sw1("ip address 1.1.1.1/24")
sw1("ip address 11.11.11.11/24 secondary")
sw1("ipv6 address 1:1::1/64")
sw1("ipv6 address 11:11::11/64 secondary")
sw1("no shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
rib_ipv4_layer3_connected_route_primary = dict()
rib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
rib_ipv4_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_primary['1'] = dict()
rib_ipv4_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
fib_ipv4_layer3_connected_route_primary = rib_ipv4_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 secondary address and its next-hops.
rib_ipv4_layer3_connected_route_secondary = dict()
rib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
rib_ipv4_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_secondary['1'] = dict()
rib_ipv4_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 secndary address and its next-hops.
fib_ipv4_layer3_connected_route_secondary = rib_ipv4_layer3_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
rib_ipv6_layer3_connected_route_primary = dict()
rib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
rib_ipv6_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_primary['1'] = dict()
rib_ipv6_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
fib_ipv6_layer3_connected_route_primary = rib_ipv6_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
rib_ipv6_layer3_connected_route_secondary = dict()
rib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
rib_ipv6_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_secondary['1'] = dict()
rib_ipv6_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
fib_ipv6_layer3_connected_route_secondary = rib_ipv6_layer3_connected_route_secondary
# Configure a Vlan interface
sw1("configure terminal")
sw1("vlan 100")
sw1("no shutdown")
sw1("exit")
sw1_interface = sw1.ports["if0{}".format(2)]
sw1("configure terminal")
sw1("interface {}".format(sw1_interface))
sw1("no routing")
sw1("no shutdown")
sw1("vlan access 100")
sw1("exit")
sw1("configure terminal")
sw1("interface vlan 100")
sw1("ip address 2.2.2.2/24")
sw1("ipv6 address 2:2::2/64")
sw1("ip address 22.22.22.22/24 secondary")
sw1("ipv6 address 22:22::22/64 secondary")
sw1("no shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
rib_ipv4_vlan_connected_route_primary = dict()
rib_ipv4_vlan_connected_route_primary['Route'] = '2.2.2.0/24'
rib_ipv4_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
fib_ipv4_vlan_connected_route_primary = rib_ipv4_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
rib_ipv4_vlan_connected_route_secondary = dict()
rib_ipv4_vlan_connected_route_secondary['Route'] = '22.22.22.0/24'
rib_ipv4_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
fib_ipv4_vlan_connected_route_secondary = rib_ipv4_vlan_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
rib_ipv6_vlan_connected_route_primary = dict()
rib_ipv6_vlan_connected_route_primary['Route'] = '2:2::/64'
rib_ipv6_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
fib_ipv6_vlan_connected_route_primary = rib_ipv6_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
rib_ipv6_vlan_connected_route_secondary = dict()
rib_ipv6_vlan_connected_route_secondary['Route'] = '22:22::/64'
rib_ipv6_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
fib_ipv6_vlan_connected_route_secondary = rib_ipv6_vlan_connected_route_secondary
# Configure an L3 subinterface
# Configure the parent interface
sw1_interface = sw1.ports["if0{}".format(3)]
sw1("configure terminal")
sw1("interface {}".format(sw1_interface))
sw1("no shutdown")
sw1("exit")
# Configure the sub-interface. Secondary IP addresses are not supported within
# L3 sub-interface.
sw1("configure terminal")
sw1("interface 3.1")
sw1("encapsulation dot1Q 2")
sw1("ip address 3.3.3.3/24")
sw1("ipv6 address 3:3::3/64")
sw1("no shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
rib_ipv4_subinterface_connected_route_primary = dict()
rib_ipv4_subinterface_connected_route_primary['Route'] = '3.3.3.0/24'
rib_ipv4_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv4_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
fib_ipv4_subinterface_connected_route_primary = rib_ipv4_subinterface_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
rib_ipv6_subinterface_connected_route_primary = dict()
rib_ipv6_subinterface_connected_route_primary['Route'] = '3:3::/64'
rib_ipv6_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv6_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_subinterface_connected_route_primary = rib_ipv6_subinterface_connected_route_primary
# Configure a L3 loopback interface. Secondary IP addresses are not supported on
# L3 loopback interfaces.
sw1("configure terminal")
sw1("interface loopback 1")
sw1("ip address 4.4.4.4/24")
sw1("ipv6 address 4:4::4/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
rib_ipv4_loopback_connected_route_primary = dict()
rib_ipv4_loopback_connected_route_primary['Route'] = '4.4.4.0/24'
rib_ipv4_loopback_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_loopback_connected_route_primary['loopback1'] = dict()
rib_ipv4_loopback_connected_route_primary['loopback1']['Distance'] = '0'
rib_ipv4_loopback_connected_route_primary['loopback1']['Metric'] = '0'
rib_ipv4_loopback_connected_route_primary['loopback1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
fib_ipv4_loopback_connected_route_primary = rib_ipv4_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for loopback primary address and its next-hops.
rib_ipv6_loopback_connected_route_primary = dict()
rib_ipv6_loopback_connected_route_primary['Route'] = '4:4::/64'
rib_ipv6_loopback_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_loopback_connected_route_primary['loopback1'] = dict()
rib_ipv6_loopback_connected_route_primary['loopback1']['Distance'] = '0'
rib_ipv6_loopback_connected_route_primary['loopback1']['Metric'] = '0'
rib_ipv6_loopback_connected_route_primary['loopback1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_loopback_connected_route_primary = rib_ipv6_loopback_connected_route_primary
# Configure a L3 LAG interface.
sw1("configure terminal")
sw1("interface lag 100")
sw1("ip address 5.5.5.5/24")
sw1("ip address 55.55.55.55/24 secondary")
sw1("ipv6 address 5:5::5/64")
sw1("ipv6 address 55:55::55/64 secondary")
sw1("no shutdown")
sw1("exit")
# Configure the parent interface
sw1_interface = sw1.ports["if0{}".format(4)]
sw1("configure terminal")
sw1("interface {}".format(sw1_interface))
sw1("lag 100")
sw1("no shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
rib_ipv4_lag_connected_route_primary = dict()
rib_ipv4_lag_connected_route_primary['Route'] = '5.5.5.0/24'
rib_ipv4_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_primary['lag100'] = dict()
rib_ipv4_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
fib_ipv4_lag_connected_route_primary = rib_ipv4_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
rib_ipv4_lag_connected_route_secondary = dict()
rib_ipv4_lag_connected_route_secondary['Route'] = '55.55.55.0/24'
rib_ipv4_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_secondary['lag100'] = dict()
rib_ipv4_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
fib_ipv4_lag_connected_route_secondary = rib_ipv4_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
rib_ipv6_lag_connected_route_primary = dict()
rib_ipv6_lag_connected_route_primary['Route'] = '5:5::/64'
rib_ipv6_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_primary['lag100'] = dict()
rib_ipv6_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
fib_ipv6_lag_connected_route_primary = rib_ipv6_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG secondary address and its next-hops.
rib_ipv6_lag_connected_route_secondary = dict()
rib_ipv6_lag_connected_route_secondary['Route'] = '55:55::/64'
rib_ipv6_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_secondary['lag100'] = dict()
rib_ipv6_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG secndary address and its next-hops.
fib_ipv6_lag_connected_route_secondary = rib_ipv6_lag_connected_route_secondary
sleep(ZEBRA_TEST_SLEEP_TIME)
step("Verifying the IPv4/IPv6 connected routes on switch 1")
# Verify IPv4 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_primary)
aux_route = rib_ipv4_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_layer3_connected_route_primary)
# Verify IPv4 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_secondary)
aux_route = rib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_layer3_connected_route_secondary)
# Verify IPv6 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_primary)
aux_route = rib_ipv6_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_layer3_connected_route_primary)
# Verify IPv6 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_secondary)
aux_route = rib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_layer3_connected_route_secondary)
# Verify IPv4 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_primary)
aux_route = rib_ipv4_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_vlan_connected_route_primary)
# Verify IPv4 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_secondary)
aux_route = rib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_vlan_connected_route_secondary)
# Verify IPv6 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_primary)
aux_route = rib_ipv6_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_vlan_connected_route_primary)
# Verify IPv6 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_secondary)
aux_route = rib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_vlan_connected_route_secondary)
# Verify IPv4 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_subinterface_connected_route_primary)
aux_route = rib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_subinterface_connected_route_primary)
# Verify IPv6 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_subinterface_connected_route_primary)
aux_route = rib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_subinterface_connected_route_primary)
# Verify IPv4 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_loopback_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_loopback_connected_route_primary)
aux_route = rib_ipv4_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_loopback_connected_route_primary)
# Verify IPv6 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_loopback_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_loopback_connected_route_primary)
aux_route = rib_ipv6_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_loopback_connected_route_primary)
# Verify IPv4 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_primary)
aux_route = rib_ipv4_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_lag_connected_route_primary)
# Verify IPv4 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_secondary)
aux_route = rib_ipv4_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_lag_connected_route_secondary)
# Verify IPv6 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_primary)
aux_route = rib_ipv6_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_lag_connected_route_primary)
# Verify IPv6 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_secondary)
aux_route = rib_ipv6_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_lag_connected_route_secondary)
# This test shuts down IPv4 and IPv6 interfaces and check if the corresponding
# connected routes have been withdrawn from FIB by looking into the output of
# "show ip/ipv6 route/show rib".
def shutdown_layer3_interfaces(sw1, sw2, step):
# Shutdown layer-3 interface
sw1("configure terminal")
sw1("interface 1")
sw1("shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
rib_ipv4_layer3_connected_route_primary = dict()
rib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
rib_ipv4_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_primary['1'] = dict()
rib_ipv4_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
fib_ipv4_layer3_connected_route_primary = dict()
fib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 secondary address and its next-hops.
rib_ipv4_layer3_connected_route_secondary = dict()
rib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
rib_ipv4_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_secondary['1'] = dict()
rib_ipv4_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 secndary address and its next-hops.
fib_ipv4_layer3_connected_route_secondary = dict()
fib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
rib_ipv6_layer3_connected_route_primary = dict()
rib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
rib_ipv6_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_primary['1'] = dict()
rib_ipv6_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
fib_ipv6_layer3_connected_route_primary = dict()
fib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
rib_ipv6_layer3_connected_route_secondary = dict()
rib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
rib_ipv6_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_secondary['1'] = dict()
rib_ipv6_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
fib_ipv6_layer3_connected_route_secondary = dict()
fib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
# Shutdown the vlan interface
sw1("configure terminal")
sw1("interface vlan 100")
sw1("shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
rib_ipv4_vlan_connected_route_primary = dict()
rib_ipv4_vlan_connected_route_primary['Route'] = '2.2.2.0/24'
rib_ipv4_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
fib_ipv4_vlan_connected_route_primary = dict()
fib_ipv4_vlan_connected_route_primary['Route'] = '2.2.2.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
rib_ipv4_vlan_connected_route_secondary = dict()
rib_ipv4_vlan_connected_route_secondary['Route'] = '22.22.22.0/24'
rib_ipv4_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
fib_ipv4_vlan_connected_route_secondary = dict()
fib_ipv4_vlan_connected_route_secondary['Route'] = '22.22.22.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
rib_ipv6_vlan_connected_route_primary = dict()
rib_ipv6_vlan_connected_route_primary['Route'] = '2:2::/64'
rib_ipv6_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
fib_ipv6_vlan_connected_route_primary = dict()
fib_ipv6_vlan_connected_route_primary['Route'] = '2:2::/64'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
rib_ipv6_vlan_connected_route_secondary = dict()
rib_ipv6_vlan_connected_route_secondary['Route'] = '22:22::/64'
rib_ipv6_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
fib_ipv6_vlan_connected_route_secondary = dict()
fib_ipv6_vlan_connected_route_secondary['Route'] = '22:22::/64'
# Shutdown the L3 sub-interface.
sw1("configure terminal")
sw1("interface 3.1")
sw1("no encapsulation dot1Q 2")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
rib_ipv4_subinterface_connected_route_primary = dict()
rib_ipv4_subinterface_connected_route_primary['Route'] = '3.3.3.0/24'
rib_ipv4_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv4_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
fib_ipv4_subinterface_connected_route_primary = dict()
fib_ipv4_subinterface_connected_route_primary['Route'] = '3.3.3.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
rib_ipv6_subinterface_connected_route_primary = dict()
rib_ipv6_subinterface_connected_route_primary['Route'] = '3:3::/64'
rib_ipv6_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv6_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_subinterface_connected_route_primary = dict()
fib_ipv6_subinterface_connected_route_primary['Route'] = '3:3::/64'
# We cannot toggle(shut/no shut) loopback interface. So skip populating the
# verification dictionaries for loopback interface.
# Shutdown the L3 LAG interface.
sw1("configure terminal")
sw1("interface lag 100")
sw1("shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
rib_ipv4_lag_connected_route_primary = dict()
rib_ipv4_lag_connected_route_primary['Route'] = '5.5.5.0/24'
rib_ipv4_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_primary['lag100'] = dict()
rib_ipv4_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
fib_ipv4_lag_connected_route_primary = dict()
fib_ipv4_lag_connected_route_primary['Route'] = '5.5.5.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
rib_ipv4_lag_connected_route_secondary = dict()
rib_ipv4_lag_connected_route_secondary['Route'] = '55.55.55.0/24'
rib_ipv4_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_secondary['lag100'] = dict()
rib_ipv4_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
fib_ipv4_lag_connected_route_secondary = dict()
fib_ipv4_lag_connected_route_secondary['Route'] = '55.55.55.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
rib_ipv6_lag_connected_route_primary = dict()
rib_ipv6_lag_connected_route_primary['Route'] = '5:5::/64'
rib_ipv6_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_primary['lag100'] = dict()
rib_ipv6_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
fib_ipv6_lag_connected_route_primary = dict()
fib_ipv6_lag_connected_route_primary['Route'] = '5:5::/64'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG secondary address and its next-hops.
rib_ipv6_lag_connected_route_secondary = dict()
rib_ipv6_lag_connected_route_secondary['Route'] = '55:55::/64'
rib_ipv6_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_secondary['lag100'] = dict()
rib_ipv6_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG secndary address and its next-hops.
fib_ipv6_lag_connected_route_secondary = dict()
fib_ipv6_lag_connected_route_secondary['Route'] = '55:55::/64'
sleep(ZEBRA_TEST_SLEEP_TIME)
step("Verifying the IPv4/IPv6 connected routes on switch 1")
# Verify IPv4 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_primary)
aux_route = rib_ipv4_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_layer3_connected_route_primary)
# Verify IPv4 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_secondary)
aux_route = rib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_layer3_connected_route_secondary)
# Verify IPv6 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_primary)
aux_route = rib_ipv6_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_layer3_connected_route_primary)
# Verify IPv6 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_secondary)
aux_route = rib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_layer3_connected_route_secondary)
# Verify IPv4 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_primary)
aux_route = rib_ipv4_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_vlan_connected_route_primary)
# Verify IPv4 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_secondary)
aux_route = rib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_vlan_connected_route_secondary)
# Verify IPv6 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_primary)
aux_route = rib_ipv6_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_vlan_connected_route_primary)
# Verify IPv6 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_secondary)
aux_route = rib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_vlan_connected_route_secondary)
# Verify IPv4 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_subinterface_connected_route_primary)
aux_route = rib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_subinterface_connected_route_primary)
# Verify IPv6 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_subinterface_connected_route_primary)
aux_route = rib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_subinterface_connected_route_primary)
# Verify IPv4 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_primary)
aux_route = rib_ipv4_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_lag_connected_route_primary)
# Verify IPv4 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_secondary)
aux_route = rib_ipv4_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_lag_connected_route_secondary)
# Verify IPv6 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_primary)
aux_route = rib_ipv6_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_lag_connected_route_primary)
# Verify IPv6 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_secondary)
aux_route = rib_ipv6_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_lag_connected_route_secondary)
# This test brings up IPv4 and IPv6 interfaces and check if the corresponding
# connected routes have been reprogrammed into FIB by looking into the output of
# "show ip/ipv6 route/show rib".
def no_shutdown_layer3_interfaces(sw1, sw2, step):
# Un-shutdown layer-3 interface
sw1("configure terminal")
sw1("interface 1")
sw1("no shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
rib_ipv4_layer3_connected_route_primary = dict()
rib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
rib_ipv4_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_primary['1'] = dict()
rib_ipv4_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
fib_ipv4_layer3_connected_route_primary = rib_ipv4_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 secondary address and its next-hops.
rib_ipv4_layer3_connected_route_secondary = dict()
rib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
rib_ipv4_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_secondary['1'] = dict()
rib_ipv4_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 secndary address and its next-hops.
fib_ipv4_layer3_connected_route_secondary = rib_ipv4_layer3_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
rib_ipv6_layer3_connected_route_primary = dict()
rib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
rib_ipv6_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_primary['1'] = dict()
rib_ipv6_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
fib_ipv6_layer3_connected_route_primary = rib_ipv6_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
rib_ipv6_layer3_connected_route_secondary = dict()
rib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
rib_ipv6_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_secondary['1'] = dict()
rib_ipv6_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
fib_ipv6_layer3_connected_route_secondary = rib_ipv6_layer3_connected_route_secondary
# Un-shutdown the vlan interface
sw1("configure terminal")
sw1("interface vlan 100")
sw1("no shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
rib_ipv4_vlan_connected_route_primary = dict()
rib_ipv4_vlan_connected_route_primary['Route'] = '2.2.2.0/24'
rib_ipv4_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
fib_ipv4_vlan_connected_route_primary = rib_ipv4_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
rib_ipv4_vlan_connected_route_secondary = dict()
rib_ipv4_vlan_connected_route_secondary['Route'] = '22.22.22.0/24'
rib_ipv4_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
fib_ipv4_vlan_connected_route_secondary = rib_ipv4_vlan_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
rib_ipv6_vlan_connected_route_primary = dict()
rib_ipv6_vlan_connected_route_primary['Route'] = '2:2::/64'
rib_ipv6_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
fib_ipv6_vlan_connected_route_primary = rib_ipv6_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
rib_ipv6_vlan_connected_route_secondary = dict()
rib_ipv6_vlan_connected_route_secondary['Route'] = '22:22::/64'
rib_ipv6_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
fib_ipv6_vlan_connected_route_secondary = rib_ipv6_vlan_connected_route_secondary
# Un-shutdown the L3 sub-interface.
sw1("configure terminal")
sw1("interface 3.1")
sw1("encapsulation dot1Q 2")
sw1("no shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
rib_ipv4_subinterface_connected_route_primary = dict()
rib_ipv4_subinterface_connected_route_primary['Route'] = '3.3.3.0/24'
rib_ipv4_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv4_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
fib_ipv4_subinterface_connected_route_primary = rib_ipv4_subinterface_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
rib_ipv6_subinterface_connected_route_primary = dict()
rib_ipv6_subinterface_connected_route_primary['Route'] = '3:3::/64'
rib_ipv6_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv6_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_subinterface_connected_route_primary = rib_ipv6_subinterface_connected_route_primary
# We cannot toggle(shut/no shut) loopback interface. So skip populating the
# verification dictionaries for loopback interface.
# Un-shutdown the L3 LAG interface.
sw1("configure terminal")
sw1("interface lag 100")
sw1("no shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
rib_ipv4_lag_connected_route_primary = dict()
rib_ipv4_lag_connected_route_primary['Route'] = '5.5.5.0/24'
rib_ipv4_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_primary['lag100'] = dict()
rib_ipv4_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
fib_ipv4_lag_connected_route_primary = rib_ipv4_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
rib_ipv4_lag_connected_route_secondary = dict()
rib_ipv4_lag_connected_route_secondary['Route'] = '55.55.55.0/24'
rib_ipv4_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_secondary['lag100'] = dict()
rib_ipv4_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
fib_ipv4_lag_connected_route_secondary = rib_ipv4_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
rib_ipv6_lag_connected_route_primary = dict()
rib_ipv6_lag_connected_route_primary['Route'] = '5:5::/64'
rib_ipv6_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_primary['lag100'] = dict()
rib_ipv6_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
fib_ipv6_lag_connected_route_primary = rib_ipv6_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG secondary address and its next-hops.
rib_ipv6_lag_connected_route_secondary = dict()
rib_ipv6_lag_connected_route_secondary['Route'] = '55:55::/64'
rib_ipv6_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_secondary['lag100'] = dict()
rib_ipv6_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG secndary address and its next-hops.
fib_ipv6_lag_connected_route_secondary = rib_ipv6_lag_connected_route_secondary
sleep(ZEBRA_TEST_SLEEP_TIME)
step("Verifying the IPv4/IPv6 connected routes on switch 1")
# Verify IPv4 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_primary)
aux_route = rib_ipv4_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_layer3_connected_route_primary)
# Verify IPv4 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_secondary)
aux_route = rib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_layer3_connected_route_secondary)
# Verify IPv6 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_primary)
aux_route = rib_ipv6_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_layer3_connected_route_primary)
# Verify IPv6 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_secondary)
aux_route = rib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_layer3_connected_route_secondary)
# Verify IPv4 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_primary)
aux_route = rib_ipv4_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_vlan_connected_route_primary)
# Verify IPv4 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_secondary)
aux_route = rib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_vlan_connected_route_secondary)
# Verify IPv6 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_primary)
aux_route = rib_ipv6_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_vlan_connected_route_primary)
# Verify IPv6 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_secondary)
aux_route = rib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_vlan_connected_route_secondary)
# Verify IPv4 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_subinterface_connected_route_primary)
aux_route = rib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_subinterface_connected_route_primary)
# Verify IPv6 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_subinterface_connected_route_primary)
aux_route = rib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_subinterface_connected_route_primary)
# Verify IPv4 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_primary)
aux_route = rib_ipv4_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_lag_connected_route_primary)
# Verify IPv4 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_secondary)
aux_route = rib_ipv4_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_lag_connected_route_secondary)
# Verify IPv6 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_primary)
aux_route = rib_ipv6_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_lag_connected_route_primary)
# Verify IPv6 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_secondary)
aux_route = rib_ipv6_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_lag_connected_route_secondary)
# This test removes IPv4 and IPv6 interfaces addresses (both primary and secondary
# )and check if the corresponding connected routes have been removed from FIB and RIB
# by looking into the output of "show ip/ipv6 route/show rib".
def remove_addresses_from_layer3_interfaces(sw1, sw2, step):
# Un-configure layer-3 interface addresses
sw1("configure terminal")
sw1("interface 1")
sw1("no ip address 11.11.11.11/24 secondary")
sw1("no ipv6 address 11:11::11/64 secondary")
sw1("no ip address 1.1.1.1/24")
sw1("no ipv6 address 1:1::1/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
rib_ipv4_layer3_connected_route_primary = dict()
rib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
fib_ipv4_layer3_connected_route_primary = dict()
fib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 secondary address and its next-hops.
rib_ipv4_layer3_connected_route_secondary = dict()
rib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 secndary address and its next-hops.
fib_ipv4_layer3_connected_route_secondary = dict()
fib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
rib_ipv6_layer3_connected_route_primary = dict()
rib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
fib_ipv6_layer3_connected_route_primary = dict()
fib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
rib_ipv6_layer3_connected_route_secondary = dict()
rib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
fib_ipv6_layer3_connected_route_secondary = dict()
fib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
# Un-configure vlan interface addresses
sw1("configure terminal")
sw1("interface vlan 100")
sw1("no ip address 22.22.22.22/24 secondary")
sw1("no ipv6 address 22:22::22/64 secondary")
sw1("no ip address 2.2.2.2/24")
sw1("no ipv6 address 2:2::2/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
rib_ipv4_vlan_connected_route_primary = dict()
rib_ipv4_vlan_connected_route_primary['Route'] = '2.2.2.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
fib_ipv4_vlan_connected_route_primary = rib_ipv4_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
rib_ipv4_vlan_connected_route_secondary = dict()
rib_ipv4_vlan_connected_route_secondary['Route'] = '22.22.22.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
fib_ipv4_vlan_connected_route_secondary = rib_ipv4_vlan_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
rib_ipv6_vlan_connected_route_primary = dict()
rib_ipv6_vlan_connected_route_primary['Route'] = '2:2::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
fib_ipv6_vlan_connected_route_primary = rib_ipv6_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
rib_ipv6_vlan_connected_route_secondary = dict()
rib_ipv6_vlan_connected_route_secondary['Route'] = '22:22::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
fib_ipv6_vlan_connected_route_secondary = rib_ipv6_vlan_connected_route_secondary
# Un-configure L3 sub-interface interface addresses
sw1("configure terminal")
sw1("interface 3.1")
sw1("no ip address 3.3.3.3/24")
sw1("no ipv6 address 3:3::3/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
rib_ipv4_subinterface_connected_route_primary = dict()
rib_ipv4_subinterface_connected_route_primary['Route'] = '3.3.3.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
fib_ipv4_subinterface_connected_route_primary = rib_ipv4_subinterface_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
rib_ipv6_subinterface_connected_route_primary = dict()
rib_ipv6_subinterface_connected_route_primary['Route'] = '3:3::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_subinterface_connected_route_primary = rib_ipv6_subinterface_connected_route_primary
# Un-configure loopback interface addresses
sw1("configure terminal")
sw1("interface loopback 1")
sw1("no ip address 4.4.4.4/24")
sw1("no ipv6 address 4:4::4/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
rib_ipv4_loopback_connected_route_primary = dict()
rib_ipv4_loopback_connected_route_primary['Route'] = '4.4.4.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
fib_ipv4_loopback_connected_route_primary = rib_ipv4_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for loopback primary address and its next-hops.
rib_ipv6_loopback_connected_route_primary = dict()
rib_ipv6_loopback_connected_route_primary['Route'] = '4:4::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_loopback_connected_route_primary = rib_ipv6_loopback_connected_route_primary
# Un-configure L3 lag interface addresses
sw1("configure terminal")
sw1("interface lag 100")
sw1("no ip address 55.55.55.55/24 secondary")
sw1("no ipv6 address 55:55::55/64 secondary")
sw1("no ip address 5.5.5.5/24")
sw1("no ipv6 address 5:5::5/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
rib_ipv4_lag_connected_route_primary = dict()
rib_ipv4_lag_connected_route_primary['Route'] = '5.5.5.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
fib_ipv4_lag_connected_route_primary = rib_ipv4_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
rib_ipv4_lag_connected_route_secondary = dict()
rib_ipv4_lag_connected_route_secondary['Route'] = '55.55.55.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
fib_ipv4_lag_connected_route_secondary = rib_ipv4_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
rib_ipv6_lag_connected_route_primary = dict()
rib_ipv6_lag_connected_route_primary['Route'] = '5:5::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
fib_ipv6_lag_connected_route_primary = rib_ipv6_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG secondary address and its next-hops.
rib_ipv6_lag_connected_route_secondary = dict()
rib_ipv6_lag_connected_route_secondary['Route'] = '55:55::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG secndary address and its next-hops.
fib_ipv6_lag_connected_route_secondary = rib_ipv6_lag_connected_route_secondary
sleep(ZEBRA_TEST_SLEEP_TIME)
step("Verifying the IPv4/IPv6 connected routes on switch 1")
# Verify IPv4 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_primary)
aux_route = rib_ipv4_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_layer3_connected_route_primary)
# Verify IPv4 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_secondary)
aux_route = rib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_layer3_connected_route_secondary)
# Verify IPv6 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_primary)
aux_route = rib_ipv6_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_layer3_connected_route_primary)
# Verify IPv6 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_secondary)
aux_route = rib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_layer3_connected_route_secondary)
# Verify IPv4 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_primary)
aux_route = rib_ipv4_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_vlan_connected_route_primary)
# Verify IPv4 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_secondary)
aux_route = rib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_vlan_connected_route_secondary)
# Verify IPv6 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_primary)
aux_route = rib_ipv6_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_vlan_connected_route_primary)
# Verify IPv6 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_secondary)
aux_route = rib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_vlan_connected_route_secondary)
# Verify IPv4 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_subinterface_connected_route_primary)
aux_route = rib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_subinterface_connected_route_primary)
# Verify IPv6 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_subinterface_connected_route_primary)
aux_route = rib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_subinterface_connected_route_primary)
# Verify IPv4 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_loopback_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_loopback_connected_route_primary)
aux_route = rib_ipv4_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_loopback_connected_route_primary)
# Verify IPv6 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_loopback_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_loopback_connected_route_primary)
aux_route = rib_ipv6_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_loopback_connected_route_primary)
# Verify IPv4 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_primary)
aux_route = rib_ipv4_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_lag_connected_route_primary)
# Verify IPv4 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_secondary)
aux_route = rib_ipv4_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_lag_connected_route_secondary)
# Verify IPv6 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_primary)
aux_route = rib_ipv6_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_lag_connected_route_primary)
# Verify IPv6 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_secondary)
aux_route = rib_ipv6_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_lag_connected_route_secondary)
# This test adds back IPv4 and IPv6 interfaces addresses (both primary and secondary
# )and check if the corresponding connected routes have been added into FIB and RIB
# by looking into the output of "show ip/ipv6 route/show rib".
def reconfigure_addresses_on_layer3_interfaces(sw1, sw2, step):
# Re-configure layer-3 interface addresses
sw1("configure terminal")
sw1("interface 1")
sw1("ip address 1.1.1.1/24")
sw1("ipv6 address 1:1::1/64")
sw1("ip address 11.11.11.11/24 secondary")
sw1("ipv6 address 11:11::11/64 secondary")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
rib_ipv4_layer3_connected_route_primary = dict()
rib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
rib_ipv4_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_primary['1'] = dict()
rib_ipv4_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
fib_ipv4_layer3_connected_route_primary = rib_ipv4_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 secondary address and its next-hops.
rib_ipv4_layer3_connected_route_secondary = dict()
rib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
rib_ipv4_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_secondary['1'] = dict()
rib_ipv4_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 secndary address and its next-hops.
fib_ipv4_layer3_connected_route_secondary = rib_ipv4_layer3_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
rib_ipv6_layer3_connected_route_primary = dict()
rib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
rib_ipv6_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_primary['1'] = dict()
rib_ipv6_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
fib_ipv6_layer3_connected_route_primary = rib_ipv6_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
rib_ipv6_layer3_connected_route_secondary = dict()
rib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
rib_ipv6_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_secondary['1'] = dict()
rib_ipv6_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
fib_ipv6_layer3_connected_route_secondary = rib_ipv6_layer3_connected_route_secondary
# Re-configure vlan interface addresses
sw1("configure terminal")
sw1("interface vlan 100")
sw1("ip address 22.22.22.22/24 secondary")
sw1("ipv6 address 22:22::22/64 secondary")
sw1("ip address 2.2.2.2/24")
sw1("ipv6 address 2:2::2/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
rib_ipv4_vlan_connected_route_primary = dict()
rib_ipv4_vlan_connected_route_primary['Route'] = '2.2.2.0/24'
rib_ipv4_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
fib_ipv4_vlan_connected_route_primary = rib_ipv4_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
rib_ipv4_vlan_connected_route_secondary = dict()
rib_ipv4_vlan_connected_route_secondary['Route'] = '22.22.22.0/24'
rib_ipv4_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
fib_ipv4_vlan_connected_route_secondary = rib_ipv4_vlan_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
rib_ipv6_vlan_connected_route_primary = dict()
rib_ipv6_vlan_connected_route_primary['Route'] = '2:2::/64'
rib_ipv6_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
fib_ipv6_vlan_connected_route_primary = rib_ipv6_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
rib_ipv6_vlan_connected_route_secondary = dict()
rib_ipv6_vlan_connected_route_secondary['Route'] = '22:22::/64'
rib_ipv6_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
fib_ipv6_vlan_connected_route_secondary = rib_ipv6_vlan_connected_route_secondary
# Re-configure L3 sub-interface interface addresses
sw1("configure terminal")
sw1("interface 3.1")
sw1("ip address 3.3.3.3/24")
sw1("ipv6 address 3:3::3/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
rib_ipv4_subinterface_connected_route_primary = dict()
rib_ipv4_subinterface_connected_route_primary['Route'] = '3.3.3.0/24'
rib_ipv4_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv4_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
fib_ipv4_subinterface_connected_route_primary = rib_ipv4_subinterface_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
rib_ipv6_subinterface_connected_route_primary = dict()
rib_ipv6_subinterface_connected_route_primary['Route'] = '3:3::/64'
rib_ipv6_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv6_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_subinterface_connected_route_primary = rib_ipv6_subinterface_connected_route_primary
# Re-configure loopback interface addresses
sw1("configure terminal")
sw1("interface loopback 1")
sw1("ip address 4.4.4.4/24")
sw1("ipv6 address 4:4::4/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
rib_ipv4_loopback_connected_route_primary = dict()
rib_ipv4_loopback_connected_route_primary['Route'] = '4.4.4.0/24'
rib_ipv4_loopback_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_loopback_connected_route_primary['loopback1'] = dict()
rib_ipv4_loopback_connected_route_primary['loopback1']['Distance'] = '0'
rib_ipv4_loopback_connected_route_primary['loopback1']['Metric'] = '0'
rib_ipv4_loopback_connected_route_primary['loopback1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
fib_ipv4_loopback_connected_route_primary = rib_ipv4_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for loopback primary address and its next-hops.
rib_ipv6_loopback_connected_route_primary = dict()
rib_ipv6_loopback_connected_route_primary['Route'] = '4:4::/64'
rib_ipv6_loopback_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_loopback_connected_route_primary['loopback1'] = dict()
rib_ipv6_loopback_connected_route_primary['loopback1']['Distance'] = '0'
rib_ipv6_loopback_connected_route_primary['loopback1']['Metric'] = '0'
rib_ipv6_loopback_connected_route_primary['loopback1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_loopback_connected_route_primary = rib_ipv6_loopback_connected_route_primary
# Re-configure L3 lag interface addresses
sw1("configure terminal")
sw1("interface lag 100")
sw1("ip address 5.5.5.5/24")
sw1("ipv6 address 5:5::5/64")
sw1("ip address 55.55.55.55/24 secondary")
sw1("ipv6 address 55:55::55/64 secondary")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
rib_ipv4_lag_connected_route_primary = dict()
rib_ipv4_lag_connected_route_primary['Route'] = '5.5.5.0/24'
rib_ipv4_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_primary['lag100'] = dict()
rib_ipv4_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
fib_ipv4_lag_connected_route_primary = rib_ipv4_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
rib_ipv4_lag_connected_route_secondary = dict()
rib_ipv4_lag_connected_route_secondary['Route'] = '55.55.55.0/24'
rib_ipv4_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_secondary['lag100'] = dict()
rib_ipv4_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
fib_ipv4_lag_connected_route_secondary = rib_ipv4_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
rib_ipv6_lag_connected_route_primary = dict()
rib_ipv6_lag_connected_route_primary['Route'] = '5:5::/64'
rib_ipv6_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_primary['lag100'] = dict()
rib_ipv6_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
fib_ipv6_lag_connected_route_primary = rib_ipv6_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG secondary address and its next-hops.
rib_ipv6_lag_connected_route_secondary = dict()
rib_ipv6_lag_connected_route_secondary['Route'] = '55:55::/64'
rib_ipv6_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_secondary['lag100'] = dict()
rib_ipv6_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG secndary address and its next-hops.
fib_ipv6_lag_connected_route_secondary = rib_ipv6_lag_connected_route_secondary
sleep(ZEBRA_TEST_SLEEP_TIME)
step("Verifying the IPv4/IPv6 connected routes on switch 1")
# Verify IPv4 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_primary)
aux_route = rib_ipv4_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_layer3_connected_route_primary)
# Verify IPv4 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_secondary)
aux_route = rib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_layer3_connected_route_secondary)
# Verify IPv6 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_primary)
aux_route = rib_ipv6_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_layer3_connected_route_primary)
# Verify IPv6 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_secondary)
aux_route = rib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_layer3_connected_route_secondary)
# Verify IPv4 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_primary)
aux_route = rib_ipv4_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_vlan_connected_route_primary)
# Verify IPv4 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_secondary)
aux_route = rib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_vlan_connected_route_secondary)
# Verify IPv6 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_primary)
aux_route = rib_ipv6_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_vlan_connected_route_primary)
# Verify IPv6 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_secondary)
aux_route = rib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_vlan_connected_route_secondary)
# Verify IPv4 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_subinterface_connected_route_primary)
aux_route = rib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_subinterface_connected_route_primary)
# Verify IPv6 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_subinterface_connected_route_primary)
aux_route = rib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_subinterface_connected_route_primary)
# Verify IPv4 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_loopback_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_loopback_connected_route_primary)
aux_route = rib_ipv4_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_loopback_connected_route_primary)
# Verify IPv6 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_loopback_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_loopback_connected_route_primary)
aux_route = rib_ipv6_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_loopback_connected_route_primary)
# Verify IPv4 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_primary)
aux_route = rib_ipv4_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_lag_connected_route_primary)
# Verify IPv4 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_secondary)
aux_route = rib_ipv4_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_lag_connected_route_secondary)
# Verify IPv6 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_primary)
aux_route = rib_ipv6_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_lag_connected_route_primary)
# Verify IPv6 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_secondary)
aux_route = rib_ipv6_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_lag_connected_route_secondary)
# This test case shuts down zebra process and then changes some L3 interface
# configuration. The test case then brings up the zebra process and tests if
# with the new L3 interface configuration, the zebra process cleans or programs
# OVSDB correctly for the connected routes. We test the connected routes using
# the output of "show ip/ipv6 route/show rib".
def restart_zebra_with_config_change_for_layer3_interfaces(sw1, sw2, step):
step("Stopping the ops-zebra process on switch 1")
# Stop ops-zebra process on sw1
sw1(zebra_stop_command_string, shell='bash')
# Change configuration for Layer-3 interface by shutting down the interface
sw1("configure terminal")
sw1("interface 1")
sw1("shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
rib_ipv4_layer3_connected_route_primary = dict()
rib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
rib_ipv4_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_primary['1'] = dict()
rib_ipv4_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
fib_ipv4_layer3_connected_route_primary = dict()
fib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 secondary address and its next-hops.
rib_ipv4_layer3_connected_route_secondary = dict()
rib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
rib_ipv4_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_secondary['1'] = dict()
rib_ipv4_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 secndary address and its next-hops.
fib_ipv4_layer3_connected_route_secondary = dict()
fib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
rib_ipv6_layer3_connected_route_primary = dict()
rib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
rib_ipv6_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_primary['1'] = dict()
rib_ipv6_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
fib_ipv6_layer3_connected_route_primary = dict()
fib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
rib_ipv6_layer3_connected_route_secondary = dict()
rib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
rib_ipv6_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_secondary['1'] = dict()
rib_ipv6_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
fib_ipv6_layer3_connected_route_secondary = dict()
fib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
# Change configuration for Vlan interface by removing all primary and
# secondary IPv4 and IPV6 addresses.
sw1("configure terminal")
sw1("interface vlan 100")
sw1("no ip address 22.22.22.22/24 secondary")
sw1("no ipv6 address 22:22::22/64 secondary")
sw1("no ip address 2.2.2.2/24")
sw1("no ipv6 address 2:2::2/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
rib_ipv4_vlan_connected_route_primary = dict()
rib_ipv4_vlan_connected_route_primary['Route'] = '2.2.2.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
fib_ipv4_vlan_connected_route_primary = rib_ipv4_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
rib_ipv4_vlan_connected_route_secondary = dict()
rib_ipv4_vlan_connected_route_secondary['Route'] = '22.22.22.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
fib_ipv4_vlan_connected_route_secondary = rib_ipv4_vlan_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
rib_ipv6_vlan_connected_route_primary = dict()
rib_ipv6_vlan_connected_route_primary['Route'] = '2:2::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
fib_ipv6_vlan_connected_route_primary = rib_ipv6_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
rib_ipv6_vlan_connected_route_secondary = dict()
rib_ipv6_vlan_connected_route_secondary['Route'] = '22:22::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
fib_ipv6_vlan_connected_route_secondary = rib_ipv6_vlan_connected_route_secondary
# Do not change the configuration for the L3 sub-interface
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
rib_ipv4_subinterface_connected_route_primary = dict()
rib_ipv4_subinterface_connected_route_primary['Route'] = '3.3.3.0/24'
rib_ipv4_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv4_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
fib_ipv4_subinterface_connected_route_primary = rib_ipv4_subinterface_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
rib_ipv6_subinterface_connected_route_primary = dict()
rib_ipv6_subinterface_connected_route_primary['Route'] = '3:3::/64'
rib_ipv6_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv6_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_subinterface_connected_route_primary = rib_ipv6_subinterface_connected_route_primary
# Change the IPv4 and IPv6 addresses on the loopback interface
sw1("configure terminal")
sw1("interface loopback 1")
sw1("ip address 6.6.6.6/24")
sw1("ipv6 address 6:6::6/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
rib_ipv4_loopback_connected_route_primary = dict()
rib_ipv4_loopback_connected_route_primary['Route'] = '6.6.6.0/24'
rib_ipv4_loopback_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_loopback_connected_route_primary['loopback1'] = dict()
rib_ipv4_loopback_connected_route_primary['loopback1']['Distance'] = '0'
rib_ipv4_loopback_connected_route_primary['loopback1']['Metric'] = '0'
rib_ipv4_loopback_connected_route_primary['loopback1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
fib_ipv4_loopback_connected_route_primary = rib_ipv4_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for loopback primary address and its next-hops.
rib_ipv6_loopback_connected_route_primary = dict()
rib_ipv6_loopback_connected_route_primary['Route'] = '6:6::/64'
rib_ipv6_loopback_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_loopback_connected_route_primary['loopback1'] = dict()
rib_ipv6_loopback_connected_route_primary['loopback1']['Distance'] = '0'
rib_ipv6_loopback_connected_route_primary['loopback1']['Metric'] = '0'
rib_ipv6_loopback_connected_route_primary['loopback1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for loopback primary address and its next-hops.
fib_ipv6_loopback_connected_route_primary = rib_ipv6_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for old loopback primary address and its next-hops.
rib_ipv4_old_loopback_connected_route_primary = dict()
rib_ipv4_old_loopback_connected_route_primary['Route'] = '4.4.4.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for old loopback primary address and its next-hops.
fib_ipv4_old_loopback_connected_route_primary = rib_ipv4_old_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for old loopback primary address and its next-hops.
rib_ipv6_old_loopback_connected_route_primary = dict()
rib_ipv6_old_loopback_connected_route_primary['Route'] = '4:4::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for old loopback primary address and its next-hops.
fib_ipv6_old_loopback_connected_route_primary = rib_ipv6_old_loopback_connected_route_primary
# Add more secondary IPv4 and IPv6 addresses on the L3 LAG interface
sw1("configure terminal")
sw1("interface lag 100")
sw1("ip address 77.77.77.77/24 secondary")
sw1("ipv6 address 77:77::77/64 secondary")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
rib_ipv4_lag_connected_route_primary = dict()
rib_ipv4_lag_connected_route_primary['Route'] = '5.5.5.0/24'
rib_ipv4_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_primary['lag100'] = dict()
rib_ipv4_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
fib_ipv4_lag_connected_route_primary = rib_ipv4_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for first LAG secondary address and its next-hops.
rib_ipv4_first_lag_connected_route_secondary = dict()
rib_ipv4_first_lag_connected_route_secondary['Route'] = '55.55.55.0/24'
rib_ipv4_first_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_first_lag_connected_route_secondary['lag100'] = dict()
rib_ipv4_first_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv4_first_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv4_first_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for first LAG secondary address and its next-hops.
fib_ipv4_first_lag_connected_route_secondary = rib_ipv4_first_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for second LAG secondary address and its next-hops.
rib_ipv4_second_lag_connected_route_secondary = dict()
rib_ipv4_second_lag_connected_route_secondary['Route'] = '77.77.77.0/24'
rib_ipv4_second_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_second_lag_connected_route_secondary['lag100'] = dict()
rib_ipv4_second_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv4_second_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv4_second_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for second LAG secondary address and its next-hops.
fib_ipv4_second_lag_connected_route_secondary = rib_ipv4_second_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
rib_ipv6_lag_connected_route_primary = dict()
rib_ipv6_lag_connected_route_primary['Route'] = '5:5::/64'
rib_ipv6_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_primary['lag100'] = dict()
rib_ipv6_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
fib_ipv6_lag_connected_route_primary = rib_ipv6_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for first LAG secondary address and its next-hops.
rib_ipv6_first_lag_connected_route_secondary = dict()
rib_ipv6_first_lag_connected_route_secondary['Route'] = '55:55::/64'
rib_ipv6_first_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_first_lag_connected_route_secondary['lag100'] = dict()
rib_ipv6_first_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv6_first_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv6_first_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for first LAG secndary address and its next-hops.
fib_ipv6_first_lag_connected_route_secondary = rib_ipv6_first_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for second LAG secondary address and its next-hops.
rib_ipv6_second_lag_connected_route_secondary = dict()
rib_ipv6_second_lag_connected_route_secondary['Route'] = '77:77::/64'
rib_ipv6_second_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_second_lag_connected_route_secondary['lag100'] = dict()
rib_ipv6_second_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv6_second_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv6_second_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for second LAG secndary address and its next-hops.
fib_ipv6_second_lag_connected_route_secondary = rib_ipv6_second_lag_connected_route_secondary
step("Starting the ops-zebra process on switch 1")
# Start ops-zebra process on sw1
sw1(zebra_start_command_string, shell='bash')
sleep(ZEBRA_TEST_SLEEP_TIME)
step("Verifying the IPv4/IPv6 connected routes on switch 1")
# Verify IPv4 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_primary)
aux_route = rib_ipv4_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_layer3_connected_route_primary)
# Verify IPv4 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_secondary)
aux_route = rib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_layer3_connected_route_secondary)
# Verify IPv6 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_primary)
aux_route = rib_ipv6_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_layer3_connected_route_primary)
# Verify IPv6 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_secondary)
aux_route = rib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_layer3_connected_route_secondary)
# Verify IPv4 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_primary)
aux_route = rib_ipv4_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_vlan_connected_route_primary)
# Verify IPv4 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_secondary)
aux_route = rib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_vlan_connected_route_secondary)
# Verify IPv6 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_primary)
aux_route = rib_ipv6_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_vlan_connected_route_primary)
# Verify IPv6 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_secondary)
aux_route = rib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_vlan_connected_route_secondary)
# Verify IPv4 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_subinterface_connected_route_primary)
aux_route = rib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_subinterface_connected_route_primary)
# Verify IPv6 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_subinterface_connected_route_primary)
aux_route = rib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_subinterface_connected_route_primary)
# Verify IPv4 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_loopback_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_loopback_connected_route_primary)
aux_route = rib_ipv4_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_loopback_connected_route_primary)
# Verify IPv6 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_loopback_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_loopback_connected_route_primary)
aux_route = rib_ipv6_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_loopback_connected_route_primary)
# Verify IPv4 route for old loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_old_loopback_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_old_loopback_connected_route_primary)
aux_route = rib_ipv4_old_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_old_loopback_connected_route_primary)
# Verify IPv6 route for old loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_old_loopback_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_old_loopback_connected_route_primary)
aux_route = rib_ipv6_old_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_old_loopback_connected_route_primary)
# Verify IPv4 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_primary)
aux_route = rib_ipv4_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_lag_connected_route_primary)
# Verify IPv4 route for first LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_first_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_first_lag_connected_route_secondary)
aux_route = rib_ipv4_first_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_first_lag_connected_route_secondary)
# Verify IPv4 route for second LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_second_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_second_lag_connected_route_secondary)
aux_route = rib_ipv4_second_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_second_lag_connected_route_secondary)
# Verify IPv6 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_primary)
aux_route = rib_ipv6_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_lag_connected_route_primary)
# Verify IPv6 route for first LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_first_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_first_lag_connected_route_secondary)
aux_route = rib_ipv6_first_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_first_lag_connected_route_secondary)
# Verify IPv6 route for second LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_second_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_second_lag_connected_route_secondary)
aux_route = rib_ipv6_second_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_second_lag_connected_route_secondary)
# This test changes some L3 interface configuration after zebra has come up after
# restart. We test the connected routes using the output of
# "show ip/ipv6 route/show rib".
def change_layer3_interface_config_after_zebra_restart(sw1, sw2, step):
# Change configuration for Layer-3 interface by bringing up the interface
sw1("configure terminal")
sw1("interface 1")
sw1("no shutdown")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
rib_ipv4_layer3_connected_route_primary = dict()
rib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
rib_ipv4_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_primary['1'] = dict()
rib_ipv4_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
fib_ipv4_layer3_connected_route_primary = rib_ipv4_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 secondary address and its next-hops.
rib_ipv4_layer3_connected_route_secondary = dict()
rib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
rib_ipv4_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_layer3_connected_route_secondary['1'] = dict()
rib_ipv4_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv4_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 secndary address and its next-hops.
fib_ipv4_layer3_connected_route_secondary = rib_ipv4_layer3_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
rib_ipv6_layer3_connected_route_primary = dict()
rib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
rib_ipv6_layer3_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_primary['1'] = dict()
rib_ipv6_layer3_connected_route_primary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_primary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
fib_ipv6_layer3_connected_route_primary = rib_ipv6_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
rib_ipv6_layer3_connected_route_secondary = dict()
rib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
rib_ipv6_layer3_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_layer3_connected_route_secondary['1'] = dict()
rib_ipv6_layer3_connected_route_secondary['1']['Distance'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['Metric'] = '0'
rib_ipv6_layer3_connected_route_secondary['1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
fib_ipv6_layer3_connected_route_secondary = rib_ipv6_layer3_connected_route_secondary
# Reconfigure the IPv4 and IPv6 addresses on the Vlan interface
sw1("configure terminal")
sw1("interface vlan 100")
sw1("ip address 2.2.2.2/24")
sw1("ipv6 address 2:2::2/64")
sw1("ip address 22.22.22.22/24 secondary")
sw1("ipv6 address 22:22::22/64 secondary")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
rib_ipv4_vlan_connected_route_primary = dict()
rib_ipv4_vlan_connected_route_primary['Route'] = '2.2.2.0/24'
rib_ipv4_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
fib_ipv4_vlan_connected_route_primary = rib_ipv4_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
rib_ipv4_vlan_connected_route_secondary = dict()
rib_ipv4_vlan_connected_route_secondary['Route'] = '22.22.22.0/24'
rib_ipv4_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv4_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv4_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
fib_ipv4_vlan_connected_route_secondary = rib_ipv4_vlan_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
rib_ipv6_vlan_connected_route_primary = dict()
rib_ipv6_vlan_connected_route_primary['Route'] = '2:2::/64'
rib_ipv6_vlan_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_primary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_primary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_primary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
fib_ipv6_vlan_connected_route_primary = rib_ipv6_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
rib_ipv6_vlan_connected_route_secondary = dict()
rib_ipv6_vlan_connected_route_secondary['Route'] = '22:22::/64'
rib_ipv6_vlan_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_vlan_connected_route_secondary['vlan100'] = dict()
rib_ipv6_vlan_connected_route_secondary['vlan100']['Distance'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['Metric'] = '0'
rib_ipv6_vlan_connected_route_secondary['vlan100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
fib_ipv6_vlan_connected_route_secondary = rib_ipv6_vlan_connected_route_secondary
# Do not change the L3 configure on the L3 sub-interface
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
rib_ipv4_subinterface_connected_route_primary = dict()
rib_ipv4_subinterface_connected_route_primary['Route'] = '3.3.3.0/24'
rib_ipv4_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv4_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv4_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
fib_ipv4_subinterface_connected_route_primary = rib_ipv4_subinterface_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
rib_ipv6_subinterface_connected_route_primary = dict()
rib_ipv6_subinterface_connected_route_primary['Route'] = '3:3::/64'
rib_ipv6_subinterface_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_subinterface_connected_route_primary['3.1'] = dict()
rib_ipv6_subinterface_connected_route_primary['3.1']['Distance'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['Metric'] = '0'
rib_ipv6_subinterface_connected_route_primary['3.1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_subinterface_connected_route_primary = rib_ipv6_subinterface_connected_route_primary
# Change back the IPv4 and IPv6 addresses on the loopback interface
sw1("configure terminal")
sw1("interface loopback 1")
sw1("ip address 4.4.4.6/24")
sw1("ipv6 address 4:4::4/64")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
rib_ipv4_loopback_connected_route_primary = dict()
rib_ipv4_loopback_connected_route_primary['Route'] = '4.4.4.0/24'
rib_ipv4_loopback_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_loopback_connected_route_primary['loopback1'] = dict()
rib_ipv4_loopback_connected_route_primary['loopback1']['Distance'] = '0'
rib_ipv4_loopback_connected_route_primary['loopback1']['Metric'] = '0'
rib_ipv4_loopback_connected_route_primary['loopback1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
fib_ipv4_loopback_connected_route_primary = rib_ipv4_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for loopback primary address and its next-hops.
rib_ipv6_loopback_connected_route_primary = dict()
rib_ipv6_loopback_connected_route_primary['Route'] = '4:4::/64'
rib_ipv6_loopback_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_loopback_connected_route_primary['loopback1'] = dict()
rib_ipv6_loopback_connected_route_primary['loopback1']['Distance'] = '0'
rib_ipv6_loopback_connected_route_primary['loopback1']['Metric'] = '0'
rib_ipv6_loopback_connected_route_primary['loopback1']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for loopback primary address and its next-hops.
fib_ipv6_loopback_connected_route_primary = rib_ipv6_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for old loopback primary address and its next-hops.
rib_ipv4_old_loopback_connected_route_primary = dict()
rib_ipv4_old_loopback_connected_route_primary['Route'] = '6.6.6.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for old loopback primary address and its next-hops.
fib_ipv4_old_loopback_connected_route_primary = rib_ipv4_old_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for old loopback primary address and its next-hops.
rib_ipv6_old_loopback_connected_route_primary = dict()
rib_ipv6_old_loopback_connected_route_primary['Route'] = '6:6::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for old loopback primary address and its next-hops.
fib_ipv6_old_loopback_connected_route_primary = rib_ipv6_old_loopback_connected_route_primary
# Delete the second secondary IPv4 and IPv6 addresses on the L3 LAG interface
sw1("configure terminal")
sw1("interface lag 100")
sw1("no ip address 77.77.77.77/24 secondary")
sw1("no ipv6 address 77:77::77/64 secondary")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
rib_ipv4_lag_connected_route_primary = dict()
rib_ipv4_lag_connected_route_primary['Route'] = '5.5.5.0/24'
rib_ipv4_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv4_lag_connected_route_primary['lag100'] = dict()
rib_ipv4_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv4_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
fib_ipv4_lag_connected_route_primary = rib_ipv4_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for first LAG secondary address and its next-hops.
rib_ipv4_first_lag_connected_route_secondary = dict()
rib_ipv4_first_lag_connected_route_secondary['Route'] = '55.55.55.0/24'
rib_ipv4_first_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv4_first_lag_connected_route_secondary['lag100'] = dict()
rib_ipv4_first_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv4_first_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv4_first_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for first LAG secondary address and its next-hops.
fib_ipv4_first_lag_connected_route_secondary = rib_ipv4_first_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for second LAG secondary address and its next-hops.
rib_ipv4_second_lag_connected_route_secondary = dict()
rib_ipv4_second_lag_connected_route_secondary['Route'] = '77.77.77.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for second LAG secondary address and its next-hops.
fib_ipv4_second_lag_connected_route_secondary = rib_ipv4_second_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
rib_ipv6_lag_connected_route_primary = dict()
rib_ipv6_lag_connected_route_primary['Route'] = '5:5::/64'
rib_ipv6_lag_connected_route_primary['NumberNexthops'] = '1'
rib_ipv6_lag_connected_route_primary['lag100'] = dict()
rib_ipv6_lag_connected_route_primary['lag100']['Distance'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['Metric'] = '0'
rib_ipv6_lag_connected_route_primary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
fib_ipv6_lag_connected_route_primary = rib_ipv6_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for first LAG secondary address and its next-hops.
rib_ipv6_first_lag_connected_route_secondary = dict()
rib_ipv6_first_lag_connected_route_secondary['Route'] = '55:55::/64'
rib_ipv6_first_lag_connected_route_secondary['NumberNexthops'] = '1'
rib_ipv6_first_lag_connected_route_secondary['lag100'] = dict()
rib_ipv6_first_lag_connected_route_secondary['lag100']['Distance'] = '0'
rib_ipv6_first_lag_connected_route_secondary['lag100']['Metric'] = '0'
rib_ipv6_first_lag_connected_route_secondary['lag100']['RouteType'] = 'connected'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for first LAG secndary address and its next-hops.
fib_ipv6_first_lag_connected_route_secondary = rib_ipv6_first_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for second LAG secondary address and its next-hops.
rib_ipv6_second_lag_connected_route_secondary = dict()
rib_ipv6_second_lag_connected_route_secondary['Route'] = '77:77::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for second LAG secndary address and its next-hops.
fib_ipv6_second_lag_connected_route_secondary = rib_ipv6_second_lag_connected_route_secondary
sleep(ZEBRA_TEST_SLEEP_TIME)
step("Verifying the IPv4/IPv6 connected routes on switch 1")
# Verify IPv4 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_primary)
aux_route = rib_ipv4_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_layer3_connected_route_primary)
# Verify IPv4 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_secondary)
aux_route = rib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_layer3_connected_route_secondary)
# Verify IPv6 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_primary)
aux_route = rib_ipv6_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_layer3_connected_route_primary)
# Verify IPv6 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_secondary)
aux_route = rib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_layer3_connected_route_secondary)
# Verify IPv4 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_primary)
aux_route = rib_ipv4_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_vlan_connected_route_primary)
# Verify IPv4 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_secondary)
aux_route = rib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_vlan_connected_route_secondary)
# Verify IPv6 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_primary)
aux_route = rib_ipv6_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_vlan_connected_route_primary)
# Verify IPv6 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_secondary)
aux_route = rib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_vlan_connected_route_secondary)
# Verify IPv4 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_subinterface_connected_route_primary)
aux_route = rib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_subinterface_connected_route_primary)
# Verify IPv6 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_subinterface_connected_route_primary)
aux_route = rib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_subinterface_connected_route_primary)
# Verify IPv4 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_loopback_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_loopback_connected_route_primary)
aux_route = rib_ipv4_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_loopback_connected_route_primary)
# Verify IPv6 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_loopback_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_loopback_connected_route_primary)
aux_route = rib_ipv6_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_loopback_connected_route_primary)
# Verify IPv4 route for old loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_old_loopback_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_old_loopback_connected_route_primary)
aux_route = rib_ipv4_old_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_old_loopback_connected_route_primary)
# Verify IPv6 route for old loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_old_loopback_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_old_loopback_connected_route_primary)
aux_route = rib_ipv6_old_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_old_loopback_connected_route_primary)
# Verify IPv4 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_primary)
aux_route = rib_ipv4_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_lag_connected_route_primary)
# Verify IPv4 route for first LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_first_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_first_lag_connected_route_secondary)
aux_route = rib_ipv4_first_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_first_lag_connected_route_secondary)
# Verify IPv4 route for second LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_second_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_second_lag_connected_route_secondary)
aux_route = rib_ipv4_second_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_second_lag_connected_route_secondary)
# Verify IPv6 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_primary)
aux_route = rib_ipv6_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_lag_connected_route_primary)
# Verify IPv6 route for first LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_first_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_first_lag_connected_route_secondary)
aux_route = rib_ipv6_first_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_first_lag_connected_route_secondary)
# Verify IPv6 route for second LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_second_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_second_lag_connected_route_secondary)
aux_route = rib_ipv6_second_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_second_lag_connected_route_secondary)
# This test does "no routing/no interface" triggers in L3 interfaces and check
# if the corresponding connected routes have been cleaned-up from FIB and RIB by
# looking into the output of "show ip/ipv6 route/show rib".
def no_routing_or_delete_layer3_interfaces(sw1, sw2, step):
# Do "no routing" in layer-3 interface
sw1("configure terminal")
sw1("interface 1")
sw1("no routing")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
rib_ipv4_layer3_connected_route_primary = dict()
rib_ipv4_layer3_connected_route_primary['Route'] = '1.1.1.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 primary address and its next-hops.
fib_ipv4_layer3_connected_route_primary = rib_ipv4_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for layer-3 secondary address and its next-hops.
rib_ipv4_layer3_connected_route_secondary = dict()
rib_ipv4_layer3_connected_route_secondary['Route'] = '11.11.11.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for layer-3 secndary address and its next-hops.
fib_ipv4_layer3_connected_route_secondary = rib_ipv4_layer3_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
rib_ipv6_layer3_connected_route_primary = dict()
rib_ipv6_layer3_connected_route_primary['Route'] = '1:1::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 primary address and its next-hops.
fib_ipv6_layer3_connected_route_primary = rib_ipv6_layer3_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
rib_ipv6_layer3_connected_route_secondary = dict()
rib_ipv6_layer3_connected_route_secondary['Route'] = '11:11::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for layer-3 secondary address and its next-hops.
fib_ipv6_layer3_connected_route_secondary = rib_ipv6_layer3_connected_route_secondary
# Un-configure the vlan interface
sw1("configure terminal")
sw1("no interface vlan 100")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
rib_ipv4_vlan_connected_route_primary = dict()
rib_ipv4_vlan_connected_route_primary['Route'] = '2.2.2.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan primary address and its next-hops.
fib_ipv4_vlan_connected_route_primary = rib_ipv4_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
rib_ipv4_vlan_connected_route_secondary = dict()
rib_ipv4_vlan_connected_route_secondary['Route'] = '22.22.22.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for vlan secondary address and its next-hops.
fib_ipv4_vlan_connected_route_secondary = rib_ipv4_vlan_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
rib_ipv6_vlan_connected_route_primary = dict()
rib_ipv6_vlan_connected_route_primary['Route'] = '2:2::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan primary address and its next-hops.
fib_ipv6_vlan_connected_route_primary = rib_ipv6_vlan_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
rib_ipv6_vlan_connected_route_secondary = dict()
rib_ipv6_vlan_connected_route_secondary['Route'] = '22:22::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for vlan secondary address and its next-hops.
fib_ipv6_vlan_connected_route_secondary = rib_ipv6_vlan_connected_route_secondary
# Do "no routing" in the parent interface for the L3 sub-interface.
sw1("configure terminal")
sw1("interface 3")
sw1("no routing")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
rib_ipv4_subinterface_connected_route_primary = dict()
rib_ipv4_subinterface_connected_route_primary['Route'] = '3.3.3.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for sub-interface primary address and its next-hops.
fib_ipv4_subinterface_connected_route_primary = rib_ipv4_subinterface_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
rib_ipv6_subinterface_connected_route_primary = dict()
rib_ipv6_subinterface_connected_route_primary['Route'] = '3:3::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_subinterface_connected_route_primary = rib_ipv6_subinterface_connected_route_primary
# Un-configure the loopback interface to remove the loopback interface
sw1("configure terminal")
sw1("no interface loopback 1")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
rib_ipv4_loopback_connected_route_primary = dict()
rib_ipv4_loopback_connected_route_primary['Route'] = '4.4.4.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for loopback primary address and its next-hops.
fib_ipv4_loopback_connected_route_primary = rib_ipv4_loopback_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for loopback primary address and its next-hops.
rib_ipv6_loopback_connected_route_primary = dict()
rib_ipv6_loopback_connected_route_primary['Route'] = '4:4::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for sub-interface primary address and its next-hops.
fib_ipv6_loopback_connected_route_primary = rib_ipv6_loopback_connected_route_primary
# Do "no routing" in the L3 lag interface addresses
sw1("configure terminal")
sw1("interface lag 100")
sw1("no routing")
sw1("exit")
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
rib_ipv4_lag_connected_route_primary = dict()
rib_ipv4_lag_connected_route_primary['Route'] = '5.5.5.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG primary address and its next-hops.
fib_ipv4_lag_connected_route_primary = rib_ipv4_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
rib_ipv4_lag_connected_route_secondary = dict()
rib_ipv4_lag_connected_route_secondary['Route'] = '55.55.55.0/24'
# Populate the expected RIB ("show ip route") route dictionary for the connected
# IPv4 route for LAG secondary address and its next-hops.
fib_ipv4_lag_connected_route_secondary = rib_ipv4_lag_connected_route_secondary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
rib_ipv6_lag_connected_route_primary = dict()
rib_ipv6_lag_connected_route_primary['Route'] = '5:5::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG primary address and its next-hops.
fib_ipv6_lag_connected_route_primary = rib_ipv6_lag_connected_route_primary
# Populate the expected RIB ("show rib") route dictionary for the connected
# IPv6 route for LAG secondary address and its next-hops.
rib_ipv6_lag_connected_route_secondary = dict()
rib_ipv6_lag_connected_route_secondary['Route'] = '55:55::/64'
# Populate the expected RIB ("show ipv6 route") route dictionary for the connected
# IPv6 route for LAG secndary address and its next-hops.
fib_ipv6_lag_connected_route_secondary = rib_ipv6_lag_connected_route_secondary
sleep(ZEBRA_TEST_SLEEP_TIME)
step("Verifying the IPv4/IPv6 connected routes on switch 1")
# Verify IPv4 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_primary)
aux_route = rib_ipv4_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_layer3_connected_route_primary)
# Verify IPv4 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_layer3_connected_route_secondary)
aux_route = rib_ipv4_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_layer3_connected_route_secondary)
# Verify IPv6 route for layer-3 primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_primary)
aux_route = rib_ipv6_layer3_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_layer3_connected_route_primary)
# Verify IPv6 route for layer-3 secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_layer3_connected_route_secondary)
aux_route = rib_ipv6_layer3_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_layer3_connected_route_secondary)
# Verify IPv4 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_primary)
aux_route = rib_ipv4_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_vlan_connected_route_primary)
# Verify IPv4 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_vlan_connected_route_secondary)
aux_route = rib_ipv4_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_vlan_connected_route_secondary)
# Verify IPv6 route for vlan primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_primary)
aux_route = rib_ipv6_vlan_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_vlan_connected_route_primary)
# Verify IPv6 route for vlan secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_vlan_connected_route_secondary)
aux_route = rib_ipv6_vlan_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_vlan_connected_route_secondary)
# Verify IPv4 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_subinterface_connected_route_primary)
aux_route = rib_ipv4_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_subinterface_connected_route_primary)
# Verify IPv6 route for L3-subinterface primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_subinterface_connected_route_primary)
aux_route = rib_ipv6_subinterface_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_subinterface_connected_route_primary)
# Verify IPv4 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_loopback_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_loopback_connected_route_primary)
aux_route = rib_ipv4_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_loopback_connected_route_primary)
# Verify IPv6 route for loopback primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_loopback_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_loopback_connected_route_primary)
aux_route = rib_ipv6_loopback_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_loopback_connected_route_primary)
# Verify IPv4 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_primary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_primary)
aux_route = rib_ipv4_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv4_lag_connected_route_primary)
# Verify IPv4 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv4_lag_connected_route_secondary["Route"]
verify_show_ip_route(sw1, aux_route, 'connected',
fib_ipv4_lag_connected_route_secondary)
aux_route = rib_ipv4_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv4_lag_connected_route_secondary)
# Verify IPv6 route for LAG primary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_primary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_primary)
aux_route = rib_ipv6_lag_connected_route_primary["Route"]
verify_show_rib(sw1, aux_route, 'connected', rib_ipv6_lag_connected_route_primary)
# Verify IPv6 route for LAG secondary address and next-hops in RIB and FIB
aux_route = fib_ipv6_lag_connected_route_secondary["Route"]
verify_show_ipv6_route(sw1, aux_route, 'connected',
fib_ipv6_lag_connected_route_secondary)
aux_route = rib_ipv6_lag_connected_route_secondary["Route"]
verify_show_rib(sw1, aux_route, 'connected',
rib_ipv6_lag_connected_route_secondary)
def test_zebra_ct_connected_routes(topology, step):
sw1 = topology.get("sw1")
sw2 = topology.get("sw2")
assert sw1 is not None
assert sw2 is not None
# Test case init time sleep
sleep(ZEBRA_INIT_SLEEP_TIME)
configure_layer3_interfaces(sw1, sw2, step)
shutdown_layer3_interfaces(sw1, sw2, step)
no_shutdown_layer3_interfaces(sw1, sw2, step)
remove_addresses_from_layer3_interfaces(sw1, sw2, step)
reconfigure_addresses_on_layer3_interfaces(sw1, sw2, step)
restart_zebra_with_config_change_for_layer3_interfaces(sw1, sw2, step)
change_layer3_interface_config_after_zebra_restart(sw1, sw2, step)
no_routing_or_delete_layer3_interfaces(sw1, sw2, step)
| gpl-2.0 | -6,156,353,884,264,763,000 | 53.774968 | 97 | 0.698571 | false |
hstau/manifold-cryo | get_fit_1D_open_manifold_3D_param.py | 1 | 2346 | import numpy as np
import solve_d_R_d_tau_p_3D
import a
def op(psi):
#psi = -psi
#global psi, x, a, b
#global maxIter,delta_a_max, delta_b_max,delta_tau_max,a_b_tau_result
a.maxIter = 100 # % maximum number of iterations, each iteration determines
#% optimum sets of {a,b} and {\tau} in turns
a.delta_a_max = 1 # % maximum percentage change in amplitudes
a.delta_b_max = 1 #% maximum percentage change in offsets
a.delta_tau_max = 0.01 #% maximum change in values of tau
a.a_b_tau_result = 'a_b_tau_result.pkl' #% save final results here
nS = psi.shape[0]
a.x = psi[:,0:3]
#% (1) initial guesses for {a,b} obtained by fitting data in 2D
#% (2) initial guesses for {tau} obtained by setting d(R)/d(tau) to zero
X = psi[:,0]
Z = psi[:,2]
X2 = X*X
X3 = X2*X
X4 = X2*X2
X5 = X3*X2
X6 = X3*X3
sumX = np.sum(X)
sumX2 = np.sum(X2)
sumX3 = np.sum(X3)
sumX4 = np.sum(X4)
sumX5 = np.sum(X5)
sumX6 = np.sum(X6)
sumZ = np.sum(Z)
sumXZ = np.dot(X.T,Z)
sumX2Z = np.dot(X2.T,Z)
sumX3Z = np.dot(X3.T,Z)
A = np.array([[sumX6, sumX5, sumX4, sumX3],
[sumX5, sumX4, sumX3, sumX2],
[sumX4, sumX3, sumX2, sumX],
[sumX3, sumX2, sumX, nS ]])
b = np.array([sumX3Z, sumX2Z, sumXZ, sumZ])
coeff = np.linalg.solve(A, b)
D = coeff[0]
E = coeff[1]
F = coeff[2]
G = coeff[3]
disc = np.dot(E,E)-3*np.dot(D,F)
a1 = (2.*np.sqrt(disc))/(3.*D)
a3 = (2.*disc**(3/2.))/(27.*D*D)
b1 = -E/(3*D)
b3 = (2.*E*E*E)/(27.*D*D)-(E*F)/(3*D) + G
Xb = X-2*b1
Y = psi[:,1]
XXb = X*Xb
X2Xb2 = XXb*XXb
sumXXb = np.sum(XXb)
sumX2Xb2 = np.sum(X2Xb2)
sumY = np.sum(Y)
sumXXbY = np.dot(XXb.T,Y)
A = np.array([[sumX2Xb2, sumXXb],[sumXXb, nS]])
b = np.array([sumXXbY, sumY])
coeff = np.linalg.solve(A,b)
A = coeff[0]
C = coeff[1]
a2 = 2.*A*disc/(9.*D*D)
b2 = C+(A*E*E)/(9.*D*D)-(2.*A*F)/(3.*D)
a.a = np.array([a1, a2, a3])
a.b = np.array([b1, b2, b3])
tau = np.zeros((nS,1))
for a.p in xrange(nS):
tau[a.p],beta = solve_d_R_d_tau_p_3D.op() #added
return tau
| gpl-2.0 | 1,708,977,163,319,388,700 | 27.325 | 85 | 0.501279 | false |
nocko/cfmi | cfmi/scheduling/models.py | 1 | 3246 | from datetime import timedelta, datetime
from cfmi.database.newsite import Session, Interval
from cfmi.utils import sessions_by_date
from flask import current_app
from sqlalchemy import (and_, or_, not_)
def merge_date_time(date, time):
return(datetime(date.year, date.month, date.day, time.hour, time.minute, time.second))
class ScheduleSegment:
def __init__(self, start_dt, end=None):
self.end = start_dt+timedelta(minutes=15) if not end else end
self.start_dt = start_dt
self.end = end
def __repr__(self):
return "{}".format(self.start_dt)
class ScheduleDay:
def __init__(self, date):
self.exceptions = Interval.query.filter(Interval.date==date)
self.date = date
self.scans = sessions_by_date(date)
# Set the open and close time from the defaults in the config
# file
self.open, self.close = current_app.config['DAY_TEMPLATES']\
[date.strftime('%A')]
# One class of exception is opening before normal, or closing
# later. If the open time is before normal open or close time
# after normal day end, we need to update the schedule.
for exp in self.exceptions.filter(or_(
Interval.open<self.open,
Interval.close>self.close)):
self.open = exp.open if exp.open < self.open else self.open
self.close = exp.close if exp.close > self.close else self.close
# Remove this class of exceptions from further consideration,
# any remaining exceptions should be holes in coverage
self.exceptions = self.exceptions.filter(not_(or_(
Interval.open<=self.open,
Interval.close>=self.close)))
def _interval_conflict(self, start_dt, stop_dt):
start_time = start_dt.time
stop_time = stop_dt.time
if self.exceptions.filter(
or_(Interval.close < start_time,
Interval.open > stop_time)).count():
return True
return False
def _session_conflict(self, start_dt, stop_dt):
if self.scans.filter(or_(
and_(start_dt >= Session.sched_start,
start_dt < Session.sched_end),
and_(stop_dt <= Session.sched_end,
stop_dt > Session.sched_start))).count():
return True
return False
def conflict(self, start_dt, stop_dt):
return self._session_conflict(start_dt, stop_dt) or self._interval_conflict(start_dt, stop_dt)
@property
def segments(self):
offset = 0
segments = []
open_dt = merge_date_time(self.date, self.open)
close_dt = merge_date_time(self.date, self.close)
while offset * timedelta(minutes=15) + open_dt <= close_dt:
seg_start = offset * timedelta(minutes=15) + open_dt
seg_end = seg_start+timedelta(minutes=15)
if not self.conflict(seg_start, seg_end):
segments.append(
ScheduleSegment(
seg_start,
open_dt + offset*timedelta(minutes=15)))
offset += 1
return segments
| bsd-3-clause | -4,234,959,028,177,617,000 | 35.886364 | 102 | 0.585952 | false |
douglaz/ignition-core | tools/spark-ec2/spark_ec2.py | 1 | 52113 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import with_statement
import hashlib
import logging
import os
import os.path
import pipes
import random
import shutil
import string
from stat import S_IRUSR
import subprocess
import sys
import tarfile
import tempfile
import textwrap
import time
import urllib2
import warnings
from datetime import datetime
from optparse import OptionParser
from sys import stderr
SPARK_EC2_VERSION = "1.3.0"
SPARK_EC2_DIR = os.path.dirname(os.path.realpath(__file__))
VALID_SPARK_VERSIONS = set([
"0.7.3",
"0.8.0",
"0.8.1",
"0.9.0",
"0.9.1",
"0.9.2",
"1.0.0",
"1.0.1",
"1.0.2",
"1.1.0",
"1.1.1",
"1.2.0",
"1.2.1",
"1.3.0",
])
DEFAULT_SPARK_VERSION = SPARK_EC2_VERSION
DEFAULT_SPARK_GITHUB_REPO = "https://github.com/apache/spark"
# Default location to get the spark-ec2 scripts (and ami-list) from
DEFAULT_SPARK_EC2_GITHUB_REPO = "https://github.com/mesos/spark-ec2"
DEFAULT_SPARK_EC2_BRANCH = "branch-1.3"
import boto
from boto.ec2.blockdevicemapping import BlockDeviceMapping, BlockDeviceType, EBSBlockDeviceType
from boto import ec2
class UsageError(Exception):
pass
# Configure and parse our command-line arguments
def parse_args():
parser = OptionParser(
prog="spark-ec2",
version="%prog {v}".format(v=SPARK_EC2_VERSION),
usage="%prog [options] <action> <cluster_name>\n\n"
+ "<action> can be: launch, destroy, login, stop, start, get-master, reboot-slaves")
parser.add_option(
"-s", "--slaves", type="int", default=1,
help="Number of slaves to launch (default: %default)")
parser.add_option(
"-w", "--wait", type="int",
help="DEPRECATED (no longer necessary) - Seconds to wait for nodes to start")
parser.add_option(
"-k", "--key-pair",
help="Key pair to use on instances")
parser.add_option(
"-i", "--identity-file",
help="SSH private key file to use for logging into instances")
parser.add_option(
"-t", "--instance-type", default="m1.large",
help="Type of instance to launch (default: %default). " +
"WARNING: must be 64-bit; small instances won't work")
parser.add_option(
"-m", "--master-instance-type", default="",
help="Master instance type (leave empty for same as instance-type)")
parser.add_option(
"-r", "--region", default="us-east-1",
help="EC2 region zone to launch instances in")
parser.add_option(
"-z", "--zone", default="",
help="Availability zone to launch instances in, or 'all' to spread " +
"slaves across multiple (an additional $0.01/Gb for bandwidth" +
"between zones applies) (default: a single zone chosen at random)")
parser.add_option(
"-a", "--ami",
help="Amazon Machine Image ID to use")
parser.add_option("--master-ami",
help="Amazon Machine Image ID to use for the Master")
parser.add_option(
"-v", "--spark-version", default=DEFAULT_SPARK_VERSION,
help="Version of Spark to use: 'X.Y.Z' or a specific git hash (default: %default)")
parser.add_option(
"--spark-git-repo",
default=DEFAULT_SPARK_GITHUB_REPO,
help="Github repo from which to checkout supplied commit hash (default: %default)")
parser.add_option(
"--spark-ec2-git-repo",
default=DEFAULT_SPARK_EC2_GITHUB_REPO,
help="Github repo from which to checkout spark-ec2 (default: %default)")
parser.add_option(
"--spark-ec2-git-branch",
default=DEFAULT_SPARK_EC2_BRANCH,
help="Github repo branch of spark-ec2 to use (default: %default)")
parser.add_option(
"--hadoop-major-version", default="1",
help="Major version of Hadoop (default: %default)")
parser.add_option(
"-D", metavar="[ADDRESS:]PORT", dest="proxy_port",
help="Use SSH dynamic port forwarding to create a SOCKS proxy at " +
"the given local address (for use with login)")
parser.add_option(
"--resume", action="store_true", default=False,
help="Resume installation on a previously launched cluster " +
"(for debugging)")
parser.add_option(
"--ebs-vol-size", metavar="SIZE", type="int", default=0,
help="Size (in GB) of each EBS volume.")
parser.add_option(
"--ebs-vol-type", default="standard",
help="EBS volume type (e.g. 'gp2', 'standard').")
parser.add_option(
"--ebs-vol-num", type="int", default=1,
help="Number of EBS volumes to attach to each node as /vol[x]. " +
"The volumes will be deleted when the instances terminate. " +
"Only possible on EBS-backed AMIs. " +
"EBS volumes are only attached if --ebs-vol-size > 0." +
"Only support up to 8 EBS volumes.")
parser.add_option(
"--placement-group", type="string", default=None,
help="Which placement group to try and launch " +
"instances into. Assumes placement group is already " +
"created.")
parser.add_option(
"--swap", metavar="SWAP", type="int", default=1024,
help="Swap space to set up per node, in MB (default: %default)")
parser.add_option(
"--spot-price", metavar="PRICE", type="float",
help="If specified, launch slaves as spot instances with the given " +
"maximum price (in dollars)")
parser.add_option(
"--ganglia", action="store_true", default=True,
help="Setup Ganglia monitoring on cluster (default: %default). NOTE: " +
"the Ganglia page will be publicly accessible")
parser.add_option(
"--no-ganglia", action="store_false", dest="ganglia",
help="Disable Ganglia monitoring for the cluster")
parser.add_option(
"-u", "--user", default="root",
help="The SSH user you want to connect as (default: %default)")
parser.add_option(
"--delete-groups", action="store_true", default=False,
help="When destroying a cluster, delete the security groups that were created")
parser.add_option(
"--use-existing-master", action="store_true", default=False,
help="Launch fresh slaves, but use an existing stopped master if possible")
parser.add_option(
"--worker-instances", type="int", default=1,
help="Number of instances per worker: variable SPARK_WORKER_INSTANCES (default: %default)")
parser.add_option(
"--master-opts", type="string", default="",
help="Extra options to give to master through SPARK_MASTER_OPTS variable " +
"(e.g -Dspark.worker.timeout=180)")
parser.add_option(
"--user-data", type="string", default="",
help="Path to a user-data file (most AMI's interpret this as an initialization script)")
parser.add_option(
"--security-group-prefix", type="string", default=None,
help="Use this prefix for the security group rather than the cluster name.")
parser.add_option(
"--authorized-address", type="string", default="0.0.0.0/0",
help="Address to authorize on created security groups (default: %default)")
parser.add_option(
"--additional-security-group", type="string", default="",
help="Additional security group to place the machines in")
parser.add_option(
"--copy-aws-credentials", action="store_true", default=False,
help="Add AWS credentials to hadoop configuration to allow Spark to access S3")
parser.add_option(
"--subnet-id", default=None,
help="VPC subnet to launch instances in")
parser.add_option(
"--vpc-id", default=None,
help="VPC to launch instances in")
parser.add_option(
"--spot-timeout", type="int", default=45,
help="Maximum amount of time (in minutes) to wait for spot requests to be fulfilled")
(opts, args) = parser.parse_args()
if len(args) != 2:
parser.print_help()
sys.exit(1)
(action, cluster_name) = args
# Boto config check
# http://boto.cloudhackers.com/en/latest/boto_config_tut.html
home_dir = os.getenv('HOME')
if home_dir is None or not os.path.isfile(home_dir + '/.boto'):
if not os.path.isfile('/etc/boto.cfg'):
if os.getenv('AWS_ACCESS_KEY_ID') is None:
print >> stderr, ("ERROR: The environment variable AWS_ACCESS_KEY_ID " +
"must be set")
sys.exit(1)
if os.getenv('AWS_SECRET_ACCESS_KEY') is None:
print >> stderr, ("ERROR: The environment variable AWS_SECRET_ACCESS_KEY " +
"must be set")
sys.exit(1)
return (opts, action, cluster_name)
# Get the EC2 security group of the given name, creating it if it doesn't exist
def get_or_make_group(conn, name, vpc_id):
groups = conn.get_all_security_groups()
group = [g for g in groups if g.name == name]
if len(group) > 0:
return group[0]
else:
print "Creating security group " + name
return conn.create_security_group(name, "Spark EC2 group", vpc_id)
def check_if_http_resource_exists(resource):
request = urllib2.Request(resource)
request.get_method = lambda: 'HEAD'
try:
response = urllib2.urlopen(request)
if response.getcode() == 200:
return True
else:
raise RuntimeError("Resource {resource} not found. Error: {code}".format(resource, response.getcode()))
except urllib2.HTTPError, e:
print >> stderr, "Unable to check if HTTP resource {url} exists. Error: {code}".format(
url=resource,
code=e.code)
return False
def get_validate_spark_version(version, repo):
if version.startswith("http"):
#check if custom package URL exists
if check_if_http_resource_exists:
return version
else:
print >> stderr, "Unable to validate pre-built spark version {version}".format(version=version)
sys.exit(1)
elif "." in version:
version = version.replace("v", "")
if version not in VALID_SPARK_VERSIONS:
print >> stderr, "Don't know about Spark version: {v}".format(v=version)
sys.exit(1)
return version
else:
github_commit_url = "{repo}/commit/{commit_hash}".format(repo=repo, commit_hash=version)
if not check_if_http_resource_exists(github_commit_url):
print >> stderr, "Couldn't validate Spark commit: {repo} / {commit}".format(
repo=repo, commit=version)
sys.exit(1)
else:
return version
# Check whether a given EC2 instance object is in a state we consider active,
# i.e. not terminating or terminated. We count both stopping and stopped as
# active since we can restart stopped clusters.
def is_active(instance):
return (instance.state in ['pending', 'running', 'stopping', 'stopped'])
# Source: http://aws.amazon.com/amazon-linux-ami/instance-type-matrix/
# Last Updated: 2014-06-20
# For easy maintainability, please keep this manually-inputted dictionary sorted by key.
EC2_INSTANCE_TYPES = {
"c1.medium": "pvm",
"c1.xlarge": "pvm",
"c3.2xlarge": "pvm",
"c3.4xlarge": "pvm",
"c3.8xlarge": "pvm",
"c3.large": "pvm",
"c3.xlarge": "pvm",
"cc1.4xlarge": "hvm",
"cc2.8xlarge": "hvm",
"cg1.4xlarge": "hvm",
"cr1.8xlarge": "hvm",
"hi1.4xlarge": "pvm",
"hs1.8xlarge": "pvm",
"i2.2xlarge": "hvm",
"i2.4xlarge": "hvm",
"i2.8xlarge": "hvm",
"i2.xlarge": "hvm",
"m1.large": "pvm",
"m1.medium": "pvm",
"m1.small": "pvm",
"m1.xlarge": "pvm",
"m2.2xlarge": "pvm",
"m2.4xlarge": "pvm",
"m2.xlarge": "pvm",
"m3.2xlarge": "hvm",
"m3.large": "hvm",
"m3.medium": "hvm",
"m3.xlarge": "hvm",
"r3.2xlarge": "hvm",
"r3.4xlarge": "hvm",
"r3.8xlarge": "hvm",
"r3.large": "hvm",
"r3.xlarge": "hvm",
"t1.micro": "pvm",
"t2.medium": "hvm",
"t2.micro": "hvm",
"t2.small": "hvm",
"d2.2xlarge": "hvm",
"d2.4xlarge": "hvm",
"d2.8xlarge": "hvm",
"d2.large": "hvm",
"d2.xlarge": "hvm",
}
# Attempt to resolve an appropriate AMI given the architecture and region of the request.
def get_spark_ami(instance_type, region, spark_ec2_git_repo, spark_ec2_git_branch):
if instance_type in EC2_INSTANCE_TYPES:
instance_type = EC2_INSTANCE_TYPES[instance_type]
else:
instance_type = "pvm"
print >> stderr,\
"Don't recognize %s, assuming type is pvm" % instance_type
# URL prefix from which to fetch AMI information
ami_prefix = "{r}/{b}/ami-list".format(
r=spark_ec2_git_repo.replace("https://github.com", "https://raw.github.com", 1),
b=spark_ec2_git_branch)
ami_path = "%s/%s/%s" % (ami_prefix, region, instance_type)
try:
ami = urllib2.urlopen(ami_path).read().strip()
print "Spark AMI for %s: %s" % (instance_type, ami)
except:
print >> stderr, "Could not resolve AMI at: " + ami_path
sys.exit(1)
return ami
# Launch a cluster of the given name, by setting up its security groups,
# and then starting new instances in them.
# Returns a tuple of EC2 reservation objects for the master and slaves
# Fails if there already instances running in the cluster's groups.
def launch_cluster(conn, opts, cluster_name):
if opts.identity_file is None:
print >> stderr, "ERROR: Must provide an identity file (-i) for ssh connections."
sys.exit(1)
if opts.key_pair is None:
print >> stderr, "ERROR: Must provide a key pair name (-k) to use on instances."
sys.exit(1)
user_data_content = None
if opts.user_data:
with open(opts.user_data) as user_data_file:
user_data_content = user_data_file.read()
print "Setting up security groups..."
if opts.security_group_prefix is None:
master_group = get_or_make_group(conn, cluster_name + "-master", opts.vpc_id)
slave_group = get_or_make_group(conn, cluster_name + "-slaves", opts.vpc_id)
else:
master_group = get_or_make_group(conn, opts.security_group_prefix + "-master", opts.vpc_id)
slave_group = get_or_make_group(conn, opts.security_group_prefix + "-slaves", opts.vpc_id)
authorized_address = opts.authorized_address
if master_group.rules == []: # Group was just now created
if opts.vpc_id is None:
master_group.authorize(src_group=master_group)
master_group.authorize(src_group=slave_group)
else:
master_group.authorize(ip_protocol='icmp', from_port=-1, to_port=-1,
src_group=master_group)
master_group.authorize(ip_protocol='tcp', from_port=0, to_port=65535,
src_group=master_group)
master_group.authorize(ip_protocol='udp', from_port=0, to_port=65535,
src_group=master_group)
master_group.authorize(ip_protocol='icmp', from_port=-1, to_port=-1,
src_group=slave_group)
master_group.authorize(ip_protocol='tcp', from_port=0, to_port=65535,
src_group=slave_group)
master_group.authorize(ip_protocol='udp', from_port=0, to_port=65535,
src_group=slave_group)
master_group.authorize('tcp', 22, 22, authorized_address)
master_group.authorize('tcp', 8080, 8081, authorized_address)
master_group.authorize('tcp', 18080, 18080, authorized_address)
master_group.authorize('tcp', 19999, 19999, authorized_address)
master_group.authorize('tcp', 50030, 50030, authorized_address)
master_group.authorize('tcp', 50070, 50070, authorized_address)
master_group.authorize('tcp', 60070, 60070, authorized_address)
master_group.authorize('tcp', 4040, 4045, authorized_address)
if opts.ganglia:
master_group.authorize('tcp', 5080, 5080, authorized_address)
if slave_group.rules == []: # Group was just now created
if opts.vpc_id is None:
slave_group.authorize(src_group=master_group)
slave_group.authorize(src_group=slave_group)
else:
slave_group.authorize(ip_protocol='icmp', from_port=-1, to_port=-1,
src_group=master_group)
slave_group.authorize(ip_protocol='tcp', from_port=0, to_port=65535,
src_group=master_group)
slave_group.authorize(ip_protocol='udp', from_port=0, to_port=65535,
src_group=master_group)
slave_group.authorize(ip_protocol='icmp', from_port=-1, to_port=-1,
src_group=slave_group)
slave_group.authorize(ip_protocol='tcp', from_port=0, to_port=65535,
src_group=slave_group)
slave_group.authorize(ip_protocol='udp', from_port=0, to_port=65535,
src_group=slave_group)
slave_group.authorize('tcp', 22, 22, authorized_address)
slave_group.authorize('tcp', 8080, 8081, authorized_address)
slave_group.authorize('tcp', 50060, 50060, authorized_address)
slave_group.authorize('tcp', 50075, 50075, authorized_address)
slave_group.authorize('tcp', 60060, 60060, authorized_address)
slave_group.authorize('tcp', 60075, 60075, authorized_address)
# Check if instances are already running in our groups
existing_masters, existing_slaves = get_existing_cluster(conn, opts, cluster_name,
die_on_error=False)
if existing_slaves or (existing_masters and not opts.use_existing_master):
print >> stderr, ("ERROR: There are already instances running in " +
"group %s or %s" % (master_group.name, slave_group.name))
sys.exit(1)
# Figure out Spark AMI
if opts.ami is None:
opts.ami = get_spark_ami(opts.instance_type, opts.region, opts.spark_ec2_git_repo, opts.spark_ec2_git_branch)
if opts.master_ami is None:
opts.master_ami = get_spark_ami(opts.master_instance_type, opts.region, opts.spark_ec2_git_repo, opts.spark_ec2_git_branch)
# we use group ids to work around https://github.com/boto/boto/issues/350
additional_group_ids = []
if opts.additional_security_group:
additional_group_ids = [sg.id
for sg in conn.get_all_security_groups()
if opts.additional_security_group in (sg.name, sg.id)]
print "Launching instances..."
try:
image = conn.get_all_images(image_ids=[opts.ami])[0]
except:
print >> stderr, "Could not find AMI " + opts.ami
sys.exit(1)
try:
master_image = conn.get_all_images(image_ids=[opts.master_ami])[0]
except:
print >> stderr, "Could not find AMI " + opts.master_ami
sys.exit(1)
# Create block device mapping so that we can add EBS volumes if asked to.
# The first drive is attached as /dev/sds, 2nd as /dev/sdt, ... /dev/sdz
block_map = BlockDeviceMapping()
if opts.ebs_vol_size > 0:
for i in range(opts.ebs_vol_num):
device = EBSBlockDeviceType()
device.size = opts.ebs_vol_size
device.volume_type = opts.ebs_vol_type
device.delete_on_termination = True
block_map["/dev/sd" + chr(ord('s') + i)] = device
for i in range(get_num_disks(opts.instance_type)):
dev = BlockDeviceType()
dev.ephemeral_name = 'ephemeral%d' % i
name = '/dev/xvd' + string.letters[i + 1]
block_map[name] = dev
# Launch slaves
if opts.spot_price is not None:
# Launch spot instances with the requested price
print ("Requesting %d slaves as spot instances with price $%.3f" %
(opts.slaves, opts.spot_price))
zones = get_zones(conn, opts)
num_zones = len(zones)
i = 0
my_req_ids = []
for zone in zones:
num_slaves_this_zone = get_partition(opts.slaves, num_zones, i)
slave_reqs = conn.request_spot_instances(
price=opts.spot_price,
image_id=opts.ami,
launch_group="launch-group-%s" % cluster_name,
placement=zone,
count=num_slaves_this_zone,
key_name=opts.key_pair,
security_group_ids=[slave_group.id] + additional_group_ids,
instance_type=opts.instance_type,
block_device_map=block_map,
subnet_id=opts.subnet_id,
placement_group=opts.placement_group,
user_data=user_data_content)
my_req_ids += [req.id for req in slave_reqs]
i += 1
start_time = datetime.now()
print "Waiting for spot instances to be granted... Request IDs: %s " % my_req_ids
try:
while True:
time.sleep(10)
reqs = conn.get_all_spot_instance_requests(my_req_ids)
active_instance_ids = filter(lambda req: req.state == "active", reqs)
invalid_states = ["capacity-not-available", "capacity-oversubscribed", "price-too-low"]
invalid = filter(lambda req: req.status.code in invalid_states, reqs)
if len(invalid) > 0:
raise Exception("Invalid state for spot request: %s - status: %s" %
(invalid[0].id, invalid[0].status.message))
if len(active_instance_ids) == opts.slaves:
print "All %d slaves granted" % opts.slaves
reservations = conn.get_all_reservations(active_instance_ids)
slave_nodes = []
for r in reservations:
slave_nodes += r.instances
break
else:
print "%d of %d slaves granted, waiting longer" % (
len(active_instance_ids), opts.slaves)
if (datetime.now() - start_time).seconds > opts.spot_timeout * 60:
raise Exception("Timed out while waiting for spot instances")
except:
print "Error: %s" % sys.exc_info()[1]
print "Canceling spot instance requests"
conn.cancel_spot_instance_requests(my_req_ids)
# Log a warning if any of these requests actually launched instances:
(master_nodes, slave_nodes) = get_existing_cluster(
conn, opts, cluster_name, die_on_error=False)
running = len(master_nodes) + len(slave_nodes)
if running:
print >> stderr, ("WARNING: %d instances are still running" % running)
sys.exit(0)
else:
# Launch non-spot instances
zones = get_zones(conn, opts)
num_zones = len(zones)
i = 0
slave_nodes = []
for zone in zones:
num_slaves_this_zone = get_partition(opts.slaves, num_zones, i)
if num_slaves_this_zone > 0:
slave_res = image.run(key_name=opts.key_pair,
security_group_ids=[slave_group.id] + additional_group_ids,
instance_type=opts.instance_type,
placement=zone,
min_count=num_slaves_this_zone,
max_count=num_slaves_this_zone,
block_device_map=block_map,
subnet_id=opts.subnet_id,
placement_group=opts.placement_group,
user_data=user_data_content)
slave_nodes += slave_res.instances
print "Launched %d slaves in %s, regid = %s" % (num_slaves_this_zone,
zone, slave_res.id)
i += 1
# Launch or resume masters
if existing_masters:
print "Starting master..."
for inst in existing_masters:
if inst.state not in ["shutting-down", "terminated"]:
inst.start()
master_nodes = existing_masters
else:
master_type = opts.master_instance_type
if master_type == "":
master_type = opts.instance_type
if opts.zone == 'all':
opts.zone = random.choice(conn.get_all_zones()).name
master_res = master_image.run(key_name=opts.key_pair,
security_group_ids=[master_group.id] + additional_group_ids,
instance_type=master_type,
placement=opts.zone,
min_count=1,
max_count=1,
block_device_map=block_map,
subnet_id=opts.subnet_id,
placement_group=opts.placement_group,
user_data=user_data_content)
master_nodes = master_res.instances
print "Launched master in %s, regid = %s" % (zone, master_res.id)
# This wait time corresponds to SPARK-4983
print "Waiting for AWS to propagate instance metadata..."
time.sleep(5)
# Give the instances descriptive names
for master in master_nodes:
master.add_tag(
key='Name',
value='{cn}-master-{iid}'.format(cn=cluster_name, iid=master.id))
for slave in slave_nodes:
slave.add_tag(
key='Name',
value='{cn}-slave-{iid}'.format(cn=cluster_name, iid=slave.id))
# Return all the instances
return (master_nodes, slave_nodes)
# Get the EC2 instances in an existing cluster if available.
# Returns a tuple of lists of EC2 instance objects for the masters and slaves
def get_existing_cluster(conn, opts, cluster_name, die_on_error=True):
print "Searching for existing cluster " + cluster_name + "..."
reservations = conn.get_all_reservations()
master_nodes = []
slave_nodes = []
for res in reservations:
active = [i for i in res.instances if is_active(i)]
for inst in active:
group_names = [g.name for g in inst.groups]
if (cluster_name + "-master") in group_names:
master_nodes.append(inst)
elif (cluster_name + "-slaves") in group_names:
slave_nodes.append(inst)
if any((master_nodes, slave_nodes)):
print "Found %d master(s), %d slaves" % (len(master_nodes), len(slave_nodes))
if master_nodes != [] or not die_on_error:
return (master_nodes, slave_nodes)
else:
if master_nodes == [] and slave_nodes != []:
print >> sys.stderr, "ERROR: Could not find master in group " + cluster_name + "-master"
else:
print >> sys.stderr, "ERROR: Could not find any existing cluster"
sys.exit(1)
# Deploy configuration files and run setup scripts on a newly launched
# or started EC2 cluster.
def setup_cluster(conn, master_nodes, slave_nodes, opts, deploy_ssh_key):
master = master_nodes[0].public_dns_name
if deploy_ssh_key:
print "Generating cluster's SSH key on master..."
key_setup = """
[ -f ~/.ssh/id_rsa ] ||
(ssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa &&
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys)
"""
ssh(master, opts, key_setup)
dot_ssh_tar = ssh_read(master, opts, ['tar', 'c', '.ssh'])
print "Transferring cluster's SSH key to slaves..."
for slave in slave_nodes:
print slave.public_dns_name
ssh_write(slave.public_dns_name, opts, ['tar', 'x'], dot_ssh_tar)
modules = ['spark', 'ephemeral-hdfs', 'persistent-hdfs',
'mapreduce', 'spark-standalone', 'tachyon']
if opts.hadoop_major_version == "1":
modules = filter(lambda x: x != "mapreduce", modules)
if opts.ganglia:
modules.append('ganglia')
# NOTE: We should clone the repository before running deploy_files to
# prevent ec2-variables.sh from being overwritten
print "Cloning spark-ec2 scripts from {r}/tree/{b} on master...".format(
r=opts.spark_ec2_git_repo, b=opts.spark_ec2_git_branch)
ssh(
host=master,
opts=opts,
command="rm -rf spark-ec2"
+ " && "
+ "git clone {r} -b {b} spark-ec2".format(r=opts.spark_ec2_git_repo,
b=opts.spark_ec2_git_branch)
)
print "Deploying files to master..."
deploy_files(
conn=conn,
root_dir=SPARK_EC2_DIR + "/" + "deploy.generic",
opts=opts,
master_nodes=master_nodes,
slave_nodes=slave_nodes,
modules=modules
)
print "Running setup on master..."
setup_spark_cluster(master, opts)
print "Done!"
def setup_spark_cluster(master, opts):
ssh(master, opts, "chmod u+x spark-ec2/setup.sh")
ssh(master, opts, "spark-ec2/setup.sh")
print "Spark standalone cluster started at http://%s:8080" % master
if opts.ganglia:
print "Ganglia started at http://%s:5080/ganglia" % master
def is_ssh_available(host, opts, print_ssh_output=True):
"""
Check if SSH is available on a host.
"""
s = subprocess.Popen(
ssh_command(opts) + ['-t', '-t', '-o', 'ConnectTimeout=3',
'%s@%s' % (opts.user, host), stringify_command('true')],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT # we pipe stderr through stdout to preserve output order
)
cmd_output = s.communicate()[0] # [1] is stderr, which we redirected to stdout
if s.returncode != 0 and print_ssh_output:
# extra leading newline is for spacing in wait_for_cluster_state()
print textwrap.dedent("""\n
Warning: SSH connection error. (This could be temporary.)
Host: {h}
SSH return code: {r}
SSH output: {o}
""").format(
h=host,
r=s.returncode,
o=cmd_output.strip()
)
return s.returncode == 0
def is_cluster_ssh_available(cluster_instances, opts):
"""
Check if SSH is available on all the instances in a cluster.
"""
for i in cluster_instances:
if not is_ssh_available(host=i.ip_address, opts=opts):
return False
else:
return True
def wait_for_cluster_state(conn, opts, cluster_instances, cluster_state):
"""
Wait for all the instances in the cluster to reach a designated state.
cluster_instances: a list of boto.ec2.instance.Instance
cluster_state: a string representing the desired state of all the instances in the cluster
value can be 'ssh-ready' or a valid value from boto.ec2.instance.InstanceState such as
'running', 'terminated', etc.
(would be nice to replace this with a proper enum: http://stackoverflow.com/a/1695250)
"""
sys.stdout.write(
"Waiting for cluster to enter '{s}' state.".format(s=cluster_state)
)
sys.stdout.flush()
start_time = datetime.now()
num_attempts = 0
while True:
time.sleep(5 * num_attempts) # seconds
for i in cluster_instances:
i.update()
statuses = conn.get_all_instance_status(instance_ids=[i.id for i in cluster_instances])
if cluster_state == 'ssh-ready':
if all(i.state == 'running' for i in cluster_instances) and \
all(s.system_status.status == 'ok' for s in statuses) and \
all(s.instance_status.status == 'ok' for s in statuses) and \
is_cluster_ssh_available(cluster_instances, opts):
break
else:
if all(i.state == cluster_state for i in cluster_instances):
break
num_attempts += 1
sys.stdout.write(".")
sys.stdout.flush()
sys.stdout.write("\n")
end_time = datetime.now()
print "Cluster is now in '{s}' state. Waited {t} seconds.".format(
s=cluster_state,
t=(end_time - start_time).seconds
)
# Get number of local disks available for a given EC2 instance type.
def get_num_disks(instance_type):
# Source: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html
# Last Updated: 2014-06-20
# For easy maintainability, please keep this manually-inputted dictionary sorted by key.
disks_by_instance = {
"c1.medium": 1,
"c1.xlarge": 4,
"c3.2xlarge": 2,
"c3.4xlarge": 2,
"c3.8xlarge": 2,
"c3.large": 2,
"c3.xlarge": 2,
"cc1.4xlarge": 2,
"cc2.8xlarge": 4,
"cg1.4xlarge": 2,
"cr1.8xlarge": 2,
"g2.2xlarge": 1,
"hi1.4xlarge": 2,
"hs1.8xlarge": 24,
"i2.2xlarge": 2,
"i2.4xlarge": 4,
"i2.8xlarge": 8,
"i2.xlarge": 1,
"m1.large": 2,
"m1.medium": 1,
"m1.small": 1,
"m1.xlarge": 4,
"m2.2xlarge": 1,
"m2.4xlarge": 2,
"m2.xlarge": 1,
"m3.2xlarge": 2,
"m3.large": 1,
"m3.medium": 1,
"m3.xlarge": 2,
"r3.2xlarge": 1,
"r3.4xlarge": 1,
"r3.8xlarge": 2,
"r3.large": 1,
"r3.xlarge": 1,
"t1.micro": 0,
'd2.xlarge': 3,
'd2.2xlarge': 6,
'd2.4xlarge': 12,
'd2.8xlarge': 24,
}
if instance_type in disks_by_instance:
return disks_by_instance[instance_type]
else:
print >> stderr, ("WARNING: Don't know number of disks on instance type %s; assuming 1"
% instance_type)
return 1
# Deploy the configuration file templates in a given local directory to
# a cluster, filling in any template parameters with information about the
# cluster (e.g. lists of masters and slaves). Files are only deployed to
# the first master instance in the cluster, and we expect the setup
# script to be run on that instance to copy them to other nodes.
#
# root_dir should be an absolute path to the directory with the files we want to deploy.
def deploy_files(conn, root_dir, opts, master_nodes, slave_nodes, modules):
active_master = master_nodes[0].public_dns_name
num_disks = get_num_disks(opts.instance_type)
hdfs_data_dirs = "/mnt/ephemeral-hdfs/data"
mapred_local_dirs = "/mnt/hadoop/mrlocal"
spark_local_dirs = "/mnt/spark"
if num_disks > 1:
for i in range(2, num_disks + 1):
hdfs_data_dirs += ",/mnt%d/ephemeral-hdfs/data" % i
mapred_local_dirs += ",/mnt%d/hadoop/mrlocal" % i
spark_local_dirs += ",/mnt%d/spark" % i
cluster_url = "%s:7077" % active_master
if opts.spark_version.startswith("http"):
# Custom pre-built spark package
spark_v = get_validate_spark_version(opts.spark_version, opts.spark_git_repo)
elif "." in opts.spark_version:
# Pre-built Spark deploy
spark_v = get_validate_spark_version(opts.spark_version, opts.spark_git_repo)
else:
# Spark-only custom deploy
spark_v = "%s|%s" % (opts.spark_git_repo, opts.spark_version)
template_vars = {
"master_list": '\n'.join([i.public_dns_name for i in master_nodes]),
"active_master": active_master,
"slave_list": '\n'.join([i.public_dns_name for i in slave_nodes]),
"cluster_url": cluster_url,
"hdfs_data_dirs": hdfs_data_dirs,
"mapred_local_dirs": mapred_local_dirs,
"spark_local_dirs": spark_local_dirs,
"swap": str(opts.swap),
"modules": '\n'.join(modules),
"spark_version": spark_v,
"hadoop_major_version": opts.hadoop_major_version,
"spark_worker_instances": "%d" % opts.worker_instances,
"spark_master_opts": opts.master_opts
}
if opts.copy_aws_credentials:
template_vars["aws_access_key_id"] = conn.aws_access_key_id
template_vars["aws_secret_access_key"] = conn.aws_secret_access_key
else:
template_vars["aws_access_key_id"] = ""
template_vars["aws_secret_access_key"] = ""
# Create a temp directory in which we will place all the files to be
# deployed after we substitue template parameters in them
tmp_dir = tempfile.mkdtemp()
for path, dirs, files in os.walk(root_dir):
if path.find(".svn") == -1:
dest_dir = os.path.join('/', path[len(root_dir):])
local_dir = tmp_dir + dest_dir
if not os.path.exists(local_dir):
os.makedirs(local_dir)
for filename in files:
if filename[0] not in '#.~' and filename[-1] != '~':
dest_file = os.path.join(dest_dir, filename)
local_file = tmp_dir + dest_file
with open(os.path.join(path, filename)) as src:
with open(local_file, "w") as dest:
text = src.read()
for key in template_vars:
text = text.replace("{{" + key + "}}", template_vars[key])
dest.write(text)
dest.close()
# rsync the whole directory over to the master machine
command = [
'rsync', '-rv',
'-e', stringify_command(ssh_command(opts)),
"%s/" % tmp_dir,
"%s@%s:/" % (opts.user, active_master)
]
subprocess.check_call(command)
# Remove the temp directory we created above
shutil.rmtree(tmp_dir)
def stringify_command(parts):
if isinstance(parts, str):
return parts
else:
return ' '.join(map(pipes.quote, parts))
def ssh_args(opts):
parts = ['-o', 'StrictHostKeyChecking=no']
parts += ['-o', 'UserKnownHostsFile=/dev/null']
if opts.identity_file is not None:
parts += ['-i', opts.identity_file]
return parts
def ssh_command(opts):
return ['ssh'] + ssh_args(opts)
# Run a command on a host through ssh, retrying up to five times
# and then throwing an exception if ssh continues to fail.
def ssh(host, opts, command):
tries = 0
while True:
try:
return subprocess.check_call(
ssh_command(opts) + ['-t', '-t', '%s@%s' % (opts.user, host),
stringify_command(command)])
except subprocess.CalledProcessError as e:
if tries > 5:
# If this was an ssh failure, provide the user with hints.
if e.returncode == 255:
raise UsageError(
"Failed to SSH to remote host {0}.\n" +
"Please check that you have provided the correct --identity-file and " +
"--key-pair parameters and try again.".format(host))
else:
raise e
print >> stderr, \
"Error executing remote command, retrying after 30 seconds: {0}".format(e)
time.sleep(30)
tries = tries + 1
# Backported from Python 2.7 for compatiblity with 2.6 (See SPARK-1990)
def _check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output
def ssh_read(host, opts, command):
return _check_output(
ssh_command(opts) + ['%s@%s' % (opts.user, host), stringify_command(command)])
def ssh_write(host, opts, command, arguments):
tries = 0
while True:
proc = subprocess.Popen(
ssh_command(opts) + ['%s@%s' % (opts.user, host), stringify_command(command)],
stdin=subprocess.PIPE)
proc.stdin.write(arguments)
proc.stdin.close()
status = proc.wait()
if status == 0:
break
elif tries > 5:
raise RuntimeError("ssh_write failed with error %s" % proc.returncode)
else:
print >> stderr, \
"Error {0} while executing remote command, retrying after 30 seconds".format(status)
time.sleep(30)
tries = tries + 1
# Gets a list of zones to launch instances in
def get_zones(conn, opts):
if opts.zone == 'all':
zones = [z.name for z in conn.get_all_zones()]
else:
zones = [opts.zone]
return zones
# Gets the number of items in a partition
def get_partition(total, num_partitions, current_partitions):
num_slaves_this_zone = total / num_partitions
if (total % num_partitions) - current_partitions > 0:
num_slaves_this_zone += 1
return num_slaves_this_zone
def real_main():
(opts, action, cluster_name) = parse_args()
# Input parameter validation
get_validate_spark_version(opts.spark_version, opts.spark_git_repo)
if opts.wait is not None:
# NOTE: DeprecationWarnings are silent in 2.7+ by default.
# To show them, run Python with the -Wdefault switch.
# See: https://docs.python.org/3.5/whatsnew/2.7.html
warnings.warn(
"This option is deprecated and has no effect. "
"spark-ec2 automatically waits as long as necessary for clusters to start up.",
DeprecationWarning
)
if opts.identity_file is not None:
if not os.path.exists(opts.identity_file):
print >> stderr,\
"ERROR: The identity file '{f}' doesn't exist.".format(f=opts.identity_file)
sys.exit(1)
file_mode = os.stat(opts.identity_file).st_mode
if not (file_mode & S_IRUSR) or not oct(file_mode)[-2:] == '00':
print >> stderr, "ERROR: The identity file must be accessible only by you."
print >> stderr, 'You can fix this with: chmod 400 "{f}"'.format(f=opts.identity_file)
sys.exit(1)
if opts.instance_type not in EC2_INSTANCE_TYPES:
print >> stderr, "Warning: Unrecognized EC2 instance type for instance-type: {t}".format(
t=opts.instance_type)
if opts.master_instance_type != "":
if opts.master_instance_type not in EC2_INSTANCE_TYPES:
print >> stderr, \
"Warning: Unrecognized EC2 instance type for master-instance-type: {t}".format(
t=opts.master_instance_type)
if opts.ebs_vol_num > 8:
print >> stderr, "ebs-vol-num cannot be greater than 8"
sys.exit(1)
# Prevent breaking ami_prefix (/, .git and startswith checks)
# Prevent forks with non spark-ec2 names for now.
if opts.spark_ec2_git_repo.endswith("/") or \
opts.spark_ec2_git_repo.endswith(".git") or \
not opts.spark_ec2_git_repo.startswith("https://github.com") or \
not opts.spark_ec2_git_repo.endswith("spark-ec2"):
print >> stderr, "spark-ec2-git-repo must be a github repo and it must not have a " \
"trailing / or .git. " \
"Furthermore, we currently only support forks named spark-ec2."
sys.exit(1)
try:
conn = ec2.connect_to_region(opts.region)
except Exception as e:
print >> stderr, (e)
sys.exit(1)
# Select an AZ at random if it was not specified.
if opts.zone == "":
opts.zone = random.choice(conn.get_all_zones()).name
if action == "launch":
if opts.slaves <= 0:
print >> sys.stderr, "ERROR: You have to start at least 1 slave"
sys.exit(1)
if opts.resume:
(master_nodes, slave_nodes) = get_existing_cluster(conn, opts, cluster_name)
else:
(master_nodes, slave_nodes) = launch_cluster(conn, opts, cluster_name)
wait_for_cluster_state(
conn=conn,
opts=opts,
cluster_instances=(master_nodes + slave_nodes),
cluster_state='ssh-ready'
)
setup_cluster(conn, master_nodes, slave_nodes, opts, True)
elif action == "destroy":
print "Are you sure you want to destroy the cluster %s?" % cluster_name
print "The following instances will be terminated:"
(master_nodes, slave_nodes) = get_existing_cluster(
conn, opts, cluster_name, die_on_error=False)
for inst in master_nodes + slave_nodes:
print "> %s" % inst.public_dns_name
msg = "ALL DATA ON ALL NODES WILL BE LOST!!\nDestroy cluster %s (y/N): " % cluster_name
response = raw_input(msg)
if response == "y":
print "Terminating master..."
for inst in master_nodes:
inst.terminate()
print "Terminating slaves..."
for inst in slave_nodes:
inst.terminate()
# Delete security groups as well
if opts.delete_groups:
print "Deleting security groups (this will take some time)..."
group_names = [cluster_name + "-master", cluster_name + "-slaves"]
wait_for_cluster_state(
conn=conn,
opts=opts,
cluster_instances=(master_nodes + slave_nodes),
cluster_state='terminated'
)
attempt = 1
while attempt <= 3:
print "Attempt %d" % attempt
groups = [g for g in conn.get_all_security_groups() if g.name in group_names]
success = True
# Delete individual rules in all groups before deleting groups to
# remove dependencies between them
for group in groups:
print "Deleting rules in security group " + group.name
for rule in group.rules:
for grant in rule.grants:
success &= group.revoke(ip_protocol=rule.ip_protocol,
from_port=rule.from_port,
to_port=rule.to_port,
src_group=grant)
# Sleep for AWS eventual-consistency to catch up, and for instances
# to terminate
time.sleep(30) # Yes, it does have to be this long :-(
for group in groups:
try:
conn.delete_security_group(group.name)
print "Deleted security group " + group.name
except boto.exception.EC2ResponseError:
success = False
print "Failed to delete security group " + group.name
# Unfortunately, group.revoke() returns True even if a rule was not
# deleted, so this needs to be rerun if something fails
if success:
break
attempt += 1
if not success:
print "Failed to delete all security groups after 3 tries."
print "Try re-running in a few minutes."
elif action == "login":
(master_nodes, slave_nodes) = get_existing_cluster(conn, opts, cluster_name)
master = master_nodes[0].public_dns_name
print "Logging into master " + master + "..."
proxy_opt = []
if opts.proxy_port is not None:
proxy_opt = ['-D', opts.proxy_port]
subprocess.check_call(
ssh_command(opts) + proxy_opt + ['-t', '-t', "%s@%s" % (opts.user, master)])
elif action == "reboot-slaves":
response = raw_input(
"Are you sure you want to reboot the cluster " +
cluster_name + " slaves?\n" +
"Reboot cluster slaves " + cluster_name + " (y/N): ")
if response == "y":
(master_nodes, slave_nodes) = get_existing_cluster(
conn, opts, cluster_name, die_on_error=False)
print "Rebooting slaves..."
for inst in slave_nodes:
if inst.state not in ["shutting-down", "terminated"]:
print "Rebooting " + inst.id
inst.reboot()
elif action == "get-master":
(master_nodes, slave_nodes) = get_existing_cluster(conn, opts, cluster_name)
print master_nodes[0].public_dns_name
elif action == "stop":
response = raw_input(
"Are you sure you want to stop the cluster " +
cluster_name + "?\nDATA ON EPHEMERAL DISKS WILL BE LOST, " +
"BUT THE CLUSTER WILL KEEP USING SPACE ON\n" +
"AMAZON EBS IF IT IS EBS-BACKED!!\n" +
"All data on spot-instance slaves will be lost.\n" +
"Stop cluster " + cluster_name + " (y/N): ")
if response == "y":
(master_nodes, slave_nodes) = get_existing_cluster(
conn, opts, cluster_name, die_on_error=False)
print "Stopping master..."
for inst in master_nodes:
if inst.state not in ["shutting-down", "terminated"]:
inst.stop()
print "Stopping slaves..."
for inst in slave_nodes:
if inst.state not in ["shutting-down", "terminated"]:
if inst.spot_instance_request_id:
inst.terminate()
else:
inst.stop()
elif action == "start":
(master_nodes, slave_nodes) = get_existing_cluster(conn, opts, cluster_name)
print "Starting slaves..."
for inst in slave_nodes:
if inst.state not in ["shutting-down", "terminated"]:
inst.start()
print "Starting master..."
for inst in master_nodes:
if inst.state not in ["shutting-down", "terminated"]:
inst.start()
wait_for_cluster_state(
conn=conn,
opts=opts,
cluster_instances=(master_nodes + slave_nodes),
cluster_state='ssh-ready'
)
setup_cluster(conn, master_nodes, slave_nodes, opts, False)
else:
print >> stderr, "Invalid action: %s" % action
sys.exit(1)
def main():
try:
real_main()
except UsageError, e:
print >> stderr, "\nError:\n", e
sys.exit(1)
if __name__ == "__main__":
logging.basicConfig()
main()
| mit | -2,970,042,283,297,121,300 | 39.523328 | 132 | 0.573811 | false |
cloudera/hue | desktop/core/ext-py/SQLAlchemy-1.3.17/examples/performance/__init__.py | 4 | 14298 | """A performance profiling suite for a variety of SQLAlchemy use cases.
Each suite focuses on a specific use case with a particular performance
profile and associated implications:
* bulk inserts
* individual inserts, with or without transactions
* fetching large numbers of rows
* running lots of short queries
All suites include a variety of use patterns illustrating both Core
and ORM use, and are generally sorted in order of performance from worst
to greatest, inversely based on amount of functionality provided by SQLAlchemy,
greatest to least (these two things generally correspond perfectly).
A command line tool is presented at the package level which allows
individual suites to be run::
$ python -m examples.performance --help
usage: python -m examples.performance [-h] [--test TEST] [--dburl DBURL]
[--num NUM] [--profile] [--dump]
[--runsnake] [--echo]
{bulk_inserts,large_resultsets,single_inserts}
positional arguments:
{bulk_inserts,large_resultsets,single_inserts}
suite to run
optional arguments:
-h, --help show this help message and exit
--test TEST run specific test name
--dburl DBURL database URL, default sqlite:///profile.db
--num NUM Number of iterations/items/etc for tests;
default is module-specific
--profile run profiling and dump call counts
--dump dump full call profile (implies --profile)
--runsnake invoke runsnakerun (implies --profile)
--echo Echo SQL output
An example run looks like::
$ python -m examples.performance bulk_inserts
Or with options::
$ python -m examples.performance bulk_inserts \\
--dburl mysql+mysqldb://scott:tiger@localhost/test \\
--profile --num 1000
.. seealso::
:ref:`faq_how_to_profile`
File Listing
-------------
.. autosource::
Running all tests with time
---------------------------
This is the default form of run::
$ python -m examples.performance single_inserts
Tests to run: test_orm_commit, test_bulk_save,
test_bulk_insert_dictionaries, test_core,
test_core_query_caching, test_dbapi_raw_w_connect,
test_dbapi_raw_w_pool
test_orm_commit : Individual INSERT/COMMIT pairs via the
ORM (10000 iterations); total time 13.690218 sec
test_bulk_save : Individual INSERT/COMMIT pairs using
the "bulk" API (10000 iterations); total time 11.290371 sec
test_bulk_insert_dictionaries : Individual INSERT/COMMIT pairs using
the "bulk" API with dictionaries (10000 iterations);
total time 10.814626 sec
test_core : Individual INSERT/COMMIT pairs using Core.
(10000 iterations); total time 9.665620 sec
test_core_query_caching : Individual INSERT/COMMIT pairs using Core
with query caching (10000 iterations); total time 9.209010 sec
test_dbapi_raw_w_connect : Individual INSERT/COMMIT pairs w/ DBAPI +
connection each time (10000 iterations); total time 9.551103 sec
test_dbapi_raw_w_pool : Individual INSERT/COMMIT pairs w/ DBAPI +
connection pool (10000 iterations); total time 8.001813 sec
Dumping Profiles for Individual Tests
--------------------------------------
A Python profile output can be dumped for all tests, or more commonly
individual tests::
$ python -m examples.performance single_inserts --test test_core --num 1000 --dump
Tests to run: test_core
test_core : Individual INSERT/COMMIT pairs using Core. (1000 iterations); total fn calls 186109
186109 function calls (186102 primitive calls) in 1.089 seconds
Ordered by: internal time, call count
ncalls tottime percall cumtime percall filename:lineno(function)
1000 0.634 0.001 0.634 0.001 {method 'commit' of 'sqlite3.Connection' objects}
1000 0.154 0.000 0.154 0.000 {method 'execute' of 'sqlite3.Cursor' objects}
1000 0.021 0.000 0.074 0.000 /Users/classic/dev/sqlalchemy/lib/sqlalchemy/sql/compiler.py:1950(_get_colparams)
1000 0.015 0.000 0.034 0.000 /Users/classic/dev/sqlalchemy/lib/sqlalchemy/engine/default.py:503(_init_compiled)
1 0.012 0.012 1.091 1.091 examples/performance/single_inserts.py:79(test_core)
...
Using RunSnake
--------------
This option requires the `RunSnake <https://pypi.python.org/pypi/RunSnakeRun>`_
command line tool be installed::
$ python -m examples.performance single_inserts --test test_core --num 1000 --runsnake
A graphical RunSnake output will be displayed.
.. _examples_profiling_writeyourown:
Writing your Own Suites
-----------------------
The profiler suite system is extensible, and can be applied to your own set
of tests. This is a valuable technique to use in deciding upon the proper
approach for some performance-critical set of routines. For example,
if we wanted to profile the difference between several kinds of loading,
we can create a file ``test_loads.py``, with the following content::
from examples.performance import Profiler
from sqlalchemy import Integer, Column, create_engine, ForeignKey
from sqlalchemy.orm import relationship, joinedload, subqueryload, Session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = None
session = None
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship("Child")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
# Init with name of file, default number of items
Profiler.init("test_loads", 1000)
@Profiler.setup_once
def setup_once(dburl, echo, num):
"setup once. create an engine, insert fixture data"
global engine
engine = create_engine(dburl, echo=echo)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
sess = Session(engine)
sess.add_all([
Parent(children=[Child() for j in range(100)])
for i in range(num)
])
sess.commit()
@Profiler.setup
def setup(dburl, echo, num):
"setup per test. create a new Session."
global session
session = Session(engine)
# pre-connect so this part isn't profiled (if we choose)
session.connection()
@Profiler.profile
def test_lazyload(n):
"load everything, no eager loading."
for parent in session.query(Parent):
parent.children
@Profiler.profile
def test_joinedload(n):
"load everything, joined eager loading."
for parent in session.query(Parent).options(joinedload("children")):
parent.children
@Profiler.profile
def test_subqueryload(n):
"load everything, subquery eager loading."
for parent in session.query(Parent).options(subqueryload("children")):
parent.children
if __name__ == '__main__':
Profiler.main()
We can run our new script directly::
$ python test_loads.py --dburl postgresql+psycopg2://scott:tiger@localhost/test
Running setup once...
Tests to run: test_lazyload, test_joinedload, test_subqueryload
test_lazyload : load everything, no eager loading. (1000 iterations); total time 11.971159 sec
test_joinedload : load everything, joined eager loading. (1000 iterations); total time 2.754592 sec
test_subqueryload : load everything, subquery eager loading. (1000 iterations); total time 2.977696 sec
As well as see RunSnake output for an individual test::
$ python test_loads.py --num 100 --runsnake --test test_joinedload
""" # noqa
import argparse
import cProfile
import os
import pstats
import re
import sys
import time
class Profiler(object):
tests = []
_setup = None
_setup_once = None
name = None
num = 0
def __init__(self, options):
self.test = options.test
self.dburl = options.dburl
self.runsnake = options.runsnake
self.profile = options.profile
self.dump = options.dump
self.callers = options.callers
self.num = options.num
self.echo = options.echo
self.stats = []
@classmethod
def init(cls, name, num):
cls.name = name
cls.num = num
@classmethod
def profile(cls, fn):
if cls.name is None:
raise ValueError(
"Need to call Profile.init(<suitename>, <default_num>) first."
)
cls.tests.append(fn)
return fn
@classmethod
def setup(cls, fn):
if cls._setup is not None:
raise ValueError("setup function already set to %s" % cls._setup)
cls._setup = staticmethod(fn)
return fn
@classmethod
def setup_once(cls, fn):
if cls._setup_once is not None:
raise ValueError(
"setup_once function already set to %s" % cls._setup_once
)
cls._setup_once = staticmethod(fn)
return fn
def run(self):
if self.test:
tests = [fn for fn in self.tests if fn.__name__ == self.test]
if not tests:
raise ValueError("No such test: %s" % self.test)
else:
tests = self.tests
if self._setup_once:
print("Running setup once...")
self._setup_once(self.dburl, self.echo, self.num)
print("Tests to run: %s" % ", ".join([t.__name__ for t in tests]))
for test in tests:
self._run_test(test)
self.stats[-1].report()
def _run_with_profile(self, fn):
pr = cProfile.Profile()
pr.enable()
try:
result = fn(self.num)
finally:
pr.disable()
stats = pstats.Stats(pr).sort_stats("cumulative")
self.stats.append(TestResult(self, fn, stats=stats))
return result
def _run_with_time(self, fn):
now = time.time()
try:
return fn(self.num)
finally:
total = time.time() - now
self.stats.append(TestResult(self, fn, total_time=total))
def _run_test(self, fn):
if self._setup:
self._setup(self.dburl, self.echo, self.num)
if self.profile or self.runsnake or self.dump:
self._run_with_profile(fn)
else:
self._run_with_time(fn)
@classmethod
def main(cls):
parser = argparse.ArgumentParser("python -m examples.performance")
if cls.name is None:
parser.add_argument(
"name", choices=cls._suite_names(), help="suite to run"
)
if len(sys.argv) > 1:
potential_name = sys.argv[1]
try:
__import__(__name__ + "." + potential_name)
except ImportError:
pass
parser.add_argument("--test", type=str, help="run specific test name")
parser.add_argument(
"--dburl",
type=str,
default="sqlite:///profile.db",
help="database URL, default sqlite:///profile.db",
)
parser.add_argument(
"--num",
type=int,
default=cls.num,
help="Number of iterations/items/etc for tests; "
"default is %d module-specific" % cls.num,
)
parser.add_argument(
"--profile",
action="store_true",
help="run profiling and dump call counts",
)
parser.add_argument(
"--dump",
action="store_true",
help="dump full call profile (implies --profile)",
)
parser.add_argument(
"--callers",
action="store_true",
help="print callers as well (implies --dump)",
)
parser.add_argument(
"--runsnake",
action="store_true",
help="invoke runsnakerun (implies --profile)",
)
parser.add_argument(
"--echo", action="store_true", help="Echo SQL output"
)
args = parser.parse_args()
args.dump = args.dump or args.callers
args.profile = args.profile or args.dump or args.runsnake
if cls.name is None:
__import__(__name__ + "." + args.name)
Profiler(args).run()
@classmethod
def _suite_names(cls):
suites = []
for file_ in os.listdir(os.path.dirname(__file__)):
match = re.match(r"^([a-z].*).py$", file_)
if match:
suites.append(match.group(1))
return suites
class TestResult(object):
def __init__(self, profile, test, stats=None, total_time=None):
self.profile = profile
self.test = test
self.stats = stats
self.total_time = total_time
def report(self):
print(self._summary())
if self.profile.profile:
self.report_stats()
def _summary(self):
summary = "%s : %s (%d iterations)" % (
self.test.__name__,
self.test.__doc__,
self.profile.num,
)
if self.total_time:
summary += "; total time %f sec" % self.total_time
if self.stats:
summary += "; total fn calls %d" % self.stats.total_calls
return summary
def report_stats(self):
if self.profile.runsnake:
self._runsnake()
elif self.profile.dump:
self._dump()
def _dump(self):
self.stats.sort_stats("time", "calls")
self.stats.print_stats()
if self.profile.callers:
self.stats.print_callers()
def _runsnake(self):
filename = "%s.profile" % self.test.__name__
try:
self.stats.dump_stats(filename)
os.system("runsnake %s" % filename)
finally:
os.remove(filename)
| apache-2.0 | 5,206,350,444,372,951,000 | 31.421769 | 132 | 0.595258 | false |
mrluker/hdrnet | hdrnet/bin/train.py | 2 | 10910 | #!/usr/bin/env python
# Copyright 2016 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.
"""Train a model."""
import argparse
import logging
import numpy as np
import os
import setproctitle
import tensorflow as tf
import time
import hdrnet.metrics as metrics
import hdrnet.models as models
import hdrnet.data_pipeline as dp
logging.basicConfig(format="[%(process)d] %(levelname)s %(filename)s:%(lineno)s | %(message)s")
log = logging.getLogger("train")
log.setLevel(logging.INFO)
def log_hook(sess, log_fetches):
"""Message display at every log step."""
data = sess.run(log_fetches)
step = data['step']
loss = data['loss']
psnr = data['psnr']
log.info('Step {} | loss = {:.4f} | psnr = {:.1f} dB'.format(step, loss, psnr))
def main(args, model_params, data_params):
procname = os.path.basename(args.checkpoint_dir)
setproctitle.setproctitle('hdrnet_{}'.format(procname))
log.info('Preparing summary and checkpoint directory {}'.format(
args.checkpoint_dir))
if not os.path.exists(args.checkpoint_dir):
os.makedirs(args.checkpoint_dir)
tf.set_random_seed(1234) # Make experiments repeatable
# Select an architecture
mdl = getattr(models, args.model_name)
# Add model parameters to the graph (so they are saved to disk at checkpoint)
for p in model_params:
p_ = tf.convert_to_tensor(model_params[p], name=p)
tf.add_to_collection('model_params', p_)
# --- Train/Test datasets ---------------------------------------------------
data_pipe = getattr(dp, args.data_pipeline)
with tf.variable_scope('train_data'):
train_data_pipeline = data_pipe(
args.data_dir,
shuffle=True,
batch_size=args.batch_size, nthreads=args.data_threads,
fliplr=args.fliplr, flipud=args.flipud, rotate=args.rotate,
random_crop=args.random_crop, params=data_params,
output_resolution=args.output_resolution)
train_samples = train_data_pipeline.samples
if args.eval_data_dir is not None:
with tf.variable_scope('eval_data'):
eval_data_pipeline = data_pipe(
args.eval_data_dir,
shuffle=False,
batch_size=1, nthreads=1,
fliplr=False, flipud=False, rotate=False,
random_crop=False, params=data_params,
output_resolution=args.output_resolution)
eval_samples = train_data_pipeline.samples
# ---------------------------------------------------------------------------
# Training graph
with tf.name_scope('train'):
with tf.variable_scope('inference'):
prediction = mdl.inference(
train_samples['lowres_input'], train_samples['image_input'],
model_params, is_training=True)
loss = metrics.l2_loss(train_samples['image_output'], prediction)
psnr = metrics.psnr(train_samples['image_output'], prediction)
# Evaluation graph
if args.eval_data_dir is not None:
with tf.name_scope('eval'):
with tf.variable_scope('inference', reuse=True):
eval_prediction = mdl.inference(
eval_samples['lowres_input'], eval_samples['image_input'],
model_params, is_training=False)
eval_psnr = metrics.psnr(eval_samples['image_output'], prediction)
# Optimizer
global_step = tf.contrib.framework.get_or_create_global_step()
with tf.name_scope('optimizer'):
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
updates = tf.group(*update_ops, name='update_ops')
log.info("Adding {} update ops".format(len(update_ops)))
with tf.control_dependencies([updates]):
opt = tf.train.AdamOptimizer(args.learning_rate)
minimize = opt.minimize(loss, name='optimizer', global_step=global_step)
# Average loss and psnr for display
with tf.name_scope("moving_averages"):
ema = tf.train.ExponentialMovingAverage(decay=0.99)
update_ma = ema.apply([loss, psnr])
loss = ema.average(loss)
psnr = ema.average(psnr)
# Training stepper operation
train_op = tf.group(minimize, update_ma)
# Save a few graphs to tensorboard
summaries = [
tf.summary.scalar('loss', loss),
tf.summary.scalar('psnr', psnr),
tf.summary.scalar('learning_rate', args.learning_rate),
tf.summary.scalar('batch_size', args.batch_size),
]
log_fetches = {
"step": global_step,
"loss": loss,
"psnr": psnr}
# Train config
config = tf.ConfigProto()
config.gpu_options.allow_growth = True # Do not canibalize the entire GPU
sv = tf.train.Supervisor(
logdir=args.checkpoint_dir,
save_summaries_secs=args.summary_interval,
save_model_secs=args.checkpoint_interval)
# Train loop
with sv.managed_session(config=config) as sess:
sv.loop(args.log_interval, log_hook, (sess, log_fetches))
last_eval = time.time()
while True:
if sv.should_stop():
log.info("stopping supervisor")
break
try:
step, _ = sess.run([global_step, train_op])
since_eval = time.time()-last_eval
if args.eval_data_dir is not None and since_eval > args.eval_interval:
log.info("Evaluating on {} images at step {}".format(
eval_data_pipeline.nsamples, step))
p_ = 0
for it in range(eval_data_pipeline.nsamples):
p_ += sess.run(eval_psnr)
p_ /= eval_data_pipeline.nsamples
sv.summary_writer.add_summary(tf.Summary(value=[
tf.Summary.Value(tag="psnr/eval", simple_value=p_)]), global_step=step)
log.info(" Evaluation PSNR = {:.1f} dB".format(p_))
last_eval = time.time()
except tf.errors.AbortedError:
log.error("Aborted")
break
except KeyboardInterrupt:
break
chkpt_path = os.path.join(args.checkpoint_dir, 'on_stop.ckpt')
log.info("Training complete, saving chkpt {}".format(chkpt_path))
sv.saver.save(sess, chkpt_path)
sv.request_stop()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# pylint: disable=line-too-long
# ----------------------------------------------------------------------------
req_grp = parser.add_argument_group('required')
req_grp.add_argument('checkpoint_dir', default=None, help='directory to save checkpoints to.')
req_grp.add_argument('data_dir', default=None, help='input directory containing the training .tfrecords or images.')
req_grp.add_argument('--eval_data_dir', default=None, type=str, help='directory with the validation data.')
# Training, logging and checkpointing parameters
train_grp = parser.add_argument_group('training')
train_grp.add_argument('--learning_rate', default=1e-4, type=float, help='learning rate for the stochastic gradient update.')
train_grp.add_argument('--log_interval', type=int, default=1, help='interval between log messages (in s).')
train_grp.add_argument('--summary_interval', type=int, default=120, help='interval between tensorboard summaries (in s)')
train_grp.add_argument('--checkpoint_interval', type=int, default=600, help='interval between model checkpoints (in s)')
train_grp.add_argument('--eval_interval', type=int, default=3600, help='interval between evaluations (in s)')
# Debug and perf profiling
debug_grp = parser.add_argument_group('debug and profiling')
debug_grp.add_argument('--profiling', dest='profiling', action='store_true', help='outputs a profiling trace.')
debug_grp.add_argument('--noprofiling', dest='profiling', action='store_false')
# Data pipeline and data augmentation
data_grp = parser.add_argument_group('data pipeline')
data_grp.add_argument('--batch_size', default=16, type=int, help='size of a batch for each gradient update.')
data_grp.add_argument('--data_threads', default=2, help='number of threads to load and enqueue samples.')
data_grp.add_argument('--rotate', dest="rotate", action="store_true", help='rotate data augmentation.')
data_grp.add_argument('--norotate', dest="rotate", action="store_false")
data_grp.add_argument('--flipud', dest="flipud", action="store_true", help='flip up/down data augmentation.')
data_grp.add_argument('--noflipud', dest="flipud", action="store_false")
data_grp.add_argument('--fliplr', dest="fliplr", action="store_true", help='flip left/right data augmentation.')
data_grp.add_argument('--nofliplr', dest="fliplr", action="store_false")
data_grp.add_argument('--random_crop', dest="random_crop", action="store_true", help='random crop data augmentation.')
data_grp.add_argument('--norandom_crop', dest="random_crop", action="store_false")
# Model parameters
model_grp = parser.add_argument_group('model_params')
model_grp.add_argument('--model_name', default=models.__all__[0], type=str, help='classname of the model to use.', choices=models.__all__)
model_grp.add_argument('--data_pipeline', default='ImageFilesDataPipeline', help='classname of the data pipeline to use.', choices=dp.__all__)
model_grp.add_argument('--net_input_size', default=256, type=int, help="size of the network's lowres image input.")
model_grp.add_argument('--output_resolution', default=[512, 512], type=int, nargs=2, help='resolution of the output image.')
model_grp.add_argument('--batch_norm', dest='batch_norm', action='store_true', help='normalize batches. If False, uses the moving averages.')
model_grp.add_argument('--nobatch_norm', dest='batch_norm', action='store_false')
model_grp.add_argument('--channel_multiplier', default=1, type=int, help='Factor to control net throughput (number of intermediate channels).')
model_grp.add_argument('--guide_complexity', default=16, type=int, help='Control complexity of the guide network.')
# Bilateral grid parameters
model_grp.add_argument('--luma_bins', default=8, type=int, help='Number of BGU bins for the luminance.')
model_grp.add_argument('--spatial_bin', default=16, type=int, help='Size of the spatial BGU bins (pixels).')
parser.set_defaults(
profiling=False,
flipud=False,
fliplr=False,
rotate=False,
random_crop=True,
batch_norm=False)
# ----------------------------------------------------------------------------
# pylint: enable=line-too-long
args = parser.parse_args()
model_params = {}
for a in model_grp._group_actions:
model_params[a.dest] = getattr(args, a.dest, None)
data_params = {}
for a in data_grp._group_actions:
data_params[a.dest] = getattr(args, a.dest, None)
main(args, model_params, data_params)
| apache-2.0 | 7,337,033,957,576,542,000 | 41.286822 | 146 | 0.668194 | false |
ondrejmular/pcs | pcs/lib/communication/sbd.py | 3 | 10962 | import json
from pcs.common import reports
from pcs.common.node_communicator import (
Request,
RequestData,
)
from pcs.common.reports import ReportItemSeverity
from pcs.common.reports.item import ReportItem
from pcs.lib.communication.tools import (
AllAtOnceStrategyMixin,
AllSameDataMixin,
MarkSuccessfulMixin,
OneByOneStrategyMixin,
RunRemotelyBase,
SimpleResponseProcessingMixin,
)
from pcs.lib.node_communication import response_to_report_item
from pcs.lib.tools import environment_file_to_dict
class ServiceAction(
SimpleResponseProcessingMixin,
AllSameDataMixin,
AllAtOnceStrategyMixin,
RunRemotelyBase,
):
def _get_request_action(self):
raise NotImplementedError()
def _get_before_report(self):
raise NotImplementedError()
def _get_success_report(self, node_label):
raise NotImplementedError()
def _get_request_data(self):
return RequestData(self._get_request_action())
def before(self):
self._report(self._get_before_report())
class EnableSbdService(ServiceAction):
def _get_request_action(self):
return "remote/sbd_enable"
def _get_before_report(self):
return ReportItem.info(
reports.messages.ServiceActionStarted(
reports.const.SERVICE_ACTION_ENABLE, "sbd"
)
)
def _get_success_report(self, node_label):
return ReportItem.info(
reports.messages.ServiceActionSucceeded(
reports.const.SERVICE_ACTION_ENABLE, "sbd", node_label
)
)
class DisableSbdService(ServiceAction):
def _get_request_action(self):
return "remote/sbd_disable"
def _get_before_report(self):
return ReportItem.info(
reports.messages.ServiceActionStarted(
reports.const.SERVICE_ACTION_DISABLE,
"sbd",
)
)
def _get_success_report(self, node_label):
return ReportItem.info(
reports.messages.ServiceActionSucceeded(
reports.const.SERVICE_ACTION_DISABLE, "sbd", node_label
)
)
class StonithWatchdogTimeoutAction(
AllSameDataMixin,
MarkSuccessfulMixin,
OneByOneStrategyMixin,
RunRemotelyBase,
):
def _get_request_action(self):
raise NotImplementedError()
def _get_request_data(self):
return RequestData(self._get_request_action())
def _process_response(self, response):
report_item = response_to_report_item(
response, severity=ReportItemSeverity.WARNING
)
if report_item is None:
self._on_success()
return []
self._report(report_item)
return self._get_next_list()
class RemoveStonithWatchdogTimeout(StonithWatchdogTimeoutAction):
def _get_request_action(self):
return "remote/remove_stonith_watchdog_timeout"
class SetStonithWatchdogTimeoutToZero(StonithWatchdogTimeoutAction):
def _get_request_action(self):
return "remote/set_stonith_watchdog_timeout_to_zero"
class SetSbdConfig(
SimpleResponseProcessingMixin, AllAtOnceStrategyMixin, RunRemotelyBase
):
def __init__(self, report_processor):
super().__init__(report_processor)
self._request_data_list = []
def _prepare_initial_requests(self):
return [
Request(
target,
RequestData("remote/set_sbd_config", [("config", config)]),
)
for target, config in self._request_data_list
]
def _get_success_report(self, node_label):
return ReportItem.info(
reports.messages.SbdConfigAcceptedByNode(node_label)
)
def add_request(self, target, config):
self._request_data_list.append((target, config))
def before(self):
self._report(
ReportItem.info(reports.messages.SbdConfigDistributionStarted())
)
class GetSbdConfig(AllSameDataMixin, AllAtOnceStrategyMixin, RunRemotelyBase):
def __init__(self, report_processor):
super().__init__(report_processor)
self._config_list = []
self._successful_target_list = []
def _get_request_data(self):
return RequestData("remote/get_sbd_config")
def _process_response(self, response):
report_item = response_to_report_item(
response, severity=ReportItemSeverity.WARNING
)
node_label = response.request.target.label
if report_item is not None:
if not response.was_connected:
self._report(report_item)
self._report(
ReportItem.warning(
reports.messages.UnableToGetSbdConfig(node_label, "")
)
)
return
self._config_list.append(
{
"node": node_label,
"config": environment_file_to_dict(response.data),
}
)
self._successful_target_list.append(node_label)
def on_complete(self):
for node in self._target_list:
if node.label not in self._successful_target_list:
self._config_list.append({"node": node.label, "config": None})
return self._config_list
class GetSbdStatus(AllSameDataMixin, AllAtOnceStrategyMixin, RunRemotelyBase):
def __init__(self, report_processor):
super().__init__(report_processor)
self._status_list = []
self._successful_target_list = []
def _get_request_data(self):
return RequestData(
"remote/check_sbd",
# here we just need info about sbd service, therefore watchdog and
# device list is empty
[
("watchdog", ""),
("device_list", "[]"),
],
)
def _process_response(self, response):
report_item = response_to_report_item(
response, severity=ReportItemSeverity.WARNING
)
node_label = response.request.target.label
if report_item is not None:
self._report_list(
[
report_item,
# reason is in previous report item, warning is there
# implicit
ReportItem.warning(
reports.messages.UnableToGetSbdStatus(node_label, "")
),
]
)
return
try:
self._status_list.append(
{"node": node_label, "status": json.loads(response.data)["sbd"]}
)
self._successful_target_list.append(node_label)
except (ValueError, KeyError) as e:
self._report(
ReportItem.warning(
reports.messages.UnableToGetSbdStatus(node_label, str(e))
)
)
def on_complete(self):
for node in self._target_list:
if node.label not in self._successful_target_list:
self._status_list.append(
{
"node": node.label,
"status": {
"installed": None,
"enabled": None,
"running": None,
},
}
)
return self._status_list
class CheckSbd(AllAtOnceStrategyMixin, RunRemotelyBase):
def __init__(self, report_processor):
super().__init__(report_processor)
self._request_data_list = []
def _prepare_initial_requests(self):
return [
Request(
target,
RequestData(
"remote/check_sbd",
[
("watchdog", watchdog),
("device_list", json.dumps(device_list)),
],
),
)
for target, watchdog, device_list in self._request_data_list
]
def _process_response(self, response):
report_item = response_to_report_item(response)
if report_item:
self._report(report_item)
return
report_list = []
node_label = response.request.target.label
try:
data = json.loads(response.data)
if not data["sbd"]["installed"]:
report_list.append(
ReportItem.error(
reports.messages.SbdNotInstalled(node_label)
)
)
if "watchdog" in data:
if data["watchdog"]["exist"]:
if not data["watchdog"].get("is_supported", True):
report_list.append(
ReportItem.error(
reports.messages.SbdWatchdogNotSupported(
node_label, data["watchdog"]["path"]
)
)
)
else:
report_list.append(
ReportItem.error(
reports.messages.WatchdogNotFound(
node_label, data["watchdog"]["path"]
)
)
)
for device in data.get("device_list", []):
if not device["exist"]:
report_list.append(
ReportItem.error(
reports.messages.SbdDeviceDoesNotExist(
device["path"], node_label
)
)
)
elif not device["block_device"]:
report_list.append(
ReportItem.error(
reports.messages.SbdDeviceIsNotBlockDevice(
device["path"], node_label
)
)
)
# TODO maybe we can check whenever device is initialized by sbd
# (by running 'sbd -d <dev> dump;')
except (ValueError, KeyError, TypeError):
report_list.append(
ReportItem.error(
reports.messages.InvalidResponseFormat(node_label)
)
)
if report_list:
self._report_list(report_list)
else:
self._report(
ReportItem.info(
reports.messages.SbdCheckSuccess(
response.request.target.label
)
)
)
def add_request(self, target, watchdog, device_list):
self._request_data_list.append((target, watchdog, device_list))
def before(self):
self._report(ReportItem.info(reports.messages.SbdCheckStarted()))
| gpl-2.0 | -8,674,690,028,321,442,000 | 31.241176 | 80 | 0.530743 | false |
reiniervdwindt/power-rangers-api | src/api/v1/rangers/serializers.py | 1 | 1093 | from rest_framework import serializers
from rangers.models import Appearance, Ranger
from weapons.models import Weapon
from zords.models import Zord
class RangerWeaponSerializer(serializers.ModelSerializer):
class Meta(object):
fields = ('id', 'name', 'type',)
model = Weapon
class RangerZordSerializer(serializers.ModelSerializer):
class Meta(object):
fields = ('id', 'name', 'type',)
model = Zord
class SeriesSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='series')
weapon = RangerWeaponSerializer()
zord = RangerZordSerializer()
class Meta(object):
fields = ('name', 'weapon', 'zord',)
model = Appearance
class RangerDetailSerializer(serializers.ModelSerializer):
series = SeriesSerializer(source='appearance_set', many=True)
class Meta(object):
fields = ('id', 'name', 'color', 'series',)
model = Ranger
class RangerListSerializer(serializers.ModelSerializer):
class Meta(object):
fields = ('id', 'name', 'color',)
model = Ranger
| mit | -700,959,239,394,694,900 | 25.658537 | 65 | 0.67978 | false |
kevdougful/PyWeather | Server/forecastdata.py | 1 | 9833 | """Classes for encapsulating forecast data.
This file is part of PyWeather.
PyWeather 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.
PyWeather 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 PyWeather. If not, see <http://www.gnu.org/licenses/>.
Inspiration as well as coding strategies are borrowed heavily from
Matthew Petroff's Kindle Weather Display project.
http://mpetroff.net/2012/09/kindle-weather-display/
https://github.com/mpetroff/kindle-weather-display
"""
from apirequest import xml_request
from datetime import datetime
def _getNodeValue(xml_element, tag_name):
"""Extracts the enclosed text from a specific tag within an XML element
Args:
xml_element: XML element to extract from.
tag_name: Specific tag (by name) from which to extract enclosed text.
Returns:
The enclosed text.
"""
element_string = xml_element.toxml()
# handle self closing tags
if element_string.find('/>', 0, len(element_string)) > -1:
return 0.0
else:
return xml_element.getElementsByTagName(tag_name)[0].firstChild.nodeValue
class Forecast(object):
"""Encapsulates all data from a particular forecast.
This class is responsible for making the API request and parsing and storing
the response data in a collection of ForecastDay objects.
Attributes:
ForecastDays: list of ForecastDay objects containing the forecast's data.
"""
def __init__(self, request_query):
"""Creates a new instance of the Forecast class.
Args:
request_query: Geographical location for which to request.
Acceptable forms:
<State>/<City> (e.g. MO/St_Louis)
<ZIP Code> (e.g. 63167)
<County>/<City? (e.g. Australia/Sydney)
<latitude>/<longitude> (e.g. 37.8,-122.4)
<Airport code> (e.g. KJFK)
<PWS id> (e.g. pws:KCASANFR70)
AutoIP (e.g. autoip)
specific IP (e.g. autoip.xml?geo_ip=38.102.136.138)
Returns:
A new instance of the Forecast class.
"""
xml = xml_request('forecast', request_query)
txt_forecast = xml.getElementsByTagName('txt_forecast')
simpleforecast = xml.getElementsByTagName('simpleforecast')
self.ForecastDays = list()
# The API response is broken into two main sections: txt_forecast and
# simpleforecast. txt_forecast contains data for day and night,
# including a short, plain english description of the data.
# simpleforecast contains data for each calendar day but does not
# include any descriptions. The Forecast object is responsible to
# creating ForecastDay objects that contain all the data from both
# txt_forecast and simpleforecast for a particular calendar day.
# Get all forecastday elements from simple forecast
simplexml = list()
for simpleday in simpleforecast[0].getElementsByTagName('forecastday'):
simplexml.append(simpleday)
# Get all periods in the txt_forecast
txtdays = txt_forecast[0].getElementsByTagName('forecastday')
# Get day forecastday elements from txt_forecast
dayxml = list()
for i in range(0, 8, 2):
dayxml.append(txtdays[i])
# Get night forecastday elements from txt_forecast
nightxml = list()
for i in range(1, 9, 2):
nightxml.append(txtdays[i])
# Create ForecastDay objects
for i in range(0, 4):
self.ForecastDays.append(ForecastDay(dayxml[i], nightxml[i], simplexml[i]))
class ForecastDay(object):
"""Encapsulates data from both txt_forecast and simpleforecast for a single day.
txt_forecast contains data for day and night, including a short, plain
english description of the data. simpleforecast contains data for each
calendar day but does not include any descriptions.
Attributes:
forecast_date: datetime object for day this object represents.
day_icon: SVG icon name to use for the day-time forecast.
night_icon: SVG icon name to use for the night-time forecast.
day_text: Plain english description of the day-time forecast.
night_text: Plain english description of the night-time forecast.
pop: Probability of precipitation for entire day.
day_pop: Probability of precipitation for day-time.
night_pop: Probability of precipitation for night-time.
period: Relative position of day in the rest of the forecast (1 = today).
high_F: Forecasted high temperature (fahrenheit).
low_F: Forecasted low temperature (fahrenheit).
humidity: Forecasted relative humidity.
qpf_allday_in: Quantity of precipitation forecasted for entire day (inches).
qpf_day_in: Quantity of precipitation forecasted for day-time (inches).
qpf_night_in: Quantity of precipitation forecasted for night-time (inches).
minwind_mph: Minimum wind speed forecasted (miles per hour).
minwind_degrees: Forecasted prevailing wind direction (compass heading 0-360).
minwind_dir: Forecasted prevailing wind direction (e.g. NNE).
maxwind_mph: Maximum wind speed forecasted (miles per hour).
maxwind_degrees: Forecasted prevailing wind direction (compass heading 0-360).
maxwind_dir: Forecasted prevailing wind direction (e.g. NNE).
"""
def __init__(self, day_xml, night_xml, simple_xml):
"""Creates a new instance of the ForecastDay class.
Args:
day_xml: The day-time periods of the txt_forecast section.
night_xml: The day-time periods of the txt_forecast section.
simple_xml: The simpleforecast section of the API response.
Returns:
A new instance of the ForecastDay class.
"""
# NOTE:
# metric values not yet implemented
# snow_allday, snow_day, snow_night elements not yet implemented
# set the date
epoch = simple_xml.getElementsByTagName('epoch')[0].firstChild.nodeValue
self.forecast_date = datetime.fromtimestamp(int(epoch))
# txt_forecast elements
self.day_icon = _getNodeValue(day_xml, 'icon')
self.night_icon = _getNodeValue(night_xml, 'icon')
self.day_text = _getNodeValue(day_xml, 'fcttext')
self.night_text = _getNodeValue(night_xml, 'fcttext')
# probability of precipitation
self.pop = simple_xml.getElementsByTagName('pop')[0].firstChild.nodeValue
self.day_pop = int(_getNodeValue(day_xml, 'pop'))
self.night_pop = int(_getNodeValue(night_xml, 'pop'))
# simpleforecast elements
self.period = simple_xml.getElementsByTagName('period')[0].firstChild.nodeValue
high = simple_xml.getElementsByTagName('high')
self.high_F = int(_getNodeValue(high[0], 'fahrenheit'))
low = simple_xml.getElementsByTagName('low')
self.low_F = int(_getNodeValue(low[0], 'fahrenheit'))
self.humidity = simple_xml.getElementsByTagName('avehumidity')[0].firstChild.nodeValue
# quantity precipitation forecasted
qpf_allday = simple_xml.getElementsByTagName('qpf_allday')
self.qpf_allday_in = float(_getNodeValue(qpf_allday[0], 'in'))
qpf_day = simple_xml.getElementsByTagName('qpf_day')
self.qpf_day_in = float(_getNodeValue(qpf_day[0], 'in'))
qpf_night = simple_xml.getElementsByTagName('qpf_night')
self.qpf_night_in = float(_getNodeValue(qpf_night[0], 'in'))
# wind
minwind = simple_xml.getElementsByTagName('avewind')
self.minwind_mph = int(_getNodeValue(minwind[0], 'mph'))
self.minwind_degrees = float(_getNodeValue(minwind[0], 'degrees'))
self.minwind_dir = _getNodeValue(minwind[0], 'dir')
maxwind = simple_xml.getElementsByTagName('maxwind')
self.maxwind_mph = int(_getNodeValue(maxwind[0], 'mph'))
self.maxwind_degrees = float(_getNodeValue(maxwind[0], 'degrees'))
self.maxwind_dir = _getNodeValue(maxwind[0], 'dir')
def __str__(self):
"""Creates a neatly formatted string using this object's encapsulated data.
Returns:
Neatly formatted string using this object's encapsulated data.
"""
output = self.forecast_date.strftime('%A %b-%d-%Y') + '\n'
output += '\tHigh: ' + str(self.high_F) + '\n'
output += '\tLow: ' + str(self.low_F) + '\n'
output += '\tHumidity: ' + str(self.humidity) + '\n'
output += '\tprecip: ' + str(self.qpf_allday_in) + '\"\n'
output += '\tchance: ' + str(self.pop) + '%\n'
output += '\twinds: ' + self.minwind_dir + ' @ ' \
+ str(self.minwind_mph) + '-' + str(self.maxwind_mph) + 'mph\n'
output += '\tDay-time:\n'
output += '\t\t' + self.day_text + '\n'
output += '\t\tprecip: ' + str(self.qpf_day_in) + '\"\n'
output += '\t\tchance: ' + str(self.day_pop) + '%\n'
output += '\tNight-time:\n'
output += '\t\t' + self.night_text + '\n'
output += '\t\tprecip: ' + str(self.qpf_night_in) + '\"\n'
output += '\t\tchance: ' + str(self.night_pop) + '%\n'
return output | gpl-2.0 | 6,107,496,749,409,317,000 | 43.497738 | 94 | 0.643242 | false |
helenjin/scanalysis | src/scanalysis/sca_gui.py | 1 | 7517 | #!/usr/local/bin/python3
import tkinter as tk
from tkinter import filedialog, ttk
class sca_gui(tk.Tk):
def __init__(self, parent):
tk.Tk.__init__(self, parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.vals = None
self.currentPlot = None
self.data = {}
#set up menu bar
self.menubar = tk.Menu(self)
self.fileMenu = tk.Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label="File", menu=self.fileMenu)
self.fileMenu.add_command(label="Load csv file", command=self.loadCSV)
# self.fileMenu.add_command(label="Load sparse data file", command=self.loadMTX)
# self.fileMenu.add_command(label="Load 10x file", command=self.load10x)
# self.fileMenu.add_command(label="Load saved session from pickle file", command=self.loadPickle)
# self.fileMenu.add_command(label="Save data", state='disabled', command=self.saveData)
# self.fileMenu.add_command(label="Exit", command=self.quitMAGIC)
# self.analysisMenu = tk.Menu(self.menubar, tearoff=0)
# self.menubar.add_cascade(label="Analysis", menu=self.analysisMenu)
# self.analysisMenu.add_command(label="Principal component analysis", state='disabled', command=self.runPCA)
# self.analysisMenu.add_command(label="tSNE", state='disabled', command=self.runTSNE)
# self.analysisMenu.add_command(label="Diffusion map", state='disabled', command=self.runDM)
# self.analysisMenu.add_command(label="MAGIC", state='disabled', command=self.runMagic)
# self.visMenu = tk.Menu(self.menubar, tearoff=0)
# self.menubar.add_cascade(label="Visualization", menu=self.visMenu)
# self.visMenu.add_command(label="Scatter plot", state='disabled', command=self.scatterPlot)
# self.visMenu.add_command(label="PCA-variance plot", state='disabled', command=self.plotPCAVariance)
self.config(menu=self.menubar)
#intro screen
tk.Label(self, text=u"SCAnalysis", font=('Helvetica', 48), fg="black", bg="white", padx=100, pady=20).grid(row=0)
tk.Label(self, text=u"Single Cell Analysis", font=('Helvetica', 25), fg="black", bg="white", padx=100, pady=40).grid(row=1)
tk.Label(self, text=u"Includes Wishbone, MAGIC, and Palantir", font=('Helvetica', 20), fg="black", bg="white", padx=100, pady=40).grid(row=2)
tk.Label(self, text=u"To get started, select a data file by clicking File > Load Data", fg="black", bg="white", padx=100, pady=25).grid(row=3)
#update
self.protocol('WM_DELETE_WINDOW', self.quitGUI)
self.grid_columnconfigure(0,weight=1)
self.resizable(True,True)
self.update()
self.geometry(self.geometry())
self.focus_force()
def loadCSV(self):
self.dataFileName = filedialog.askopenfilename(title='Load data file', initialdir='~/.magic/data')
if(self.dataFileName != ""):
#pop up data options menu
self.fileInfo = tk.Toplevel()
self.fileInfo.title("Data options")
tk.Label(self.fileInfo, text=u"File name: ").grid(column=0, row=0)
tk.Label(self.fileInfo, text=self.dataFileName.split('/')[-1]).grid(column=1, row=0)
tk.Label(self.fileInfo,text=u"Name:" ,fg="black",bg="white").grid(column=0, row=1)
self.fileNameEntryVar = tk.StringVar()
self.fileNameEntryVar.set('Data ' + str(len(self.data)))
tk.Entry(self.fileInfo, textvariable=self.fileNameEntryVar).grid(column=1,row=1)
tk.Label(self.fileInfo, text=u"Delimiter:").grid(column=0, row=2)
self.delimiter = tk.StringVar()
self.delimiter.set(',')
tk.Entry(self.fileInfo, textvariable=self.delimiter).grid(column=1, row=2)
tk.Label(self.fileInfo, text=u"Rows:", fg="black",bg="white").grid(column=0, row=3)
self.rowVar = tk.IntVar()
self.rowVar.set(0)
tk.Radiobutton(self.fileInfo, text="Cells", variable=self.rowVar, value=0).grid(column=1, row=3)
tk.Radiobutton(self.fileInfo, text="Genes", variable=self.rowVar, value=1).grid(column=2, row=3)
tk.Label(self.fileInfo, text=u"Number of additional rows/columns to skip after gene/cell names").grid(column=0, row=4, columnspan=3)
tk.Label(self.fileInfo, text=u"Number of rows:").grid(column=0, row=5)
self.rowHeader = tk.IntVar()
self.rowHeader.set(0)
tk.Entry(self.fileInfo, textvariable=self.rowHeader).grid(column=1, row=5)
tk.Label(self.fileInfo, text=u"Number of columns:").grid(column=0, row=6)
self.colHeader = tk.IntVar()
self.colHeader.set(0)
tk.Entry(self.fileInfo, textvariable=self.colHeader).grid(column=1, row=6)
tk.Button(self.fileInfo, text="Compute data statistics", command=partial(self.showRawDataDistributions, file_type='csv')).grid(column=1, row=7)
#filter parameters
self.filterCellMinVar = tk.StringVar()
tk.Label(self.fileInfo,text=u"Filter by molecules per cell. Min:" ,fg="black",bg="white").grid(column=0, row=8)
tk.Entry(self.fileInfo, textvariable=self.filterCellMinVar).grid(column=1,row=8)
self.filterCellMaxVar = tk.StringVar()
tk.Label(self.fileInfo, text=u" Max:" ,fg="black",bg="white").grid(column=2, row=8)
tk.Entry(self.fileInfo, textvariable=self.filterCellMaxVar).grid(column=3,row=8)
self.filterGeneNonzeroVar = tk.StringVar()
tk.Label(self.fileInfo,text=u"Filter by nonzero cells per gene. Min:" ,fg="black",bg="white").grid(column=0, row=9)
tk.Entry(self.fileInfo, textvariable=self.filterGeneNonzeroVar).grid(column=1,row=9)
self.filterGeneMolsVar = tk.StringVar()
tk.Label(self.fileInfo,text=u"Filter by molecules per gene. Min:" ,fg="black",bg="white").grid(column=0, row=10)
tk.Entry(self.fileInfo, textvariable=self.filterGeneMolsVar).grid(column=1,row=10)
#normalize
self.normalizeVar = tk.BooleanVar()
self.normalizeVar.set(True)
tk.Checkbutton(self.fileInfo, text=u"Normalize by library size", variable=self.normalizeVar).grid(column=0, row=11, columnspan=4)
#log transform
self.logTransform = tk.BooleanVar()
self.logTransform.set(False)
tk.Checkbutton(self.fileInfo, text=u"Log-transform data", variable=self.logTransform).grid(column=0, row=12)
self.pseudocount = tk.DoubleVar()
self.pseudocount.set(0.1)
tk.Label(self.fileInfo, text=u"Pseudocount (for log-transform)", fg="black",bg="white").grid(column=1, row=12)
tk.Entry(self.fileInfo, textvariable=self.pseudocount).grid(column=2, row=12)
tk.Button(self.fileInfo, text="Cancel", command=self.fileInfo.destroy).grid(column=1, row=13)
tk.Button(self.fileInfo, text="Load", command=partial(self.processData, file_type='csv')).grid(column=2, row=13)
self.wait_window(self.fileInfo)
def quitGUI(self):
self.quit()
self.destroy()
def launch():
app = sca_gui(None)
app.title('SCAnalysis')
try:
app.mainloop()
except UnicodeDecodeError:
pass
if __name__ == "__main__":
launch()
| gpl-2.0 | 659,605,362,825,649,500 | 49.449664 | 155 | 0.634562 | false |
nharraud/invenio-demosite | invenio_demosite/config.py | 7 | 1033 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio Demosite.
# Copyright (C) 2014 CERN.
#
# Invenio Demosite is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio Demosite is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02D111-1307, USA.
from invenio.base.config import PACKAGES as _PACKAGES
PACKAGES = [
"invenio_demosite.base",
"invenio_demosite.modules.*",
] + _PACKAGES
DEPOSIT_TYPES = [
'invenio_demosite.modules.deposit.workflows.article.article',
]
| gpl-2.0 | -5,843,752,253,668,208,000 | 34.62069 | 74 | 0.743466 | false |
ysuarez/Evergreen-Customizations | Open-ILS/src/extras/Evergreen.py | 11 | 2004 | """
Evergreen IRC Interface plugin for supybot
"""
import supybot
import urllib
import xml.dom.minidom
import re
__revision__ = "$Id$"
__author__ = 'PINES'
__contributors__ = {}
import supybot.conf as conf
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.ircmsgs as ircmsgs
import supybot.privmsgs as privmsgs
import supybot.registry as registry
import supybot.callbacks as callbacks
def configure(advanced):
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('Evergreen', True)
conf.registerPlugin('Evergreen')
class Evergreen(callbacks.PrivmsgCommandAndRegexp):
threaded = True
def __init__(self):
self.__parent = super(Evergreen, self)
self.__parent.__init__()
#super(Evergreen, self).__init__()
def callCommand(self, name, irc, msg, *L, **kwargs):
self.__parent.callCommand(name, irc, msg, *L, **kwargs)
def osearch(self, irc, msg, args, word):
"""<terms>
Performs an OpenSearch against Evergreen for <terms>.
"""
url = 'http://192.168.2.112/opensearch/?target=mr_result&mr_search_type=keyword&mr_search_query=' + urllib.quote(word) + '&page=1&mr_search_depth=0&mr_search_location=1&pagesize=5&max_rank=100'
irc.reply( 'Searching for ' + word + '...' );
rss = urllib.urlopen( url )
dom = xml.dom.minidom.parseString( rss.read() )
regexp = re.compile(r'http://tinyurl.com/\w+');
for item in dom.getElementsByTagName('item'):
title = item.getElementsByTagName('title')[0]
link = item.getElementsByTagName('link')[0]
f = urllib.urlopen('http://tinyurl.com/create.php?url='+link.firstChild.data)
tiny = regexp.search( f.read() ).group(0)
s = title.firstChild.data
s += " | " + tiny
irc.reply( s )
osearch = wrap(osearch, ['Text'])
Class = Evergreen
| gpl-2.0 | 5,851,850,775,180,706,000 | 31.852459 | 201 | 0.649202 | false |
erinspace/osf.io | website/profile/utils.py | 3 | 6903 | # -*- coding: utf-8 -*-
from framework import auth
from website import settings
from osf.models import Contributor
from website.filters import profile_image_url
from osf.models.contributor import get_contributor_permissions
from osf.utils.permissions import reduce_permissions
from osf.utils import workflows
def get_profile_image_url(user, size=settings.PROFILE_IMAGE_MEDIUM):
return profile_image_url(settings.PROFILE_IMAGE_PROVIDER,
user,
use_ssl=True,
size=size)
def serialize_user(user, node=None, admin=False, full=False, is_profile=False, include_node_counts=False):
"""
Return a dictionary representation of a registered user.
:param User user: A User object
:param bool full: Include complete user properties
"""
contrib = None
if isinstance(user, Contributor):
contrib = user
user = contrib.user
fullname = user.display_full_name(node=node)
ret = {
'id': str(user._id),
'registered': user.is_registered,
'surname': user.family_name,
'fullname': fullname,
'shortname': fullname if len(fullname) < 50 else fullname[:23] + '...' + fullname[-23:],
'profile_image_url': user.profile_image_url(size=settings.PROFILE_IMAGE_MEDIUM),
'active': user.is_active,
}
if node is not None:
if admin:
flags = {
'visible': False,
'permission': 'read',
}
else:
is_contributor_obj = isinstance(contrib, Contributor)
flags = {
'visible': contrib.visible if is_contributor_obj else node.contributor_set.filter(user=user, visible=True).exists(),
'permission': get_contributor_permissions(contrib, as_list=False) if is_contributor_obj else reduce_permissions(node.get_permissions(user)),
}
ret.update(flags)
if user.is_registered:
ret.update({
'url': user.url,
'absolute_url': user.absolute_url,
'display_absolute_url': user.display_absolute_url,
'date_registered': user.date_registered.strftime('%Y-%m-%d'),
})
if full:
# Add emails
if is_profile:
ret['emails'] = [
{
'address': each,
'primary': each.strip().lower() == user.username.strip().lower(),
'confirmed': True,
} for each in user.emails.values_list('address', flat=True)
] + [
{
'address': each,
'primary': each.strip().lower() == user.username.strip().lower(),
'confirmed': False
}
for each in user.get_unconfirmed_emails_exclude_external_identity()
]
if user.is_merged:
merger = user.merged_by
merged_by = {
'id': str(merger._primary_key),
'url': merger.url,
'absolute_url': merger.absolute_url
}
else:
merged_by = None
ret.update({
'activity_points': user.get_activity_points(),
'profile_image_url': user.profile_image_url(size=settings.PROFILE_IMAGE_LARGE),
'is_merged': user.is_merged,
'merged_by': merged_by,
})
if include_node_counts:
projects = user.nodes.exclude(is_deleted=True).filter(type='osf.node').get_roots()
ret.update({
'number_projects': projects.count(),
'number_public_projects': projects.filter(is_public=True).count(),
})
return ret
def serialize_contributors(contribs, node, **kwargs):
return [
serialize_user(contrib, node, **kwargs)
for contrib in contribs
]
def serialize_visible_contributors(node):
# This is optimized when node has .include('contributor__user__guids')
return [
serialize_user(c, node) for c in node.contributor_set.all() if c.visible
]
def add_contributor_json(user, current_user=None, node=None):
"""
Generate a dictionary representation of a user, optionally including # projects shared with `current_user`
:param User user: The user object to serialize
:param User current_user : The user object for a different user, to calculate number of projects in common
:return dict: A dict representing the serialized user data
"""
# get shared projects
if current_user:
n_projects_in_common = current_user.n_projects_in_common(user)
else:
n_projects_in_common = 0
current_employment = None
education = None
if user.jobs:
current_employment = user.jobs[0]['institution']
if user.schools:
education = user.schools[0]['institution']
contributor_json = {
'fullname': user.fullname,
'email': user.email,
'id': user._primary_key,
'employment': current_employment,
'education': education,
'n_projects_in_common': n_projects_in_common,
'registered': user.is_registered,
'active': user.is_active,
'profile_image_url': user.profile_image_url(size=settings.PROFILE_IMAGE_MEDIUM),
'profile_url': user.profile_url
}
if node:
contributor_info = user.contributor_set.get(node=node.parent_node)
contributor_json['permission'] = get_contributor_permissions(contributor_info, as_list=False)
contributor_json['visible'] = contributor_info.visible
return contributor_json
def serialize_unregistered(fullname, email):
"""Serializes an unregistered user."""
user = auth.get_user(email=email)
if user is None:
serialized = {
'fullname': fullname,
'id': None,
'registered': False,
'active': False,
'profile_image_url': profile_image_url(settings.PROFILE_IMAGE_PROVIDER,
email,
use_ssl=True,
size=settings.PROFILE_IMAGE_MEDIUM),
'email': email,
}
else:
serialized = add_contributor_json(user)
serialized['fullname'] = fullname
serialized['email'] = email
return serialized
def serialize_access_requests(node):
"""Serialize access requests for a node"""
return [
{
'user': serialize_user(access_request.creator),
'comment': access_request.comment,
'id': access_request._id
} for access_request in node.requests.filter(
request_type=workflows.RequestTypes.ACCESS.value,
machine_state=workflows.DefaultStates.PENDING.value
).select_related('creator')
]
| apache-2.0 | 3,013,846,338,002,016,000 | 34.219388 | 156 | 0.578299 | false |
momingsong/ns-3 | src/applications/bindings/modulegen__gcc_LP64.py | 28 | 717210 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
return True
pybindgen.settings.error_handler = ErrorHandler()
import sys
def module_init():
root_module = Module('ns.applications', cpp_namespace='::ns3')
return root_module
def register_types(module):
root_module = module.get_root()
## packetbb.h (module 'network'): ns3::PbbAddressLength [enumeration]
module.add_enum('PbbAddressLength', ['IPV4', 'IPV6'], import_from_module='ns.network')
## ethernet-header.h (module 'network'): ns3::ethernet_header_t [enumeration]
module.add_enum('ethernet_header_t', ['LENGTH', 'VLAN', 'QINQ'], import_from_module='ns.network')
## address.h (module 'network'): ns3::Address [class]
module.add_class('Address', import_from_module='ns.network')
## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration]
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
## application-container.h (module 'network'): ns3::ApplicationContainer [class]
module.add_class('ApplicationContainer', import_from_module='ns.network')
## ascii-file.h (module 'network'): ns3::AsciiFile [class]
module.add_class('AsciiFile', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class]
module.add_class('AsciiTraceHelper', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class]
module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True, import_from_module='ns.network')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class]
module.add_class('AttributeConstructionList', import_from_module='ns.core')
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct]
module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList'])
## average.h (module 'stats'): ns3::Average<double> [class]
module.add_class('Average', import_from_module='ns.stats', template_parameters=['double'])
## buffer.h (module 'network'): ns3::Buffer [class]
module.add_class('Buffer', import_from_module='ns.network')
## buffer.h (module 'network'): ns3::Buffer::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer'])
## bulk-send-helper.h (module 'applications'): ns3::BulkSendHelper [class]
module.add_class('BulkSendHelper')
## packet.h (module 'network'): ns3::ByteTagIterator [class]
module.add_class('ByteTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::ByteTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList [class]
module.add_class('ByteTagList', import_from_module='ns.network')
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class]
module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList'])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator'])
## callback.h (module 'core'): ns3::CallbackBase [class]
module.add_class('CallbackBase', import_from_module='ns.core')
## channel-list.h (module 'network'): ns3::ChannelList [class]
module.add_class('ChannelList', import_from_module='ns.network')
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback [class]
module.add_class('DataOutputCallback', allow_subclassing=True, import_from_module='ns.stats')
## data-rate.h (module 'network'): ns3::DataRate [class]
module.add_class('DataRate', import_from_module='ns.network')
## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation [class]
module.add_class('DelayJitterEstimation', 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')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
module.add_class('Inet6SocketAddress', import_from_module='ns.network')
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class]
root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
module.add_class('InetSocketAddress', import_from_module='ns.network')
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class]
root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
module.add_class('Ipv4Address', import_from_module='ns.network')
## ipv4-address.h (module 'network'): ns3::Ipv4Address [class]
root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class]
module.add_class('Ipv6Prefix', import_from_module='ns.network')
## mac16-address.h (module 'network'): ns3::Mac16Address [class]
module.add_class('Mac16Address', import_from_module='ns.network')
## mac16-address.h (module 'network'): ns3::Mac16Address [class]
root_module['ns3::Mac16Address'].implicitly_converts_to(root_module['ns3::Address'])
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
module.add_class('Mac48Address', import_from_module='ns.network')
## mac48-address.h (module 'network'): ns3::Mac48Address [class]
root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address'])
## mac64-address.h (module 'network'): ns3::Mac64Address [class]
module.add_class('Mac64Address', import_from_module='ns.network')
## mac64-address.h (module 'network'): ns3::Mac64Address [class]
root_module['ns3::Mac64Address'].implicitly_converts_to(root_module['ns3::Address'])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class]
module.add_class('NetDeviceContainer', import_from_module='ns.network')
## node-container.h (module 'network'): ns3::NodeContainer [class]
module.add_class('NodeContainer', import_from_module='ns.network')
## node-list.h (module 'network'): ns3::NodeList [class]
module.add_class('NodeList', import_from_module='ns.network')
## non-copyable.h (module 'core'): ns3::NonCopyable [class]
module.add_class('NonCopyable', destructor_visibility='protected', import_from_module='ns.core')
## object-base.h (module 'core'): ns3::ObjectBase [class]
module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core')
## object.h (module 'core'): ns3::ObjectDeleter [struct]
module.add_class('ObjectDeleter', import_from_module='ns.core')
## object-factory.h (module 'core'): ns3::ObjectFactory [class]
module.add_class('ObjectFactory', import_from_module='ns.core')
## on-off-helper.h (module 'applications'): ns3::OnOffHelper [class]
module.add_class('OnOffHelper')
## packet-loss-counter.h (module 'applications'): ns3::PacketLossCounter [class]
module.add_class('PacketLossCounter')
## packet-metadata.h (module 'network'): ns3::PacketMetadata [class]
module.add_class('PacketMetadata', import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration]
module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network')
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class]
module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata'])
## packet-sink-helper.h (module 'applications'): ns3::PacketSinkHelper [class]
module.add_class('PacketSinkHelper')
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class]
module.add_class('PacketSocketAddress', import_from_module='ns.network')
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress [class]
root_module['ns3::PacketSocketAddress'].implicitly_converts_to(root_module['ns3::Address'])
## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper [class]
module.add_class('PacketSocketHelper', import_from_module='ns.network')
## packet.h (module 'network'): ns3::PacketTagIterator [class]
module.add_class('PacketTagIterator', import_from_module='ns.network')
## packet.h (module 'network'): ns3::PacketTagIterator::Item [class]
module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator'])
## packet-tag-list.h (module 'network'): ns3::PacketTagList [class]
module.add_class('PacketTagList', import_from_module='ns.network')
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct]
module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList'])
## 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')
## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock [class]
module.add_class('PbbAddressTlvBlock', import_from_module='ns.network')
## packetbb.h (module 'network'): ns3::PbbTlvBlock [class]
module.add_class('PbbTlvBlock', import_from_module='ns.network')
## pcap-file.h (module 'network'): ns3::PcapFile [class]
module.add_class('PcapFile', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelper [class]
module.add_class('PcapHelper', import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelper [enumeration]
module.add_enum('', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_LINUX_SSL', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO', 'DLT_IEEE802_15_4', 'DLT_NETLINK'], outer_class=root_module['ns3::PcapHelper'], import_from_module='ns.network')
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class]
module.add_class('PcapHelperForDevice', allow_subclassing=True, import_from_module='ns.network')
## ping6-helper.h (module 'applications'): ns3::Ping6Helper [class]
module.add_class('Ping6Helper')
## radvd-helper.h (module 'applications'): ns3::RadvdHelper [class]
module.add_class('RadvdHelper')
## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper [class]
module.add_class('SimpleNetDeviceHelper', import_from_module='ns.network')
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simulator.h (module 'core'): ns3::Simulator [class]
module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core')
## data-calculator.h (module 'stats'): ns3::StatisticalSummary [class]
module.add_class('StatisticalSummary', allow_subclassing=True, import_from_module='ns.stats')
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs [class]
module.add_class('SystemWallClockMs', import_from_module='ns.core')
## tag.h (module 'network'): ns3::Tag [class]
module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase'])
## tag-buffer.h (module 'network'): ns3::TagBuffer [class]
module.add_class('TagBuffer', import_from_module='ns.network')
## 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'])
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper [class]
module.add_class('UdpClientHelper')
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper [class]
module.add_class('UdpEchoClientHelper')
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoServerHelper [class]
module.add_class('UdpEchoServerHelper')
## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper [class]
module.add_class('UdpServerHelper')
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper [class]
module.add_class('UdpTraceClientHelper')
## v4ping-helper.h (module 'applications'): ns3::V4PingHelper [class]
module.add_class('V4PingHelper')
## empty.h (module 'core'): ns3::empty [class]
module.add_class('empty', import_from_module='ns.core')
## int64x64-double.h (module 'core'): ns3::int64x64_t [class]
module.add_class('int64x64_t', import_from_module='ns.core')
## 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'])
## packet-socket.h (module 'network'): ns3::DeviceNameTag [class]
module.add_class('DeviceNameTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## flow-id-tag.h (module 'network'): ns3::FlowIdTag [class]
module.add_class('FlowIdTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## header.h (module 'network'): ns3::Header [class]
module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk'])
## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader [class]
module.add_class('LlcSnapHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
## object.h (module 'core'): ns3::Object [class]
module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
## object.h (module 'core'): ns3::Object::AggregateIterator [class]
module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object'])
## packet-burst.h (module 'network'): ns3::PacketBurst [class]
module.add_class('PacketBurst', import_from_module='ns.network', parent=root_module['ns3::Object'])
## packet-socket.h (module 'network'): ns3::PacketSocketTag [class]
module.add_class('PacketSocketTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class]
module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=root_module['ns3::Object'])
## queue.h (module 'network'): ns3::Queue [class]
module.add_class('Queue', import_from_module='ns.network', parent=root_module['ns3::Object'])
## queue.h (module 'network'): ns3::Queue::QueueMode [enumeration]
module.add_enum('QueueMode', ['QUEUE_MODE_PACKETS', 'QUEUE_MODE_BYTES'], outer_class=root_module['ns3::Queue'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [class]
module.add_class('RadiotapHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [enumeration]
module.add_enum('', ['FRAME_FLAG_NONE', 'FRAME_FLAG_CFP', 'FRAME_FLAG_SHORT_PREAMBLE', 'FRAME_FLAG_WEP', 'FRAME_FLAG_FRAGMENTED', 'FRAME_FLAG_FCS_INCLUDED', 'FRAME_FLAG_DATA_PADDING', 'FRAME_FLAG_BAD_FCS', 'FRAME_FLAG_SHORT_GUARD'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [enumeration]
module.add_enum('', ['CHANNEL_FLAG_NONE', 'CHANNEL_FLAG_TURBO', 'CHANNEL_FLAG_CCK', 'CHANNEL_FLAG_OFDM', 'CHANNEL_FLAG_SPECTRUM_2GHZ', 'CHANNEL_FLAG_SPECTRUM_5GHZ', 'CHANNEL_FLAG_PASSIVE', 'CHANNEL_FLAG_DYNAMIC', 'CHANNEL_FLAG_GFSK'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [enumeration]
module.add_enum('', ['MCS_KNOWN_NONE', 'MCS_KNOWN_BANDWIDTH', 'MCS_KNOWN_INDEX', 'MCS_KNOWN_GUARD_INTERVAL', 'MCS_KNOWN_HT_FORMAT', 'MCS_KNOWN_FEC_TYPE', 'MCS_KNOWN_STBC', 'MCS_KNOWN_NESS', 'MCS_KNOWN_NESS_BIT_1'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [enumeration]
module.add_enum('', ['MCS_FLAGS_NONE', 'MCS_FLAGS_BANDWIDTH_40', 'MCS_FLAGS_BANDWIDTH_20L', 'MCS_FLAGS_BANDWIDTH_20U', 'MCS_FLAGS_GUARD_INTERVAL', 'MCS_FLAGS_HT_GREENFIELD', 'MCS_FLAGS_FEC_TYPE', 'MCS_FLAGS_STBC_STREAMS', 'MCS_FLAGS_NESS_BIT_0'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [enumeration]
module.add_enum('', ['A_MPDU_STATUS_NONE', 'A_MPDU_STATUS_REPORT_ZERO_LENGTH', 'A_MPDU_STATUS_IS_ZERO_LENGTH', 'A_MPDU_STATUS_LAST_KNOWN', 'A_MPDU_STATUS_LAST', 'A_MPDU_STATUS_DELIMITER_CRC_ERROR', 'A_MPDU_STATUS_DELIMITER_CRC_KNOWN'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [enumeration]
module.add_enum('', ['VHT_KNOWN_NONE', 'VHT_KNOWN_STBC', 'VHT_KNOWN_TXOP_PS_NOT_ALLOWED', 'VHT_KNOWN_GUARD_INTERVAL', 'VHT_KNOWN_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_KNOWN_LDPC_EXTRA_OFDM_SYMBOL', 'VHT_KNOWN_BEAMFORMED', 'VHT_KNOWN_BANDWIDTH', 'VHT_KNOWN_GROUP_ID', 'VHT_KNOWN_PARTIAL_AID'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## radiotap-header.h (module 'network'): ns3::RadiotapHeader [enumeration]
module.add_enum('', ['VHT_FLAGS_NONE', 'VHT_FLAGS_STBC', 'VHT_FLAGS_TXOP_PS_NOT_ALLOWED', 'VHT_FLAGS_GUARD_INTERVAL', 'VHT_FLAGS_SHORT_GI_NSYM_DISAMBIGUATION', 'VHT_FLAGS__LDPC_EXTRA_OFDM_SYMBOL', 'VHT_FLAGS_BEAMFORMED'], outer_class=root_module['ns3::RadiotapHeader'], import_from_module='ns.network')
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class]
module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object'])
## red-queue.h (module 'network'): ns3::RedQueue [class]
module.add_class('RedQueue', import_from_module='ns.network', parent=root_module['ns3::Queue'])
## red-queue.h (module 'network'): ns3::RedQueue [enumeration]
module.add_enum('', ['DTYPE_NONE', 'DTYPE_FORCED', 'DTYPE_UNFORCED'], outer_class=root_module['ns3::RedQueue'], import_from_module='ns.network')
## red-queue.h (module 'network'): ns3::RedQueue::Stats [struct]
module.add_class('Stats', import_from_module='ns.network', outer_class=root_module['ns3::RedQueue'])
## seq-ts-header.h (module 'applications'): ns3::SeqTsHeader [class]
module.add_class('SeqTsHeader', parent=root_module['ns3::Header'])
## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class]
module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbAddressBlock', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbAddressBlock>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbMessage', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbMessage>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbPacket', 'ns3::Header', 'ns3::DefaultDeleter<ns3::PbbPacket>'], parent=root_module['ns3::Header'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::PbbTlv', 'ns3::empty', 'ns3::DefaultDeleter<ns3::PbbTlv>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::RadvdInterface', 'ns3::empty', 'ns3::DefaultDeleter<ns3::RadvdInterface>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::RadvdPrefix', 'ns3::empty', 'ns3::DefaultDeleter<ns3::RadvdPrefix>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class]
module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount'))
## socket.h (module 'network'): ns3::Socket [class]
module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object'])
## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration]
module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::Socket::SocketType [enumeration]
module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network')
## socket.h (module 'network'): ns3::SocketAddressTag [class]
module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket-factory.h (module 'network'): ns3::SocketFactory [class]
module.add_class('SocketFactory', import_from_module='ns.network', parent=root_module['ns3::Object'])
## socket.h (module 'network'): ns3::SocketIpTosTag [class]
module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpTtlTag [class]
module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class]
module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class]
module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class]
module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag'])
## nstime.h (module 'core'): ns3::Time [class]
module.add_class('Time', import_from_module='ns.core')
## nstime.h (module 'core'): ns3::Time::Unit [enumeration]
module.add_enum('Unit', ['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'])
## application.h (module 'network'): ns3::Application [class]
module.add_class('Application', import_from_module='ns.network', parent=root_module['ns3::Object'])
## attribute.h (module 'core'): ns3::AttributeAccessor [class]
module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
## attribute.h (module 'core'): ns3::AttributeChecker [class]
module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
## attribute.h (module 'core'): ns3::AttributeValue [class]
module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
## boolean.h (module 'core'): ns3::BooleanChecker [class]
module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## boolean.h (module 'core'): ns3::BooleanValue [class]
module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## bulk-send-application.h (module 'applications'): ns3::BulkSendApplication [class]
module.add_class('BulkSendApplication', parent=root_module['ns3::Application'])
## callback.h (module 'core'): ns3::CallbackChecker [class]
module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## callback.h (module 'core'): ns3::CallbackImplBase [class]
module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
## callback.h (module 'core'): ns3::CallbackValue [class]
module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## channel.h (module 'network'): ns3::Channel [class]
module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class]
module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## data-calculator.h (module 'stats'): ns3::DataCalculator [class]
module.add_class('DataCalculator', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-collection-object.h (module 'stats'): ns3::DataCollectionObject [class]
module.add_class('DataCollectionObject', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface [class]
module.add_class('DataOutputInterface', import_from_module='ns.stats', parent=root_module['ns3::Object'])
## data-rate.h (module 'network'): ns3::DataRateChecker [class]
module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## data-rate.h (module 'network'): ns3::DataRateValue [class]
module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class]
module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## double.h (module 'core'): ns3::DoubleValue [class]
module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## drop-tail-queue.h (module 'network'): ns3::DropTailQueue [class]
module.add_class('DropTailQueue', import_from_module='ns.network', parent=root_module['ns3::Queue'])
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class]
module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## attribute.h (module 'core'): ns3::EmptyAttributeValue [class]
module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## enum.h (module 'core'): ns3::EnumChecker [class]
module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## enum.h (module 'core'): ns3::EnumValue [class]
module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class]
module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## error-model.h (module 'network'): ns3::ErrorModel [class]
module.add_class('ErrorModel', import_from_module='ns.network', parent=root_module['ns3::Object'])
## ethernet-header.h (module 'network'): ns3::EthernetHeader [class]
module.add_class('EthernetHeader', import_from_module='ns.network', parent=root_module['ns3::Header'])
## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer [class]
module.add_class('EthernetTrailer', import_from_module='ns.network', parent=root_module['ns3::Trailer'])
## event-impl.h (module 'core'): ns3::EventImpl [class]
module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class]
module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class]
module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## integer.h (module 'core'): ns3::IntegerValue [class]
module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## 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'])
## mac16-address.h (module 'network'): ns3::Mac16AddressChecker [class]
module.add_class('Mac16AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac16-address.h (module 'network'): ns3::Mac16AddressValue [class]
module.add_class('Mac16AddressValue', 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'])
## mac64-address.h (module 'network'): ns3::Mac64AddressChecker [class]
module.add_class('Mac64AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## mac64-address.h (module 'network'): ns3::Mac64AddressValue [class]
module.add_class('Mac64AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<double> [class]
module.add_class('MinMaxAvgTotalCalculator', import_from_module='ns.stats', template_parameters=['double'], parent=[root_module['ns3::DataCalculator'], root_module['ns3::StatisticalSummary']])
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int> [class]
module.add_class('MinMaxAvgTotalCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=[root_module['ns3::DataCalculator'], root_module['ns3::StatisticalSummary']])
## net-device.h (module 'network'): ns3::NetDevice [class]
module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object'])
## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration]
module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network')
## nix-vector.h (module 'network'): ns3::NixVector [class]
module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >'])
## node.h (module 'network'): ns3::Node [class]
module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object'])
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class]
module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class]
module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class]
module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## onoff-application.h (module 'applications'): ns3::OnOffApplication [class]
module.add_class('OnOffApplication', parent=root_module['ns3::Application'])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class]
module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >'])
## packet.h (module 'network'): ns3::Packet [class]
module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >'])
## packet-sink.h (module 'applications'): ns3::PacketSink [class]
module.add_class('PacketSink', parent=root_module['ns3::Application'])
## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator [class]
module.add_class('PacketSizeMinMaxAvgTotalCalculator', import_from_module='ns.network', parent=root_module['ns3::MinMaxAvgTotalCalculator< unsigned int >'])
## packet-socket.h (module 'network'): ns3::PacketSocket [class]
module.add_class('PacketSocket', import_from_module='ns.network', parent=root_module['ns3::Socket'])
## packet-socket-client.h (module 'network'): ns3::PacketSocketClient [class]
module.add_class('PacketSocketClient', import_from_module='ns.network', parent=root_module['ns3::Application'])
## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory [class]
module.add_class('PacketSocketFactory', import_from_module='ns.network', parent=root_module['ns3::SocketFactory'])
## packet-socket-server.h (module 'network'): ns3::PacketSocketServer [class]
module.add_class('PacketSocketServer', import_from_module='ns.network', parent=root_module['ns3::Application'])
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class]
module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream'])
## packetbb.h (module 'network'): ns3::PbbAddressBlock [class]
module.add_class('PbbAddressBlock', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >'])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4 [class]
module.add_class('PbbAddressBlockIpv4', import_from_module='ns.network', parent=root_module['ns3::PbbAddressBlock'])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6 [class]
module.add_class('PbbAddressBlockIpv6', import_from_module='ns.network', parent=root_module['ns3::PbbAddressBlock'])
## packetbb.h (module 'network'): ns3::PbbMessage [class]
module.add_class('PbbMessage', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >'])
## packetbb.h (module 'network'): ns3::PbbMessageIpv4 [class]
module.add_class('PbbMessageIpv4', import_from_module='ns.network', parent=root_module['ns3::PbbMessage'])
## packetbb.h (module 'network'): ns3::PbbMessageIpv6 [class]
module.add_class('PbbMessageIpv6', import_from_module='ns.network', parent=root_module['ns3::PbbMessage'])
## packetbb.h (module 'network'): ns3::PbbPacket [class]
module.add_class('PbbPacket', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >'])
## packetbb.h (module 'network'): ns3::PbbTlv [class]
module.add_class('PbbTlv', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >'])
## ping6.h (module 'applications'): ns3::Ping6 [class]
module.add_class('Ping6', parent=root_module['ns3::Application'])
## probe.h (module 'stats'): ns3::Probe [class]
module.add_class('Probe', import_from_module='ns.stats', parent=root_module['ns3::DataCollectionObject'])
## radvd.h (module 'applications'): ns3::Radvd [class]
module.add_class('Radvd', parent=root_module['ns3::Application'])
## radvd-interface.h (module 'applications'): ns3::RadvdInterface [class]
module.add_class('RadvdInterface', parent=root_module['ns3::SimpleRefCount< ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >'])
## radvd-prefix.h (module 'applications'): ns3::RadvdPrefix [class]
module.add_class('RadvdPrefix', parent=root_module['ns3::SimpleRefCount< ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >'])
## error-model.h (module 'network'): ns3::RateErrorModel [class]
module.add_class('RateErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit [enumeration]
module.add_enum('ErrorUnit', ['ERROR_UNIT_BIT', 'ERROR_UNIT_BYTE', 'ERROR_UNIT_PACKET'], outer_class=root_module['ns3::RateErrorModel'], import_from_module='ns.network')
## error-model.h (module 'network'): ns3::ReceiveListErrorModel [class]
module.add_class('ReceiveListErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
## simple-channel.h (module 'network'): ns3::SimpleChannel [class]
module.add_class('SimpleChannel', import_from_module='ns.network', parent=root_module['ns3::Channel'])
## simple-net-device.h (module 'network'): ns3::SimpleNetDevice [class]
module.add_class('SimpleNetDevice', import_from_module='ns.network', parent=root_module['ns3::NetDevice'])
## nstime.h (module 'core'): ns3::TimeValue [class]
module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## type-id.h (module 'core'): ns3::TypeIdChecker [class]
module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker'])
## type-id.h (module 'core'): ns3::TypeIdValue [class]
module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## udp-client.h (module 'applications'): ns3::UdpClient [class]
module.add_class('UdpClient', parent=root_module['ns3::Application'])
## udp-echo-client.h (module 'applications'): ns3::UdpEchoClient [class]
module.add_class('UdpEchoClient', parent=root_module['ns3::Application'])
## udp-echo-server.h (module 'applications'): ns3::UdpEchoServer [class]
module.add_class('UdpEchoServer', parent=root_module['ns3::Application'])
## udp-server.h (module 'applications'): ns3::UdpServer [class]
module.add_class('UdpServer', parent=root_module['ns3::Application'])
## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient [class]
module.add_class('UdpTraceClient', parent=root_module['ns3::Application'])
## uinteger.h (module 'core'): ns3::UintegerValue [class]
module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue'])
## v4ping.h (module 'applications'): ns3::V4Ping [class]
module.add_class('V4Ping', parent=root_module['ns3::Application'])
## address.h (module 'network'): ns3::AddressChecker [class]
module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker'])
## address.h (module 'network'): ns3::AddressValue [class]
module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue'])
## application-packet-probe.h (module 'applications'): ns3::ApplicationPacketProbe [class]
module.add_class('ApplicationPacketProbe', parent=root_module['ns3::Probe'])
## error-model.h (module 'network'): ns3::BurstErrorModel [class]
module.add_class('BurstErrorModel', import_from_module='ns.network', parent=root_module['ns3::ErrorModel'])
## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int> [class]
module.add_class('CounterCalculator', import_from_module='ns.stats', template_parameters=['unsigned int'], parent=root_module['ns3::DataCalculator'])
## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator [class]
module.add_class('PacketCounterCalculator', import_from_module='ns.network', parent=root_module['ns3::CounterCalculator< unsigned int >'])
## packet-probe.h (module 'network'): ns3::PacketProbe [class]
module.add_class('PacketProbe', import_from_module='ns.network', parent=root_module['ns3::Probe'])
## packetbb.h (module 'network'): ns3::PbbAddressTlv [class]
module.add_class('PbbAddressTlv', import_from_module='ns.network', parent=root_module['ns3::PbbTlv'])
module.add_container('std::vector< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector')
module.add_container('std::list< ns3::Ptr< ns3::Packet > >', 'ns3::Ptr< ns3::Packet >', container_type=u'list')
module.add_container('std::list< unsigned int >', 'unsigned int', container_type=u'list')
module.add_container('std::list< ns3::Ptr< ns3::Socket > >', 'ns3::Ptr< ns3::Socket >', container_type=u'list')
module.add_container('std::list< ns3::Ptr< ns3::RadvdPrefix > >', 'ns3::Ptr< ns3::RadvdPrefix >', container_type=u'list')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxEndCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxEndCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxEndCallback&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< short unsigned int, short int >', u'ns3::SequenceNumber16')
typehandlers.add_type_alias(u'ns3::SequenceNumber< short unsigned int, short int >*', u'ns3::SequenceNumber16*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< short unsigned int, short int >&', u'ns3::SequenceNumber16&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >', u'ns3::SequenceNumber32')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >*', u'ns3::SequenceNumber32*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned int, int >&', u'ns3::SequenceNumber32&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxStartCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxStartCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxStartCallback&')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >', u'ns3::SequenceNumber8')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >*', u'ns3::SequenceNumber8*')
typehandlers.add_type_alias(u'ns3::SequenceNumber< unsigned char, signed char >&', u'ns3::SequenceNumber8&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndErrorCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndErrorCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndErrorCallback&')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyTxStartCallback')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyTxStartCallback*')
typehandlers.add_type_alias(u'ns3::Callback< bool, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyTxStartCallback&')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', u'ns3::GenericPhyRxEndOkCallback')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >*', u'ns3::GenericPhyRxEndOkCallback*')
typehandlers.add_type_alias(u'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >&', u'ns3::GenericPhyRxEndOkCallback&')
## Register a nested module for the namespace FatalImpl
nested_module = module.add_cpp_namespace('FatalImpl')
register_types_ns3_FatalImpl(nested_module)
## Register a nested module for the namespace 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)
## Register a nested module for the namespace addressUtils
nested_module = module.add_cpp_namespace('addressUtils')
register_types_ns3_addressUtils(nested_module)
## Register a nested module for the namespace internal
nested_module = module.add_cpp_namespace('internal')
register_types_ns3_internal(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 ( * ) ( double, double ) *', u'ns3::TracedValueCallback::Double')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) **', u'ns3::TracedValueCallback::Double*')
typehandlers.add_type_alias(u'void ( * ) ( double, double ) *&', u'ns3::TracedValueCallback::Double&')
typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 ) *', u'ns3::TracedValueCallback::SequenceNumber32')
typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 ) **', u'ns3::TracedValueCallback::SequenceNumber32*')
typehandlers.add_type_alias(u'void ( * ) ( ns3::SequenceNumber32, ns3::SequenceNumber32 ) *&', u'ns3::TracedValueCallback::SequenceNumber32&')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *', u'ns3::TracedValueCallback::Int8')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) **', u'ns3::TracedValueCallback::Int8*')
typehandlers.add_type_alias(u'void ( * ) ( int8_t, int8_t ) *&', u'ns3::TracedValueCallback::Int8&')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *', u'ns3::TracedValueCallback::Uint8')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) **', u'ns3::TracedValueCallback::Uint8*')
typehandlers.add_type_alias(u'void ( * ) ( uint8_t, uint8_t ) *&', u'ns3::TracedValueCallback::Uint8&')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *', u'ns3::TracedValueCallback::Int32')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) **', u'ns3::TracedValueCallback::Int32*')
typehandlers.add_type_alias(u'void ( * ) ( int32_t, int32_t ) *&', u'ns3::TracedValueCallback::Int32&')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *', u'ns3::TracedValueCallback::Bool')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) **', u'ns3::TracedValueCallback::Bool*')
typehandlers.add_type_alias(u'void ( * ) ( bool, bool ) *&', u'ns3::TracedValueCallback::Bool&')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *', u'ns3::TracedValueCallback::Uint16')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) **', u'ns3::TracedValueCallback::Uint16*')
typehandlers.add_type_alias(u'void ( * ) ( uint16_t, uint16_t ) *&', u'ns3::TracedValueCallback::Uint16&')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *', u'ns3::TracedValueCallback::Uint32')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) **', u'ns3::TracedValueCallback::Uint32*')
typehandlers.add_type_alias(u'void ( * ) ( uint32_t, uint32_t ) *&', u'ns3::TracedValueCallback::Uint32&')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *', u'ns3::TracedValueCallback::Int16')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) **', u'ns3::TracedValueCallback::Int16*')
typehandlers.add_type_alias(u'void ( * ) ( int16_t, int16_t ) *&', u'ns3::TracedValueCallback::Int16&')
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_types_ns3_addressUtils(module):
root_module = module.get_root()
def register_types_ns3_internal(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3Address_methods(root_module, root_module['ns3::Address'])
register_Ns3ApplicationContainer_methods(root_module, root_module['ns3::ApplicationContainer'])
register_Ns3AsciiFile_methods(root_module, root_module['ns3::AsciiFile'])
register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper'])
register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice'])
register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList'])
register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item'])
register_Ns3Average__Double_methods(root_module, root_module['ns3::Average< double >'])
register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer'])
register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator'])
register_Ns3BulkSendHelper_methods(root_module, root_module['ns3::BulkSendHelper'])
register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator'])
register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item'])
register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList'])
register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator'])
register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item'])
register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase'])
register_Ns3ChannelList_methods(root_module, root_module['ns3::ChannelList'])
register_Ns3DataOutputCallback_methods(root_module, root_module['ns3::DataOutputCallback'])
register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate'])
register_Ns3DelayJitterEstimation_methods(root_module, root_module['ns3::DelayJitterEstimation'])
register_Ns3EventId_methods(root_module, root_module['ns3::EventId'])
register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher'])
register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress'])
register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress'])
register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address'])
register_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_Ns3Mac16Address_methods(root_module, root_module['ns3::Mac16Address'])
register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address'])
register_Ns3Mac64Address_methods(root_module, root_module['ns3::Mac64Address'])
register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer'])
register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer'])
register_Ns3NodeList_methods(root_module, root_module['ns3::NodeList'])
register_Ns3NonCopyable_methods(root_module, root_module['ns3::NonCopyable'])
register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase'])
register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter'])
register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory'])
register_Ns3OnOffHelper_methods(root_module, root_module['ns3::OnOffHelper'])
register_Ns3PacketLossCounter_methods(root_module, root_module['ns3::PacketLossCounter'])
register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata'])
register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item'])
register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator'])
register_Ns3PacketSinkHelper_methods(root_module, root_module['ns3::PacketSinkHelper'])
register_Ns3PacketSocketAddress_methods(root_module, root_module['ns3::PacketSocketAddress'])
register_Ns3PacketSocketHelper_methods(root_module, root_module['ns3::PacketSocketHelper'])
register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator'])
register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item'])
register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList'])
register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData'])
register_Ns3PbbAddressTlvBlock_methods(root_module, root_module['ns3::PbbAddressTlvBlock'])
register_Ns3PbbTlvBlock_methods(root_module, root_module['ns3::PbbTlvBlock'])
register_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile'])
register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper'])
register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice'])
register_Ns3Ping6Helper_methods(root_module, root_module['ns3::Ping6Helper'])
register_Ns3RadvdHelper_methods(root_module, root_module['ns3::RadvdHelper'])
register_Ns3SimpleNetDeviceHelper_methods(root_module, root_module['ns3::SimpleNetDeviceHelper'])
register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >'])
register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator'])
register_Ns3StatisticalSummary_methods(root_module, root_module['ns3::StatisticalSummary'])
register_Ns3SystemWallClockMs_methods(root_module, root_module['ns3::SystemWallClockMs'])
register_Ns3Tag_methods(root_module, root_module['ns3::Tag'])
register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer'])
register_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_Ns3UdpClientHelper_methods(root_module, root_module['ns3::UdpClientHelper'])
register_Ns3UdpEchoClientHelper_methods(root_module, root_module['ns3::UdpEchoClientHelper'])
register_Ns3UdpEchoServerHelper_methods(root_module, root_module['ns3::UdpEchoServerHelper'])
register_Ns3UdpServerHelper_methods(root_module, root_module['ns3::UdpServerHelper'])
register_Ns3UdpTraceClientHelper_methods(root_module, root_module['ns3::UdpTraceClientHelper'])
register_Ns3V4PingHelper_methods(root_module, root_module['ns3::V4PingHelper'])
register_Ns3Empty_methods(root_module, root_module['ns3::empty'])
register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t'])
register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk'])
register_Ns3DeviceNameTag_methods(root_module, root_module['ns3::DeviceNameTag'])
register_Ns3FlowIdTag_methods(root_module, root_module['ns3::FlowIdTag'])
register_Ns3Header_methods(root_module, root_module['ns3::Header'])
register_Ns3LlcSnapHeader_methods(root_module, root_module['ns3::LlcSnapHeader'])
register_Ns3Object_methods(root_module, root_module['ns3::Object'])
register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator'])
register_Ns3PacketBurst_methods(root_module, root_module['ns3::PacketBurst'])
register_Ns3PacketSocketTag_methods(root_module, root_module['ns3::PacketSocketTag'])
register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper'])
register_Ns3Queue_methods(root_module, root_module['ns3::Queue'])
register_Ns3RadiotapHeader_methods(root_module, root_module['ns3::RadiotapHeader'])
register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream'])
register_Ns3RedQueue_methods(root_module, root_module['ns3::RedQueue'])
register_Ns3RedQueueStats_methods(root_module, root_module['ns3::RedQueue::Stats'])
register_Ns3SeqTsHeader_methods(root_module, root_module['ns3::SeqTsHeader'])
register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable'])
register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >'])
register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >'])
register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >'])
register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >'])
register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >'])
register_Ns3SimpleRefCount__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__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >'])
register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >'])
register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >'])
register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >'])
register_Ns3SimpleRefCount__Ns3RadvdInterface_Ns3Empty_Ns3DefaultDeleter__lt__ns3RadvdInterface__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >'])
register_Ns3SimpleRefCount__Ns3RadvdPrefix_Ns3Empty_Ns3DefaultDeleter__lt__ns3RadvdPrefix__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >'])
register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >'])
register_Ns3Socket_methods(root_module, root_module['ns3::Socket'])
register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag'])
register_Ns3SocketFactory_methods(root_module, root_module['ns3::SocketFactory'])
register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag'])
register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag'])
register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag'])
register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag'])
register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag'])
register_Ns3Time_methods(root_module, root_module['ns3::Time'])
register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor'])
register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer'])
register_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable'])
register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable'])
register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable'])
register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable'])
register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable'])
register_Ns3Application_methods(root_module, root_module['ns3::Application'])
register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor'])
register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker'])
register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue'])
register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker'])
register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue'])
register_Ns3BulkSendApplication_methods(root_module, root_module['ns3::BulkSendApplication'])
register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker'])
register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase'])
register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue'])
register_Ns3Channel_methods(root_module, root_module['ns3::Channel'])
register_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable'])
register_Ns3DataCalculator_methods(root_module, root_module['ns3::DataCalculator'])
register_Ns3DataCollectionObject_methods(root_module, root_module['ns3::DataCollectionObject'])
register_Ns3DataOutputInterface_methods(root_module, root_module['ns3::DataOutputInterface'])
register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker'])
register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue'])
register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable'])
register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue'])
register_Ns3DropTailQueue_methods(root_module, root_module['ns3::DropTailQueue'])
register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable'])
register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue'])
register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker'])
register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue'])
register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable'])
register_Ns3ErrorModel_methods(root_module, root_module['ns3::ErrorModel'])
register_Ns3EthernetHeader_methods(root_module, root_module['ns3::EthernetHeader'])
register_Ns3EthernetTrailer_methods(root_module, root_module['ns3::EthernetTrailer'])
register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl'])
register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable'])
register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable'])
register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue'])
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_Ns3Mac16AddressChecker_methods(root_module, root_module['ns3::Mac16AddressChecker'])
register_Ns3Mac16AddressValue_methods(root_module, root_module['ns3::Mac16AddressValue'])
register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker'])
register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue'])
register_Ns3Mac64AddressChecker_methods(root_module, root_module['ns3::Mac64AddressChecker'])
register_Ns3Mac64AddressValue_methods(root_module, root_module['ns3::Mac64AddressValue'])
register_Ns3MinMaxAvgTotalCalculator__Double_methods(root_module, root_module['ns3::MinMaxAvgTotalCalculator< double >'])
register_Ns3MinMaxAvgTotalCalculator__Unsigned_int_methods(root_module, root_module['ns3::MinMaxAvgTotalCalculator< unsigned int >'])
register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice'])
register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector'])
register_Ns3Node_methods(root_module, root_module['ns3::Node'])
register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable'])
register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker'])
register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue'])
register_Ns3OnOffApplication_methods(root_module, root_module['ns3::OnOffApplication'])
register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper'])
register_Ns3Packet_methods(root_module, root_module['ns3::Packet'])
register_Ns3PacketSink_methods(root_module, root_module['ns3::PacketSink'])
register_Ns3PacketSizeMinMaxAvgTotalCalculator_methods(root_module, root_module['ns3::PacketSizeMinMaxAvgTotalCalculator'])
register_Ns3PacketSocket_methods(root_module, root_module['ns3::PacketSocket'])
register_Ns3PacketSocketClient_methods(root_module, root_module['ns3::PacketSocketClient'])
register_Ns3PacketSocketFactory_methods(root_module, root_module['ns3::PacketSocketFactory'])
register_Ns3PacketSocketServer_methods(root_module, root_module['ns3::PacketSocketServer'])
register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable'])
register_Ns3PbbAddressBlock_methods(root_module, root_module['ns3::PbbAddressBlock'])
register_Ns3PbbAddressBlockIpv4_methods(root_module, root_module['ns3::PbbAddressBlockIpv4'])
register_Ns3PbbAddressBlockIpv6_methods(root_module, root_module['ns3::PbbAddressBlockIpv6'])
register_Ns3PbbMessage_methods(root_module, root_module['ns3::PbbMessage'])
register_Ns3PbbMessageIpv4_methods(root_module, root_module['ns3::PbbMessageIpv4'])
register_Ns3PbbMessageIpv6_methods(root_module, root_module['ns3::PbbMessageIpv6'])
register_Ns3PbbPacket_methods(root_module, root_module['ns3::PbbPacket'])
register_Ns3PbbTlv_methods(root_module, root_module['ns3::PbbTlv'])
register_Ns3Ping6_methods(root_module, root_module['ns3::Ping6'])
register_Ns3Probe_methods(root_module, root_module['ns3::Probe'])
register_Ns3Radvd_methods(root_module, root_module['ns3::Radvd'])
register_Ns3RadvdInterface_methods(root_module, root_module['ns3::RadvdInterface'])
register_Ns3RadvdPrefix_methods(root_module, root_module['ns3::RadvdPrefix'])
register_Ns3RateErrorModel_methods(root_module, root_module['ns3::RateErrorModel'])
register_Ns3ReceiveListErrorModel_methods(root_module, root_module['ns3::ReceiveListErrorModel'])
register_Ns3SimpleChannel_methods(root_module, root_module['ns3::SimpleChannel'])
register_Ns3SimpleNetDevice_methods(root_module, root_module['ns3::SimpleNetDevice'])
register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue'])
register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker'])
register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue'])
register_Ns3UdpClient_methods(root_module, root_module['ns3::UdpClient'])
register_Ns3UdpEchoClient_methods(root_module, root_module['ns3::UdpEchoClient'])
register_Ns3UdpEchoServer_methods(root_module, root_module['ns3::UdpEchoServer'])
register_Ns3UdpServer_methods(root_module, root_module['ns3::UdpServer'])
register_Ns3UdpTraceClient_methods(root_module, root_module['ns3::UdpTraceClient'])
register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue'])
register_Ns3V4Ping_methods(root_module, root_module['ns3::V4Ping'])
register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker'])
register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue'])
register_Ns3ApplicationPacketProbe_methods(root_module, root_module['ns3::ApplicationPacketProbe'])
register_Ns3BurstErrorModel_methods(root_module, root_module['ns3::BurstErrorModel'])
register_Ns3CounterCalculator__Unsigned_int_methods(root_module, root_module['ns3::CounterCalculator< unsigned int >'])
register_Ns3PacketCounterCalculator_methods(root_module, root_module['ns3::PacketCounterCalculator'])
register_Ns3PacketProbe_methods(root_module, root_module['ns3::PacketProbe'])
register_Ns3PbbAddressTlv_methods(root_module, root_module['ns3::PbbAddressTlv'])
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_Ns3ApplicationContainer_methods(root_module, cls):
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::ApplicationContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ApplicationContainer const &', 'arg0')])
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer() [constructor]
cls.add_constructor([])
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(ns3::Ptr<ns3::Application> application) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Application >', 'application')])
## application-container.h (module 'network'): ns3::ApplicationContainer::ApplicationContainer(std::string name) [constructor]
cls.add_constructor([param('std::string', 'name')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::ApplicationContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::ApplicationContainer', 'other')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Application >', 'application')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Add(std::string name) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name')])
## application-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Application>*,std::vector<ns3::Ptr<ns3::Application>, std::allocator<ns3::Ptr<ns3::Application> > > > ns3::ApplicationContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Application > const, std::vector< ns3::Ptr< ns3::Application > > >',
[],
is_const=True)
## application-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Application>*,std::vector<ns3::Ptr<ns3::Application>, std::allocator<ns3::Ptr<ns3::Application> > > > ns3::ApplicationContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Application > const, std::vector< ns3::Ptr< ns3::Application > > >',
[],
is_const=True)
## application-container.h (module 'network'): ns3::Ptr<ns3::Application> ns3::ApplicationContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'i')],
is_const=True)
## application-container.h (module 'network'): uint32_t ns3::ApplicationContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
## application-container.h (module 'network'): void ns3::ApplicationContainer::Start(ns3::Time start) [member function]
cls.add_method('Start',
'void',
[param('ns3::Time', 'start')])
## application-container.h (module 'network'): void ns3::ApplicationContainer::Stop(ns3::Time stop) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time', 'stop')])
return
def register_Ns3AsciiFile_methods(root_module, cls):
## ascii-file.h (module 'network'): ns3::AsciiFile::AsciiFile() [constructor]
cls.add_constructor([])
## ascii-file.h (module 'network'): bool ns3::AsciiFile::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## ascii-file.h (module 'network'): bool ns3::AsciiFile::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## ascii-file.h (module 'network'): void ns3::AsciiFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## ascii-file.h (module 'network'): void ns3::AsciiFile::Close() [member function]
cls.add_method('Close',
'void',
[])
## ascii-file.h (module 'network'): void ns3::AsciiFile::Read(std::string & line) [member function]
cls.add_method('Read',
'void',
[param('std::string &', 'line')])
## ascii-file.h (module 'network'): static bool ns3::AsciiFile::Diff(std::string const & f1, std::string const & f2, uint64_t & lineNumber) [member function]
cls.add_method('Diff',
'bool',
[param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint64_t &', 'lineNumber')],
is_static=True)
return
def register_Ns3AsciiTraceHelper_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::_Ios_Openmode filemode=std::ios_base::out) [member function]
cls.add_method('CreateFileStream',
'ns3::Ptr< ns3::OutputStreamWrapper >',
[param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode', default_value='std::ios_base::out')])
## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> 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<ns3::Packet const> p) [member function]
cls.add_method('DefaultReceiveSinkWithoutContext',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')],
is_static=True)
## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromDevice',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')])
## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromInterfacePair',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')])
return
def register_Ns3AsciiTraceHelperForDevice_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice(ns3::AsciiTraceHelperForDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AsciiTraceHelperForDevice const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename=false) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::NetDevice> nd) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::NetDevice >', 'nd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, std::string ndName, bool explicitFilename=false) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ndName) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ndName')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NetDeviceContainer d) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NetDeviceContainer', 'd')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function]
cls.add_method('EnableAscii',
'void',
[param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t deviceid) [member function]
cls.add_method('EnableAscii',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(std::string prefix) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('std::string', 'prefix')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function]
cls.add_method('EnableAsciiAll',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')])
## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function]
cls.add_method('EnableAsciiInternal',
'void',
[param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3AttributeConstructionList_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')])
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::AttributeConstructionList::Item >',
[],
is_const=True)
## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('Find',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True)
return
def register_Ns3AttributeConstructionListItem_methods(root_module, cls):
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor]
cls.add_constructor([])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')])
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable]
cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False)
return
def register_Ns3Average__Double_methods(root_module, cls):
## average.h (module 'stats'): ns3::Average<double>::Average(ns3::Average<double> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Average< double > const &', 'arg0')])
## average.h (module 'stats'): ns3::Average<double>::Average() [constructor]
cls.add_constructor([])
## average.h (module 'stats'): double ns3::Average<double>::Avg() const [member function]
cls.add_method('Avg',
'double',
[],
is_const=True)
## average.h (module 'stats'): uint32_t ns3::Average<double>::Count() const [member function]
cls.add_method('Count',
'uint32_t',
[],
is_const=True)
## average.h (module 'stats'): double ns3::Average<double>::Error90() const [member function]
cls.add_method('Error90',
'double',
[],
is_const=True)
## average.h (module 'stats'): double ns3::Average<double>::Error95() const [member function]
cls.add_method('Error95',
'double',
[],
is_const=True)
## average.h (module 'stats'): double ns3::Average<double>::Error99() const [member function]
cls.add_method('Error99',
'double',
[],
is_const=True)
## average.h (module 'stats'): double ns3::Average<double>::Max() const [member function]
cls.add_method('Max',
'double',
[],
is_const=True)
## average.h (module 'stats'): double ns3::Average<double>::Mean() const [member function]
cls.add_method('Mean',
'double',
[],
is_const=True)
## average.h (module 'stats'): double ns3::Average<double>::Min() const [member function]
cls.add_method('Min',
'double',
[],
is_const=True)
## average.h (module 'stats'): void ns3::Average<double>::Reset() [member function]
cls.add_method('Reset',
'void',
[])
## average.h (module 'stats'): double ns3::Average<double>::Stddev() const [member function]
cls.add_method('Stddev',
'double',
[],
is_const=True)
## average.h (module 'stats'): void ns3::Average<double>::Update(double const & x) [member function]
cls.add_method('Update',
'void',
[param('double const &', 'x')])
## average.h (module 'stats'): double ns3::Average<double>::Var() const [member function]
cls.add_method('Var',
'double',
[],
is_const=True)
return
def register_Ns3Buffer_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor]
cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')])
## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor]
cls.add_constructor([param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function]
cls.add_method('AddAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::Buffer const &', 'o')])
## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function]
cls.add_method('AddAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function]
cls.add_method('Begin',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function]
cls.add_method('CopyData',
'void',
[param('std::ostream *', 'os'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function]
cls.add_method('CopyData',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')],
is_const=True)
## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function]
cls.add_method('CreateFragment',
'ns3::Buffer',
[param('uint32_t', 'start'), param('uint32_t', 'length')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function]
cls.add_method('End',
'ns3::Buffer::Iterator',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function]
cls.add_method('PeekData',
'uint8_t const *',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3BufferIterator_methods(root_module, cls):
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')])
## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor]
cls.add_constructor([])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function]
cls.add_method('CalculateIpChecksum',
'uint16_t',
[param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function]
cls.add_method('GetDistanceFrom',
'uint32_t',
[param('ns3::Buffer::Iterator const &', 'o')],
is_const=True)
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function]
cls.add_method('IsEnd',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function]
cls.add_method('IsStart',
'bool',
[],
is_const=True)
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function]
cls.add_method('Next',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function]
cls.add_method('Next',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function]
cls.add_method('PeekU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function]
cls.add_method('Prev',
'void',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function]
cls.add_method('Prev',
'void',
[param('uint32_t', 'delta')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function]
cls.add_method('ReadLsbtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function]
cls.add_method('ReadLsbtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function]
cls.add_method('ReadLsbtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function]
cls.add_method('ReadNtohU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function]
cls.add_method('ReadNtohU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function]
cls.add_method('ReadNtohU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function]
cls.add_method('Write',
'void',
[param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function]
cls.add_method('WriteHtolsbU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function]
cls.add_method('WriteHtolsbU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function]
cls.add_method('WriteHtolsbU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function]
cls.add_method('WriteHtonU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function]
cls.add_method('WriteHtonU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function]
cls.add_method('WriteHtonU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data')])
## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'data'), param('uint32_t', 'len')])
return
def register_Ns3BulkSendHelper_methods(root_module, cls):
## bulk-send-helper.h (module 'applications'): ns3::BulkSendHelper::BulkSendHelper(ns3::BulkSendHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BulkSendHelper const &', 'arg0')])
## bulk-send-helper.h (module 'applications'): ns3::BulkSendHelper::BulkSendHelper(std::string protocol, ns3::Address address) [constructor]
cls.add_constructor([param('std::string', 'protocol'), param('ns3::Address', 'address')])
## bulk-send-helper.h (module 'applications'): ns3::ApplicationContainer ns3::BulkSendHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## bulk-send-helper.h (module 'applications'): ns3::ApplicationContainer ns3::BulkSendHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## bulk-send-helper.h (module 'applications'): ns3::ApplicationContainer ns3::BulkSendHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## bulk-send-helper.h (module 'applications'): void ns3::BulkSendHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3ByteTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::ByteTagIterator::Item',
[])
return
def register_Ns3ByteTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function]
cls.add_method('GetEnd',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function]
cls.add_method('GetStart',
'uint32_t',
[],
is_const=True)
## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3ByteTagList_methods(root_module, cls):
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor]
cls.add_constructor([])
## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function]
cls.add_method('Add',
'ns3::TagBuffer',
[param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function]
cls.add_method('Add',
'void',
[param('ns3::ByteTagList const &', 'o')])
## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t 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_Ns3ChannelList_methods(root_module, cls):
## channel-list.h (module 'network'): ns3::ChannelList::ChannelList() [constructor]
cls.add_constructor([])
## channel-list.h (module 'network'): ns3::ChannelList::ChannelList(ns3::ChannelList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ChannelList const &', 'arg0')])
## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::Add(ns3::Ptr<ns3::Channel> channel) [member function]
cls.add_method('Add',
'uint32_t',
[param('ns3::Ptr< ns3::Channel >', 'channel')],
is_static=True)
## channel-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >',
[],
is_static=True)
## channel-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Channel>*,std::vector<ns3::Ptr<ns3::Channel>, std::allocator<ns3::Ptr<ns3::Channel> > > > ns3::ChannelList::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Channel > const, std::vector< ns3::Ptr< ns3::Channel > > >',
[],
is_static=True)
## channel-list.h (module 'network'): static ns3::Ptr<ns3::Channel> ns3::ChannelList::GetChannel(uint32_t n) [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[param('uint32_t', 'n')],
is_static=True)
## channel-list.h (module 'network'): static uint32_t ns3::ChannelList::GetNChannels() [member function]
cls.add_method('GetNChannels',
'uint32_t',
[],
is_static=True)
return
def register_Ns3DataOutputCallback_methods(root_module, cls):
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback() [constructor]
cls.add_constructor([])
## data-output-interface.h (module 'stats'): ns3::DataOutputCallback::DataOutputCallback(ns3::DataOutputCallback const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataOutputCallback const &', 'arg0')])
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, int val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('int', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, uint32_t val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('uint32_t', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, double val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('double', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, std::string val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('std::string', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputSingleton(std::string key, std::string variable, ns3::Time val) [member function]
cls.add_method('OutputSingleton',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('ns3::Time', 'val')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputCallback::OutputStatistic(std::string key, std::string variable, ns3::StatisticalSummary const * statSum) [member function]
cls.add_method('OutputStatistic',
'void',
[param('std::string', 'key'), param('std::string', 'variable'), param('ns3::StatisticalSummary const *', 'statSum')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3DataRate_methods(root_module, cls):
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('>')
cls.add_binary_comparison_operator('>=')
## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRate const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor]
cls.add_constructor([param('uint64_t', 'bps')])
## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor]
cls.add_constructor([param('std::string', 'rate')])
## data-rate.h (module 'network'): 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_Ns3DelayJitterEstimation_methods(root_module, cls):
## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation::DelayJitterEstimation(ns3::DelayJitterEstimation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DelayJitterEstimation const &', 'arg0')])
## delay-jitter-estimation.h (module 'network'): ns3::DelayJitterEstimation::DelayJitterEstimation() [constructor]
cls.add_constructor([])
## delay-jitter-estimation.h (module 'network'): ns3::Time ns3::DelayJitterEstimation::GetLastDelay() const [member function]
cls.add_method('GetLastDelay',
'ns3::Time',
[],
is_const=True)
## delay-jitter-estimation.h (module 'network'): uint64_t ns3::DelayJitterEstimation::GetLastJitter() const [member function]
cls.add_method('GetLastJitter',
'uint64_t',
[],
is_const=True)
## delay-jitter-estimation.h (module 'network'): static void ns3::DelayJitterEstimation::PrepareTx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('PrepareTx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')],
is_static=True)
## delay-jitter-estimation.h (module 'network'): void ns3::DelayJitterEstimation::RecordRx(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('RecordRx',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
return
def register_Ns3EventId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('==')
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventId const &', 'arg0')])
## event-id.h (module 'core'): ns3::EventId::EventId() [constructor]
cls.add_constructor([])
## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')])
## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function]
cls.add_method('GetTs',
'uint64_t',
[],
is_const=True)
## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function]
cls.add_method('GetUid',
'uint32_t',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function]
cls.add_method('IsExpired',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function]
cls.add_method('IsRunning',
'bool',
[],
is_const=True)
## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function]
cls.add_method('PeekEventImpl',
'ns3::EventImpl *',
[],
is_const=True)
return
def register_Ns3Hasher_methods(root_module, cls):
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Hasher const &', 'arg0')])
## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor]
cls.add_constructor([])
## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function]
cls.add_method('GetHash32',
'uint32_t',
[param('std::string const', 's')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('char const *', 'buffer'), param('size_t const', 'size')])
## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function]
cls.add_method('GetHash64',
'uint64_t',
[param('std::string const', 's')])
## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function]
cls.add_method('clear',
'ns3::Hasher &',
[])
return
def register_Ns3Inet6SocketAddress_methods(root_module, cls):
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')])
## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor]
cls.add_constructor([param('char const *', 'ipv6')])
## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function]
cls.add_method('ConvertFrom',
'ns3::Inet6SocketAddress',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function]
cls.add_method('GetIpv6',
'ns3::Ipv6Address',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'addr')],
is_static=True)
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function]
cls.add_method('SetIpv6',
'void',
[param('ns3::Ipv6Address', 'ipv6')])
## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function]
cls.add_method('SetPort',
'void',
[param('uint16_t', 'port')])
return
def register_Ns3InetSocketAddress_methods(root_module, cls):
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor]
cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')])
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor]
cls.add_constructor([param('char const *', 'ipv4')])
## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::InetSocketAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function]
cls.add_method('GetIpv4',
'ns3::Ipv4Address',
[],
is_const=True)
## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function]
cls.add_method('GetPort',
'uint16_t',
[],
is_const=True)
## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function]
cls.add_method('SetIpv4',
'void',
[param('ns3::Ipv4Address', 'address')])
## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function]
cls.add_method('SetPort',
'void',
[param('uint16_t', 'port')])
return
def register_Ns3Ipv4Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor]
cls.add_constructor([])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor]
cls.add_constructor([param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor]
cls.add_constructor([param('char const *', 'address')])
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('CombineMask',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Ipv4Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function]
cls.add_method('Deserialize',
'ns3::Ipv4Address',
[param('uint8_t const *', 'buf')],
is_static=True)
## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function]
cls.add_method('Get',
'uint32_t',
[],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function]
cls.add_method('GetAny',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function]
cls.add_method('GetLoopback',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('GetSubnetDirectedBroadcast',
'ns3::Ipv4Address',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function]
cls.add_method('GetZero',
'ns3::Ipv4Address',
[],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ipv4Address const &', 'other')],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function]
cls.add_method('IsLocalMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True)
## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function]
cls.add_method('IsSubnetDirectedBroadcast',
'bool',
[param('ns3::Ipv4Mask const &', 'mask')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function]
cls.add_method('Serialize',
'void',
[param('uint8_t *', 'buf')],
is_const=True)
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function]
cls.add_method('Set',
'void',
[param('uint32_t', 'address')])
## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function]
cls.add_method('Set',
'void',
[param('char const *', 'address')])
return
def register_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_Ns3Mac16Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(ns3::Mac16Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac16Address const &', 'arg0')])
## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address() [constructor]
cls.add_constructor([])
## mac16-address.h (module 'network'): ns3::Mac16Address::Mac16Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac16Address',
[],
is_static=True)
## mac16-address.h (module 'network'): static ns3::Mac16Address ns3::Mac16Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac16Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac16-address.h (module 'network'): void ns3::Mac16Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac16-address.h (module 'network'): static bool ns3::Mac16Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3Mac48Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor]
cls.add_constructor([])
## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac48Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function]
cls.add_method('GetBroadcast',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv4Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function]
cls.add_method('GetMulticast',
'ns3::Mac48Address',
[param('ns3::Ipv6Address', 'address')],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function]
cls.add_method('GetMulticast6Prefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function]
cls.add_method('GetMulticastPrefix',
'ns3::Mac48Address',
[],
is_static=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function]
cls.add_method('IsGroup',
'bool',
[],
is_const=True)
## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3Mac64Address_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(ns3::Mac64Address const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac64Address const &', 'arg0')])
## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address() [constructor]
cls.add_constructor([])
## mac64-address.h (module 'network'): ns3::Mac64Address::Mac64Address(char const * str) [constructor]
cls.add_constructor([param('char const *', 'str')])
## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::Allocate() [member function]
cls.add_method('Allocate',
'ns3::Mac64Address',
[],
is_static=True)
## mac64-address.h (module 'network'): static ns3::Mac64Address ns3::Mac64Address::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::Mac64Address',
[param('ns3::Address const &', 'address')],
is_static=True)
## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyFrom(uint8_t const * buffer) [member function]
cls.add_method('CopyFrom',
'void',
[param('uint8_t const *', 'buffer')])
## mac64-address.h (module 'network'): void ns3::Mac64Address::CopyTo(uint8_t * buffer) const [member function]
cls.add_method('CopyTo',
'void',
[param('uint8_t *', 'buffer')],
is_const=True)
## mac64-address.h (module 'network'): static bool ns3::Mac64Address::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
return
def register_Ns3NetDeviceContainer_methods(root_module, cls):
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor]
cls.add_constructor([])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor]
cls.add_constructor([param('std::string', 'devName')])
## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor]
cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NetDeviceContainer', 'other')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'deviceName')])
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >',
[],
is_const=True)
## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True)
## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeContainer_methods(root_module, cls):
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor]
cls.add_constructor([])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor]
cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor]
cls.add_constructor([param('std::string', 'nodeName')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')])
## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor]
cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function]
cls.add_method('Add',
'void',
[param('ns3::NodeContainer', 'other')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function]
cls.add_method('Add',
'void',
[param('std::string', 'nodeName')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n')])
## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function]
cls.add_method('Create',
'void',
[param('uint32_t', 'n'), param('uint32_t', 'systemId')])
## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_const=True)
## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function]
cls.add_method('Get',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'i')],
is_const=True)
## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function]
cls.add_method('GetGlobal',
'ns3::NodeContainer',
[],
is_static=True)
## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function]
cls.add_method('GetN',
'uint32_t',
[],
is_const=True)
return
def register_Ns3NodeList_methods(root_module, cls):
## node-list.h (module 'network'): ns3::NodeList::NodeList() [constructor]
cls.add_constructor([])
## node-list.h (module 'network'): ns3::NodeList::NodeList(ns3::NodeList const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NodeList const &', 'arg0')])
## node-list.h (module 'network'): static uint32_t ns3::NodeList::Add(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Add',
'uint32_t',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_static=True)
## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::Begin() [member function]
cls.add_method('Begin',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_static=True)
## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::End() [member function]
cls.add_method('End',
'__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >',
[],
is_static=True)
## node-list.h (module 'network'): static uint32_t ns3::NodeList::GetNNodes() [member function]
cls.add_method('GetNNodes',
'uint32_t',
[],
is_static=True)
## node-list.h (module 'network'): static ns3::Ptr<ns3::Node> ns3::NodeList::GetNode(uint32_t n) [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[param('uint32_t', 'n')],
is_static=True)
return
def register_Ns3NonCopyable_methods(root_module, cls):
## non-copyable.h (module 'core'): ns3::NonCopyable::NonCopyable() [constructor]
cls.add_constructor([],
visibility='protected')
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_Ns3OnOffHelper_methods(root_module, cls):
## on-off-helper.h (module 'applications'): ns3::OnOffHelper::OnOffHelper(ns3::OnOffHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OnOffHelper const &', 'arg0')])
## on-off-helper.h (module 'applications'): ns3::OnOffHelper::OnOffHelper(std::string protocol, ns3::Address address) [constructor]
cls.add_constructor([param('std::string', 'protocol'), param('ns3::Address', 'address')])
## on-off-helper.h (module 'applications'): int64_t ns3::OnOffHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')])
## on-off-helper.h (module 'applications'): ns3::ApplicationContainer ns3::OnOffHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## on-off-helper.h (module 'applications'): ns3::ApplicationContainer ns3::OnOffHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## on-off-helper.h (module 'applications'): ns3::ApplicationContainer ns3::OnOffHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## on-off-helper.h (module 'applications'): void ns3::OnOffHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## on-off-helper.h (module 'applications'): void ns3::OnOffHelper::SetConstantRate(ns3::DataRate dataRate, uint32_t packetSize=512) [member function]
cls.add_method('SetConstantRate',
'void',
[param('ns3::DataRate', 'dataRate'), param('uint32_t', 'packetSize', default_value='512')])
return
def register_Ns3PacketLossCounter_methods(root_module, cls):
## packet-loss-counter.h (module 'applications'): ns3::PacketLossCounter::PacketLossCounter(ns3::PacketLossCounter const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketLossCounter const &', 'arg0')])
## packet-loss-counter.h (module 'applications'): ns3::PacketLossCounter::PacketLossCounter(uint8_t bitmapSize) [constructor]
cls.add_constructor([param('uint8_t', 'bitmapSize')])
## packet-loss-counter.h (module 'applications'): uint16_t ns3::PacketLossCounter::GetBitMapSize() const [member function]
cls.add_method('GetBitMapSize',
'uint16_t',
[],
is_const=True)
## packet-loss-counter.h (module 'applications'): uint32_t ns3::PacketLossCounter::GetLost() const [member function]
cls.add_method('GetLost',
'uint32_t',
[],
is_const=True)
## packet-loss-counter.h (module 'applications'): void ns3::PacketLossCounter::NotifyReceived(uint32_t seq) [member function]
cls.add_method('NotifyReceived',
'void',
[param('uint32_t', 'seq')])
## packet-loss-counter.h (module 'applications'): void ns3::PacketLossCounter::SetBitMapSize(uint16_t size) [member function]
cls.add_method('SetBitMapSize',
'void',
[param('uint16_t', 'size')])
return
def register_Ns3PacketMetadata_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor]
cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function]
cls.add_method('AddAtEnd',
'void',
[param('ns3::PacketMetadata const &', 'o')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('AddHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function]
cls.add_method('AddPaddingAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('AddTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function]
cls.add_method('BeginItem',
'ns3::PacketMetadata::ItemIterator',
[param('ns3::Buffer', 'buffer')],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function]
cls.add_method('CreateFragment',
'ns3::PacketMetadata',
[param('uint32_t', 'start'), param('uint32_t', 'end')],
is_const=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function]
cls.add_method('Enable',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function]
cls.add_method('EnableChecking',
'void',
[],
is_static=True)
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function]
cls.add_method('GetUid',
'uint64_t',
[],
is_const=True)
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function]
cls.add_method('RemoveAtEnd',
'void',
[param('uint32_t', 'end')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function]
cls.add_method('RemoveAtStart',
'void',
[param('uint32_t', 'start')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function]
cls.add_method('RemoveHeader',
'void',
[param('ns3::Header const &', 'header'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function]
cls.add_method('RemoveTrailer',
'void',
[param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')])
## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3PacketMetadataItem_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor]
cls.add_constructor([])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable]
cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable]
cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable]
cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable]
cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable]
cls.add_instance_attribute('isFragment', 'bool', is_const=False)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable]
cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False)
return
def register_Ns3PacketMetadataItemIterator_methods(root_module, cls):
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')])
## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor]
cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')])
## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketMetadata::Item',
[])
return
def register_Ns3PacketSinkHelper_methods(root_module, cls):
## packet-sink-helper.h (module 'applications'): ns3::PacketSinkHelper::PacketSinkHelper(ns3::PacketSinkHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSinkHelper const &', 'arg0')])
## packet-sink-helper.h (module 'applications'): ns3::PacketSinkHelper::PacketSinkHelper(std::string protocol, ns3::Address address) [constructor]
cls.add_constructor([param('std::string', 'protocol'), param('ns3::Address', 'address')])
## packet-sink-helper.h (module 'applications'): ns3::ApplicationContainer ns3::PacketSinkHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## packet-sink-helper.h (module 'applications'): ns3::ApplicationContainer ns3::PacketSinkHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## packet-sink-helper.h (module 'applications'): ns3::ApplicationContainer ns3::PacketSinkHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## packet-sink-helper.h (module 'applications'): void ns3::PacketSinkHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3PacketSocketAddress_methods(root_module, cls):
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress(ns3::PacketSocketAddress const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketAddress const &', 'arg0')])
## packet-socket-address.h (module 'network'): ns3::PacketSocketAddress::PacketSocketAddress() [constructor]
cls.add_constructor([])
## packet-socket-address.h (module 'network'): static ns3::PacketSocketAddress ns3::PacketSocketAddress::ConvertFrom(ns3::Address const & address) [member function]
cls.add_method('ConvertFrom',
'ns3::PacketSocketAddress',
[param('ns3::Address const &', 'address')],
is_static=True)
## packet-socket-address.h (module 'network'): ns3::Address ns3::PacketSocketAddress::GetPhysicalAddress() const [member function]
cls.add_method('GetPhysicalAddress',
'ns3::Address',
[],
is_const=True)
## packet-socket-address.h (module 'network'): uint16_t ns3::PacketSocketAddress::GetProtocol() const [member function]
cls.add_method('GetProtocol',
'uint16_t',
[],
is_const=True)
## packet-socket-address.h (module 'network'): uint32_t ns3::PacketSocketAddress::GetSingleDevice() const [member function]
cls.add_method('GetSingleDevice',
'uint32_t',
[],
is_const=True)
## packet-socket-address.h (module 'network'): static bool ns3::PacketSocketAddress::IsMatchingType(ns3::Address const & address) [member function]
cls.add_method('IsMatchingType',
'bool',
[param('ns3::Address const &', 'address')],
is_static=True)
## packet-socket-address.h (module 'network'): bool ns3::PacketSocketAddress::IsSingleDevice() const [member function]
cls.add_method('IsSingleDevice',
'bool',
[],
is_const=True)
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetAllDevices() [member function]
cls.add_method('SetAllDevices',
'void',
[])
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetPhysicalAddress(ns3::Address const address) [member function]
cls.add_method('SetPhysicalAddress',
'void',
[param('ns3::Address const', 'address')])
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetProtocol(uint16_t protocol) [member function]
cls.add_method('SetProtocol',
'void',
[param('uint16_t', 'protocol')])
## packet-socket-address.h (module 'network'): void ns3::PacketSocketAddress::SetSingleDevice(uint32_t device) [member function]
cls.add_method('SetSingleDevice',
'void',
[param('uint32_t', 'device')])
return
def register_Ns3PacketSocketHelper_methods(root_module, cls):
## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper() [constructor]
cls.add_constructor([])
## packet-socket-helper.h (module 'network'): ns3::PacketSocketHelper::PacketSocketHelper(ns3::PacketSocketHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketHelper const &', 'arg0')])
## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'void',
[param('std::string', 'nodeName')],
is_const=True)
## packet-socket-helper.h (module 'network'): void ns3::PacketSocketHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'void',
[param('ns3::NodeContainer', 'c')],
is_const=True)
return
def register_Ns3PacketTagIterator_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')])
## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function]
cls.add_method('Next',
'ns3::PacketTagIterator::Item',
[])
return
def register_Ns3PacketTagIteratorItem_methods(root_module, cls):
## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')])
## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function]
cls.add_method('GetTag',
'void',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_const=True)
return
def register_Ns3PacketTagList_methods(root_module, cls):
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor]
cls.add_constructor([])
## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor]
cls.add_constructor([param('ns3::PacketTagList const &', 'o')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function]
cls.add_method('Add',
'void',
[param('ns3::Tag const &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function]
cls.add_method('Head',
'ns3::PacketTagList::TagData const *',
[],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function]
cls.add_method('Peek',
'bool',
[param('ns3::Tag &', 'tag')],
is_const=True)
## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function]
cls.add_method('Remove',
'bool',
[param('ns3::Tag &', 'tag')])
## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function]
cls.add_method('RemoveAll',
'void',
[])
## 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_Ns3PbbAddressTlvBlock_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock(ns3::PbbAddressTlvBlock const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressTlvBlock const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressTlvBlock::PbbAddressTlvBlock() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Back() const [member function]
cls.add_method('Back',
'ns3::Ptr< ns3::PbbAddressTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() [member function]
cls.add_method('Begin',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): bool ns3::PbbAddressTlvBlock::Empty() const [member function]
cls.add_method('Empty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() [member function]
cls.add_method('End',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressTlvBlock::Front() const [member function]
cls.add_method('Front',
'ns3::Ptr< ns3::PbbAddressTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbAddressTlvBlock::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbAddressTlv> const tlv) [member function]
cls.add_method('Insert',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbAddressTlv > const', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopBack() [member function]
cls.add_method('PopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PopFront() [member function]
cls.add_method('PopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushBack(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function]
cls.add_method('PushBack',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::PushFront(ns3::Ptr<ns3::PbbAddressTlv> tlv) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): int ns3::PbbAddressTlvBlock::Size() const [member function]
cls.add_method('Size',
'int',
[],
is_const=True)
return
def register_Ns3PbbTlvBlock_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock(ns3::PbbTlvBlock const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbTlvBlock const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbTlvBlock::PbbTlvBlock() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Back() const [member function]
cls.add_method('Back',
'ns3::Ptr< ns3::PbbTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() [member function]
cls.add_method('Begin',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): bool ns3::PbbTlvBlock::Empty() const [member function]
cls.add_method('Empty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() [member function]
cls.add_method('End',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbTlvBlock::Front() const [member function]
cls.add_method('Front',
'ns3::Ptr< ns3::PbbTlv >',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbTlvBlock::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbTlvBlock::Insert(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position, ns3::Ptr<ns3::PbbTlv> const tlv) [member function]
cls.add_method('Insert',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopBack() [member function]
cls.add_method('PopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PopFront() [member function]
cls.add_method('PopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('PushBack',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::PushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('PushFront',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbTlvBlock::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): int ns3::PbbTlvBlock::Size() const [member function]
cls.add_method('Size',
'int',
[],
is_const=True)
return
def register_Ns3PcapFile_methods(root_module, cls):
## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor]
cls.add_constructor([])
## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t & packets, 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 &', 'packets'), 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<ns3::Packet const> 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 const & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header const &', '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=std::numeric_limits<unsigned int>::max(), 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='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='0')])
## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromDevice',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')])
## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function]
cls.add_method('GetFilenameFromInterfacePair',
'std::string',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')])
return
def register_Ns3PcapHelperForDevice_methods(root_module, cls):
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')])
## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor]
cls.add_constructor([])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function]
cls.add_method('EnablePcap',
'void',
[param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function]
cls.add_method('EnablePcapAll',
'void',
[param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')])
## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function]
cls.add_method('EnablePcapInternal',
'void',
[param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')],
is_pure_virtual=True, is_virtual=True)
return
def register_Ns3Ping6Helper_methods(root_module, cls):
## ping6-helper.h (module 'applications'): ns3::Ping6Helper::Ping6Helper(ns3::Ping6Helper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ping6Helper const &', 'arg0')])
## ping6-helper.h (module 'applications'): ns3::Ping6Helper::Ping6Helper() [constructor]
cls.add_constructor([])
## ping6-helper.h (module 'applications'): ns3::ApplicationContainer ns3::Ping6Helper::Install(ns3::NodeContainer c) [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')])
## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetIfIndex(uint32_t ifIndex) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t', 'ifIndex')])
## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetLocal(ns3::Ipv6Address ip) [member function]
cls.add_method('SetLocal',
'void',
[param('ns3::Ipv6Address', 'ip')])
## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetRemote(ns3::Ipv6Address ip) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Ipv6Address', 'ip')])
## ping6-helper.h (module 'applications'): void ns3::Ping6Helper::SetRoutersAddress(std::vector<ns3::Ipv6Address, std::allocator<ns3::Ipv6Address> > routers) [member function]
cls.add_method('SetRoutersAddress',
'void',
[param('std::vector< ns3::Ipv6Address >', 'routers')])
return
def register_Ns3RadvdHelper_methods(root_module, cls):
## radvd-helper.h (module 'applications'): ns3::RadvdHelper::RadvdHelper(ns3::RadvdHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RadvdHelper const &', 'arg0')])
## radvd-helper.h (module 'applications'): ns3::RadvdHelper::RadvdHelper() [constructor]
cls.add_constructor([])
## radvd-helper.h (module 'applications'): void ns3::RadvdHelper::AddAnnouncedPrefix(uint32_t interface, ns3::Ipv6Address prefix, uint32_t prefixLength) [member function]
cls.add_method('AddAnnouncedPrefix',
'void',
[param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'prefix'), param('uint32_t', 'prefixLength')])
## radvd-helper.h (module 'applications'): void ns3::RadvdHelper::ClearPrefixes() [member function]
cls.add_method('ClearPrefixes',
'void',
[])
## radvd-helper.h (module 'applications'): void ns3::RadvdHelper::DisableDefaultRouterForInterface(uint32_t interface) [member function]
cls.add_method('DisableDefaultRouterForInterface',
'void',
[param('uint32_t', 'interface')])
## radvd-helper.h (module 'applications'): void ns3::RadvdHelper::EnableDefaultRouterForInterface(uint32_t interface) [member function]
cls.add_method('EnableDefaultRouterForInterface',
'void',
[param('uint32_t', 'interface')])
## radvd-helper.h (module 'applications'): ns3::Ptr<ns3::RadvdInterface> ns3::RadvdHelper::GetRadvdInterface(uint32_t interface) [member function]
cls.add_method('GetRadvdInterface',
'ns3::Ptr< ns3::RadvdInterface >',
[param('uint32_t', 'interface')])
## radvd-helper.h (module 'applications'): ns3::ApplicationContainer ns3::RadvdHelper::Install(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')])
## radvd-helper.h (module 'applications'): void ns3::RadvdHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3SimpleNetDeviceHelper_methods(root_module, cls):
## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper::SimpleNetDeviceHelper(ns3::SimpleNetDeviceHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimpleNetDeviceHelper const &', 'arg0')])
## simple-net-device-helper.h (module 'network'): ns3::SimpleNetDeviceHelper::SimpleNetDeviceHelper() [constructor]
cls.add_constructor([])
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::SimpleChannel> channel) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::SimpleChannel >', 'channel')],
is_const=True)
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::NodeContainer const & c) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer const &', 'c')],
is_const=True)
## simple-net-device-helper.h (module 'network'): ns3::NetDeviceContainer ns3::SimpleNetDeviceHelper::Install(ns3::NodeContainer const & c, ns3::Ptr<ns3::SimpleChannel> channel) const [member function]
cls.add_method('Install',
'ns3::NetDeviceContainer',
[param('ns3::NodeContainer const &', 'c'), param('ns3::Ptr< ns3::SimpleChannel >', 'channel')],
is_const=True)
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetChannel(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('SetChannel',
'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()')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetChannelAttribute(std::string n1, ns3::AttributeValue const & v1) [member function]
cls.add_method('SetChannelAttribute',
'void',
[param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function]
cls.add_method('SetDeviceAttribute',
'void',
[param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::SetNetDevicePointToPointMode(bool pointToPointMode) [member function]
cls.add_method('SetNetDevicePointToPointMode',
'void',
[param('bool', 'pointToPointMode')])
## simple-net-device-helper.h (module 'network'): void ns3::SimpleNetDeviceHelper::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()')])
return
def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Simulator_methods(root_module, cls):
## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Simulator const &', 'arg0')])
## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function]
cls.add_method('Cancel',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function]
cls.add_method('Destroy',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function]
cls.add_method('GetContext',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function]
cls.add_method('GetDelayLeft',
'ns3::Time',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function]
cls.add_method('GetImplementation',
'ns3::Ptr< ns3::SimulatorImpl >',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function]
cls.add_method('GetMaximumSimulationTime',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function]
cls.add_method('IsExpired',
'bool',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function]
cls.add_method('IsFinished',
'bool',
[],
is_static=True)
## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function]
cls.add_method('Now',
'ns3::Time',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function]
cls.add_method('Remove',
'void',
[param('ns3::EventId const &', 'id')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function]
cls.add_method('SetImplementation',
'void',
[param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function]
cls.add_method('SetScheduler',
'void',
[param('ns3::ObjectFactory', 'schedulerFactory')],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function]
cls.add_method('Stop',
'void',
[],
is_static=True)
## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & delay) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'delay')],
is_static=True)
return
def register_Ns3StatisticalSummary_methods(root_module, cls):
## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary() [constructor]
cls.add_constructor([])
## data-calculator.h (module 'stats'): ns3::StatisticalSummary::StatisticalSummary(ns3::StatisticalSummary const & arg0) [copy constructor]
cls.add_constructor([param('ns3::StatisticalSummary const &', 'arg0')])
## data-calculator.h (module 'stats'): long int ns3::StatisticalSummary::getCount() const [member function]
cls.add_method('getCount',
'long int',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMax() const [member function]
cls.add_method('getMax',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMean() const [member function]
cls.add_method('getMean',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getMin() const [member function]
cls.add_method('getMin',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSqrSum() const [member function]
cls.add_method('getSqrSum',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getStddev() const [member function]
cls.add_method('getStddev',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getSum() const [member function]
cls.add_method('getSum',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): double ns3::StatisticalSummary::getVariance() const [member function]
cls.add_method('getVariance',
'double',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3SystemWallClockMs_methods(root_module, cls):
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs(ns3::SystemWallClockMs const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SystemWallClockMs const &', 'arg0')])
## system-wall-clock-ms.h (module 'core'): ns3::SystemWallClockMs::SystemWallClockMs() [constructor]
cls.add_constructor([])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::End() [member function]
cls.add_method('End',
'int64_t',
[])
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedReal() const [member function]
cls.add_method('GetElapsedReal',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedSystem() const [member function]
cls.add_method('GetElapsedSystem',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): int64_t ns3::SystemWallClockMs::GetElapsedUser() const [member function]
cls.add_method('GetElapsedUser',
'int64_t',
[],
is_const=True)
## system-wall-clock-ms.h (module 'core'): void ns3::SystemWallClockMs::Start() [member function]
cls.add_method('Start',
'void',
[])
return
def register_Ns3Tag_methods(root_module, cls):
## tag.h (module 'network'): ns3::Tag::Tag() [constructor]
cls.add_constructor([])
## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Tag const &', 'arg0')])
## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_virtual=True)
## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3TagBuffer_methods(root_module, cls):
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')])
## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor]
cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function]
cls.add_method('CopyFrom',
'void',
[param('ns3::TagBuffer', 'o')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function]
cls.add_method('Read',
'void',
[param('uint8_t *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function]
cls.add_method('ReadDouble',
'double',
[])
## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function]
cls.add_method('ReadU16',
'uint16_t',
[])
## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function]
cls.add_method('ReadU32',
'uint32_t',
[])
## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function]
cls.add_method('ReadU64',
'uint64_t',
[])
## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function]
cls.add_method('ReadU8',
'uint8_t',
[])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function]
cls.add_method('TrimAtEnd',
'void',
[param('uint32_t', 'trim')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('Write',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function]
cls.add_method('WriteDouble',
'void',
[param('double', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function]
cls.add_method('WriteU16',
'void',
[param('uint16_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function]
cls.add_method('WriteU32',
'void',
[param('uint32_t', 'data')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function]
cls.add_method('WriteU64',
'void',
[param('uint64_t', 'v')])
## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function]
cls.add_method('WriteU8',
'void',
[param('uint8_t', 'v')])
return
def register_Ns3TimeWithUnit_methods(root_module, cls):
cls.add_output_stream_operator()
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor]
cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')])
return
def register_Ns3TypeId_methods(root_module, cls):
cls.add_binary_comparison_operator('!=')
cls.add_binary_comparison_operator('<')
cls.add_output_stream_operator()
cls.add_binary_comparison_operator('==')
## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor]
cls.add_constructor([param('char const *', 'name')])
## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor]
cls.add_constructor([param('ns3::TypeId const &', 'o')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('AddAttribute',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')],
deprecated=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback) [member function]
cls.add_method('AddTraceSource',
'ns3::TypeId',
[param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function]
cls.add_method('GetAttribute',
'ns3::TypeId::AttributeInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function]
cls.add_method('GetAttributeFullName',
'std::string',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function]
cls.add_method('GetAttributeN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function]
cls.add_method('GetConstructor',
'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function]
cls.add_method('GetGroupName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function]
cls.add_method('GetHash',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function]
cls.add_method('GetParent',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function]
cls.add_method('GetRegistered',
'ns3::TypeId',
[param('uint32_t', 'i')],
is_static=True)
## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function]
cls.add_method('GetRegisteredN',
'uint32_t',
[],
is_static=True)
## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function]
cls.add_method('GetSize',
'std::size_t',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function]
cls.add_method('GetTraceSource',
'ns3::TypeId::TraceSourceInformation',
[param('uint32_t', 'i')],
is_const=True)
## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function]
cls.add_method('GetTraceSourceN',
'uint32_t',
[],
is_const=True)
## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function]
cls.add_method('GetUid',
'uint16_t',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function]
cls.add_method('HasConstructor',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function]
cls.add_method('HasParent',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function]
cls.add_method('HideFromDocumentation',
'ns3::TypeId',
[])
## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function]
cls.add_method('IsChildOf',
'bool',
[param('ns3::TypeId', 'other')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function]
cls.add_method('LookupAttributeByName',
'bool',
[param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)],
is_const=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function]
cls.add_method('LookupByHash',
'ns3::TypeId',
[param('uint32_t', 'hash')],
is_static=True)
## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function]
cls.add_method('LookupByHashFailSafe',
'bool',
[param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')],
is_static=True)
## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function]
cls.add_method('LookupTraceSourceByName',
'ns3::Ptr< ns3::TraceSourceAccessor const >',
[param('std::string', 'name')],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function]
cls.add_method('MustHideFromDocumentation',
'bool',
[],
is_const=True)
## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function]
cls.add_method('SetAttributeInitialValue',
'bool',
[param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function]
cls.add_method('SetGroupName',
'ns3::TypeId',
[param('std::string', 'groupName')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[param('ns3::TypeId', 'tid')])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent() [member function]
cls.add_method('SetParent',
'ns3::TypeId',
[],
template_parameters=['ns3::Object'])
## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function]
cls.add_method('SetSize',
'ns3::TypeId',
[param('std::size_t', 'size')])
## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function]
cls.add_method('SetUid',
'void',
[param('uint16_t', 'tid')])
return
def register_Ns3TypeIdAttributeInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable]
cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable]
cls.add_instance_attribute('flags', 'uint32_t', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable]
cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable]
cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False)
return
def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable]
cls.add_instance_attribute('callback', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable]
cls.add_instance_attribute('name', 'std::string', is_const=False)
return
def register_Ns3UdpClientHelper_methods(root_module, cls):
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::UdpClientHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpClientHelper const &', 'arg0')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper() [constructor]
cls.add_constructor([])
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::Ipv4Address ip, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::Ipv6Address ip, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpClientHelper::UdpClientHelper(ns3::Address ip, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-client-server-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpClientHelper::Install(ns3::NodeContainer c) [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')])
## udp-client-server-helper.h (module 'applications'): void ns3::UdpClientHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3UdpEchoClientHelper_methods(root_module, cls):
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::UdpEchoClientHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpEchoClientHelper const &', 'arg0')])
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::Address ip, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::Ipv4Address ip, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')])
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoClientHelper::UdpEchoClientHelper(ns3::Ipv6Address ip, uint16_t port) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')])
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoClientHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoClientHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoClientHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetFill(ns3::Ptr<ns3::Application> app, std::string fill) [member function]
cls.add_method('SetFill',
'void',
[param('ns3::Ptr< ns3::Application >', 'app'), param('std::string', 'fill')])
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetFill(ns3::Ptr<ns3::Application> app, uint8_t fill, uint32_t dataLength) [member function]
cls.add_method('SetFill',
'void',
[param('ns3::Ptr< ns3::Application >', 'app'), param('uint8_t', 'fill'), param('uint32_t', 'dataLength')])
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoClientHelper::SetFill(ns3::Ptr<ns3::Application> app, uint8_t * fill, uint32_t fillLength, uint32_t dataLength) [member function]
cls.add_method('SetFill',
'void',
[param('ns3::Ptr< ns3::Application >', 'app'), param('uint8_t *', 'fill'), param('uint32_t', 'fillLength'), param('uint32_t', 'dataLength')])
return
def register_Ns3UdpEchoServerHelper_methods(root_module, cls):
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoServerHelper::UdpEchoServerHelper(ns3::UdpEchoServerHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpEchoServerHelper const &', 'arg0')])
## udp-echo-helper.h (module 'applications'): ns3::UdpEchoServerHelper::UdpEchoServerHelper(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoServerHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoServerHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## udp-echo-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpEchoServerHelper::Install(ns3::NodeContainer c) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')],
is_const=True)
## udp-echo-helper.h (module 'applications'): void ns3::UdpEchoServerHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3UdpServerHelper_methods(root_module, cls):
## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper::UdpServerHelper(ns3::UdpServerHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpServerHelper const &', 'arg0')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper::UdpServerHelper() [constructor]
cls.add_constructor([])
## udp-client-server-helper.h (module 'applications'): ns3::UdpServerHelper::UdpServerHelper(uint16_t port) [constructor]
cls.add_constructor([param('uint16_t', 'port')])
## udp-client-server-helper.h (module 'applications'): ns3::Ptr<ns3::UdpServer> ns3::UdpServerHelper::GetServer() [member function]
cls.add_method('GetServer',
'ns3::Ptr< ns3::UdpServer >',
[])
## udp-client-server-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpServerHelper::Install(ns3::NodeContainer c) [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')])
## udp-client-server-helper.h (module 'applications'): void ns3::UdpServerHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3UdpTraceClientHelper_methods(root_module, cls):
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::UdpTraceClientHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpTraceClientHelper const &', 'arg0')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper() [constructor]
cls.add_constructor([])
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::Address ip, uint16_t port, std::string filename) [constructor]
cls.add_constructor([param('ns3::Address', 'ip'), param('uint16_t', 'port'), param('std::string', 'filename')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::Ipv4Address ip, uint16_t port, std::string filename) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port'), param('std::string', 'filename')])
## udp-client-server-helper.h (module 'applications'): ns3::UdpTraceClientHelper::UdpTraceClientHelper(ns3::Ipv6Address ip, uint16_t port, std::string filename) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port'), param('std::string', 'filename')])
## udp-client-server-helper.h (module 'applications'): ns3::ApplicationContainer ns3::UdpTraceClientHelper::Install(ns3::NodeContainer c) [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'c')])
## udp-client-server-helper.h (module 'applications'): void ns3::UdpTraceClientHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3V4PingHelper_methods(root_module, cls):
## v4ping-helper.h (module 'applications'): ns3::V4PingHelper::V4PingHelper(ns3::V4PingHelper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::V4PingHelper const &', 'arg0')])
## v4ping-helper.h (module 'applications'): ns3::V4PingHelper::V4PingHelper(ns3::Ipv4Address remote) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'remote')])
## v4ping-helper.h (module 'applications'): ns3::ApplicationContainer ns3::V4PingHelper::Install(ns3::NodeContainer nodes) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::NodeContainer', 'nodes')],
is_const=True)
## v4ping-helper.h (module 'applications'): ns3::ApplicationContainer ns3::V4PingHelper::Install(ns3::Ptr<ns3::Node> node) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_const=True)
## v4ping-helper.h (module 'applications'): ns3::ApplicationContainer ns3::V4PingHelper::Install(std::string nodeName) const [member function]
cls.add_method('Install',
'ns3::ApplicationContainer',
[param('std::string', 'nodeName')],
is_const=True)
## v4ping-helper.h (module 'applications'): void ns3::V4PingHelper::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function]
cls.add_method('SetAttribute',
'void',
[param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')])
return
def register_Ns3Empty_methods(root_module, cls):
## empty.h (module 'core'): ns3::empty::empty() [constructor]
cls.add_constructor([])
## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor]
cls.add_constructor([param('ns3::empty const &', 'arg0')])
return
def register_Ns3Int64x64_t_methods(root_module, cls):
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', 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_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_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('>=')
## 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_Ns3DeviceNameTag_methods(root_module, cls):
## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag(ns3::DeviceNameTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DeviceNameTag const &', 'arg0')])
## packet-socket.h (module 'network'): ns3::DeviceNameTag::DeviceNameTag() [constructor]
cls.add_constructor([])
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## packet-socket.h (module 'network'): std::string ns3::DeviceNameTag::GetDeviceName() const [member function]
cls.add_method('GetDeviceName',
'std::string',
[],
is_const=True)
## packet-socket.h (module 'network'): ns3::TypeId ns3::DeviceNameTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): uint32_t ns3::DeviceNameTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): static ns3::TypeId ns3::DeviceNameTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::DeviceNameTag::SetDeviceName(std::string n) [member function]
cls.add_method('SetDeviceName',
'void',
[param('std::string', 'n')])
return
def register_Ns3FlowIdTag_methods(root_module, cls):
## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(ns3::FlowIdTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::FlowIdTag const &', 'arg0')])
## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag() [constructor]
cls.add_constructor([])
## flow-id-tag.h (module 'network'): ns3::FlowIdTag::FlowIdTag(uint32_t flowId) [constructor]
cls.add_constructor([param('uint32_t', 'flowId')])
## flow-id-tag.h (module 'network'): static uint32_t ns3::FlowIdTag::AllocateFlowId() [member function]
cls.add_method('AllocateFlowId',
'uint32_t',
[],
is_static=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Deserialize(ns3::TagBuffer buf) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'buf')],
is_virtual=True)
## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetFlowId() const [member function]
cls.add_method('GetFlowId',
'uint32_t',
[],
is_const=True)
## flow-id-tag.h (module 'network'): ns3::TypeId ns3::FlowIdTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): uint32_t ns3::FlowIdTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): static ns3::TypeId ns3::FlowIdTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::Serialize(ns3::TagBuffer buf) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'buf')],
is_const=True, is_virtual=True)
## flow-id-tag.h (module 'network'): void ns3::FlowIdTag::SetFlowId(uint32_t flowId) [member function]
cls.add_method('SetFlowId',
'void',
[param('uint32_t', 'flowId')])
return
def register_Ns3Header_methods(root_module, cls):
cls.add_output_stream_operator()
## header.h (module 'network'): ns3::Header::Header() [constructor]
cls.add_constructor([])
## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Header const &', 'arg0')])
## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_virtual=True)
## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3LlcSnapHeader_methods(root_module, cls):
## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader(ns3::LlcSnapHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::LlcSnapHeader const &', 'arg0')])
## llc-snap-header.h (module 'network'): ns3::LlcSnapHeader::LlcSnapHeader() [constructor]
cls.add_constructor([])
## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## llc-snap-header.h (module 'network'): ns3::TypeId ns3::LlcSnapHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): uint32_t ns3::LlcSnapHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): uint16_t ns3::LlcSnapHeader::GetType() [member function]
cls.add_method('GetType',
'uint16_t',
[])
## llc-snap-header.h (module 'network'): static ns3::TypeId ns3::LlcSnapHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## llc-snap-header.h (module 'network'): void ns3::LlcSnapHeader::SetType(uint16_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint16_t', 'type')])
return
def register_Ns3Object_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::Object() [constructor]
cls.add_constructor([])
## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function]
cls.add_method('AggregateObject',
'void',
[param('ns3::Ptr< ns3::Object >', 'other')])
## object.h (module 'core'): void ns3::Object::Dispose() [member function]
cls.add_method('Dispose',
'void',
[])
## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function]
cls.add_method('GetAggregateIterator',
'ns3::Object::AggregateIterator',
[],
is_const=True)
## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## object.h (module 'core'): void ns3::Object::Initialize() [member function]
cls.add_method('Initialize',
'void',
[])
## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor]
cls.add_constructor([param('ns3::Object const &', 'o')],
visibility='protected')
## object.h (module 'core'): void ns3::Object::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function]
cls.add_method('NotifyNewAggregate',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3ObjectAggregateIterator_methods(root_module, cls):
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')])
## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor]
cls.add_constructor([])
## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function]
cls.add_method('HasNext',
'bool',
[],
is_const=True)
## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function]
cls.add_method('Next',
'ns3::Ptr< ns3::Object const >',
[])
return
def register_Ns3PacketBurst_methods(root_module, cls):
## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst(ns3::PacketBurst const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketBurst const &', 'arg0')])
## packet-burst.h (module 'network'): ns3::PacketBurst::PacketBurst() [constructor]
cls.add_constructor([])
## packet-burst.h (module 'network'): void ns3::PacketBurst::AddPacket(ns3::Ptr<ns3::Packet> packet) [member function]
cls.add_method('AddPacket',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet')])
## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::Begin() const [member function]
cls.add_method('Begin',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): ns3::Ptr<ns3::PacketBurst> ns3::PacketBurst::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::PacketBurst >',
[],
is_const=True)
## packet-burst.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::Packet> > ns3::PacketBurst::End() const [member function]
cls.add_method('End',
'std::_List_const_iterator< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetNPackets() const [member function]
cls.add_method('GetNPackets',
'uint32_t',
[],
is_const=True)
## packet-burst.h (module 'network'): std::list<ns3::Ptr<ns3::Packet>, std::allocator<ns3::Ptr<ns3::Packet> > > ns3::PacketBurst::GetPackets() const [member function]
cls.add_method('GetPackets',
'std::list< ns3::Ptr< ns3::Packet > >',
[],
is_const=True)
## packet-burst.h (module 'network'): uint32_t ns3::PacketBurst::GetSize() const [member function]
cls.add_method('GetSize',
'uint32_t',
[],
is_const=True)
## packet-burst.h (module 'network'): static ns3::TypeId ns3::PacketBurst::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-burst.h (module 'network'): void ns3::PacketBurst::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSocketTag_methods(root_module, cls):
## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag(ns3::PacketSocketTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketTag const &', 'arg0')])
## packet-socket.h (module 'network'): ns3::PacketSocketTag::PacketSocketTag() [constructor]
cls.add_constructor([])
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## packet-socket.h (module 'network'): ns3::Address ns3::PacketSocketTag::GetDestAddress() const [member function]
cls.add_method('GetDestAddress',
'ns3::Address',
[],
is_const=True)
## packet-socket.h (module 'network'): ns3::TypeId ns3::PacketSocketTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::NetDevice::PacketType ns3::PacketSocketTag::GetPacketType() const [member function]
cls.add_method('GetPacketType',
'ns3::NetDevice::PacketType',
[],
is_const=True)
## packet-socket.h (module 'network'): uint32_t ns3::PacketSocketTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocketTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetDestAddress(ns3::Address a) [member function]
cls.add_method('SetDestAddress',
'void',
[param('ns3::Address', 'a')])
## packet-socket.h (module 'network'): void ns3::PacketSocketTag::SetPacketType(ns3::NetDevice::PacketType t) [member function]
cls.add_method('SetPacketType',
'void',
[param('ns3::NetDevice::PacketType', 't')])
return
def register_Ns3PcapFileWrapper_methods(root_module, cls):
## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor]
cls.add_constructor([])
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function]
cls.add_method('Fail',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function]
cls.add_method('Eof',
'bool',
[],
is_const=True)
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function]
cls.add_method('Clear',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::_Ios_Openmode mode) [member function]
cls.add_method('Open',
'void',
[param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function]
cls.add_method('Close',
'void',
[])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function]
cls.add_method('Init',
'void',
[param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<ns3::Packet const> 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 const & header, ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('ns3::Header const &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')])
## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function]
cls.add_method('Write',
'void',
[param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function]
cls.add_method('GetMagic',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function]
cls.add_method('GetVersionMajor',
'uint16_t',
[])
## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function]
cls.add_method('GetVersionMinor',
'uint16_t',
[])
## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function]
cls.add_method('GetTimeZoneOffset',
'int32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function]
cls.add_method('GetSigFigs',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function]
cls.add_method('GetSnapLen',
'uint32_t',
[])
## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function]
cls.add_method('GetDataLinkType',
'uint32_t',
[])
return
def register_Ns3Queue_methods(root_module, cls):
## queue.h (module 'network'): ns3::Queue::Queue(ns3::Queue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Queue const &', 'arg0')])
## queue.h (module 'network'): ns3::Queue::Queue() [constructor]
cls.add_constructor([])
## queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Queue::Dequeue() [member function]
cls.add_method('Dequeue',
'ns3::Ptr< ns3::Packet >',
[])
## queue.h (module 'network'): void ns3::Queue::DequeueAll() [member function]
cls.add_method('DequeueAll',
'void',
[])
## queue.h (module 'network'): bool ns3::Queue::Enqueue(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('Enqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## queue.h (module 'network'): uint32_t ns3::Queue::GetNBytes() const [member function]
cls.add_method('GetNBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::Queue::GetNPackets() const [member function]
cls.add_method('GetNPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedBytes() const [member function]
cls.add_method('GetTotalDroppedBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalDroppedPackets() const [member function]
cls.add_method('GetTotalDroppedPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedBytes() const [member function]
cls.add_method('GetTotalReceivedBytes',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): uint32_t ns3::Queue::GetTotalReceivedPackets() const [member function]
cls.add_method('GetTotalReceivedPackets',
'uint32_t',
[],
is_const=True)
## queue.h (module 'network'): static ns3::TypeId ns3::Queue::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## queue.h (module 'network'): bool ns3::Queue::IsEmpty() const [member function]
cls.add_method('IsEmpty',
'bool',
[],
is_const=True)
## queue.h (module 'network'): ns3::Ptr<ns3::Packet const> 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<ns3::Packet const> ns3::Queue::DoPeek() const [member function]
cls.add_method('DoPeek',
'ns3::Ptr< ns3::Packet const >',
[],
is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3RadiotapHeader_methods(root_module, cls):
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader(ns3::RadiotapHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RadiotapHeader const &', 'arg0')])
## radiotap-header.h (module 'network'): ns3::RadiotapHeader::RadiotapHeader() [constructor]
cls.add_constructor([])
## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetAmpduStatusFlags() const [member function]
cls.add_method('GetAmpduStatusFlags',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::GetAmpduStatusRef() const [member function]
cls.add_method('GetAmpduStatusRef',
'uint32_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetAntennaNoisePower() const [member function]
cls.add_method('GetAntennaNoisePower',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetAntennaSignalPower() const [member function]
cls.add_method('GetAntennaSignalPower',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetChannelFlags() const [member function]
cls.add_method('GetChannelFlags',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetChannelFrequency() const [member function]
cls.add_method('GetChannelFrequency',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetFrameFlags() const [member function]
cls.add_method('GetFrameFlags',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): ns3::TypeId ns3::RadiotapHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetMcsFlags() const [member function]
cls.add_method('GetMcsFlags',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetMcsKnown() const [member function]
cls.add_method('GetMcsKnown',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetMcsRate() const [member function]
cls.add_method('GetMcsRate',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetRate() const [member function]
cls.add_method('GetRate',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint32_t ns3::RadiotapHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): uint64_t ns3::RadiotapHeader::GetTsft() const [member function]
cls.add_method('GetTsft',
'uint64_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): static ns3::TypeId ns3::RadiotapHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtBandwidth() const [member function]
cls.add_method('GetVhtBandwidth',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtCoding() const [member function]
cls.add_method('GetVhtCoding',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtFlags() const [member function]
cls.add_method('GetVhtFlags',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtGroupId() const [member function]
cls.add_method('GetVhtGroupId',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint16_t ns3::RadiotapHeader::GetVhtKnown() const [member function]
cls.add_method('GetVhtKnown',
'uint16_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser1() const [member function]
cls.add_method('GetVhtMcsNssUser1',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser2() const [member function]
cls.add_method('GetVhtMcsNssUser2',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser3() const [member function]
cls.add_method('GetVhtMcsNssUser3',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtMcsNssUser4() const [member function]
cls.add_method('GetVhtMcsNssUser4',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): uint8_t ns3::RadiotapHeader::GetVhtPartialAid() const [member function]
cls.add_method('GetVhtPartialAid',
'uint8_t',
[],
is_const=True)
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAmpduStatus(uint32_t referenceNumber, uint16_t flags, uint8_t crc) [member function]
cls.add_method('SetAmpduStatus',
'void',
[param('uint32_t', 'referenceNumber'), param('uint16_t', 'flags'), param('uint8_t', 'crc')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaNoisePower(double noise) [member function]
cls.add_method('SetAntennaNoisePower',
'void',
[param('double', 'noise')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetAntennaSignalPower(double signal) [member function]
cls.add_method('SetAntennaSignalPower',
'void',
[param('double', 'signal')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetChannelFrequencyAndFlags(uint16_t frequency, uint16_t flags) [member function]
cls.add_method('SetChannelFrequencyAndFlags',
'void',
[param('uint16_t', 'frequency'), param('uint16_t', 'flags')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetFrameFlags(uint8_t flags) [member function]
cls.add_method('SetFrameFlags',
'void',
[param('uint8_t', 'flags')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetMcsFields(uint8_t known, uint8_t flags, uint8_t mcs) [member function]
cls.add_method('SetMcsFields',
'void',
[param('uint8_t', 'known'), param('uint8_t', 'flags'), param('uint8_t', 'mcs')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetRate(uint8_t rate) [member function]
cls.add_method('SetRate',
'void',
[param('uint8_t', 'rate')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetTsft(uint64_t tsft) [member function]
cls.add_method('SetTsft',
'void',
[param('uint64_t', 'tsft')])
## radiotap-header.h (module 'network'): void ns3::RadiotapHeader::SetVhtFields(uint16_t known, uint8_t flags, uint8_t bandwidth, uint8_t * mcs_nss, uint8_t coding, uint8_t group_id, uint16_t partial_aid) [member function]
cls.add_method('SetVhtFields',
'void',
[param('uint16_t', 'known'), param('uint8_t', 'flags'), param('uint8_t', 'bandwidth'), param('uint8_t *', 'mcs_nss'), param('uint8_t', 'coding'), param('uint8_t', 'group_id'), param('uint16_t', 'partial_aid')])
return
def register_Ns3RandomVariableStream_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function]
cls.add_method('SetStream',
'void',
[param('int64_t', 'stream')])
## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function]
cls.add_method('GetStream',
'int64_t',
[],
is_const=True)
## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function]
cls.add_method('SetAntithetic',
'void',
[param('bool', 'isAntithetic')])
## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function]
cls.add_method('IsAntithetic',
'bool',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_pure_virtual=True, is_virtual=True)
## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function]
cls.add_method('Peek',
'ns3::RngStream *',
[],
is_const=True, visibility='protected')
return
def register_Ns3RedQueue_methods(root_module, cls):
## red-queue.h (module 'network'): ns3::RedQueue::RedQueue(ns3::RedQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RedQueue const &', 'arg0')])
## red-queue.h (module 'network'): ns3::RedQueue::RedQueue() [constructor]
cls.add_constructor([])
## red-queue.h (module 'network'): int64_t ns3::RedQueue::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## red-queue.h (module 'network'): ns3::Queue::QueueMode ns3::RedQueue::GetMode() [member function]
cls.add_method('GetMode',
'ns3::Queue::QueueMode',
[])
## red-queue.h (module 'network'): uint32_t ns3::RedQueue::GetQueueSize() [member function]
cls.add_method('GetQueueSize',
'uint32_t',
[])
## red-queue.h (module 'network'): ns3::RedQueue::Stats ns3::RedQueue::GetStats() [member function]
cls.add_method('GetStats',
'ns3::RedQueue::Stats',
[])
## red-queue.h (module 'network'): static ns3::TypeId ns3::RedQueue::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## red-queue.h (module 'network'): void ns3::RedQueue::SetMode(ns3::Queue::QueueMode mode) [member function]
cls.add_method('SetMode',
'void',
[param('ns3::Queue::QueueMode', 'mode')])
## red-queue.h (module 'network'): void ns3::RedQueue::SetQueueLimit(uint32_t lim) [member function]
cls.add_method('SetQueueLimit',
'void',
[param('uint32_t', 'lim')])
## red-queue.h (module 'network'): void ns3::RedQueue::SetTh(double minTh, double maxTh) [member function]
cls.add_method('SetTh',
'void',
[param('double', 'minTh'), param('double', 'maxTh')])
## red-queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::RedQueue::DoDequeue() [member function]
cls.add_method('DoDequeue',
'ns3::Ptr< ns3::Packet >',
[],
visibility='private', is_virtual=True)
## red-queue.h (module 'network'): bool ns3::RedQueue::DoEnqueue(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoEnqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## red-queue.h (module 'network'): ns3::Ptr<ns3::Packet const> ns3::RedQueue::DoPeek() const [member function]
cls.add_method('DoPeek',
'ns3::Ptr< ns3::Packet const >',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3RedQueueStats_methods(root_module, cls):
## red-queue.h (module 'network'): ns3::RedQueue::Stats::Stats() [constructor]
cls.add_constructor([])
## red-queue.h (module 'network'): ns3::RedQueue::Stats::Stats(ns3::RedQueue::Stats const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RedQueue::Stats const &', 'arg0')])
## red-queue.h (module 'network'): ns3::RedQueue::Stats::forcedDrop [variable]
cls.add_instance_attribute('forcedDrop', 'uint32_t', is_const=False)
## red-queue.h (module 'network'): ns3::RedQueue::Stats::qLimDrop [variable]
cls.add_instance_attribute('qLimDrop', 'uint32_t', is_const=False)
## red-queue.h (module 'network'): ns3::RedQueue::Stats::unforcedDrop [variable]
cls.add_instance_attribute('unforcedDrop', 'uint32_t', is_const=False)
return
def register_Ns3SeqTsHeader_methods(root_module, cls):
## seq-ts-header.h (module 'applications'): ns3::SeqTsHeader::SeqTsHeader(ns3::SeqTsHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SeqTsHeader const &', 'arg0')])
## seq-ts-header.h (module 'applications'): ns3::SeqTsHeader::SeqTsHeader() [constructor]
cls.add_constructor([])
## seq-ts-header.h (module 'applications'): uint32_t ns3::SeqTsHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## seq-ts-header.h (module 'applications'): ns3::TypeId ns3::SeqTsHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## seq-ts-header.h (module 'applications'): uint32_t ns3::SeqTsHeader::GetSeq() const [member function]
cls.add_method('GetSeq',
'uint32_t',
[],
is_const=True)
## seq-ts-header.h (module 'applications'): uint32_t ns3::SeqTsHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## seq-ts-header.h (module 'applications'): ns3::Time ns3::SeqTsHeader::GetTs() const [member function]
cls.add_method('GetTs',
'ns3::Time',
[],
is_const=True)
## seq-ts-header.h (module 'applications'): static ns3::TypeId ns3::SeqTsHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## seq-ts-header.h (module 'applications'): void ns3::SeqTsHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## seq-ts-header.h (module 'applications'): void ns3::SeqTsHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## seq-ts-header.h (module 'applications'): void ns3::SeqTsHeader::SetSeq(uint32_t seq) [member function]
cls.add_method('SetSeq',
'void',
[param('uint32_t', 'seq')])
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__Ns3PbbAddressBlock_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbAddressBlock__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter< ns3::PbbAddressBlock > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbAddressBlock, ns3::empty, ns3::DefaultDeleter<ns3::PbbAddressBlock> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbMessage_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbMessage__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter< ns3::PbbMessage > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbMessage, ns3::empty, ns3::DefaultDeleter<ns3::PbbMessage> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbPacket_Ns3Header_Ns3DefaultDeleter__lt__ns3PbbPacket__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter< ns3::PbbPacket > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbPacket, ns3::Header, ns3::DefaultDeleter<ns3::PbbPacket> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3PbbTlv_Ns3Empty_Ns3DefaultDeleter__lt__ns3PbbTlv__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::SimpleRefCount(ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter< ns3::PbbTlv > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::PbbTlv, ns3::empty, ns3::DefaultDeleter<ns3::PbbTlv> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3RadvdInterface_Ns3Empty_Ns3DefaultDeleter__lt__ns3RadvdInterface__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >::SimpleRefCount(ns3::SimpleRefCount<ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter< ns3::RadvdInterface > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::RadvdInterface, ns3::empty, ns3::DefaultDeleter<ns3::RadvdInterface> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3RadvdPrefix_Ns3Empty_Ns3DefaultDeleter__lt__ns3RadvdPrefix__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >::SimpleRefCount(ns3::SimpleRefCount<ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter< ns3::RadvdPrefix > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::RadvdPrefix, ns3::empty, ns3::DefaultDeleter<ns3::RadvdPrefix> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls):
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor]
cls.add_constructor([])
## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor]
cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')])
## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function]
cls.add_method('Cleanup',
'void',
[],
is_static=True)
return
def register_Ns3Socket_methods(root_module, cls):
## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Socket const &', 'arg0')])
## socket.h (module 'network'): ns3::Socket::Socket() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function]
cls.add_method('Bind',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind() [member function]
cls.add_method('Bind',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Bind6() [member function]
cls.add_method('Bind6',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function]
cls.add_method('BindToNetDevice',
'void',
[param('ns3::Ptr< ns3::NetDevice >', 'netdevice')],
is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Close() [member function]
cls.add_method('Close',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function]
cls.add_method('Connect',
'int',
[param('ns3::Address const &', 'address')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')],
is_static=True)
## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function]
cls.add_method('GetAllowBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function]
cls.add_method('GetBoundNetDevice',
'ns3::Ptr< ns3::NetDevice >',
[])
## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function]
cls.add_method('GetErrno',
'ns3::Socket::SocketErrno',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTos() const [member function]
cls.add_method('GetIpTos',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function]
cls.add_method('GetIpTtl',
'uint8_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function]
cls.add_method('GetIpv6HopLimit',
'uint8_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function]
cls.add_method('GetIpv6Tclass',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function]
cls.add_method('GetRxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function]
cls.add_method('GetSockName',
'int',
[param('ns3::Address &', 'address')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function]
cls.add_method('GetSocketType',
'ns3::Socket::SocketType',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function]
cls.add_method('GetTxAvailable',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function]
cls.add_method('IsIpRecvTos',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function]
cls.add_method('IsIpRecvTtl',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function]
cls.add_method('IsIpv6RecvHopLimit',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function]
cls.add_method('IsIpv6RecvTclass',
'bool',
[],
is_const=True)
## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function]
cls.add_method('IsRecvPktInfo',
'bool',
[],
is_const=True)
## socket.h (module 'network'): int ns3::Socket::Listen() [member function]
cls.add_method('Listen',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[])
## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Recv',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'int',
[param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')])
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p')])
## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')])
## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function]
cls.add_method('SendTo',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function]
cls.add_method('SendTo',
'int',
[param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')])
## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function]
cls.add_method('SetAcceptCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')])
## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function]
cls.add_method('SetAllowBroadcast',
'bool',
[param('bool', 'allowBroadcast')],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function]
cls.add_method('SetCloseCallbacks',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')])
## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function]
cls.add_method('SetConnectCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')])
## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function]
cls.add_method('SetDataSentCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')])
## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function]
cls.add_method('SetIpRecvTos',
'void',
[param('bool', 'ipv4RecvTos')])
## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function]
cls.add_method('SetIpRecvTtl',
'void',
[param('bool', 'ipv4RecvTtl')])
## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function]
cls.add_method('SetIpTos',
'void',
[param('uint8_t', 'ipTos')])
## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function]
cls.add_method('SetIpTtl',
'void',
[param('uint8_t', 'ipTtl')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function]
cls.add_method('SetIpv6HopLimit',
'void',
[param('uint8_t', 'ipHopLimit')],
is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function]
cls.add_method('SetIpv6RecvHopLimit',
'void',
[param('bool', 'ipv6RecvHopLimit')])
## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function]
cls.add_method('SetIpv6RecvTclass',
'void',
[param('bool', 'ipv6RecvTclass')])
## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function]
cls.add_method('SetIpv6Tclass',
'void',
[param('int', 'ipTclass')])
## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function]
cls.add_method('SetRecvCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')])
## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function]
cls.add_method('SetRecvPktInfo',
'void',
[param('bool', 'flag')])
## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function]
cls.add_method('SetSendCallback',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')])
## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function]
cls.add_method('ShutdownRecv',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function]
cls.add_method('ShutdownSend',
'int',
[],
is_pure_virtual=True, is_virtual=True)
## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## socket.h (module 'network'): bool ns3::Socket::IsManualIpTos() const [member function]
cls.add_method('IsManualIpTos',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function]
cls.add_method('IsManualIpTtl',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function]
cls.add_method('IsManualIpv6HopLimit',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function]
cls.add_method('IsManualIpv6Tclass',
'bool',
[],
is_const=True, visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function]
cls.add_method('NotifyConnectionFailed',
'void',
[],
visibility='protected')
## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function]
cls.add_method('NotifyConnectionRequest',
'bool',
[param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function]
cls.add_method('NotifyConnectionSucceeded',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function]
cls.add_method('NotifyDataRecv',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function]
cls.add_method('NotifyDataSent',
'void',
[param('uint32_t', 'size')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function]
cls.add_method('NotifyErrorClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function]
cls.add_method('NotifyNewConnectionCreated',
'void',
[param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function]
cls.add_method('NotifyNormalClose',
'void',
[],
visibility='protected')
## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function]
cls.add_method('NotifySend',
'void',
[param('uint32_t', 'spaceAvailable')],
visibility='protected')
return
def register_Ns3SocketAddressTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::Address ns3::SocketAddressTag::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketAddressTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketAddressTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketAddressTag::SetAddress(ns3::Address addr) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'addr')])
return
def register_Ns3SocketFactory_methods(root_module, cls):
## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory(ns3::SocketFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketFactory const &', 'arg0')])
## socket-factory.h (module 'network'): ns3::SocketFactory::SocketFactory() [constructor]
cls.add_constructor([])
## socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::SocketFactory::CreateSocket() [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_pure_virtual=True, is_virtual=True)
## socket-factory.h (module 'network'): static ns3::TypeId ns3::SocketFactory::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3SocketIpTosTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function]
cls.add_method('GetTos',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function]
cls.add_method('SetTos',
'void',
[param('uint8_t', 'tos')])
return
def register_Ns3SocketIpTtlTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function]
cls.add_method('GetTtl',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function]
cls.add_method('SetTtl',
'void',
[param('uint8_t', 'ttl')])
return
def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function]
cls.add_method('GetHopLimit',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function]
cls.add_method('SetHopLimit',
'void',
[param('uint8_t', 'hopLimit')])
return
def register_Ns3SocketIpv6TclassTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function]
cls.add_method('GetTclass',
'uint8_t',
[],
is_const=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function]
cls.add_method('SetTclass',
'void',
[param('uint8_t', 'tclass')])
return
def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls):
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')])
## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor]
cls.add_constructor([])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::TagBuffer', 'i')],
is_const=True, is_virtual=True)
return
def register_Ns3Time_methods(root_module, cls):
cls.add_binary_comparison_operator('<=')
cls.add_binary_comparison_operator('!=')
cls.add_inplace_numeric_operator('+=', 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_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_inplace_numeric_operator('-=', param('ns3::Time const &', u'right'))
cls.add_output_stream_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_Ns3Application_methods(root_module, cls):
## application.h (module 'network'): ns3::Application::Application(ns3::Application const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Application const &', 'arg0')])
## application.h (module 'network'): ns3::Application::Application() [constructor]
cls.add_constructor([])
## application.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Application::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True)
## application.h (module 'network'): static ns3::TypeId ns3::Application::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## application.h (module 'network'): void ns3::Application::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## application.h (module 'network'): void ns3::Application::SetStartTime(ns3::Time start) [member function]
cls.add_method('SetStartTime',
'void',
[param('ns3::Time', 'start')])
## application.h (module 'network'): void ns3::Application::SetStopTime(ns3::Time stop) [member function]
cls.add_method('SetStopTime',
'void',
[param('ns3::Time', 'stop')])
## application.h (module 'network'): void ns3::Application::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## application.h (module 'network'): void ns3::Application::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
## application.h (module 'network'): void ns3::Application::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## application.h (module 'network'): void ns3::Application::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3AttributeAccessor_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function]
cls.add_method('Get',
'bool',
[param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function]
cls.add_method('HasGetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function]
cls.add_method('HasSetter',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function]
cls.add_method('Set',
'bool',
[param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeChecker_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function]
cls.add_method('CreateValidValue',
'ns3::Ptr< ns3::AttributeValue >',
[param('ns3::AttributeValue const &', 'value')],
is_const=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3AttributeValue_methods(root_module, cls):
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')])
## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor]
cls.add_constructor([])
## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_virtual=True)
## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3BooleanChecker_methods(root_module, cls):
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')])
return
def register_Ns3BooleanValue_methods(root_module, cls):
cls.add_output_stream_operator()
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor]
cls.add_constructor([])
## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor]
cls.add_constructor([param('bool', 'value')])
## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function]
cls.add_method('Get',
'bool',
[],
is_const=True)
## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function]
cls.add_method('Set',
'void',
[param('bool', 'value')])
return
def register_Ns3BulkSendApplication_methods(root_module, cls):
## bulk-send-application.h (module 'applications'): ns3::BulkSendApplication::BulkSendApplication(ns3::BulkSendApplication const & arg0) [copy constructor]
cls.add_constructor([param('ns3::BulkSendApplication const &', 'arg0')])
## bulk-send-application.h (module 'applications'): ns3::BulkSendApplication::BulkSendApplication() [constructor]
cls.add_constructor([])
## bulk-send-application.h (module 'applications'): ns3::Ptr<ns3::Socket> ns3::BulkSendApplication::GetSocket() const [member function]
cls.add_method('GetSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_const=True)
## bulk-send-application.h (module 'applications'): static ns3::TypeId ns3::BulkSendApplication::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::SetMaxBytes(uint32_t maxBytes) [member function]
cls.add_method('SetMaxBytes',
'void',
[param('uint32_t', 'maxBytes')])
## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## bulk-send-application.h (module 'applications'): void ns3::BulkSendApplication::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3CallbackChecker_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')])
return
def register_Ns3CallbackImplBase_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')])
## callback.h (module 'core'): std::string ns3::CallbackImplBase::GetTypeid() const [member function]
cls.add_method('GetTypeid',
'std::string',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function]
cls.add_method('IsEqual',
'bool',
[param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function]
cls.add_method('Demangle',
'std::string',
[param('std::string const &', 'mangled')],
is_static=True, visibility='protected')
return
def register_Ns3CallbackValue_methods(root_module, cls):
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor]
cls.add_constructor([])
## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor]
cls.add_constructor([param('ns3::CallbackBase const &', 'base')])
## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function]
cls.add_method('Set',
'void',
[param('ns3::CallbackBase', 'base')])
return
def register_Ns3Channel_methods(root_module, cls):
## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Channel const &', 'arg0')])
## channel.h (module 'network'): ns3::Channel::Channel() [constructor]
cls.add_constructor([])
## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3ConstantRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function]
cls.add_method('GetConstant',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'constant')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'constant')])
## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DataCalculator_methods(root_module, cls):
## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator(ns3::DataCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataCalculator const &', 'arg0')])
## data-calculator.h (module 'stats'): ns3::DataCalculator::DataCalculator() [constructor]
cls.add_constructor([])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetContext() const [member function]
cls.add_method('GetContext',
'std::string',
[],
is_const=True)
## data-calculator.h (module 'stats'): bool ns3::DataCalculator::GetEnabled() const [member function]
cls.add_method('GetEnabled',
'bool',
[],
is_const=True)
## data-calculator.h (module 'stats'): std::string ns3::DataCalculator::GetKey() const [member function]
cls.add_method('GetKey',
'std::string',
[],
is_const=True)
## data-calculator.h (module 'stats'): static ns3::TypeId ns3::DataCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetContext(std::string const context) [member function]
cls.add_method('SetContext',
'void',
[param('std::string const', 'context')])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::SetKey(std::string const key) [member function]
cls.add_method('SetKey',
'void',
[param('std::string const', 'key')])
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Start(ns3::Time const & startTime) [member function]
cls.add_method('Start',
'void',
[param('ns3::Time const &', 'startTime')],
is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::Stop(ns3::Time const & stopTime) [member function]
cls.add_method('Stop',
'void',
[param('ns3::Time const &', 'stopTime')],
is_virtual=True)
## data-calculator.h (module 'stats'): void ns3::DataCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3DataCollectionObject_methods(root_module, cls):
## data-collection-object.h (module 'stats'): ns3::DataCollectionObject::DataCollectionObject(ns3::DataCollectionObject const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataCollectionObject const &', 'arg0')])
## data-collection-object.h (module 'stats'): ns3::DataCollectionObject::DataCollectionObject() [constructor]
cls.add_constructor([])
## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::Disable() [member function]
cls.add_method('Disable',
'void',
[])
## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::Enable() [member function]
cls.add_method('Enable',
'void',
[])
## data-collection-object.h (module 'stats'): std::string ns3::DataCollectionObject::GetName() const [member function]
cls.add_method('GetName',
'std::string',
[],
is_const=True)
## data-collection-object.h (module 'stats'): static ns3::TypeId ns3::DataCollectionObject::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## data-collection-object.h (module 'stats'): bool ns3::DataCollectionObject::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True, is_virtual=True)
## data-collection-object.h (module 'stats'): void ns3::DataCollectionObject::SetName(std::string name) [member function]
cls.add_method('SetName',
'void',
[param('std::string', 'name')])
return
def register_Ns3DataOutputInterface_methods(root_module, cls):
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface(ns3::DataOutputInterface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataOutputInterface const &', 'arg0')])
## data-output-interface.h (module 'stats'): ns3::DataOutputInterface::DataOutputInterface() [constructor]
cls.add_constructor([])
## data-output-interface.h (module 'stats'): std::string ns3::DataOutputInterface::GetFilePrefix() const [member function]
cls.add_method('GetFilePrefix',
'std::string',
[],
is_const=True)
## data-output-interface.h (module 'stats'): static ns3::TypeId ns3::DataOutputInterface::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::Output(ns3::DataCollector & dc) [member function]
cls.add_method('Output',
'void',
[param('ns3::DataCollector &', 'dc')],
is_pure_virtual=True, is_virtual=True)
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::SetFilePrefix(std::string const prefix) [member function]
cls.add_method('SetFilePrefix',
'void',
[param('std::string const', 'prefix')])
## data-output-interface.h (module 'stats'): void ns3::DataOutputInterface::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3DataRateChecker_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')])
return
def register_Ns3DataRateValue_methods(root_module, cls):
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor]
cls.add_constructor([])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')])
## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor]
cls.add_constructor([param('ns3::DataRate const &', 'value')])
## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## data-rate.h (module 'network'): bool ns3::DataRateValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function]
cls.add_method('Get',
'ns3::DataRate',
[],
is_const=True)
## data-rate.h (module 'network'): std::string ns3::DataRateValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::DataRate const &', 'value')])
return
def register_Ns3DeterministicRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function]
cls.add_method('SetValueArray',
'void',
[param('double *', 'values'), param('uint64_t', 'length')])
## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3DoubleValue_methods(root_module, cls):
## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor]
cls.add_constructor([])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')])
## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor]
cls.add_constructor([param('double const &', 'value')])
## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## double.h (module 'core'): bool ns3::DoubleValue::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)
## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function]
cls.add_method('Get',
'double',
[],
is_const=True)
## double.h (module 'core'): std::string ns3::DoubleValue::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)
## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function]
cls.add_method('Set',
'void',
[param('double const &', 'value')])
return
def register_Ns3DropTailQueue_methods(root_module, cls):
## drop-tail-queue.h (module 'network'): ns3::DropTailQueue::DropTailQueue(ns3::DropTailQueue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::DropTailQueue const &', 'arg0')])
## drop-tail-queue.h (module 'network'): ns3::DropTailQueue::DropTailQueue() [constructor]
cls.add_constructor([])
## drop-tail-queue.h (module 'network'): ns3::Queue::QueueMode ns3::DropTailQueue::GetMode() const [member function]
cls.add_method('GetMode',
'ns3::Queue::QueueMode',
[],
is_const=True)
## drop-tail-queue.h (module 'network'): static ns3::TypeId ns3::DropTailQueue::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## drop-tail-queue.h (module 'network'): void ns3::DropTailQueue::SetMode(ns3::Queue::QueueMode mode) [member function]
cls.add_method('SetMode',
'void',
[param('ns3::Queue::QueueMode', 'mode')])
## drop-tail-queue.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::DropTailQueue::DoDequeue() [member function]
cls.add_method('DoDequeue',
'ns3::Ptr< ns3::Packet >',
[],
visibility='private', is_virtual=True)
## drop-tail-queue.h (module 'network'): bool ns3::DropTailQueue::DoEnqueue(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoEnqueue',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## drop-tail-queue.h (module 'network'): ns3::Ptr<ns3::Packet const> ns3::DropTailQueue::DoPeek() const [member function]
cls.add_method('DoPeek',
'ns3::Ptr< ns3::Packet const >',
[],
is_const=True, visibility='private', is_virtual=True)
return
def register_Ns3EmpiricalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function]
cls.add_method('CDF',
'void',
[param('double', 'v'), param('double', 'c')])
## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double c1, double c2, double v1, double v2, double r) [member function]
cls.add_method('Interpolate',
'double',
[param('double', 'c1'), param('double', 'c2'), param('double', 'v1'), param('double', 'v2'), param('double', 'r')],
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_Ns3EnumChecker_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): void ns3::EnumChecker::Add(int value, std::string name) [member function]
cls.add_method('Add',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int value, std::string name) [member function]
cls.add_method('AddDefault',
'void',
[param('int', 'value'), param('std::string', 'name')])
## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function]
cls.add_method('Check',
'bool',
[param('ns3::AttributeValue const &', 'value')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function]
cls.add_method('Copy',
'bool',
[param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')],
is_const=True, is_virtual=True)
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function]
cls.add_method('Create',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function]
cls.add_method('GetUnderlyingTypeInformation',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function]
cls.add_method('GetValueTypeName',
'std::string',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function]
cls.add_method('HasUnderlyingTypeInformation',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3EnumValue_methods(root_module, cls):
## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EnumValue const &', 'arg0')])
## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor]
cls.add_constructor([])
## enum.h (module 'core'): ns3::EnumValue::EnumValue(int value) [constructor]
cls.add_constructor([param('int', 'value')])
## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## enum.h (module 'core'): bool ns3::EnumValue::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)
## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function]
cls.add_method('Get',
'int',
[],
is_const=True)
## enum.h (module 'core'): std::string ns3::EnumValue::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)
## enum.h (module 'core'): void ns3::EnumValue::Set(int value) [member function]
cls.add_method('Set',
'void',
[param('int', 'value')])
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_Ns3EthernetHeader_methods(root_module, cls):
## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(ns3::EthernetHeader const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EthernetHeader const &', 'arg0')])
## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader(bool hasPreamble) [constructor]
cls.add_constructor([param('bool', 'hasPreamble')])
## ethernet-header.h (module 'network'): ns3::EthernetHeader::EthernetHeader() [constructor]
cls.add_constructor([])
## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetDestination() const [member function]
cls.add_method('GetDestination',
'ns3::Mac48Address',
[],
is_const=True)
## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetHeaderSize() const [member function]
cls.add_method('GetHeaderSize',
'uint32_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): ns3::TypeId ns3::EthernetHeader::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): uint16_t ns3::EthernetHeader::GetLengthType() const [member function]
cls.add_method('GetLengthType',
'uint16_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): ns3::ethernet_header_t ns3::EthernetHeader::GetPacketType() const [member function]
cls.add_method('GetPacketType',
'ns3::ethernet_header_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): uint64_t ns3::EthernetHeader::GetPreambleSfd() const [member function]
cls.add_method('GetPreambleSfd',
'uint64_t',
[],
is_const=True)
## ethernet-header.h (module 'network'): uint32_t ns3::EthernetHeader::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): ns3::Mac48Address ns3::EthernetHeader::GetSource() const [member function]
cls.add_method('GetSource',
'ns3::Mac48Address',
[],
is_const=True)
## ethernet-header.h (module 'network'): static ns3::TypeId ns3::EthernetHeader::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetDestination(ns3::Mac48Address destination) [member function]
cls.add_method('SetDestination',
'void',
[param('ns3::Mac48Address', 'destination')])
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetLengthType(uint16_t size) [member function]
cls.add_method('SetLengthType',
'void',
[param('uint16_t', 'size')])
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetPreambleSfd(uint64_t preambleSfd) [member function]
cls.add_method('SetPreambleSfd',
'void',
[param('uint64_t', 'preambleSfd')])
## ethernet-header.h (module 'network'): void ns3::EthernetHeader::SetSource(ns3::Mac48Address source) [member function]
cls.add_method('SetSource',
'void',
[param('ns3::Mac48Address', 'source')])
return
def register_Ns3EthernetTrailer_methods(root_module, cls):
## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer(ns3::EthernetTrailer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EthernetTrailer const &', 'arg0')])
## ethernet-trailer.h (module 'network'): ns3::EthernetTrailer::EthernetTrailer() [constructor]
cls.add_constructor([])
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::CalcFcs(ns3::Ptr<ns3::Packet const> p) [member function]
cls.add_method('CalcFcs',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'p')])
## ethernet-trailer.h (module 'network'): bool ns3::EthernetTrailer::CheckFcs(ns3::Ptr<ns3::Packet const> p) const [member function]
cls.add_method('CheckFcs',
'bool',
[param('ns3::Ptr< ns3::Packet const >', 'p')],
is_const=True)
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::Deserialize(ns3::Buffer::Iterator end) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'end')],
is_virtual=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::EnableFcs(bool enable) [member function]
cls.add_method('EnableFcs',
'void',
[param('bool', 'enable')])
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetFcs() [member function]
cls.add_method('GetFcs',
'uint32_t',
[])
## ethernet-trailer.h (module 'network'): ns3::TypeId ns3::EthernetTrailer::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): uint32_t ns3::EthernetTrailer::GetTrailerSize() const [member function]
cls.add_method('GetTrailerSize',
'uint32_t',
[],
is_const=True)
## ethernet-trailer.h (module 'network'): static ns3::TypeId ns3::EthernetTrailer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::Serialize(ns3::Buffer::Iterator end) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'end')],
is_const=True, is_virtual=True)
## ethernet-trailer.h (module 'network'): void ns3::EthernetTrailer::SetFcs(uint32_t fcs) [member function]
cls.add_method('SetFcs',
'void',
[param('uint32_t', 'fcs')])
return
def register_Ns3EventImpl_methods(root_module, cls):
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor]
cls.add_constructor([param('ns3::EventImpl const &', 'arg0')])
## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor]
cls.add_constructor([])
## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function]
cls.add_method('Cancel',
'void',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function]
cls.add_method('Invoke',
'void',
[])
## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function]
cls.add_method('IsCancelled',
'bool',
[])
## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function]
cls.add_method('Notify',
'void',
[],
is_pure_virtual=True, visibility='protected', is_virtual=True)
return
def register_Ns3ExponentialRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3GammaRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function]
cls.add_method('GetAlpha',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function]
cls.add_method('GetBeta',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'alpha'), param('double', 'beta')])
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'alpha'), param('uint32_t', 'beta')])
## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3IntegerValue_methods(root_module, cls):
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor]
cls.add_constructor([])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')])
## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor]
cls.add_constructor([param('int64_t const &', 'value')])
## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## integer.h (module 'core'): bool ns3::IntegerValue::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)
## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function]
cls.add_method('Get',
'int64_t',
[],
is_const=True)
## integer.h (module 'core'): std::string ns3::IntegerValue::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)
## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('int64_t const &', 'value')])
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_Ns3Mac16AddressChecker_methods(root_module, cls):
## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker() [constructor]
cls.add_constructor([])
## mac16-address.h (module 'network'): ns3::Mac16AddressChecker::Mac16AddressChecker(ns3::Mac16AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac16AddressChecker const &', 'arg0')])
return
def register_Ns3Mac16AddressValue_methods(root_module, cls):
## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue() [constructor]
cls.add_constructor([])
## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac16AddressValue const &', 'arg0')])
## mac16-address.h (module 'network'): ns3::Mac16AddressValue::Mac16AddressValue(ns3::Mac16Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac16Address const &', 'value')])
## mac16-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac16AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac16-address.h (module 'network'): bool ns3::Mac16AddressValue::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)
## mac16-address.h (module 'network'): ns3::Mac16Address ns3::Mac16AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac16Address',
[],
is_const=True)
## mac16-address.h (module 'network'): std::string ns3::Mac16AddressValue::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)
## mac16-address.h (module 'network'): void ns3::Mac16AddressValue::Set(ns3::Mac16Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac16Address 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_Ns3Mac64AddressChecker_methods(root_module, cls):
## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker() [constructor]
cls.add_constructor([])
## mac64-address.h (module 'network'): ns3::Mac64AddressChecker::Mac64AddressChecker(ns3::Mac64AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac64AddressChecker const &', 'arg0')])
return
def register_Ns3Mac64AddressValue_methods(root_module, cls):
## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue() [constructor]
cls.add_constructor([])
## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Mac64AddressValue const &', 'arg0')])
## mac64-address.h (module 'network'): ns3::Mac64AddressValue::Mac64AddressValue(ns3::Mac64Address const & value) [constructor]
cls.add_constructor([param('ns3::Mac64Address const &', 'value')])
## mac64-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac64AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## mac64-address.h (module 'network'): bool ns3::Mac64AddressValue::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)
## mac64-address.h (module 'network'): ns3::Mac64Address ns3::Mac64AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Mac64Address',
[],
is_const=True)
## mac64-address.h (module 'network'): std::string ns3::Mac64AddressValue::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)
## mac64-address.h (module 'network'): void ns3::Mac64AddressValue::Set(ns3::Mac64Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Mac64Address const &', 'value')])
return
def register_Ns3MinMaxAvgTotalCalculator__Double_methods(root_module, cls):
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<double>::MinMaxAvgTotalCalculator(ns3::MinMaxAvgTotalCalculator<double> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MinMaxAvgTotalCalculator< double > const &', 'arg0')])
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<double>::MinMaxAvgTotalCalculator() [constructor]
cls.add_constructor([])
## basic-data-calculators.h (module 'stats'): static ns3::TypeId ns3::MinMaxAvgTotalCalculator<double>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<double>::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<double>::Reset() [member function]
cls.add_method('Reset',
'void',
[])
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<double>::Update(double const i) [member function]
cls.add_method('Update',
'void',
[param('double const', 'i')])
## basic-data-calculators.h (module 'stats'): long int ns3::MinMaxAvgTotalCalculator<double>::getCount() const [member function]
cls.add_method('getCount',
'long int',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getMax() const [member function]
cls.add_method('getMax',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getMean() const [member function]
cls.add_method('getMean',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getMin() const [member function]
cls.add_method('getMin',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getSqrSum() const [member function]
cls.add_method('getSqrSum',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getStddev() const [member function]
cls.add_method('getStddev',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getSum() const [member function]
cls.add_method('getSum',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<double>::getVariance() const [member function]
cls.add_method('getVariance',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<double>::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3MinMaxAvgTotalCalculator__Unsigned_int_methods(root_module, cls):
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int>::MinMaxAvgTotalCalculator(ns3::MinMaxAvgTotalCalculator<unsigned int> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::MinMaxAvgTotalCalculator< unsigned int > const &', 'arg0')])
## basic-data-calculators.h (module 'stats'): ns3::MinMaxAvgTotalCalculator<unsigned int>::MinMaxAvgTotalCalculator() [constructor]
cls.add_constructor([])
## basic-data-calculators.h (module 'stats'): static ns3::TypeId ns3::MinMaxAvgTotalCalculator<unsigned int>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Reset() [member function]
cls.add_method('Reset',
'void',
[])
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::Update(unsigned int const i) [member function]
cls.add_method('Update',
'void',
[param('unsigned int const', 'i')])
## basic-data-calculators.h (module 'stats'): long int ns3::MinMaxAvgTotalCalculator<unsigned int>::getCount() const [member function]
cls.add_method('getCount',
'long int',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMax() const [member function]
cls.add_method('getMax',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMean() const [member function]
cls.add_method('getMean',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getMin() const [member function]
cls.add_method('getMin',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getSqrSum() const [member function]
cls.add_method('getSqrSum',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getStddev() const [member function]
cls.add_method('getStddev',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getSum() const [member function]
cls.add_method('getSum',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): double ns3::MinMaxAvgTotalCalculator<unsigned int>::getVariance() const [member function]
cls.add_method('getVariance',
'double',
[],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::MinMaxAvgTotalCalculator<unsigned int>::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3NetDevice_methods(root_module, cls):
## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor]
cls.add_constructor([])
## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::NetDevice const &', 'arg0')])
## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_pure_virtual=True, is_virtual=True)
## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_pure_virtual=True, is_const=True, is_virtual=True)
return
def register_Ns3NixVector_methods(root_module, cls):
cls.add_output_stream_operator()
## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor]
cls.add_constructor([])
## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor]
cls.add_constructor([param('ns3::NixVector const &', 'o')])
## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function]
cls.add_method('AddNeighborIndex',
'void',
[param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function]
cls.add_method('BitCount',
'uint32_t',
[param('uint32_t', 'numberOfNeighbors')],
is_const=True)
## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::NixVector >',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('uint32_t const *', 'buffer'), param('uint32_t', 'size')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function]
cls.add_method('ExtractNeighborIndex',
'uint32_t',
[param('uint32_t', 'numberOfBits')])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function]
cls.add_method('GetRemainingBits',
'uint32_t',
[])
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function]
cls.add_method('Serialize',
'uint32_t',
[param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')],
is_const=True)
return
def register_Ns3Node_methods(root_module, cls):
## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Node const &', 'arg0')])
## node.h (module 'network'): ns3::Node::Node() [constructor]
cls.add_constructor([])
## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor]
cls.add_constructor([param('uint32_t', 'systemId')])
## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function]
cls.add_method('AddApplication',
'uint32_t',
[param('ns3::Ptr< ns3::Application >', 'application')])
## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function]
cls.add_method('AddDevice',
'uint32_t',
[param('ns3::Ptr< ns3::NetDevice >', 'device')])
## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function]
cls.add_method('ChecksumEnabled',
'bool',
[],
is_static=True)
## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function]
cls.add_method('GetApplication',
'ns3::Ptr< ns3::Application >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'index')],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function]
cls.add_method('GetId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function]
cls.add_method('GetNApplications',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function]
cls.add_method('GetSystemId',
'uint32_t',
[],
is_const=True)
## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('RegisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function]
cls.add_method('RegisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')])
## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function]
cls.add_method('UnregisterDeviceAdditionListener',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')])
## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function]
cls.add_method('UnregisterProtocolHandler',
'void',
[param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')])
## node.h (module 'network'): void ns3::Node::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## node.h (module 'network'): void ns3::Node::DoInitialize() [member function]
cls.add_method('DoInitialize',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3NormalRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable]
cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True)
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function]
cls.add_method('GetVariance',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')])
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3ObjectFactoryChecker_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')])
return
def register_Ns3ObjectFactoryValue_methods(root_module, cls):
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor]
cls.add_constructor([])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')])
## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor]
cls.add_constructor([param('ns3::ObjectFactory const &', 'value')])
## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function]
cls.add_method('Get',
'ns3::ObjectFactory',
[],
is_const=True)
## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::ObjectFactory const &', 'value')])
return
def register_Ns3OnOffApplication_methods(root_module, cls):
## onoff-application.h (module 'applications'): ns3::OnOffApplication::OnOffApplication(ns3::OnOffApplication const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OnOffApplication const &', 'arg0')])
## onoff-application.h (module 'applications'): ns3::OnOffApplication::OnOffApplication() [constructor]
cls.add_constructor([])
## onoff-application.h (module 'applications'): int64_t ns3::OnOffApplication::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## onoff-application.h (module 'applications'): ns3::Ptr<ns3::Socket> ns3::OnOffApplication::GetSocket() const [member function]
cls.add_method('GetSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_const=True)
## onoff-application.h (module 'applications'): static ns3::TypeId ns3::OnOffApplication::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## onoff-application.h (module 'applications'): void ns3::OnOffApplication::SetMaxBytes(uint32_t maxBytes) [member function]
cls.add_method('SetMaxBytes',
'void',
[param('uint32_t', 'maxBytes')])
## onoff-application.h (module 'applications'): void ns3::OnOffApplication::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## onoff-application.h (module 'applications'): void ns3::OnOffApplication::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## onoff-application.h (module 'applications'): void ns3::OnOffApplication::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3OutputStreamWrapper_methods(root_module, cls):
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor]
cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor]
cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')])
## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor]
cls.add_constructor([param('std::ostream *', 'os')])
## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function]
cls.add_method('GetStream',
'std::ostream *',
[])
return
def register_Ns3Packet_methods(root_module, cls):
cls.add_output_stream_operator()
## packet.h (module 'network'): ns3::Packet::Packet() [constructor]
cls.add_constructor([])
## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor]
cls.add_constructor([param('ns3::Packet const &', 'o')])
## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor]
cls.add_constructor([param('uint32_t', 'size')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')])
## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor]
cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<ns3::Packet const> 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_Ns3PacketSink_methods(root_module, cls):
## packet-sink.h (module 'applications'): ns3::PacketSink::PacketSink(ns3::PacketSink const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSink const &', 'arg0')])
## packet-sink.h (module 'applications'): ns3::PacketSink::PacketSink() [constructor]
cls.add_constructor([])
## packet-sink.h (module 'applications'): std::list<ns3::Ptr<ns3::Socket>, std::allocator<ns3::Ptr<ns3::Socket> > > ns3::PacketSink::GetAcceptedSockets() const [member function]
cls.add_method('GetAcceptedSockets',
'std::list< ns3::Ptr< ns3::Socket > >',
[],
is_const=True)
## packet-sink.h (module 'applications'): ns3::Ptr<ns3::Socket> ns3::PacketSink::GetListeningSocket() const [member function]
cls.add_method('GetListeningSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_const=True)
## packet-sink.h (module 'applications'): uint32_t ns3::PacketSink::GetTotalRx() const [member function]
cls.add_method('GetTotalRx',
'uint32_t',
[],
is_const=True)
## packet-sink.h (module 'applications'): static ns3::TypeId ns3::PacketSink::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-sink.h (module 'applications'): void ns3::PacketSink::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## packet-sink.h (module 'applications'): void ns3::PacketSink::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## packet-sink.h (module 'applications'): void ns3::PacketSink::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSizeMinMaxAvgTotalCalculator_methods(root_module, cls):
## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator::PacketSizeMinMaxAvgTotalCalculator(ns3::PacketSizeMinMaxAvgTotalCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSizeMinMaxAvgTotalCalculator const &', 'arg0')])
## packet-data-calculators.h (module 'network'): ns3::PacketSizeMinMaxAvgTotalCalculator::PacketSizeMinMaxAvgTotalCalculator() [constructor]
cls.add_constructor([])
## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::FrameUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address realto) [member function]
cls.add_method('FrameUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'realto')])
## packet-data-calculators.h (module 'network'): static ns3::TypeId ns3::PacketSizeMinMaxAvgTotalCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::PacketUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('PacketUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet-data-calculators.h (module 'network'): void ns3::PacketSizeMinMaxAvgTotalCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3PacketSocket_methods(root_module, cls):
## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket(ns3::PacketSocket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocket const &', 'arg0')])
## packet-socket.h (module 'network'): ns3::PacketSocket::PacketSocket() [constructor]
cls.add_constructor([])
## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind() [member function]
cls.add_method('Bind',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind(ns3::Address const & address) [member function]
cls.add_method('Bind',
'int',
[param('ns3::Address const &', 'address')],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Bind6() [member function]
cls.add_method('Bind6',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Close() [member function]
cls.add_method('Close',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Connect(ns3::Address const & address) [member function]
cls.add_method('Connect',
'int',
[param('ns3::Address const &', 'address')],
is_virtual=True)
## packet-socket.h (module 'network'): bool ns3::PacketSocket::GetAllowBroadcast() const [member function]
cls.add_method('GetAllowBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::Socket::SocketErrno ns3::PacketSocket::GetErrno() const [member function]
cls.add_method('GetErrno',
'ns3::Socket::SocketErrno',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::PacketSocket::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetRxAvailable() const [member function]
cls.add_method('GetRxAvailable',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::GetSockName(ns3::Address & address) const [member function]
cls.add_method('GetSockName',
'int',
[param('ns3::Address &', 'address')],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): ns3::Socket::SocketType ns3::PacketSocket::GetSocketType() const [member function]
cls.add_method('GetSocketType',
'ns3::Socket::SocketType',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): uint32_t ns3::PacketSocket::GetTxAvailable() const [member function]
cls.add_method('GetTxAvailable',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packet-socket.h (module 'network'): static ns3::TypeId ns3::PacketSocket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Listen() [member function]
cls.add_method('Listen',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::Recv(uint32_t maxSize, uint32_t flags) [member function]
cls.add_method('Recv',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags')],
is_virtual=True)
## packet-socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::PacketSocket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function]
cls.add_method('RecvFrom',
'ns3::Ptr< ns3::Packet >',
[param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function]
cls.add_method('Send',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function]
cls.add_method('SendTo',
'int',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')],
is_virtual=True)
## packet-socket.h (module 'network'): bool ns3::PacketSocket::SetAllowBroadcast(bool allowBroadcast) [member function]
cls.add_method('SetAllowBroadcast',
'bool',
[param('bool', 'allowBroadcast')],
is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocket::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')])
## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownRecv() [member function]
cls.add_method('ShutdownRecv',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): int ns3::PacketSocket::ShutdownSend() [member function]
cls.add_method('ShutdownSend',
'int',
[],
is_virtual=True)
## packet-socket.h (module 'network'): void ns3::PacketSocket::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSocketClient_methods(root_module, cls):
## packet-socket-client.h (module 'network'): ns3::PacketSocketClient::PacketSocketClient(ns3::PacketSocketClient const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketClient const &', 'arg0')])
## packet-socket-client.h (module 'network'): ns3::PacketSocketClient::PacketSocketClient() [constructor]
cls.add_constructor([])
## packet-socket-client.h (module 'network'): static ns3::TypeId ns3::PacketSocketClient::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::SetRemote(ns3::PacketSocketAddress addr) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::PacketSocketAddress', 'addr')])
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## packet-socket-client.h (module 'network'): void ns3::PacketSocketClient::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3PacketSocketFactory_methods(root_module, cls):
## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory(ns3::PacketSocketFactory const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketFactory const &', 'arg0')])
## packet-socket-factory.h (module 'network'): ns3::PacketSocketFactory::PacketSocketFactory() [constructor]
cls.add_constructor([])
## packet-socket-factory.h (module 'network'): ns3::Ptr<ns3::Socket> ns3::PacketSocketFactory::CreateSocket() [member function]
cls.add_method('CreateSocket',
'ns3::Ptr< ns3::Socket >',
[],
is_virtual=True)
## packet-socket-factory.h (module 'network'): static ns3::TypeId ns3::PacketSocketFactory::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
return
def register_Ns3PacketSocketServer_methods(root_module, cls):
## packet-socket-server.h (module 'network'): ns3::PacketSocketServer::PacketSocketServer(ns3::PacketSocketServer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketSocketServer const &', 'arg0')])
## packet-socket-server.h (module 'network'): ns3::PacketSocketServer::PacketSocketServer() [constructor]
cls.add_constructor([])
## packet-socket-server.h (module 'network'): static ns3::TypeId ns3::PacketSocketServer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::SetLocal(ns3::PacketSocketAddress addr) [member function]
cls.add_method('SetLocal',
'void',
[param('ns3::PacketSocketAddress', 'addr')])
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## packet-socket-server.h (module 'network'): void ns3::PacketSocketServer::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3ParetoRandomVariable_methods(root_module, cls):
## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor]
cls.add_constructor([])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function]
cls.add_method('GetMean',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function]
cls.add_method('GetShape',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function]
cls.add_method('GetBound',
'double',
[],
is_const=True)
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function]
cls.add_method('GetValue',
'double',
[param('double', 'mean'), param('double', 'shape'), param('double', 'bound')])
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function]
cls.add_method('GetInteger',
'uint32_t',
[param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')])
## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function]
cls.add_method('GetValue',
'double',
[],
is_virtual=True)
## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function]
cls.add_method('GetInteger',
'uint32_t',
[],
is_virtual=True)
return
def register_Ns3PbbAddressBlock_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock(ns3::PbbAddressBlock const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressBlock const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressBlock::PbbAddressBlock() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressBack() const [member function]
cls.add_method('AddressBack',
'ns3::Address',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() [member function]
cls.add_method('AddressBegin',
'std::_List_iterator< ns3::Address >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressBegin() const [member function]
cls.add_method('AddressBegin',
'std::_List_const_iterator< ns3::Address >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressClear() [member function]
cls.add_method('AddressClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::AddressEmpty() const [member function]
cls.add_method('AddressEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() [member function]
cls.add_method('AddressEnd',
'std::_List_iterator< ns3::Address >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Address> ns3::PbbAddressBlock::AddressEnd() const [member function]
cls.add_method('AddressEnd',
'std::_List_const_iterator< ns3::Address >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> position) [member function]
cls.add_method('AddressErase',
'std::_List_iterator< ns3::Address >',
[param('std::_List_iterator< ns3::Address >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressErase(std::_List_iterator<ns3::Address> first, std::_List_iterator<ns3::Address> last) [member function]
cls.add_method('AddressErase',
'std::_List_iterator< ns3::Address >',
[param('std::_List_iterator< ns3::Address >', 'first'), param('std::_List_iterator< ns3::Address >', 'last')])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::AddressFront() const [member function]
cls.add_method('AddressFront',
'ns3::Address',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Address> ns3::PbbAddressBlock::AddressInsert(std::_List_iterator<ns3::Address> position, ns3::Address const value) [member function]
cls.add_method('AddressInsert',
'std::_List_iterator< ns3::Address >',
[param('std::_List_iterator< ns3::Address >', 'position'), param('ns3::Address const', 'value')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopBack() [member function]
cls.add_method('AddressPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPopFront() [member function]
cls.add_method('AddressPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushBack(ns3::Address address) [member function]
cls.add_method('AddressPushBack',
'void',
[param('ns3::Address', 'address')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::AddressPushFront(ns3::Address address) [member function]
cls.add_method('AddressPushFront',
'void',
[param('ns3::Address', 'address')])
## packetbb.h (module 'network'): int ns3::PbbAddressBlock::AddressSize() const [member function]
cls.add_method('AddressSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): uint32_t ns3::PbbAddressBlock::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixBack() const [member function]
cls.add_method('PrefixBack',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() [member function]
cls.add_method('PrefixBegin',
'std::_List_iterator< unsigned char >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixBegin() const [member function]
cls.add_method('PrefixBegin',
'std::_List_const_iterator< unsigned char >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixClear() [member function]
cls.add_method('PrefixClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::PrefixEmpty() const [member function]
cls.add_method('PrefixEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() [member function]
cls.add_method('PrefixEnd',
'std::_List_iterator< unsigned char >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<unsigned char> ns3::PbbAddressBlock::PrefixEnd() const [member function]
cls.add_method('PrefixEnd',
'std::_List_const_iterator< unsigned char >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> position) [member function]
cls.add_method('PrefixErase',
'std::_List_iterator< unsigned char >',
[param('std::_List_iterator< unsigned char >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixErase(std::_List_iterator<unsigned char> first, std::_List_iterator<unsigned char> last) [member function]
cls.add_method('PrefixErase',
'std::_List_iterator< unsigned char >',
[param('std::_List_iterator< unsigned char >', 'first'), param('std::_List_iterator< unsigned char >', 'last')])
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::PrefixFront() const [member function]
cls.add_method('PrefixFront',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<unsigned char> ns3::PbbAddressBlock::PrefixInsert(std::_List_iterator<unsigned char> position, uint8_t const value) [member function]
cls.add_method('PrefixInsert',
'std::_List_iterator< unsigned char >',
[param('std::_List_iterator< unsigned char >', 'position'), param('uint8_t const', 'value')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopBack() [member function]
cls.add_method('PrefixPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPopFront() [member function]
cls.add_method('PrefixPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushBack(uint8_t prefix) [member function]
cls.add_method('PrefixPushBack',
'void',
[param('uint8_t', 'prefix')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrefixPushFront(uint8_t prefix) [member function]
cls.add_method('PrefixPushFront',
'void',
[param('uint8_t', 'prefix')])
## packetbb.h (module 'network'): int ns3::PbbAddressBlock::PrefixSize() const [member function]
cls.add_method('PrefixSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvBack() [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbAddressTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvBack() const [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbAddressTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() [member function]
cls.add_method('TlvBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvBegin() const [member function]
cls.add_method('TlvBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvClear() [member function]
cls.add_method('TlvClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbAddressBlock::TlvEmpty() const [member function]
cls.add_method('TlvEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() [member function]
cls.add_method('TlvEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvEnd() const [member function]
cls.add_method('TlvEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > last) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> ns3::PbbAddressBlock::TlvFront() [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbAddressTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressTlv> const ns3::PbbAddressBlock::TlvFront() const [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbAddressTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > ns3::PbbAddressBlock::TlvInsert(std::_List_iterator<ns3::Ptr<ns3::PbbAddressTlv> > position, ns3::Ptr<ns3::PbbTlv> const value) [member function]
cls.add_method('TlvInsert',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressTlv > >', 'position'), param('ns3::Ptr< ns3::PbbTlv > const', 'value')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopBack() [member function]
cls.add_method('TlvPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPopFront() [member function]
cls.add_method('TlvPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushBack(ns3::Ptr<ns3::PbbAddressTlv> address) [member function]
cls.add_method('TlvPushBack',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')])
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::TlvPushFront(ns3::Ptr<ns3::PbbAddressTlv> address) [member function]
cls.add_method('TlvPushFront',
'void',
[param('ns3::Ptr< ns3::PbbAddressTlv >', 'address')])
## packetbb.h (module 'network'): int ns3::PbbAddressBlock::TlvSize() const [member function]
cls.add_method('TlvSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlock::DeserializeAddress(uint8_t * buffer) const [member function]
cls.add_method('DeserializeAddress',
'ns3::Address',
[param('uint8_t *', 'buffer')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlock::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'uint8_t',
[],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('PrintAddress',
'void',
[param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlock::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('SerializeAddress',
'void',
[param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbAddressBlockIpv4_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4(ns3::PbbAddressBlockIpv4 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressBlockIpv4 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv4::PbbAddressBlockIpv4() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv4::DeserializeAddress(uint8_t * buffer) const [member function]
cls.add_method('DeserializeAddress',
'ns3::Address',
[param('uint8_t *', 'buffer')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv4::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'uint8_t',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('PrintAddress',
'void',
[param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv4::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('SerializeAddress',
'void',
[param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbAddressBlockIpv6_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6(ns3::PbbAddressBlockIpv6 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressBlockIpv6 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbAddressBlockIpv6::PbbAddressBlockIpv6() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Address ns3::PbbAddressBlockIpv6::DeserializeAddress(uint8_t * buffer) const [member function]
cls.add_method('DeserializeAddress',
'ns3::Address',
[param('uint8_t *', 'buffer')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressBlockIpv6::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'uint8_t',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::PrintAddress(std::ostream & os, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('PrintAddress',
'void',
[param('std::ostream &', 'os'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbAddressBlockIpv6::SerializeAddress(uint8_t * buffer, std::_List_const_iterator<ns3::Address> iter) const [member function]
cls.add_method('SerializeAddress',
'void',
[param('uint8_t *', 'buffer'), param('std::_List_const_iterator< ns3::Address >', 'iter')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbMessage_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage(ns3::PbbMessage const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbMessage const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbMessage::PbbMessage() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockBack() [member function]
cls.add_method('AddressBlockBack',
'ns3::Ptr< ns3::PbbAddressBlock >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockBack() const [member function]
cls.add_method('AddressBlockBack',
'ns3::Ptr< ns3::PbbAddressBlock > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() [member function]
cls.add_method('AddressBlockBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockBegin() const [member function]
cls.add_method('AddressBlockBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockClear() [member function]
cls.add_method('AddressBlockClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbMessage::AddressBlockEmpty() const [member function]
cls.add_method('AddressBlockEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() [member function]
cls.add_method('AddressBlockEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockEnd() const [member function]
cls.add_method('AddressBlockEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > position) [member function]
cls.add_method('AddressBlockErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > ns3::PbbMessage::AddressBlockErase(std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > first, std::_List_iterator<ns3::Ptr<ns3::PbbAddressBlock> > last) [member function]
cls.add_method('AddressBlockErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbAddressBlock > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockFront() [member function]
cls.add_method('AddressBlockFront',
'ns3::Ptr< ns3::PbbAddressBlock >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> const ns3::PbbMessage::AddressBlockFront() const [member function]
cls.add_method('AddressBlockFront',
'ns3::Ptr< ns3::PbbAddressBlock > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopBack() [member function]
cls.add_method('AddressBlockPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPopFront() [member function]
cls.add_method('AddressBlockPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushBack(ns3::Ptr<ns3::PbbAddressBlock> block) [member function]
cls.add_method('AddressBlockPushBack',
'void',
[param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')])
## packetbb.h (module 'network'): void ns3::PbbMessage::AddressBlockPushFront(ns3::Ptr<ns3::PbbAddressBlock> block) [member function]
cls.add_method('AddressBlockPushFront',
'void',
[param('ns3::Ptr< ns3::PbbAddressBlock >', 'block')])
## packetbb.h (module 'network'): int ns3::PbbMessage::AddressBlockSize() const [member function]
cls.add_method('AddressBlockSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): static ns3::Ptr<ns3::PbbMessage> ns3::PbbMessage::DeserializeMessage(ns3::Buffer::Iterator & start) [member function]
cls.add_method('DeserializeMessage',
'ns3::Ptr< ns3::PbbMessage >',
[param('ns3::Buffer::Iterator &', 'start')],
is_static=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopCount() const [member function]
cls.add_method('GetHopCount',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetHopLimit() const [member function]
cls.add_method('GetHopLimit',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::GetOriginatorAddress() const [member function]
cls.add_method('GetOriginatorAddress',
'ns3::Address',
[],
is_const=True)
## packetbb.h (module 'network'): uint16_t ns3::PbbMessage::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbMessage::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbMessage::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopCount() const [member function]
cls.add_method('HasHopCount',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasHopLimit() const [member function]
cls.add_method('HasHopLimit',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasOriginatorAddress() const [member function]
cls.add_method('HasOriginatorAddress',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbMessage::HasSequenceNumber() const [member function]
cls.add_method('HasSequenceNumber',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopCount(uint8_t hopcount) [member function]
cls.add_method('SetHopCount',
'void',
[param('uint8_t', 'hopcount')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetHopLimit(uint8_t hoplimit) [member function]
cls.add_method('SetHopLimit',
'void',
[param('uint8_t', 'hoplimit')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetOriginatorAddress(ns3::Address address) [member function]
cls.add_method('SetOriginatorAddress',
'void',
[param('ns3::Address', 'address')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetSequenceNumber(uint16_t seqnum) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'seqnum')])
## packetbb.h (module 'network'): void ns3::PbbMessage::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvBack() [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvBack() const [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() [member function]
cls.add_method('TlvBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvBegin() const [member function]
cls.add_method('TlvBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvClear() [member function]
cls.add_method('TlvClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbMessage::TlvEmpty() const [member function]
cls.add_method('TlvEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() [member function]
cls.add_method('TlvEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvEnd() const [member function]
cls.add_method('TlvEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbMessage::TlvErase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function]
cls.add_method('TlvErase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbMessage::TlvFront() [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbMessage::TlvFront() const [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopBack() [member function]
cls.add_method('TlvPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPopFront() [member function]
cls.add_method('TlvPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushBack',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbMessage::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushFront',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): int ns3::PbbMessage::TlvSize() const [member function]
cls.add_method('TlvSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessage::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('AddressBlockDeserialize',
'ns3::Ptr< ns3::PbbAddressBlock >',
[param('ns3::Buffer::Iterator &', 'start')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessage::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('DeserializeOriginatorAddress',
'ns3::Address',
[param('ns3::Buffer::Iterator &', 'start')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessage::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'ns3::PbbAddressLength',
[],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::PrintOriginatorAddress(std::ostream & os) const [member function]
cls.add_method('PrintOriginatorAddress',
'void',
[param('std::ostream &', 'os')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessage::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('SerializeOriginatorAddress',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_pure_virtual=True, is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbMessageIpv4_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4(ns3::PbbMessageIpv4 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbMessageIpv4 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbMessageIpv4::PbbMessageIpv4() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv4::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('AddressBlockDeserialize',
'ns3::Ptr< ns3::PbbAddressBlock >',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv4::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('DeserializeOriginatorAddress',
'ns3::Address',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv4::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'ns3::PbbAddressLength',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::PrintOriginatorAddress(std::ostream & os) const [member function]
cls.add_method('PrintOriginatorAddress',
'void',
[param('std::ostream &', 'os')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv4::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('SerializeOriginatorAddress',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbMessageIpv6_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6(ns3::PbbMessageIpv6 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbMessageIpv6 const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbMessageIpv6::PbbMessageIpv6() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbAddressBlock> ns3::PbbMessageIpv6::AddressBlockDeserialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('AddressBlockDeserialize',
'ns3::Ptr< ns3::PbbAddressBlock >',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::Address ns3::PbbMessageIpv6::DeserializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('DeserializeOriginatorAddress',
'ns3::Address',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): ns3::PbbAddressLength ns3::PbbMessageIpv6::GetAddressLength() const [member function]
cls.add_method('GetAddressLength',
'ns3::PbbAddressLength',
[],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::PrintOriginatorAddress(std::ostream & os) const [member function]
cls.add_method('PrintOriginatorAddress',
'void',
[param('std::ostream &', 'os')],
is_const=True, visibility='protected', is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbMessageIpv6::SerializeOriginatorAddress(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('SerializeOriginatorAddress',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True, visibility='protected', is_virtual=True)
return
def register_Ns3PbbPacket_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket(ns3::PbbPacket const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbPacket const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbPacket::PbbPacket() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::Deserialize(ns3::Buffer::Iterator start) [member function]
cls.add_method('Deserialize',
'uint32_t',
[param('ns3::Buffer::Iterator', 'start')],
is_virtual=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > first, std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >', 'last')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > position) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'position')])
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::Erase(std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > first, std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > last) [member function]
cls.add_method('Erase',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'first'), param('std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >', 'last')])
## packetbb.h (module 'network'): ns3::TypeId ns3::PbbPacket::GetInstanceTypeId() const [member function]
cls.add_method('GetInstanceTypeId',
'ns3::TypeId',
[],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): uint16_t ns3::PbbPacket::GetSequenceNumber() const [member function]
cls.add_method('GetSequenceNumber',
'uint16_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint32_t ns3::PbbPacket::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): static ns3::TypeId ns3::PbbPacket::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbPacket::GetVersion() const [member function]
cls.add_method('GetVersion',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbPacket::HasSequenceNumber() const [member function]
cls.add_method('HasSequenceNumber',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageBack() [member function]
cls.add_method('MessageBack',
'ns3::Ptr< ns3::PbbMessage >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageBack() const [member function]
cls.add_method('MessageBack',
'ns3::Ptr< ns3::PbbMessage > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() [member function]
cls.add_method('MessageBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageBegin() const [member function]
cls.add_method('MessageBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::MessageClear() [member function]
cls.add_method('MessageClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbPacket::MessageEmpty() const [member function]
cls.add_method('MessageEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() [member function]
cls.add_method('MessageEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbMessage > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbMessage> > ns3::PbbPacket::MessageEnd() const [member function]
cls.add_method('MessageEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbMessage > >',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> ns3::PbbPacket::MessageFront() [member function]
cls.add_method('MessageFront',
'ns3::Ptr< ns3::PbbMessage >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbMessage> const ns3::PbbPacket::MessageFront() const [member function]
cls.add_method('MessageFront',
'ns3::Ptr< ns3::PbbMessage > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopBack() [member function]
cls.add_method('MessagePopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePopFront() [member function]
cls.add_method('MessagePopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushBack(ns3::Ptr<ns3::PbbMessage> message) [member function]
cls.add_method('MessagePushBack',
'void',
[param('ns3::Ptr< ns3::PbbMessage >', 'message')])
## packetbb.h (module 'network'): void ns3::PbbPacket::MessagePushFront(ns3::Ptr<ns3::PbbMessage> message) [member function]
cls.add_method('MessagePushFront',
'void',
[param('ns3::Ptr< ns3::PbbMessage >', 'message')])
## packetbb.h (module 'network'): int ns3::PbbPacket::MessageSize() const [member function]
cls.add_method('MessageSize',
'int',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::Serialize(ns3::Buffer::Iterator start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator', 'start')],
is_const=True, is_virtual=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::SetSequenceNumber(uint16_t number) [member function]
cls.add_method('SetSequenceNumber',
'void',
[param('uint16_t', 'number')])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvBack() [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvBack() const [member function]
cls.add_method('TlvBack',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() [member function]
cls.add_method('TlvBegin',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvBegin() const [member function]
cls.add_method('TlvBegin',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvClear() [member function]
cls.add_method('TlvClear',
'void',
[])
## packetbb.h (module 'network'): bool ns3::PbbPacket::TlvEmpty() const [member function]
cls.add_method('TlvEmpty',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): std::_List_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() [member function]
cls.add_method('TlvEnd',
'std::_List_iterator< ns3::Ptr< ns3::PbbTlv > >',
[])
## packetbb.h (module 'network'): std::_List_const_iterator<ns3::Ptr<ns3::PbbTlv> > ns3::PbbPacket::TlvEnd() const [member function]
cls.add_method('TlvEnd',
'std::_List_const_iterator< ns3::Ptr< ns3::PbbTlv > >',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> ns3::PbbPacket::TlvFront() [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv >',
[])
## packetbb.h (module 'network'): ns3::Ptr<ns3::PbbTlv> const ns3::PbbPacket::TlvFront() const [member function]
cls.add_method('TlvFront',
'ns3::Ptr< ns3::PbbTlv > const',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopBack() [member function]
cls.add_method('TlvPopBack',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPopFront() [member function]
cls.add_method('TlvPopFront',
'void',
[])
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushBack(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushBack',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): void ns3::PbbPacket::TlvPushFront(ns3::Ptr<ns3::PbbTlv> tlv) [member function]
cls.add_method('TlvPushFront',
'void',
[param('ns3::Ptr< ns3::PbbTlv >', 'tlv')])
## packetbb.h (module 'network'): int ns3::PbbPacket::TlvSize() const [member function]
cls.add_method('TlvSize',
'int',
[],
is_const=True)
return
def register_Ns3PbbTlv_methods(root_module, cls):
cls.add_binary_comparison_operator('==')
cls.add_binary_comparison_operator('!=')
## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv(ns3::PbbTlv const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbTlv const &', 'arg0')])
## packetbb.h (module 'network'): ns3::PbbTlv::PbbTlv() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): void ns3::PbbTlv::Deserialize(ns3::Buffer::Iterator & start) [member function]
cls.add_method('Deserialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')])
## packetbb.h (module 'network'): uint32_t ns3::PbbTlv::GetSerializedSize() const [member function]
cls.add_method('GetSerializedSize',
'uint32_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetType() const [member function]
cls.add_method('GetType',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetTypeExt() const [member function]
cls.add_method('GetTypeExt',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): ns3::Buffer ns3::PbbTlv::GetValue() const [member function]
cls.add_method('GetValue',
'ns3::Buffer',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasTypeExt() const [member function]
cls.add_method('HasTypeExt',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasValue() const [member function]
cls.add_method('HasValue',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::Print(std::ostream & os, int level) const [member function]
cls.add_method('Print',
'void',
[param('std::ostream &', 'os'), param('int', 'level')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::Serialize(ns3::Buffer::Iterator & start) const [member function]
cls.add_method('Serialize',
'void',
[param('ns3::Buffer::Iterator &', 'start')],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbTlv::SetType(uint8_t type) [member function]
cls.add_method('SetType',
'void',
[param('uint8_t', 'type')])
## packetbb.h (module 'network'): void ns3::PbbTlv::SetTypeExt(uint8_t type) [member function]
cls.add_method('SetTypeExt',
'void',
[param('uint8_t', 'type')])
## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(ns3::Buffer start) [member function]
cls.add_method('SetValue',
'void',
[param('ns3::Buffer', 'start')])
## packetbb.h (module 'network'): void ns3::PbbTlv::SetValue(uint8_t const * buffer, uint32_t size) [member function]
cls.add_method('SetValue',
'void',
[param('uint8_t const *', 'buffer'), param('uint32_t', 'size')])
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStart() const [member function]
cls.add_method('GetIndexStart',
'uint8_t',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): uint8_t ns3::PbbTlv::GetIndexStop() const [member function]
cls.add_method('GetIndexStop',
'uint8_t',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStart() const [member function]
cls.add_method('HasIndexStart',
'bool',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): bool ns3::PbbTlv::HasIndexStop() const [member function]
cls.add_method('HasIndexStop',
'bool',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): bool ns3::PbbTlv::IsMultivalue() const [member function]
cls.add_method('IsMultivalue',
'bool',
[],
is_const=True, visibility='protected')
## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStart(uint8_t index) [member function]
cls.add_method('SetIndexStart',
'void',
[param('uint8_t', 'index')],
visibility='protected')
## packetbb.h (module 'network'): void ns3::PbbTlv::SetIndexStop(uint8_t index) [member function]
cls.add_method('SetIndexStop',
'void',
[param('uint8_t', 'index')],
visibility='protected')
## packetbb.h (module 'network'): void ns3::PbbTlv::SetMultivalue(bool isMultivalue) [member function]
cls.add_method('SetMultivalue',
'void',
[param('bool', 'isMultivalue')],
visibility='protected')
return
def register_Ns3Ping6_methods(root_module, cls):
## ping6.h (module 'applications'): ns3::Ping6::Ping6(ns3::Ping6 const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Ping6 const &', 'arg0')])
## ping6.h (module 'applications'): ns3::Ping6::Ping6() [constructor]
cls.add_constructor([])
## ping6.h (module 'applications'): static ns3::TypeId ns3::Ping6::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## ping6.h (module 'applications'): void ns3::Ping6::SetIfIndex(uint32_t ifIndex) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t', 'ifIndex')])
## ping6.h (module 'applications'): void ns3::Ping6::SetLocal(ns3::Ipv6Address ipv6) [member function]
cls.add_method('SetLocal',
'void',
[param('ns3::Ipv6Address', 'ipv6')])
## ping6.h (module 'applications'): void ns3::Ping6::SetRemote(ns3::Ipv6Address ipv6) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Ipv6Address', 'ipv6')])
## ping6.h (module 'applications'): void ns3::Ping6::SetRouters(std::vector<ns3::Ipv6Address, std::allocator<ns3::Ipv6Address> > routers) [member function]
cls.add_method('SetRouters',
'void',
[param('std::vector< ns3::Ipv6Address >', 'routers')])
## ping6.h (module 'applications'): void ns3::Ping6::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## ping6.h (module 'applications'): void ns3::Ping6::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## ping6.h (module 'applications'): void ns3::Ping6::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3Probe_methods(root_module, cls):
## probe.h (module 'stats'): ns3::Probe::Probe(ns3::Probe const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Probe const &', 'arg0')])
## probe.h (module 'stats'): ns3::Probe::Probe() [constructor]
cls.add_constructor([])
## probe.h (module 'stats'): bool ns3::Probe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function]
cls.add_method('ConnectByObject',
'bool',
[param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')],
is_pure_virtual=True, is_virtual=True)
## probe.h (module 'stats'): void ns3::Probe::ConnectByPath(std::string path) [member function]
cls.add_method('ConnectByPath',
'void',
[param('std::string', 'path')],
is_pure_virtual=True, is_virtual=True)
## probe.h (module 'stats'): static ns3::TypeId ns3::Probe::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## probe.h (module 'stats'): bool ns3::Probe::IsEnabled() const [member function]
cls.add_method('IsEnabled',
'bool',
[],
is_const=True, is_virtual=True)
return
def register_Ns3Radvd_methods(root_module, cls):
## radvd.h (module 'applications'): ns3::Radvd::Radvd(ns3::Radvd const & arg0) [copy constructor]
cls.add_constructor([param('ns3::Radvd const &', 'arg0')])
## radvd.h (module 'applications'): ns3::Radvd::Radvd() [constructor]
cls.add_constructor([])
## radvd.h (module 'applications'): void ns3::Radvd::AddConfiguration(ns3::Ptr<ns3::RadvdInterface> routerInterface) [member function]
cls.add_method('AddConfiguration',
'void',
[param('ns3::Ptr< ns3::RadvdInterface >', 'routerInterface')])
## radvd.h (module 'applications'): int64_t ns3::Radvd::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## radvd.h (module 'applications'): static ns3::TypeId ns3::Radvd::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## radvd.h (module 'applications'): ns3::Radvd::MAX_INITIAL_RTR_ADVERTISEMENTS [variable]
cls.add_static_attribute('MAX_INITIAL_RTR_ADVERTISEMENTS', 'uint32_t const', is_const=True)
## radvd.h (module 'applications'): ns3::Radvd::MAX_INITIAL_RTR_ADVERT_INTERVAL [variable]
cls.add_static_attribute('MAX_INITIAL_RTR_ADVERT_INTERVAL', 'uint32_t const', is_const=True)
## radvd.h (module 'applications'): ns3::Radvd::MAX_RA_DELAY_TIME [variable]
cls.add_static_attribute('MAX_RA_DELAY_TIME', 'uint32_t const', is_const=True)
## radvd.h (module 'applications'): ns3::Radvd::MIN_DELAY_BETWEEN_RAS [variable]
cls.add_static_attribute('MIN_DELAY_BETWEEN_RAS', 'uint32_t const', is_const=True)
## radvd.h (module 'applications'): void ns3::Radvd::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## radvd.h (module 'applications'): void ns3::Radvd::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## radvd.h (module 'applications'): void ns3::Radvd::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3RadvdInterface_methods(root_module, cls):
## radvd-interface.h (module 'applications'): ns3::RadvdInterface::RadvdInterface(ns3::RadvdInterface const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RadvdInterface const &', 'arg0')])
## radvd-interface.h (module 'applications'): ns3::RadvdInterface::RadvdInterface(uint32_t interface) [constructor]
cls.add_constructor([param('uint32_t', 'interface')])
## radvd-interface.h (module 'applications'): ns3::RadvdInterface::RadvdInterface(uint32_t interface, uint32_t maxRtrAdvInterval, uint32_t minRtrAdvInterval) [constructor]
cls.add_constructor([param('uint32_t', 'interface'), param('uint32_t', 'maxRtrAdvInterval'), param('uint32_t', 'minRtrAdvInterval')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::AddPrefix(ns3::Ptr<ns3::RadvdPrefix> routerPrefix) [member function]
cls.add_method('AddPrefix',
'void',
[param('ns3::Ptr< ns3::RadvdPrefix >', 'routerPrefix')])
## radvd-interface.h (module 'applications'): uint8_t ns3::RadvdInterface::GetCurHopLimit() const [member function]
cls.add_method('GetCurHopLimit',
'uint8_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetDefaultLifeTime() const [member function]
cls.add_method('GetDefaultLifeTime',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint8_t ns3::RadvdInterface::GetDefaultPreference() const [member function]
cls.add_method('GetDefaultPreference',
'uint8_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetHomeAgentLifeTime() const [member function]
cls.add_method('GetHomeAgentLifeTime',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetHomeAgentPreference() const [member function]
cls.add_method('GetHomeAgentPreference',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetInterface() const [member function]
cls.add_method('GetInterface',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): ns3::Time ns3::RadvdInterface::GetLastRaTxTime() [member function]
cls.add_method('GetLastRaTxTime',
'ns3::Time',
[])
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetLinkMtu() const [member function]
cls.add_method('GetLinkMtu',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetMaxRtrAdvInterval() const [member function]
cls.add_method('GetMaxRtrAdvInterval',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetMinDelayBetweenRAs() const [member function]
cls.add_method('GetMinDelayBetweenRAs',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetMinRtrAdvInterval() const [member function]
cls.add_method('GetMinRtrAdvInterval',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): std::list<ns3::Ptr<ns3::RadvdPrefix>, std::allocator<ns3::Ptr<ns3::RadvdPrefix> > > ns3::RadvdInterface::GetPrefixes() const [member function]
cls.add_method('GetPrefixes',
'std::list< ns3::Ptr< ns3::RadvdPrefix > >',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetReachableTime() const [member function]
cls.add_method('GetReachableTime',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): uint32_t ns3::RadvdInterface::GetRetransTimer() const [member function]
cls.add_method('GetRetransTimer',
'uint32_t',
[],
is_const=True)
## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsHomeAgentFlag() const [member function]
cls.add_method('IsHomeAgentFlag',
'bool',
[],
is_const=True)
## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsHomeAgentInfo() const [member function]
cls.add_method('IsHomeAgentInfo',
'bool',
[],
is_const=True)
## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsInitialRtrAdv() [member function]
cls.add_method('IsInitialRtrAdv',
'bool',
[])
## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsIntervalOpt() const [member function]
cls.add_method('IsIntervalOpt',
'bool',
[],
is_const=True)
## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsManagedFlag() const [member function]
cls.add_method('IsManagedFlag',
'bool',
[],
is_const=True)
## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsMobRtrSupportFlag() const [member function]
cls.add_method('IsMobRtrSupportFlag',
'bool',
[],
is_const=True)
## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsOtherConfigFlag() const [member function]
cls.add_method('IsOtherConfigFlag',
'bool',
[],
is_const=True)
## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsSendAdvert() const [member function]
cls.add_method('IsSendAdvert',
'bool',
[],
is_const=True)
## radvd-interface.h (module 'applications'): bool ns3::RadvdInterface::IsSourceLLAddress() const [member function]
cls.add_method('IsSourceLLAddress',
'bool',
[],
is_const=True)
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetCurHopLimit(uint8_t curHopLimit) [member function]
cls.add_method('SetCurHopLimit',
'void',
[param('uint8_t', 'curHopLimit')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetDefaultLifeTime(uint32_t defaultLifeTime) [member function]
cls.add_method('SetDefaultLifeTime',
'void',
[param('uint32_t', 'defaultLifeTime')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetDefaultPreference(uint8_t defaultPreference) [member function]
cls.add_method('SetDefaultPreference',
'void',
[param('uint8_t', 'defaultPreference')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetHomeAgentFlag(bool homeAgentFlag) [member function]
cls.add_method('SetHomeAgentFlag',
'void',
[param('bool', 'homeAgentFlag')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetHomeAgentInfo(bool homeAgentFlag) [member function]
cls.add_method('SetHomeAgentInfo',
'void',
[param('bool', 'homeAgentFlag')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetHomeAgentLifeTime(uint32_t homeAgentLifeTime) [member function]
cls.add_method('SetHomeAgentLifeTime',
'void',
[param('uint32_t', 'homeAgentLifeTime')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetHomeAgentPreference(uint32_t homeAgentPreference) [member function]
cls.add_method('SetHomeAgentPreference',
'void',
[param('uint32_t', 'homeAgentPreference')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetIntervalOpt(bool intervalOpt) [member function]
cls.add_method('SetIntervalOpt',
'void',
[param('bool', 'intervalOpt')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetLastRaTxTime(ns3::Time now) [member function]
cls.add_method('SetLastRaTxTime',
'void',
[param('ns3::Time', 'now')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetLinkMtu(uint32_t linkMtu) [member function]
cls.add_method('SetLinkMtu',
'void',
[param('uint32_t', 'linkMtu')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetManagedFlag(bool managedFlag) [member function]
cls.add_method('SetManagedFlag',
'void',
[param('bool', 'managedFlag')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetMaxRtrAdvInterval(uint32_t maxRtrAdvInterval) [member function]
cls.add_method('SetMaxRtrAdvInterval',
'void',
[param('uint32_t', 'maxRtrAdvInterval')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetMinDelayBetweenRAs(uint32_t minDelayBetweenRAs) [member function]
cls.add_method('SetMinDelayBetweenRAs',
'void',
[param('uint32_t', 'minDelayBetweenRAs')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetMinRtrAdvInterval(uint32_t minRtrAdvInterval) [member function]
cls.add_method('SetMinRtrAdvInterval',
'void',
[param('uint32_t', 'minRtrAdvInterval')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetMobRtrSupportFlag(bool mobRtrSupportFlag) [member function]
cls.add_method('SetMobRtrSupportFlag',
'void',
[param('bool', 'mobRtrSupportFlag')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetOtherConfigFlag(bool otherConfigFlag) [member function]
cls.add_method('SetOtherConfigFlag',
'void',
[param('bool', 'otherConfigFlag')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetReachableTime(uint32_t reachableTime) [member function]
cls.add_method('SetReachableTime',
'void',
[param('uint32_t', 'reachableTime')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetRetransTimer(uint32_t retransTimer) [member function]
cls.add_method('SetRetransTimer',
'void',
[param('uint32_t', 'retransTimer')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetSendAdvert(bool sendAdvert) [member function]
cls.add_method('SetSendAdvert',
'void',
[param('bool', 'sendAdvert')])
## radvd-interface.h (module 'applications'): void ns3::RadvdInterface::SetSourceLLAddress(bool sourceLLAddress) [member function]
cls.add_method('SetSourceLLAddress',
'void',
[param('bool', 'sourceLLAddress')])
return
def register_Ns3RadvdPrefix_methods(root_module, cls):
## radvd-prefix.h (module 'applications'): ns3::RadvdPrefix::RadvdPrefix(ns3::RadvdPrefix const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RadvdPrefix const &', 'arg0')])
## radvd-prefix.h (module 'applications'): ns3::RadvdPrefix::RadvdPrefix(ns3::Ipv6Address network, uint8_t prefixLength, uint32_t preferredLifeTime=604800, uint32_t validLifeTime=2592000, bool onLinkFlag=true, bool autonomousFlag=true, bool routerAddrFlag=false) [constructor]
cls.add_constructor([param('ns3::Ipv6Address', 'network'), param('uint8_t', 'prefixLength'), param('uint32_t', 'preferredLifeTime', default_value='604800'), param('uint32_t', 'validLifeTime', default_value='2592000'), param('bool', 'onLinkFlag', default_value='true'), param('bool', 'autonomousFlag', default_value='true'), param('bool', 'routerAddrFlag', default_value='false')])
## radvd-prefix.h (module 'applications'): ns3::Ipv6Address ns3::RadvdPrefix::GetNetwork() const [member function]
cls.add_method('GetNetwork',
'ns3::Ipv6Address',
[],
is_const=True)
## radvd-prefix.h (module 'applications'): uint32_t ns3::RadvdPrefix::GetPreferredLifeTime() const [member function]
cls.add_method('GetPreferredLifeTime',
'uint32_t',
[],
is_const=True)
## radvd-prefix.h (module 'applications'): uint8_t ns3::RadvdPrefix::GetPrefixLength() const [member function]
cls.add_method('GetPrefixLength',
'uint8_t',
[],
is_const=True)
## radvd-prefix.h (module 'applications'): uint32_t ns3::RadvdPrefix::GetValidLifeTime() const [member function]
cls.add_method('GetValidLifeTime',
'uint32_t',
[],
is_const=True)
## radvd-prefix.h (module 'applications'): bool ns3::RadvdPrefix::IsAutonomousFlag() const [member function]
cls.add_method('IsAutonomousFlag',
'bool',
[],
is_const=True)
## radvd-prefix.h (module 'applications'): bool ns3::RadvdPrefix::IsOnLinkFlag() const [member function]
cls.add_method('IsOnLinkFlag',
'bool',
[],
is_const=True)
## radvd-prefix.h (module 'applications'): bool ns3::RadvdPrefix::IsRouterAddrFlag() const [member function]
cls.add_method('IsRouterAddrFlag',
'bool',
[],
is_const=True)
## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetAutonomousFlag(bool autonomousFlag) [member function]
cls.add_method('SetAutonomousFlag',
'void',
[param('bool', 'autonomousFlag')])
## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetNetwork(ns3::Ipv6Address network) [member function]
cls.add_method('SetNetwork',
'void',
[param('ns3::Ipv6Address', 'network')])
## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetOnLinkFlag(bool onLinkFlag) [member function]
cls.add_method('SetOnLinkFlag',
'void',
[param('bool', 'onLinkFlag')])
## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetPreferredLifeTime(uint32_t preferredLifeTime) [member function]
cls.add_method('SetPreferredLifeTime',
'void',
[param('uint32_t', 'preferredLifeTime')])
## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetPrefixLength(uint8_t prefixLength) [member function]
cls.add_method('SetPrefixLength',
'void',
[param('uint8_t', 'prefixLength')])
## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetRouterAddrFlag(bool routerAddrFlag) [member function]
cls.add_method('SetRouterAddrFlag',
'void',
[param('bool', 'routerAddrFlag')])
## radvd-prefix.h (module 'applications'): void ns3::RadvdPrefix::SetValidLifeTime(uint32_t validLifeTime) [member function]
cls.add_method('SetValidLifeTime',
'void',
[param('uint32_t', 'validLifeTime')])
return
def register_Ns3RateErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel(ns3::RateErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::RateErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::RateErrorModel::RateErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): int64_t ns3::RateErrorModel::AssignStreams(int64_t stream) [member function]
cls.add_method('AssignStreams',
'int64_t',
[param('int64_t', 'stream')])
## error-model.h (module 'network'): double ns3::RateErrorModel::GetRate() const [member function]
cls.add_method('GetRate',
'double',
[],
is_const=True)
## error-model.h (module 'network'): static ns3::TypeId ns3::RateErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): ns3::RateErrorModel::ErrorUnit ns3::RateErrorModel::GetUnit() const [member function]
cls.add_method('GetUnit',
'ns3::RateErrorModel::ErrorUnit',
[],
is_const=True)
## error-model.h (module 'network'): void ns3::RateErrorModel::SetRandomVariable(ns3::Ptr<ns3::RandomVariableStream> arg0) [member function]
cls.add_method('SetRandomVariable',
'void',
[param('ns3::Ptr< ns3::RandomVariableStream >', 'arg0')])
## error-model.h (module 'network'): void ns3::RateErrorModel::SetRate(double rate) [member function]
cls.add_method('SetRate',
'void',
[param('double', 'rate')])
## error-model.h (module 'network'): void ns3::RateErrorModel::SetUnit(ns3::RateErrorModel::ErrorUnit error_unit) [member function]
cls.add_method('SetUnit',
'void',
[param('ns3::RateErrorModel::ErrorUnit', 'error_unit')])
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptBit(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorruptBit',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptByte(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorruptByte',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): bool ns3::RateErrorModel::DoCorruptPkt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorruptPkt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::RateErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3ReceiveListErrorModel_methods(root_module, cls):
## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel(ns3::ReceiveListErrorModel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ReceiveListErrorModel const &', 'arg0')])
## error-model.h (module 'network'): ns3::ReceiveListErrorModel::ReceiveListErrorModel() [constructor]
cls.add_constructor([])
## error-model.h (module 'network'): std::list<unsigned int, std::allocator<unsigned int> > ns3::ReceiveListErrorModel::GetList() const [member function]
cls.add_method('GetList',
'std::list< unsigned int >',
[],
is_const=True)
## error-model.h (module 'network'): static ns3::TypeId ns3::ReceiveListErrorModel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::SetList(std::list<unsigned int, std::allocator<unsigned int> > const & packetlist) [member function]
cls.add_method('SetList',
'void',
[param('std::list< unsigned int > const &', 'packetlist')])
## error-model.h (module 'network'): bool ns3::ReceiveListErrorModel::DoCorrupt(ns3::Ptr<ns3::Packet> p) [member function]
cls.add_method('DoCorrupt',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'p')],
visibility='private', is_virtual=True)
## error-model.h (module 'network'): void ns3::ReceiveListErrorModel::DoReset() [member function]
cls.add_method('DoReset',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3SimpleChannel_methods(root_module, cls):
## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel(ns3::SimpleChannel const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimpleChannel const &', 'arg0')])
## simple-channel.h (module 'network'): ns3::SimpleChannel::SimpleChannel() [constructor]
cls.add_constructor([])
## simple-channel.h (module 'network'): void ns3::SimpleChannel::Add(ns3::Ptr<ns3::SimpleNetDevice> device) [member function]
cls.add_method('Add',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'device')],
is_virtual=True)
## simple-channel.h (module 'network'): void ns3::SimpleChannel::BlackList(ns3::Ptr<ns3::SimpleNetDevice> from, ns3::Ptr<ns3::SimpleNetDevice> to) [member function]
cls.add_method('BlackList',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'to')],
is_virtual=True)
## simple-channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::SimpleChannel::GetDevice(uint32_t i) const [member function]
cls.add_method('GetDevice',
'ns3::Ptr< ns3::NetDevice >',
[param('uint32_t', 'i')],
is_const=True, is_virtual=True)
## simple-channel.h (module 'network'): uint32_t ns3::SimpleChannel::GetNDevices() const [member function]
cls.add_method('GetNDevices',
'uint32_t',
[],
is_const=True, is_virtual=True)
## simple-channel.h (module 'network'): static ns3::TypeId ns3::SimpleChannel::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## simple-channel.h (module 'network'): void ns3::SimpleChannel::Send(ns3::Ptr<ns3::Packet> p, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from, ns3::Ptr<ns3::SimpleNetDevice> sender) [member function]
cls.add_method('Send',
'void',
[param('ns3::Ptr< ns3::Packet >', 'p'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'sender')],
is_virtual=True)
## simple-channel.h (module 'network'): void ns3::SimpleChannel::UnBlackList(ns3::Ptr<ns3::SimpleNetDevice> from, ns3::Ptr<ns3::SimpleNetDevice> to) [member function]
cls.add_method('UnBlackList',
'void',
[param('ns3::Ptr< ns3::SimpleNetDevice >', 'from'), param('ns3::Ptr< ns3::SimpleNetDevice >', 'to')],
is_virtual=True)
return
def register_Ns3SimpleNetDevice_methods(root_module, cls):
## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice(ns3::SimpleNetDevice const & arg0) [copy constructor]
cls.add_constructor([param('ns3::SimpleNetDevice const &', 'arg0')])
## simple-net-device.h (module 'network'): ns3::SimpleNetDevice::SimpleNetDevice() [constructor]
cls.add_constructor([])
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function]
cls.add_method('AddLinkChangeCallback',
'void',
[param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')],
is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetAddress() const [member function]
cls.add_method('GetAddress',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetBroadcast() const [member function]
cls.add_method('GetBroadcast',
'ns3::Address',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::SimpleNetDevice::GetChannel() const [member function]
cls.add_method('GetChannel',
'ns3::Ptr< ns3::Channel >',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): uint32_t ns3::SimpleNetDevice::GetIfIndex() const [member function]
cls.add_method('GetIfIndex',
'uint32_t',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): uint16_t ns3::SimpleNetDevice::GetMtu() const [member function]
cls.add_method('GetMtu',
'uint16_t',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv4Address', 'multicastGroup')],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Address ns3::SimpleNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function]
cls.add_method('GetMulticast',
'ns3::Address',
[param('ns3::Ipv6Address', 'addr')],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::SimpleNetDevice::GetNode() const [member function]
cls.add_method('GetNode',
'ns3::Ptr< ns3::Node >',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): ns3::Ptr<ns3::Queue> ns3::SimpleNetDevice::GetQueue() const [member function]
cls.add_method('GetQueue',
'ns3::Ptr< ns3::Queue >',
[],
is_const=True)
## simple-net-device.h (module 'network'): static ns3::TypeId ns3::SimpleNetDevice::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBridge() const [member function]
cls.add_method('IsBridge',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsBroadcast() const [member function]
cls.add_method('IsBroadcast',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsLinkUp() const [member function]
cls.add_method('IsLinkUp',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsMulticast() const [member function]
cls.add_method('IsMulticast',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::IsPointToPoint() const [member function]
cls.add_method('IsPointToPoint',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::NeedsArp() const [member function]
cls.add_method('NeedsArp',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::Receive(ns3::Ptr<ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address to, ns3::Mac48Address from) [member function]
cls.add_method('Receive',
'void',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'to'), param('ns3::Mac48Address', 'from')])
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('Send',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function]
cls.add_method('SendFrom',
'bool',
[param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetAddress(ns3::Address address) [member function]
cls.add_method('SetAddress',
'void',
[param('ns3::Address', 'address')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetChannel(ns3::Ptr<ns3::SimpleChannel> channel) [member function]
cls.add_method('SetChannel',
'void',
[param('ns3::Ptr< ns3::SimpleChannel >', 'channel')])
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetIfIndex(uint32_t const index) [member function]
cls.add_method('SetIfIndex',
'void',
[param('uint32_t const', 'index')],
is_virtual=True)
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SetMtu(uint16_t const mtu) [member function]
cls.add_method('SetMtu',
'bool',
[param('uint16_t const', 'mtu')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function]
cls.add_method('SetNode',
'void',
[param('ns3::Ptr< ns3::Node >', 'node')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetPromiscReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetQueue(ns3::Ptr<ns3::Queue> queue) [member function]
cls.add_method('SetQueue',
'void',
[param('ns3::Ptr< ns3::Queue >', 'queue')])
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function]
cls.add_method('SetReceiveCallback',
'void',
[param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')],
is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::SetReceiveErrorModel(ns3::Ptr<ns3::ErrorModel> em) [member function]
cls.add_method('SetReceiveErrorModel',
'void',
[param('ns3::Ptr< ns3::ErrorModel >', 'em')])
## simple-net-device.h (module 'network'): bool ns3::SimpleNetDevice::SupportsSendFrom() const [member function]
cls.add_method('SupportsSendFrom',
'bool',
[],
is_const=True, is_virtual=True)
## simple-net-device.h (module 'network'): void ns3::SimpleNetDevice::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3TimeValue_methods(root_module, cls):
## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor]
cls.add_constructor([])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TimeValue const &', 'arg0')])
## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor]
cls.add_constructor([param('ns3::Time const &', 'value')])
## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function]
cls.add_method('Get',
'ns3::Time',
[],
is_const=True)
## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Time const &', 'value')])
return
def register_Ns3TypeIdChecker_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')])
return
def register_Ns3TypeIdValue_methods(root_module, cls):
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor]
cls.add_constructor([])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor]
cls.add_constructor([param('ns3::TypeId const &', 'value')])
## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function]
cls.add_method('Get',
'ns3::TypeId',
[],
is_const=True)
## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::TypeId const &', 'value')])
return
def register_Ns3UdpClient_methods(root_module, cls):
## udp-client.h (module 'applications'): ns3::UdpClient::UdpClient(ns3::UdpClient const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpClient const &', 'arg0')])
## udp-client.h (module 'applications'): ns3::UdpClient::UdpClient() [constructor]
cls.add_constructor([])
## udp-client.h (module 'applications'): static ns3::TypeId ns3::UdpClient::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-client.h (module 'applications'): void ns3::UdpClient::SetRemote(ns3::Ipv4Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')])
## udp-client.h (module 'applications'): void ns3::UdpClient::SetRemote(ns3::Ipv6Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')])
## udp-client.h (module 'applications'): void ns3::UdpClient::SetRemote(ns3::Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-client.h (module 'applications'): void ns3::UdpClient::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-client.h (module 'applications'): void ns3::UdpClient::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-client.h (module 'applications'): void ns3::UdpClient::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UdpEchoClient_methods(root_module, cls):
## udp-echo-client.h (module 'applications'): ns3::UdpEchoClient::UdpEchoClient(ns3::UdpEchoClient const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpEchoClient const &', 'arg0')])
## udp-echo-client.h (module 'applications'): ns3::UdpEchoClient::UdpEchoClient() [constructor]
cls.add_constructor([])
## udp-echo-client.h (module 'applications'): uint32_t ns3::UdpEchoClient::GetDataSize() const [member function]
cls.add_method('GetDataSize',
'uint32_t',
[],
is_const=True)
## udp-echo-client.h (module 'applications'): static ns3::TypeId ns3::UdpEchoClient::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetDataSize(uint32_t dataSize) [member function]
cls.add_method('SetDataSize',
'void',
[param('uint32_t', 'dataSize')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetFill(std::string fill) [member function]
cls.add_method('SetFill',
'void',
[param('std::string', 'fill')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetFill(uint8_t fill, uint32_t dataSize) [member function]
cls.add_method('SetFill',
'void',
[param('uint8_t', 'fill'), param('uint32_t', 'dataSize')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetFill(uint8_t * fill, uint32_t fillSize, uint32_t dataSize) [member function]
cls.add_method('SetFill',
'void',
[param('uint8_t *', 'fill'), param('uint32_t', 'fillSize'), param('uint32_t', 'dataSize')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetRemote(ns3::Ipv4Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetRemote(ns3::Ipv6Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::SetRemote(ns3::Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-echo-client.h (module 'applications'): void ns3::UdpEchoClient::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UdpEchoServer_methods(root_module, cls):
## udp-echo-server.h (module 'applications'): ns3::UdpEchoServer::UdpEchoServer(ns3::UdpEchoServer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpEchoServer const &', 'arg0')])
## udp-echo-server.h (module 'applications'): ns3::UdpEchoServer::UdpEchoServer() [constructor]
cls.add_constructor([])
## udp-echo-server.h (module 'applications'): static ns3::TypeId ns3::UdpEchoServer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-echo-server.h (module 'applications'): void ns3::UdpEchoServer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-echo-server.h (module 'applications'): void ns3::UdpEchoServer::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-echo-server.h (module 'applications'): void ns3::UdpEchoServer::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UdpServer_methods(root_module, cls):
## udp-server.h (module 'applications'): ns3::UdpServer::UdpServer(ns3::UdpServer const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpServer const &', 'arg0')])
## udp-server.h (module 'applications'): ns3::UdpServer::UdpServer() [constructor]
cls.add_constructor([])
## udp-server.h (module 'applications'): uint32_t ns3::UdpServer::GetLost() const [member function]
cls.add_method('GetLost',
'uint32_t',
[],
is_const=True)
## udp-server.h (module 'applications'): uint16_t ns3::UdpServer::GetPacketWindowSize() const [member function]
cls.add_method('GetPacketWindowSize',
'uint16_t',
[],
is_const=True)
## udp-server.h (module 'applications'): uint32_t ns3::UdpServer::GetReceived() const [member function]
cls.add_method('GetReceived',
'uint32_t',
[],
is_const=True)
## udp-server.h (module 'applications'): static ns3::TypeId ns3::UdpServer::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-server.h (module 'applications'): void ns3::UdpServer::SetPacketWindowSize(uint16_t size) [member function]
cls.add_method('SetPacketWindowSize',
'void',
[param('uint16_t', 'size')])
## udp-server.h (module 'applications'): void ns3::UdpServer::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-server.h (module 'applications'): void ns3::UdpServer::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-server.h (module 'applications'): void ns3::UdpServer::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UdpTraceClient_methods(root_module, cls):
## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient::UdpTraceClient(ns3::UdpTraceClient const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UdpTraceClient const &', 'arg0')])
## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient::UdpTraceClient() [constructor]
cls.add_constructor([])
## udp-trace-client.h (module 'applications'): ns3::UdpTraceClient::UdpTraceClient(ns3::Ipv4Address ip, uint16_t port, char * traceFile) [constructor]
cls.add_constructor([param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port'), param('char *', 'traceFile')])
## udp-trace-client.h (module 'applications'): uint16_t ns3::UdpTraceClient::GetMaxPacketSize() [member function]
cls.add_method('GetMaxPacketSize',
'uint16_t',
[])
## udp-trace-client.h (module 'applications'): static ns3::TypeId ns3::UdpTraceClient::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetMaxPacketSize(uint16_t maxPacketSize) [member function]
cls.add_method('SetMaxPacketSize',
'void',
[param('uint16_t', 'maxPacketSize')])
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetRemote(ns3::Ipv4Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Ipv4Address', 'ip'), param('uint16_t', 'port')])
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetRemote(ns3::Ipv6Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Ipv6Address', 'ip'), param('uint16_t', 'port')])
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetRemote(ns3::Address ip, uint16_t port) [member function]
cls.add_method('SetRemote',
'void',
[param('ns3::Address', 'ip'), param('uint16_t', 'port')])
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::SetTraceFile(std::string filename) [member function]
cls.add_method('SetTraceFile',
'void',
[param('std::string', 'filename')])
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## udp-trace-client.h (module 'applications'): void ns3::UdpTraceClient::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3UintegerValue_methods(root_module, cls):
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor]
cls.add_constructor([])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')])
## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor]
cls.add_constructor([param('uint64_t const &', 'value')])
## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## uinteger.h (module 'core'): bool ns3::UintegerValue::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)
## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function]
cls.add_method('Get',
'uint64_t',
[],
is_const=True)
## uinteger.h (module 'core'): std::string ns3::UintegerValue::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)
## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function]
cls.add_method('Set',
'void',
[param('uint64_t const &', 'value')])
return
def register_Ns3V4Ping_methods(root_module, cls):
## v4ping.h (module 'applications'): ns3::V4Ping::V4Ping(ns3::V4Ping const & arg0) [copy constructor]
cls.add_constructor([param('ns3::V4Ping const &', 'arg0')])
## v4ping.h (module 'applications'): ns3::V4Ping::V4Ping() [constructor]
cls.add_constructor([])
## v4ping.h (module 'applications'): static ns3::TypeId ns3::V4Ping::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## v4ping.h (module 'applications'): void ns3::V4Ping::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='private', is_virtual=True)
## v4ping.h (module 'applications'): void ns3::V4Ping::StartApplication() [member function]
cls.add_method('StartApplication',
'void',
[],
visibility='private', is_virtual=True)
## v4ping.h (module 'applications'): void ns3::V4Ping::StopApplication() [member function]
cls.add_method('StopApplication',
'void',
[],
visibility='private', is_virtual=True)
return
def register_Ns3AddressChecker_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')])
return
def register_Ns3AddressValue_methods(root_module, cls):
## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor]
cls.add_constructor([])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor]
cls.add_constructor([param('ns3::AddressValue const &', 'arg0')])
## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor]
cls.add_constructor([param('ns3::Address const &', 'value')])
## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function]
cls.add_method('Copy',
'ns3::Ptr< ns3::AttributeValue >',
[],
is_const=True, is_virtual=True)
## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function]
cls.add_method('DeserializeFromString',
'bool',
[param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_virtual=True)
## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function]
cls.add_method('Get',
'ns3::Address',
[],
is_const=True)
## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function]
cls.add_method('SerializeToString',
'std::string',
[param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')],
is_const=True, is_virtual=True)
## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function]
cls.add_method('Set',
'void',
[param('ns3::Address const &', 'value')])
return
def register_Ns3ApplicationPacketProbe_methods(root_module, cls):
## application-packet-probe.h (module 'applications'): ns3::ApplicationPacketProbe::ApplicationPacketProbe(ns3::ApplicationPacketProbe const & arg0) [copy constructor]
cls.add_constructor([param('ns3::ApplicationPacketProbe const &', 'arg0')])
## application-packet-probe.h (module 'applications'): ns3::ApplicationPacketProbe::ApplicationPacketProbe() [constructor]
cls.add_constructor([])
## application-packet-probe.h (module 'applications'): bool ns3::ApplicationPacketProbe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function]
cls.add_method('ConnectByObject',
'bool',
[param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')],
is_virtual=True)
## application-packet-probe.h (module 'applications'): void ns3::ApplicationPacketProbe::ConnectByPath(std::string path) [member function]
cls.add_method('ConnectByPath',
'void',
[param('std::string', 'path')],
is_virtual=True)
## application-packet-probe.h (module 'applications'): static ns3::TypeId ns3::ApplicationPacketProbe::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## application-packet-probe.h (module 'applications'): void ns3::ApplicationPacketProbe::SetValue(ns3::Ptr<ns3::Packet const> packet, ns3::Address const & address) [member function]
cls.add_method('SetValue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Address const &', 'address')])
## application-packet-probe.h (module 'applications'): static void ns3::ApplicationPacketProbe::SetValueByPath(std::string path, ns3::Ptr<ns3::Packet const> packet, ns3::Address const & address) [member function]
cls.add_method('SetValueByPath',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Address const &', 'address')],
is_static=True)
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_Ns3CounterCalculator__Unsigned_int_methods(root_module, cls):
## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int>::CounterCalculator(ns3::CounterCalculator<unsigned int> const & arg0) [copy constructor]
cls.add_constructor([param('ns3::CounterCalculator< unsigned int > const &', 'arg0')])
## basic-data-calculators.h (module 'stats'): ns3::CounterCalculator<unsigned int>::CounterCalculator() [constructor]
cls.add_constructor([])
## basic-data-calculators.h (module 'stats'): unsigned int ns3::CounterCalculator<unsigned int>::GetCount() const [member function]
cls.add_method('GetCount',
'unsigned int',
[],
is_const=True)
## basic-data-calculators.h (module 'stats'): static ns3::TypeId ns3::CounterCalculator<unsigned int>::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Output(ns3::DataOutputCallback & callback) const [member function]
cls.add_method('Output',
'void',
[param('ns3::DataOutputCallback &', 'callback')],
is_const=True, is_virtual=True)
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Update() [member function]
cls.add_method('Update',
'void',
[])
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::Update(unsigned int const i) [member function]
cls.add_method('Update',
'void',
[param('unsigned int const', 'i')])
## basic-data-calculators.h (module 'stats'): void ns3::CounterCalculator<unsigned int>::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3PacketCounterCalculator_methods(root_module, cls):
## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator::PacketCounterCalculator(ns3::PacketCounterCalculator const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketCounterCalculator const &', 'arg0')])
## packet-data-calculators.h (module 'network'): ns3::PacketCounterCalculator::PacketCounterCalculator() [constructor]
cls.add_constructor([])
## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::FrameUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet, ns3::Mac48Address realto) [member function]
cls.add_method('FrameUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::Mac48Address', 'realto')])
## packet-data-calculators.h (module 'network'): static ns3::TypeId ns3::PacketCounterCalculator::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::PacketUpdate(std::string path, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('PacketUpdate',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet-data-calculators.h (module 'network'): void ns3::PacketCounterCalculator::DoDispose() [member function]
cls.add_method('DoDispose',
'void',
[],
visibility='protected', is_virtual=True)
return
def register_Ns3PacketProbe_methods(root_module, cls):
## packet-probe.h (module 'network'): ns3::PacketProbe::PacketProbe(ns3::PacketProbe const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PacketProbe const &', 'arg0')])
## packet-probe.h (module 'network'): ns3::PacketProbe::PacketProbe() [constructor]
cls.add_constructor([])
## packet-probe.h (module 'network'): bool ns3::PacketProbe::ConnectByObject(std::string traceSource, ns3::Ptr<ns3::Object> obj) [member function]
cls.add_method('ConnectByObject',
'bool',
[param('std::string', 'traceSource'), param('ns3::Ptr< ns3::Object >', 'obj')],
is_virtual=True)
## packet-probe.h (module 'network'): void ns3::PacketProbe::ConnectByPath(std::string path) [member function]
cls.add_method('ConnectByPath',
'void',
[param('std::string', 'path')],
is_virtual=True)
## packet-probe.h (module 'network'): static ns3::TypeId ns3::PacketProbe::GetTypeId() [member function]
cls.add_method('GetTypeId',
'ns3::TypeId',
[],
is_static=True)
## packet-probe.h (module 'network'): void ns3::PacketProbe::SetValue(ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('SetValue',
'void',
[param('ns3::Ptr< ns3::Packet const >', 'packet')])
## packet-probe.h (module 'network'): static void ns3::PacketProbe::SetValueByPath(std::string path, ns3::Ptr<ns3::Packet const> packet) [member function]
cls.add_method('SetValueByPath',
'void',
[param('std::string', 'path'), param('ns3::Ptr< ns3::Packet const >', 'packet')],
is_static=True)
return
def register_Ns3PbbAddressTlv_methods(root_module, cls):
## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv() [constructor]
cls.add_constructor([])
## packetbb.h (module 'network'): ns3::PbbAddressTlv::PbbAddressTlv(ns3::PbbAddressTlv const & arg0) [copy constructor]
cls.add_constructor([param('ns3::PbbAddressTlv const &', 'arg0')])
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStart() const [member function]
cls.add_method('GetIndexStart',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): uint8_t ns3::PbbAddressTlv::GetIndexStop() const [member function]
cls.add_method('GetIndexStop',
'uint8_t',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStart() const [member function]
cls.add_method('HasIndexStart',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::HasIndexStop() const [member function]
cls.add_method('HasIndexStop',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): bool ns3::PbbAddressTlv::IsMultivalue() const [member function]
cls.add_method('IsMultivalue',
'bool',
[],
is_const=True)
## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStart(uint8_t index) [member function]
cls.add_method('SetIndexStart',
'void',
[param('uint8_t', 'index')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetIndexStop(uint8_t index) [member function]
cls.add_method('SetIndexStop',
'void',
[param('uint8_t', 'index')])
## packetbb.h (module 'network'): void ns3::PbbAddressTlv::SetMultivalue(bool isMultivalue) [member function]
cls.add_method('SetMultivalue',
'void',
[param('bool', 'isMultivalue')])
return
def register_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)
register_functions_ns3_addressUtils(module.get_submodule('addressUtils'), root_module)
register_functions_ns3_internal(module.get_submodule('internal'), 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 register_functions_ns3_addressUtils(module, root_module):
return
def register_functions_ns3_internal(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 | 3,725,484,663,931,790,000 | 61.885577 | 594 | 0.603632 | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.